<commit_before>"use strict";

const eNet = require('node-enet-api');

var Service, Characteristic, Accessory, UUIDGen;

module.exports = function (homebridge) {
    Service = homebridge.hap.Service;
    Characteristic = homebridge.hap.Characteristic;
    Accessory = homebridge.platformAccessory;
    UUIDGen = homebridge.hap.uuid;

    homebridge.registerPlatform("homebridge-eNet", "eNetPlatform", eNetPlatform); //, true);
}

function eNetPlatform(log, config, api) {
    this.log = log;
    this.config = config;
    this.gateways = Array.isArray(config.gateways) ? config.gateways : [];
    this.accessories = [];
    this.gateways = [];
    this.loadState = 2; // didFinishLaunching & discover

    var discover = new eNet.discover();

    discover.on('discover', function(gw) {this.newGateway(gw)}.bind(this));

    if (api) {
        this.api = api;

        this.api.on('didFinishLaunching', function() {
            if (--this.loadState === 0) this.setupDevices();
        }.bind(this));
    }
    else --this.loadState;

    discover.discover(function(err) {
        if (err) log.console.warn('Discovery error: ' + err);
        if (--this.loadState === 0) this.setupDevices();
    }.bind(this));
};

eNetPlatform.prototype.newGateway = function (gw) {
    ++this.loadState;
    var g = new eNet.gateway(gw);

    g.getChannelInfo(function(err, res) {
        if (!err)
        {
            if (res && Array.isArray(res.DEVICES)) {
                g.devices = res.DEVICES;
                this.gateways.push(g);
            }
            else err = JSON.stringify(res);
        }

        if (err) this.log.warn("Failed to get gateway channels, ignoring gateway. Error: " + err);
        if (--this.loadState === 0) this.setupDevices();
    }.bind(this));
};

eNetPlatform.prototype.setupDevices = function() {
    if (Array.isArray(this.config.gateways)) {
        for (var i = 0; i < this.config.gateways.length; ++i) {
            var gw = this.config.gateways[i];
            if (Array.isArray(gw.accessories)) {
                var g;
                if (gw.host) g = this.findGateway(gw.host);
                if (!g && gw.mac) g = this.findGateway(gw.mac);
                if (!g && gw.name) g = this.findGateway(gw.name);

                if (!g && gw.host) {
                    g = new eNet.gateway(gw);
                    ++this.loadState;

                    g.getChannelInfo(function(err, res) {
                        if (!err)
                        {
                            if (res && Array.isArray(res.DEVICES)) {
                                g.devices = res.DEVICES;
                                this.gateways.push(g);
                            }
                            else err = JSON.stringify(res);
                        }

                        if (err) this.log.warn("Failed to get gateway channels, ignoring gateway. Error: " + err);
                        if (--this.loadState === 0) this.setupDevices();
                    }.bind(this));

                    return;
                }

                if (g) {
                    for (var j = 0; j < gw.accessories.length; ++j) {
                        var acc = gw.accessories[j];

                        var a = this.findAccessory(g.id, acc.channel);
                        if (a) {
                            if ((a.context.type != acc.type) || (a.context.name != acc.name)){
                                // kick this accessory out, create new one
                                a.reachable = false;
                            }
                            else {
                                a.context.duration = acc.duration;

                                if (!a.reachable) {
                                    a.gateway = g;
                                    a.reachable = true;
                                }
                            }
                        }
                        else {
                            this.createAccessory(g, acc);
                        }
                    }
                }
                else this.log.warn("Cannot find gateway: " + JSON.stringify(gw));
            }
            else this.log.warn("Gateway has no accessories: " + JSON.stringify(gw));
        }
    }
    else this.log.warn("No gateways defined: " + JSOM.stringify(this.config));

    var keep = [], del = [];
    for (var i = 0; i < this.accessories.length; ++i) {
        var acc = this.accessories[i];
        if (acc.reachable) keep.push(acc);
        else {
            this.log.info("Deleting old accessory: " + JSON.stringify(acc.context));
            del.push(acc);
        }
    }

    this.accessories = keep;
    if (del.length) this.api.unregisterPlatformAccessories("homebridge-eNet", "eNetPlatform", del);

    this.log.info("Platform initialization finishd: " + this.accessories.length + " accessories available.");
}

eNetPlatform.prototype.findGateway = function(id) {
    for (var i = 0; i < this.gateways.length; ++i) {
        var gw = this.gateways[i];
        if ((gw.mac === id) || (gw.name === id) || (gw.host === id)) return gw;
    }
}

eNetPlatform.prototype.findAccessory = function(gateID, channel) {
    for (var i = 0; i < this.accessories.length; ++i) {
        var a = this.accessories[i];
        if ((a.context.gateID === gateID) && (a.context.channel === channel)) return a;
    }
}

eNetPlatform.prototype.configureAccessory = function(accessory) {
    this.log.info("Configure accessory: " + JSON.stringify(accessory.context));
    if (this.setupAccessory(accessory)) {
        accessory.reachable = false;
        this.accessories.push(accessory);
    }
}

eNetPlatform.prototype.createAccessory = function(gate, conf) {
    var uuid;

    if (!conf.name || (typeof conf.channel !== 'number')) {
        this.log.warn("Cannot add accessory, invalid config: " + JSON.stringify(conf));
        return;
    }

    this.log.info("Creating accessory: " + JSON.stringify(conf));

    uuid = UUIDGen.generate(JSON.stringify(conf) + gate.id);

    var accessory = new Accessory(conf.name, uuid);

    if (conf.type === "Shutter") {
        accessory.addService(Service.WindowCovering, conf.name)
    }
    else if (conf.type === "Light") {
        accessory.addService(Service.Lightbulb, conf.name)
    }
    else if (conf.type === "Switch") {
        accessory.addService(Service.Switch, conf.name)
    }
    else {
        this.log.warn("Cannot add accessory, invalid config: " + JSON.stringify(conf));
        return;
    }

    accessory.context.gateID = gate.id;
    accessory.context.type = conf.type;
    accessory.context.channel = conf.channel;
    accessory.context.name = conf.name;

    if (this.setupAccessory(accessory)) {
        accessory.reachable = true;
        accessory.gateway = gate;
        this.accessories.push(accessory);
        this.api.registerPlatformAccessories("homebridge-eNet", "eNetPlatform", [accessory]);
    }
}

eNetPlatform.prototype.setupAccessory = function(accessory) {
    var service;

    accessory.log = this.log;

    if (service = accessory.getService(Service.Lightbulb)) {
        service
          .getCharacteristic(Characteristic.On)
//          .on('get', getCurrentPosition.bind(accessory))
          .on('set', setOn.bind(accessory));
    }
    else if (service = accessory.getService(Service.Switch)) {
        service
          .getCharacteristic(Characteristic.On)
//          .on('get', getCurrentPosition.bind(accessory))
          .on('set', setOn.bind(accessory));
    }
    else if (service = accessory.getService(Service.WindowCovering)) {
        this.position = 0;
        this.targetPosition = 0;

        // Characteristic.PositionState.DECREASING = 0;
        // Characteristic.PositionState.INCREASING = 1;
        // Characteristic.PositionState.STOPPED = 2;
        this.positionState = Characteristic.PositionState.STOPPED;

        service
          .getCharacteristic(Characteristic.CurrentPosition)
          .on('get', getCurrentPosition.bind(accessory));

        service
          .getCharacteristic(Characteristic.TargetPosition)
          .on('get', getTargetPosition.bind(accessory))
          .on('set', setTargetPosition.bind(accessory));

        service
          .getCharacteristic(Characteristic.PositionState)
          .on('get', getPositionState.bind(accessory))
          .setValue(this.positionState);

    }
    else
    {
        this.log.warn("Cannot configure accessory, no service found. " + JSON.stringify(accessory.context));
        return false;
    }

    accessory.on('identify', function(paired, callback) {
        this.log.info("Identify: " + JSON.stringify(this.context));
        callback();
    }.bind(accessory));

    return true;
}

////////////////////////////////////////////////////////////////////////////////
//
//  Accessory notifications
//

function getCurrentPosition(callback) {
  callback(null, this.position);
}

function getTargetPosition(callback) {
  callback(null, this.position);
}

function setTargetPosition(position, callback) {
  if (!this.gateway) {
    this.log.warn("eNet device not ready.");
    callback(new Error("eNet device not ready."));
    return;
  }

  if (position == 100 || position == 0) {
      this.log.info("Setting " + this.context.name + " to " + position);
      this.gateway.setValue(this.context.channel, position == 100, true, function(err, res) {
          if (err) {
              this.log.warn("Error setting " + this.context.name + " to " + position + ": " + err);
              callback(err);
          }
          else {
              this.log.info("Succeeded setting " + this.context.name + " to " + position + " : " + JSON.stringify(res));
              this.position = position;
              this.getService(Service.WindowCovering).getCharacteristic(Characteristic.CurrentPosition).setValue(this.position);

              callback(null);
          }
      }.bind(this));
  }
  else {
      callback(null);

      this.position = position;
      this.getService(Service.WindowCovering).getCharacteristic(Characteristic.CurrentPosition).setValue(this.position);
  }
}

function getPositionState(callback) {
  callback(null, this.positionState);
}

function setOn(position, callback) {
  if (!this.gateway) {
    this.log.warn("eNet device not ready.");
    callback(new Error("eNet device not ready."));
    return;
  }

  this.log.info("Setting " + this.context.name + " to " + position === true ? "on" : "off");
  this.gateway.setValue(this.context.channel, position, false, function(err, res) {
      if (err) {
          this.log.warn("Error setting " + this.context.name + " to " + position ? "on" : "off" + ": " + err);
          callback(err);
      }
      else {
          this.log.info("Succeeded setting " + this.context.name + " to " + position ? "on" : "off" + ": " + JSON.stringify(res));
          callback(null);
          if (position && this.context.duration) {
              var service = this.getService(Service.Lightbulb) || this.getService(Service.Switch);
              if (service) {
                  setTimeout(function() {
                  service.getCharacteristic(Characteristic.On).setValue(false);}, this.context.duration * 1000);
              }
          }
      }
  }.bind(this));
}
<commit_msg>bugfixes<commit_after>"use strict";

const eNet = require('node-enet-api');

var Service, Characteristic, Accessory, UUIDGen;

module.exports = function (homebridge) {
    Service = homebridge.hap.Service;
    Characteristic = homebridge.hap.Characteristic;
    Accessory = homebridge.platformAccessory;
    UUIDGen = homebridge.hap.uuid;

    homebridge.registerPlatform("homebridge-eNet", "eNetPlatform", eNetPlatform); //, true);
}

function eNetPlatform(log, config, api) {
    this.log = log;
    this.config = config;
    this.gateways = Array.isArray(config.gateways) ? config.gateways : [];
    this.accessories = [];
    this.gateways = [];
    this.loadState = 2; // didFinishLaunching & discover

    var discover = new eNet.discover();

    discover.on('discover', function(gw) {this.newGateway(gw)}.bind(this));

    if (api) {
        this.api = api;

        this.api.on('didFinishLaunching', function() {
            if (--this.loadState === 0) this.setupDevices();
        }.bind(this));
    }
    else --this.loadState;

    discover.discover(function(err) {
        if (err) log.console.warn('Discovery error: ' + err);
        if (--this.loadState === 0) this.setupDevices();
    }.bind(this));
};

eNetPlatform.prototype.newGateway = function (gw) {
    ++this.loadState;
    var g = new eNet.gateway(gw);

    g.getChannelInfo(function(err, res) {
        if (!err)
        {
            if (res && Array.isArray(res.DEVICES)) {
                g.devices = res.DEVICES;
                this.gateways.push(g);
            }
            else err = JSON.stringify(res);
        }

        if (err) this.log.warn("Failed to get gateway channels, ignoring gateway. Error: " + err);
        if (--this.loadState === 0) this.setupDevices();
    }.bind(this));
};

eNetPlatform.prototype.setupDevices = function() {
    if (Array.isArray(this.config.gateways)) {
        for (var i = 0; i < this.config.gateways.length; ++i) {
            var gw = this.config.gateways[i];
            if (Array.isArray(gw.accessories)) {
                var g;
                if (gw.host) g = this.findGateway(gw.host);
                if (!g && gw.mac) g = this.findGateway(gw.mac);
                if (!g && gw.name) g = this.findGateway(gw.name);

                if (!g && gw.host) {
                    g = new eNet.gateway(gw);
                    ++this.loadState;

                    g.getChannelInfo(function(err, res) {
                        if (!err)
                        {
                            if (res && Array.isArray(res.DEVICES)) {
                                g.devices = res.DEVICES;
                                this.gateways.push(g);
                            }
                            else err = JSON.stringify(res);
                        }

                        if (err) this.log.warn("Failed to get gateway channels, ignoring gateway. Error: " + err);
                        if (--this.loadState === 0) this.setupDevices();
                    }.bind(this));

                    return;
                }

                if (g) {
                    for (var j = 0; j < gw.accessories.length; ++j) {
                        var acc = gw.accessories[j];

                        var a = this.findAccessory(g.id, acc.channel);
                        if (a) {
                            if ((a.context.type != acc.type) || (a.context.name != acc.name)) {
                                // kick this accessory out, create new one
                                a.reachable = false;
                            }
                            else {
                                a.context.duration = acc.duration;

                                if (!a.reachable) {
                                    a.gateway = g;
                                    a.reachable = true;
                                }
                            }
                        }

                        if (!a || !a.reachable) this.createAccessory(g, acc);
                    }
                }
                else this.log.warn("Cannot find gateway: " + JSON.stringify(gw));
            }
            else this.log.warn("Gateway has no accessories: " + JSON.stringify(gw));
        }
    }
    else this.log.warn("No gateways defined: " + JSOM.stringify(this.config));

    var keep = [], del = [];
    for (var i = 0; i < this.accessories.length; ++i) {
        var acc = this.accessories[i];
        if (acc.reachable) keep.push(acc);
        else {
            this.log.info("Deleting old accessory: " + JSON.stringify(acc.context));
            del.push(acc);
        }
    }

    this.accessories = keep;
    if (del.length) this.api.unregisterPlatformAccessories("homebridge-eNet", "eNetPlatform", del);

    this.log.info("Platform initialization finishd: " + this.accessories.length + " accessories available.");
}

eNetPlatform.prototype.findGateway = function(id) {
    for (var i = 0; i < this.gateways.length; ++i) {
        var gw = this.gateways[i];
        if ((gw.mac === id) || (gw.name === id) || (gw.host === id)) return gw;
    }
}

eNetPlatform.prototype.findAccessory = function(gateID, channel) {
    for (var i = 0; i < this.accessories.length; ++i) {
        var a = this.accessories[i];
        if ((a.context.gateID === gateID) && (a.context.channel === channel)) return a;
    }
}

eNetPlatform.prototype.configureAccessory = function(accessory) {
    this.log.info("Configure accessory: " + JSON.stringify(accessory.context));
    if (this.setupAccessory(accessory)) {
        accessory.reachable = false;
        this.accessories.push(accessory);
    }
}

eNetPlatform.prototype.createAccessory = function(gate, conf) {
    var uuid;

    if (!conf.name || (typeof conf.channel !== 'number')) {
        this.log.warn("Cannot add accessory, invalid config: " + JSON.stringify(conf));
        return;
    }

    this.log.info("Creating accessory: " + JSON.stringify(conf));

    uuid = UUIDGen.generate(JSON.stringify(conf) + gate.id);

    var accessory = new Accessory(conf.name, uuid);

    if (conf.type === "Shutter") {
        accessory.addService(Service.WindowCovering, conf.name)
    }
    else if (conf.type === "Light") {
        accessory.addService(Service.Lightbulb, conf.name)
    }
    else if (conf.type === "Switch") {
        accessory.addService(Service.Switch, conf.name)
    }
    else {
        this.log.warn("Cannot add accessory, invalid config: " + JSON.stringify(conf));
        return;
    }

    accessory.context.gateID = gate.id;
    accessory.context.type = conf.type;
    accessory.context.channel = conf.channel;
    accessory.context.name = conf.name;

    if (this.setupAccessory(accessory)) {
        accessory.reachable = true;
        accessory.gateway = gate;
        this.accessories.push(accessory);
        this.api.registerPlatformAccessories("homebridge-eNet", "eNetPlatform", [accessory]);
    }
}

eNetPlatform.prototype.setupAccessory = function(accessory) {
    var service;

    accessory.log = this.log;

    if (service = accessory.getService(Service.Lightbulb)) {
        service
          .getCharacteristic(Characteristic.On)
          .on('set', setOn.bind(accessory));
    }
    else if (service = accessory.getService(Service.Switch)) {
        service
          .getCharacteristic(Characteristic.On)
          .on('set', setOn.bind(accessory));
    }
    else if (service = accessory.getService(Service.WindowCovering)) {
        this.position = 0;
        this.targetPosition = 0;

        // Characteristic.PositionState.DECREASING = 0;
        // Characteristic.PositionState.INCREASING = 1;
        // Characteristic.PositionState.STOPPED = 2;
        this.positionState = Characteristic.PositionState.STOPPED;

        service
          .getCharacteristic(Characteristic.CurrentPosition)
          .on('get', getCurrentPosition.bind(accessory));

        service
          .getCharacteristic(Characteristic.TargetPosition)
          .on('get', getTargetPosition.bind(accessory))
          .on('set', setTargetPosition.bind(accessory));

        service
          .getCharacteristic(Characteristic.PositionState)
          .on('get', getPositionState.bind(accessory))
          .setValue(this.positionState);

    }
    else
    {
        this.log.warn("Cannot configure accessory, no service found. " + JSON.stringify(accessory.context));
        return false;
    }

    accessory.on('identify', function(paired, callback) {
        this.log.info("Identify: " + JSON.stringify(this.context));
        callback();
    }.bind(accessory));

    return true;
}

////////////////////////////////////////////////////////////////////////////////
//
//  Accessory notifications
//

function getCurrentPosition(callback) {
  callback(null, this.position);
}

function getTargetPosition(callback) {
  callback(null, this.position);
}

function setTargetPosition(position, callback) {
  if (!this.gateway) {
    this.log.warn("eNet device not ready.");
    callback(new Error("eNet device not ready."));
    return;
  }

  callback(null);
  if (position == 100 || position == 0) {
      this.log.info("Setting " + this.context.name + " to " + position);

      this.position = position == 100 ? Characteristic.PositionState.DECREASING : Characteristic.PositionState.INCREASING;
      this.getService(Service.WindowCovering).setCharacteristic(Characteristic.CurrentPosition, this.position);

      this.gateway.setValue(this.context.channel, position == 100, true, function(err, res) {
          if (err) {
              this.log.warn("Error setting " + this.context.name + " to " + position + ": " + err);
              //callback(err);
          }
          else {
              this.log.info("Succeeded setting " + this.context.name + " to " + position + " : " + JSON.stringify(res));
              this.position = position;
              this.getService(Service.WindowCovering).setCharacteristic(Characteristic.CurrentPosition, this.position);

              //callback(null);
          }

          this.position = Characteristic.PositionState.STOPPED;
          this.getService(Service.WindowCovering).setCharacteristic(Characteristic.CurrentPosition, this.position);

      }.bind(this));
  }
  else {
      //callback(null);

      this.position = position;
      this.getService(Service.WindowCovering).setCharacteristic(Characteristic.CurrentPosition, this.position);
  }
}

function getPositionState(callback) {
  callback(null, this.positionState);
}

function setOn(position, callback) {
  if (!this.gateway) {
    this.log.warn("eNet device not ready.");
    callback(new Error("eNet device not ready."));
    return;
  }

  this.log.info("Setting " + this.context.name + " to " + position === true ? "on" : "off");

  callback(null);
  this.gateway.setValue(this.context.channel, position, false, function(err, res) {
      if (err) {
          this.log.warn("Error setting " + this.context.name + " to " + position ? "on" : "off" + ": " + err);
          //callback(err);
      }
      else {
          this.log.info("Succeeded setting " + this.context.name + " to " + position ? "on" : "off" + ": " + JSON.stringify(res));
          //callback(null);
          if (position && this.context.duration) {
              var service = this.getService(Service.Lightbulb) || this.getService(Service.Switch);
              if (service) {
                  setTimeout(function() {
                  service.getCharacteristic(Characteristic.On).setValue(false);}, this.context.duration * 1000);
              }
          }
      }
  }.bind(this));
}
<|endoftext|>


<commit_before>import { find, findOne, ready } from 'domassist';
import scrollTriggers from 'scroll-triggers';
import smoothScroll from 'smooth-scroller';

function init(el) {
  if (!el) {
    el = find('[data-toc]');
    el.forEach(e => init(e));
    return;
  }

  if (!el) {
    return;
  }

  const container = el.dataset.tocContainer ?
    findOne(el.dataset.tocContainer) | document.body : document.body;
  const selectors = el.dataset.toc.split(',').map(s => s.trim());
  const tocItems = [];
  const offset = el.dataset.tocOffset ? parseInt(el.dataset.tocOffset, 10) : 1;
  let i = 1;

  // Building dict
  selectors.forEach(selector => {
    const items = find(selector, container);

    items.forEach(item => {
      // Keep the id if already there
      const index = item.id || `toc-${i++}`;
      const text = item.dataset.tocTitle ?
        item.dataset.tocTitle.trim() : item.textContent.trim();
      const className = `toc-${selector}`;

      // Set it if none
      if (item.id !== index) {
        item.id = index;
      }

      tocItems.push({ index, text, className });
    });
  });

  let html = '
';
  const triggerOptions = [];

  // Building markup
  tocItems.forEach((item, j) => {
    const nextEl = tocItems[j + 1];
    const options = {
      el: `.toc-li-${j}`,
      start: `#${item.index}`,
      position: 'top',
      positionEnd: 'top',
      className: 'toc-visible'
    };
    html += `\n<li class="toc-li-${j} ${item.className}"><a href="#${item.index}">${item.text}</a></li>`;

    if (nextEl) {
      options.end = `#${nextEl.index}`;
    }

    triggerOptions.push(options);
  });

  html += '
';

  el.innerHTML = html;

  // Setting up scroll triggers and smooth scroll
  scrollTriggers(triggerOptions);
  smoothScroll(find('a', el), offset);
}

export default init;

ready(init);
<commit_msg>Pausing scroll triggers when smooth scroll happens<commit_after>import { find, findOne, ready, on, fire } from 'domassist';
import scrollTriggers from 'scroll-triggers';
import smoothScroll from 'smooth-scroller';

function init(el) {
  if (!el) {
    el = find('[data-toc]');
    el.forEach(e => init(e));
    return;
  }

  if (!el) {
    return;
  }

  const container = el.dataset.tocContainer ?
    findOne(el.dataset.tocContainer) | document.body : document.body;
  const selectors = el.dataset.toc.split(',').map(s => s.trim());
  const tocItems = [];
  const offset = el.dataset.tocOffset ? parseInt(el.dataset.tocOffset, 10) : 1;
  let i = 1;

  // Building dict
  selectors.forEach(selector => {
    const items = find(selector, container);

    items.forEach(item => {
      // Keep the id if already there
      const index = item.id || `toc-${i++}`;
      const text = item.dataset.tocTitle ?
        item.dataset.tocTitle.trim() : item.textContent.trim();
      const className = `toc-${selector}`;

      // Set it if none
      if (item.id !== index) {
        item.id = index;
      }

      tocItems.push({ index, text, className });
    });
  });

  let html = '
';
  const triggerOptions = [];

  // Building markup
  tocItems.forEach((item, j) => {
    const nextEl = tocItems[j + 1];
    const options = {
      el: `.toc-li-${j}`,
      start: `#${item.index}`,
      position: 'top',
      positionEnd: 'top',
      className: 'toc-visible'
    };
    html += `\n<li class="toc-li-${j} ${item.className}"><a href="#${item.index}">${item.text}</a></li>`;

    if (nextEl) {
      options.end = `#${nextEl.index}`;
    }

    triggerOptions.push(options);
  });

  html += '
';

  el.innerHTML = html;
  const tocs = find('li', el);
  const anchors = find('a', el);

  // Setting up scroll triggers and smooth scroll
  scrollTriggers(triggerOptions);
  smoothScroll(anchors, offset);

  // Pause scroll triggers while smoothscrolling
  on(anchors, 'smoothscroll:start', () => {
    fire(tocs, 'scrolltriggers:pause');
  });

  on(anchors, 'smoothscroll:end', () => {
    fire(tocs, 'scrolltriggers:resume');
  });
}

export default init;

ready(init);
<|endoftext|>


<commit_before>var glob = require('glob');
var path = require('path');
var fs = require('fs');

var modes = {
  'expand': require('./modes/expand'),
  'hash': require('./modes/hash'),
  'list': require('./modes/list')
};

module.exports = require('browserify-transform-tools').makeRequireTransform(
  'require-globify', {
    jsFilesOnly: true,
    evaluateArguments: true
  },
  function(args, opts, done) {
    // args: args passed to require()
    // opts: opts used by browserify for the current file
    // done: browserify callback

    var config, pattern, globOpts, mode, result, sei;

    // only trigger if require was used with exactly 2 params that match our expectations
    if (args.length !== 2 || typeof args[0] !== 'string' || typeof args[1] !== 'object') {
      return done();
    }

    // get the second param to require as our config
    config = args[1];

    var skipExtCompat = typeof config.resolve !== 'undefined';

    // backwards compatibility for glob and hash options, replaced by mode
    if (config.glob) {
      config.mode = "expand";
    } else if (config.hash) {
      config.mode = "hash";
      if (config.hash === "path") {
        config.resolve = ["path"];
      }
    }

    // set default resolve option to ["path-reduce", "strip-ext"]
    config.resolve = config.resolve || ["path-reduce", "strip-ext"];
    if (!Array.isArray(config.resolve)) {
      config.resolve = [config.resolve];
    }

    // backwards compatibility for ext option
    if (!skipExtCompat) {
    if (typeof config.ext === 'undefined' || config.ext === false) {
      if (config.resolve.indexOf('strip-ext') === -1) {
        config.resolve.push('strip-ext');
      }
    } else { // remove ext
      sei = config.resolve.indexOf('strip-ext');
      // this wont work if strip-ext is there multiple times
      // but what's the change of that happening?
      if (sei !== -1) {
        config.resolve.splice(sei, 1);
      }
    }
    }

    // if the config object doesn't match our specs, abort
    if (typeof config.mode === 'undefined') {
      console.warn('doesn\'t match require-globify api');
      return done();
    }

    // find mode
    if (typeof config.mode === 'function') {
      mode = config.mode;
    } else if (modes.hasOwnProperty(config.mode)) {
      mode = modes[config.mode];
    } else {
      console.warn("Unknown mode: " + config.mode);
      return done();
    }

    // take the first param to require as pattern
    pattern = args[0];

    // use any additional options given
    globOpts = config.options || {};

    // if no override; set the cwd for glob to the dirname of the current file
    globOpts.cwd = globOpts.cwd || path.dirname(opts.file);
    // only match files
    globOpts.nodir = true;

    glob(pattern, globOpts, function(err, files) {
      // if there was an error with glob, abort here
      if (err) {
        return done(err);
      }

      try {
        // sort files to ensure consistent order upon multiple runs
        files.sort();

        result = mode(opts.file, files, config);

        done(null, result);
      } catch (err) {
        return done(err);
      }

    });
  }
);
<commit_msg>fixes #25<commit_after>var glob = require('glob');
var path = require('path');
var fs = require('fs');

var modes = {
  'expand': require('./modes/expand'),
  'hash': require('./modes/hash'),
  'list': require('./modes/list')
};

module.exports = require('browserify-transform-tools').makeRequireTransform(
  'require-globify', {
    jsFilesOnly: true,
    evaluateArguments: true,
    falafelOptions: {ecmaVersion: 6}
  },
  function(args, opts, done) {
    // args: args passed to require()
    // opts: opts used by browserify for the current file
    // done: browserify callback

    var config, pattern, globOpts, mode, result, sei;

    // only trigger if require was used with exactly 2 params that match our expectations
    if (args.length !== 2 || typeof args[0] !== 'string' || typeof args[1] !== 'object') {
      return done();
    }

    // get the second param to require as our config
    config = args[1];

    var skipExtCompat = typeof config.resolve !== 'undefined';

    // backwards compatibility for glob and hash options, replaced by mode
    if (config.glob) {
      config.mode = "expand";
    } else if (config.hash) {
      config.mode = "hash";
      if (config.hash === "path") {
        config.resolve = ["path"];
      }
    }

    // set default resolve option to ["path-reduce", "strip-ext"]
    config.resolve = config.resolve || ["path-reduce", "strip-ext"];
    if (!Array.isArray(config.resolve)) {
      config.resolve = [config.resolve];
    }

    // backwards compatibility for ext option
    if (!skipExtCompat) {
    if (typeof config.ext === 'undefined' || config.ext === false) {
      if (config.resolve.indexOf('strip-ext') === -1) {
        config.resolve.push('strip-ext');
      }
    } else { // remove ext
      sei = config.resolve.indexOf('strip-ext');
      // this wont work if strip-ext is there multiple times
      // but what's the change of that happening?
      if (sei !== -1) {
        config.resolve.splice(sei, 1);
      }
    }
    }

    // if the config object doesn't match our specs, abort
    if (typeof config.mode === 'undefined') {
      console.warn('doesn\'t match require-globify api');
      return done();
    }

    // find mode
    if (typeof config.mode === 'function') {
      mode = config.mode;
    } else if (modes.hasOwnProperty(config.mode)) {
      mode = modes[config.mode];
    } else {
      console.warn("Unknown mode: " + config.mode);
      return done();
    }

    // take the first param to require as pattern
    pattern = args[0];

    // use any additional options given
    globOpts = config.options || {};

    // if no override; set the cwd for glob to the dirname of the current file
    globOpts.cwd = globOpts.cwd || path.dirname(opts.file);
    // only match files
    globOpts.nodir = true;

    glob(pattern, globOpts, function(err, files) {
      // if there was an error with glob, abort here
      if (err) {
        return done(err);
      }

      try {
        // sort files to ensure consistent order upon multiple runs
        files.sort();

        result = mode(opts.file, files, config);

        done(null, result);
      } catch (err) {
        return done(err);
      }

    });
  }
);
<|endoftext|>


<commit_before>var express = require('express');
var app = express();
app.use(express.logger());

app.get('/', function(request, response) {
  response.send('Hello World!');
});

var port = process.env.PORT || 5000;
app.listen(port, function() {
  console.log("Listening on " + port);
});<commit_msg>fixing fallout from accidental merge<commit_after><|endoftext|>


<commit_before>var fs      = require('fs');
var spawn   = require('child_process').spawn;

              require('colors');
var program = require('commander');
var esprima = require('esprima');
var glob    = require('glob');
var _       = require('lodash');
var request = require('request');

var headers = {

  // GitHub API requires the User-Agent Header to be set
  'User-Agent': 'mdlint'
};

var tokenFile = __dirname + '/authtoken.txt';

module.exports = function () {

  // Use Auth Token if present
  if (fs.existsSync(tokenFile)) {
    headers.Authorization = 'token ' + fs.readFileSync(tokenFile, 'utf8');
  }

  program
    .version('0.0.0')
    .option('-s, --silent',  'only report failing lints');

  program
    .command('repo <repo>')
    .description('lints a README from a GitHub repo')
    .action(function (repo) {
      fetchREADME(repo);
    });

  program
    .command('user <username>')
    .description('lints all READMEs from a user\'s GitHub repos')
    .action(function (user) {
      getUserREADMEs(user);
    });

  program
    .command('glob <glob>')
    .description('lints local markdown files that match a file glob')
    .action(function (fileGlob) {
      glob.sync(fileGlob).forEach(function (file) {
        lintMarkdown(fs.readFileSync(file, 'utf8'), file);
      });
    });

  program
    .command('query <query>')
    .option('--page', 'The page of results to return. Defaults to 0.')
    .description('lints READMEs from repos returned by a GitHub query.')
    .action(function (query) {
      request({
        uri: 'https://api.github.com/legacy/repos/search/' +
             query +
             '?language=JavaScript' +
             '&start_page=' + program.page || '0',
        headers: headers
      }, function (error, response, body) {
        if (!error && response.statusCode === 200) {
          JSON.parse(body)
            .repositories
            .forEach(function (repo) {
              fetchREADME(repo.owner + '/' + repo.name);
            });
        } else {
          if (response.headers['x-ratelimit-remaining'] === '0') {
            getAuthToken();
          } else {
            console.log(body);
            console.log(response.headers);
            console.log('Unable to reach the GitHub API :('.red);
          }
          return;
        }
      });
    });

  program
    .command('*')
    .action(function (command) {
      if (command.indexOf('/') !== -1) {
        fetchREADME(command);
      } else if (command.indexOf('*') !== -1 || command.indexOf('.') !== -1) {
        glob.sync(command).forEach(function (file) {
          lintMarkdown(fs.readFileSync(file, 'utf8'), file);
        });
      } else {
        getUserREADMEs(command);
      }
    });

  program
    .parse(process.argv);

  if (!program.args.length) {
    program.help();
  }
};

/**
 * Fetches READMEs from a user's GitHub repos
 * @param  {String} GitHub username
 */
function getUserREADMEs (user) {
  request({
    uri: 'https://api.github.com/users/' + user + '/repos',
    headers: headers
  }, function (error, response, body) {
    var responseBody = JSON.parse(body);

    if (responseBody.message) {
      console.log('Error: the following user was not found: '.red + user.blue);
      return;
    }

    JSON.parse(body)
      .forEach(function (repo) {
        fetchREADME(repo.full_name);
      });
  });
}

/**
 * Fetches a README from GitHub
 * @param  {String} repo URL of repo to fetch
 */
function fetchREADME (repo) {
  request({
    uri: 'https://api.github.com/repos/' + repo + '/readme',
    headers: _.extend(headers, {

      // Get raw README content
      'Accept': 'application/vnd.github.VERSION.raw'
    })
  },
  function (error, response, body) {
    if (!error && response.statusCode === 200) {
      lintMarkdown(body, repo);
    } else {
      if (response.headers['x-ratelimit-remaining'] === '0') {
        getAuthToken();
      } else {
        console.log('README for https://github.com/' + repo.blue + ' not found.'.red);
        return;
      }
    }
  });
}

/**
 * [parseMarkdown description]
 * @param  {String} markdownContent Content of markdown file
 * @return {Array}                  Array of objects with a language and code property
 */
function parseMarkdown (markdownContent) {
  var codeBlocks =  markdownContent

  .split('```')

  .filter(function (codeBlock, index) {

    // Delete the text in between code sections
    if (index % 2 === 0 ||

        // Remove non JavaScript and JSON code blocks
        (codeBlock.trim().toLowerCase().indexOf('js')         !== 0 &&
         codeBlock.trim().toLowerCase().indexOf('javascript') !== 0)) {
      return false;
    }
    return true;
  })

  .map(function (codeBlock) {
    return {
      lang: codeBlock.split('\n')[0].trim().toLowerCase(),
      code: codeBlock.slice(codeBlock.indexOf('\n') + 1)
    };
  });

  return codeBlocks;
}

/**
 * Parses the JavaScript code blocks from the markdown file
 * @param  {String} body Body of markdown file
 * @param  {String} file Filename
 */
function lintMarkdown (body, file) {

  if (!program.silent) {
    console.log(file.blue.bold);
  }
  var codeBlocks = parseMarkdown(body);
  if (_.all(_.compact(codeBlocks), validateCodeBlock)) {
    if (!program.silent) {
      console.log('Markdown passed linting.\n'.green);
    }
  } else {
    console.log('Markdown failed linting.\n'.red);
  }
}

/**
 * Validates that code blocks are valid JavaScript
 * @param  {Object} code A block of code from the markdown file containg the lang and code
 */
function validateCodeBlock (codeBlock) {
  var lang = codeBlock.lang;
  var code = codeBlock.code;

  if (lang === 'json') {
    try {
      JSON.parse(code);
    } catch (e) {
      console.log(e);
      console.log(code);
      return false;
    }
    return true;
  } else if (lang === 'js' || lang === 'javascript') {
    code = preprocessCode(code);
    try {
      esprima.parse(code, { tolerant: true });
    } catch (e) {

      // Get indeces from lineNumber and column
      var line   = e.lineNumber - 1;
      var column = e.column - 1;

      // Highlight error in code
      code = code.split('\n');

      code[line] = code[line].slice(0, column).magenta +
                   code[line][column].red +
                   code[line].slice(column + 1).magenta;

      code = code.join('\n');

      console.log(e);
      console.log(code);
      return false;
    }
    return true;
  }
}

/**
 * Retrieves an auth token so that the user can exceed the uauthenticated rate limit
 */
function getAuthToken () {
  console.log('You have hit the rate limit for unauthenticated requests, please log in to raise your rate limit:\n'.red);

  program.prompt('GitHub Username: ', function (user) {

    console.log('\nAfter entering your password, hit return' + ' twice.\n'.green);
    var authProcess = spawn('curl', [
      '-u',
      user,
      '-d',
      '{"scopes":["repo"],"note":"mdlint"}',
      '-s',
      'https://api.github.com/authorizations'
    ], {
      stdio: [process.stdin, 'pipe', process.stderr]
    });

    authProcess.stdout.setEncoding('utf8');
    authProcess.stdout.on('data', function (data) {
      var response = JSON.parse(data);
      if (response.message) {
        console.log(response.message.red + '\n');
        process.exit();
      } else {
        fs.writeFileSync(tokenFile, response.token);
        console.log('Authenticated :). Now try your lint again. \n'.green);
        process.exit();
      }
    });
  });
}

/**
 * Preprocesses the code block and re-formats it to allow for partial code
 * @param  {String} code A block of code from the markdown file
 * @return {String} Processed code transformed from partial code
 */
function preprocessCode (code) {

  // Remove starting comments
  if (code.indexOf('//') === 0) {
    code = code.slice(code.indexOf('\n'));
  }

  // Starts with an object literal
  if (code.indexOf('{') === 0) {
    code = 'var json = ' + code + ';';

  // Starts with an object property
  } else if (code.indexOf(': {') !== -1 && code.indexOf(': {') < code.indexOf('{')) {
    code = 'var json = {' + code + '};';
  }

  // Starts with an anonymous function
  if (code.indexOf('function') === 0) {
    code = 'var func = ' + code + ';';
  }

  // Contains ...
  return code.replace('...', '');
}<commit_msg>Fixed bug in implicit command logic<commit_after>var fs      = require('fs');
var spawn   = require('child_process').spawn;

              require('colors');
var program = require('commander');
var esprima = require('esprima');
var glob    = require('glob');
var _       = require('lodash');
var request = require('request');

var headers = {

  // GitHub API requires the User-Agent Header to be set
  'User-Agent': 'mdlint'
};

var tokenFile = __dirname + '/authtoken.txt';

module.exports = function () {

  // Use Auth Token if present
  if (fs.existsSync(tokenFile)) {
    headers.Authorization = 'token ' + fs.readFileSync(tokenFile, 'utf8');
  }

  program
    .version('0.0.0')
    .option('-s, --silent',  'only report failing lints');

  program
    .command('repo <repo>')
    .description('lints a README from a GitHub repo')
    .action(function (repo) {
      fetchREADME(repo);
    });

  program
    .command('user <username>')
    .description('lints all READMEs from a user\'s GitHub repos')
    .action(function (user) {
      getUserREADMEs(user);
    });

  program
    .command('glob <glob>')
    .description('lints local markdown files that match a file glob')
    .action(function (fileGlob) {
      glob.sync(fileGlob).forEach(function (file) {
        lintMarkdown(fs.readFileSync(file, 'utf8'), file);
      });
    });

  program
    .command('query <query>')
    .option('--page', 'The page of results to return. Defaults to 0.')
    .description('lints READMEs from repos returned by a GitHub query.')
    .action(function (query) {
      request({
        uri: 'https://api.github.com/legacy/repos/search/' +
             query +
             '?language=JavaScript' +
             '&start_page=' + program.page || '0',
        headers: headers
      }, function (error, response, body) {
        if (!error && response.statusCode === 200) {
          JSON.parse(body)
            .repositories
            .forEach(function (repo) {
              fetchREADME(repo.owner + '/' + repo.name);
            });
        } else {
          if (response.headers['x-ratelimit-remaining'] === '0') {
            getAuthToken();
          } else {
            console.log(body);
            console.log(response.headers);
            console.log('Unable to reach the GitHub API :('.red);
          }
          return;
        }
      });
    });

  program
    .command('*')
    .action(function (command) {
      if (command.indexOf('*') !== -1 || command.indexOf('.') !== -1) {
        glob.sync(command).forEach(function (file) {
          lintMarkdown(fs.readFileSync(file, 'utf8'), file);
        });
      } else if (command.indexOf('/') !== -1) {
        fetchREADME(command);
      } else {
        getUserREADMEs(command);
      }
    });

  program
    .parse(process.argv);

  if (!program.args.length) {
    program.help();
  }
};

/**
 * Fetches READMEs from a user's GitHub repos
 * @param  {String} GitHub username
 */
function getUserREADMEs (user) {
  request({
    uri: 'https://api.github.com/users/' + user + '/repos',
    headers: headers
  }, function (error, response, body) {
    var responseBody = JSON.parse(body);

    if (responseBody.message) {
      console.log('Error: the following user was not found: '.red + user.blue);
      return;
    }

    JSON.parse(body)
      .forEach(function (repo) {
        fetchREADME(repo.full_name);
      });
  });
}

/**
 * Fetches a README from GitHub
 * @param  {String} repo URL of repo to fetch
 */
function fetchREADME (repo) {
  request({
    uri: 'https://api.github.com/repos/' + repo + '/readme',
    headers: _.extend(headers, {

      // Get raw README content
      'Accept': 'application/vnd.github.VERSION.raw'
    })
  },
  function (error, response, body) {
    if (!error && response.statusCode === 200) {
      lintMarkdown(body, repo);
    } else {
      if (response.headers['x-ratelimit-remaining'] === '0') {
        getAuthToken();
      } else {
        console.log('README for https://github.com/' + repo.blue + ' not found.'.red);
        return;
      }
    }
  });
}

/**
 * [parseMarkdown description]
 * @param  {String} markdownContent Content of markdown file
 * @return {Array}                  Array of objects with a language and code property
 */
function parseMarkdown (markdownContent) {
  var codeBlocks =  markdownContent

  .split('```')

  .filter(function (codeBlock, index) {

    // Delete the text in between code sections
    if (index % 2 === 0 ||

        // Remove non JavaScript and JSON code blocks
        (codeBlock.trim().toLowerCase().indexOf('js')         !== 0 &&
         codeBlock.trim().toLowerCase().indexOf('javascript') !== 0)) {
      return false;
    }
    return true;
  })

  .map(function (codeBlock) {
    return {
      lang: codeBlock.split('\n')[0].trim().toLowerCase(),
      code: codeBlock.slice(codeBlock.indexOf('\n') + 1)
    };
  });

  return codeBlocks;
}

/**
 * Parses the JavaScript code blocks from the markdown file
 * @param  {String} body Body of markdown file
 * @param  {String} file Filename
 */
function lintMarkdown (body, file) {

  if (!program.silent) {
    console.log(file.blue.bold);
  }
  var codeBlocks = parseMarkdown(body);
  if (_.all(_.compact(codeBlocks), validateCodeBlock)) {
    if (!program.silent) {
      console.log('Markdown passed linting.\n'.green);
    }
  } else {
    console.log('Markdown failed linting.\n'.red);
  }
}

/**
 * Validates that code blocks are valid JavaScript
 * @param  {Object} code A block of code from the markdown file containg the lang and code
 */
function validateCodeBlock (codeBlock) {
  var lang = codeBlock.lang;
  var code = codeBlock.code;

  if (lang === 'json') {
    try {
      JSON.parse(code);
    } catch (e) {
      console.log(e);
      console.log(code);
      return false;
    }
    return true;
  } else if (lang === 'js' || lang === 'javascript') {
    code = preprocessCode(code);
    try {
      esprima.parse(code, { tolerant: true });
    } catch (e) {

      // Get indeces from lineNumber and column
      var line   = e.lineNumber - 1;
      var column = e.column - 1;

      // Highlight error in code
      code = code.split('\n');

      code[line] = code[line].slice(0, column).magenta +
                   code[line][column].red +
                   code[line].slice(column + 1).magenta;

      code = code.join('\n');

      console.log(e);
      console.log(code);
      return false;
    }
    return true;
  }
}

/**
 * Retrieves an auth token so that the user can exceed the uauthenticated rate limit
 */
function getAuthToken () {
  console.log('You have hit the rate limit for unauthenticated requests, please log in to raise your rate limit:\n'.red);

  program.prompt('GitHub Username: ', function (user) {

    console.log('\nAfter entering your password, hit return' + ' twice.\n'.green);
    var authProcess = spawn('curl', [
      '-u',
      user,
      '-d',
      '{"scopes":["repo"],"note":"mdlint"}',
      '-s',
      'https://api.github.com/authorizations'
    ], {
      stdio: [process.stdin, 'pipe', process.stderr]
    });

    authProcess.stdout.setEncoding('utf8');
    authProcess.stdout.on('data', function (data) {
      var response = JSON.parse(data);
      if (response.message) {
        console.log(response.message.red + '\n');
        process.exit();
      } else {
        fs.writeFileSync(tokenFile, response.token);
        console.log('Authenticated :). Now try your lint again. \n'.green);
        process.exit();
      }
    });
  });
}

/**
 * Preprocesses the code block and re-formats it to allow for partial code
 * @param  {String} code A block of code from the markdown file
 * @return {String} Processed code transformed from partial code
 */
function preprocessCode (code) {

  // Remove starting comments
  if (code.indexOf('//') === 0) {
    code = code.slice(code.indexOf('\n'));
  }

  // Starts with an object literal
  if (code.indexOf('{') === 0) {
    code = 'var json = ' + code + ';';

  // Starts with an object property
  } else if (code.indexOf(': {') !== -1 && code.indexOf(': {') < code.indexOf('{')) {
    code = 'var json = {' + code + '};';
  }

  // Starts with an anonymous function
  if (code.indexOf('function') === 0) {
    code = 'var func = ' + code + ';';
  }

  // Contains ...
  return code.replace('...', '');
}<|endoftext|>


<commit_before>var vdf = require('vdf');
var fs = require('fs');
var SteamID = require('steamid');
var ByteBuffer = require('bytebuffer');

var protomask = 0x80000000;

var Language = require('./language.js');
var Protos = require('./protos.js');

module.exports = TeamFortress2;

require('util').inherits(TeamFortress2, require('events').EventEmitter);

function TeamFortress2(steam) {
	this._steam = steam;
	this.haveGCSession = false;
	this._hadGCSession = false;
	this._isInTF2 = false;

	var self = this;

	// "extend" the default steam.gamesPlayed function so we can catch when TF2 starts up
	var gamesPlayed = steam.gamesPlayed;
	steam.gamesPlayed = function(appids) {
		if(appids.indexOf(440) != -1) {
			self._isInTF2 = true;
			if(!self.haveGCSession) {
				self._connect();
			}
		} else {
			if(self._helloInterval) {
				clearInterval(self._helloInterval);
				self._helloInterval = null;
			}

			self._isInTF2 = false;
			self.haveGCSession = false;
			self._hadGCSession = false;
		}

		gamesPlayed.call(steam, appids);
	};

	steam.on('fromGC', function(appID, type, body) {
		if(appID != 440) {
			// Not from the TF2 GC
			return;
		}

		var protobuf = !!(type & protomask);
		type &= ~protomask;

		if(self._handlers[type]) {
			self._handlers[type].call(self, protobuf ? body : ByteBuffer.wrap(body, ByteBuffer.LITTLE_ENDIAN));
		} else {
			var msgName = type;
			for(var i in Language) {
				if(Language[i] == type) {
					msgName = i;
					break;
				}
			}

			self.emit('debug', "Got unhandled GC message " + msgName + (protobuf ? " (protobuf)" : ""));
		}
	});

	steam.on('loggedOff', function() {
		self._isInTF2 = false;
		self._hadGCSession = self.haveGCSession;
		if(self.haveGCSession) {
			self.emit('disconnectedFromGC', TeamFortress2.GCGoodbyeReason.NO_SESSION);
			self.haveGCSession = false;
		}
	});

	steam.on('error', function(e) {
		self._isInTF2 = false;
		self._hadGCSession = false;
		if(self.haveGCSession) {
			self.emit('disconnectedFromGC', TeamFortress2.GCGoodbyeReason.NO_SESSION);
			self.haveGCSession = false;
		}
	});

	steam.on('loggedOn', function() {
		if(self._hadGCSession) {
			self._connect();
			self._hadGCSession = false;
		}
	});
}

TeamFortress2.prototype._connect = function() {
	if(!this._isInTF2 || this._helloInterval) {
		return; // We're not in TF2 or we're already trying to connect
	}

	var self = this;
	this._helloInterval = setInterval(function() {
		if(self.haveGCSession) {
			clearInterval(self._helloInterval);
			self._helloInterval = null;
			return;
		}

		self._send(Language.ClientHello, Protos.CMsgClientHello, {});
	}, 5000);
};

TeamFortress2.prototype._send = function(type, protobuf, body) {
	if(!this._steam.loggedOn) {
		return false;
	}

	var msgName = type;
	for(var i in Language) {
		if(Language[i] == type) {
			msgName = i;
			break;
		}
	}

	this.emit('debug', "Sending GC message " + msgName);

	if(protobuf) {
		this._steam.toGC(440, type | protomask, (new protobuf(body)).toBuffer());
	} else {
		// This is a ByteBuffer
		this._steam.toGC(440, type, body.flip().toBuffer());
	}

	return true;
};

TeamFortress2.prototype.setLang = function(langFile) {
	var lang = vdf.parse(langFile);
	// The vdf parser appears to add some random characters and quotes to the root 'lang' key, so we'll just use a loop to find it
	for(var i in lang) {
		this.lang = lang[i].Tokens;
	}
};

TeamFortress2.prototype.craft = function(items, recipe) {
	var buffer = new ByteBuffer(2 + 2 + (8 * items.length), ByteBuffer.LITTLE_ENDIAN);
	buffer.writeInt16(recipe || -2); // -2 is wildcard
	buffer.writeInt16(items.length);
	for(var i = 0; i < items.length; i++) {
		buffer.writeUint64(coerceToLong(items[i]));
	}

	this._send(Language.Craft, null, buffer);
};

TeamFortress2.prototype.trade = function(steamID) {
	var buffer = new ByteBuffer(12, ByteBuffer.LITTLE_ENDIAN);
	buffer.writeUint32(0);
	buffer.writeUint64(coerceToLong(steamID));
	this._send(Language.Trading_InitiateTradeRequest, null, buffer);
};

TeamFortress2.prototype.cancelTradeRequest = function() {
	var buffer = new ByteBuffer(0, ByteBuffer.LITTLE_ENDIAN);
	this._send(Language.Trading_CancelSession, null, buffer);
};

TeamFortress2.prototype.respondToTrade = function(tradeID, accept) {
	var buffer = new ByteBuffer(8, ByteBuffer.LITTLE_ENDIAN);
	buffer.writeUint32(accept ? TeamFortress2.TradeResponse.Accepted : TeamFortress2.TradeResponse.Declined);
	buffer.writeUint32(tradeID);
	this._send(Language.Trading_InitiateTradeResponse, null, buffer);
};

TeamFortress2.prototype.setStyle = function(item, style) {
	var buffer = new ByteBuffer(12, ByteBuffer.LITTLE_ENDIAN);
	buffer.writeUint64(coerceToLong(item));
	buffer.writeUint32(style);
	this._send(Language.SetItemStyle, null, buffer);
};

TeamFortress2.prototype.setPosition = function(item, position) {
	var buffer = new ByteBuffer(16, ByteBuffer.LITTLE_ENDIAN);
	buffer.writeUint64(coerceToLong(item));
	buffer.writeUint64(coerceToLong(position));
	this._send(Language.SetSingleItemPosition, null, buffer);
};

TeamFortress2.prototype.setPositions = function(items) {
	this._send(Language.SetItemPositions, Protos.CMsgSetItemPositions, {"itemPositions": items});
};

TeamFortress2.prototype.deleteItem = function(item) {
	var buffer = new ByteBuffer(8, ByteBuffer.LITTLE_ENDIAN);
	buffer.writeUint64(coerceToLong(item));
	this._send(Language.Delete, null, buffer);
};

TeamFortress2.prototype.wrapItem = function(wrapID, itemID) {
	var buffer = new ByteBuffer(16, ByteBuffer.LITTLE_ENDIAN);
	buffer.writeUint64(coerceToLong(wrapID));
	buffer.writeUint64(coerceToLong(itemID));
	this._send(Language.GiftWrapItem, null, buffer);
};

TeamFortress2.prototype.deliverGift = function(gift, steamID) {
	var buffer = new ByteBuffer(16, ByteBuffer.LITTLE_ENDIAN);
	buffer.writeUint64(coerceToLong(gift));
	buffer.writeUint64(coerceToLong(steamID));
	this._send(Language.DeliverGift, null, buffer);
};

TeamFortress2.prototype.unwrapGift = function(gift) {
	var buffer = new ByteBuffer(8, ByteBuffer.LITTLE_ENDIAN);
	buffer.writeUint64(coerceToLong(gift));
	this._send(Language.UnwrapGiftRequest, null, buffer);
};

TeamFortress2.prototype.useItem = function(item) {
	this._send(Language.UseItemRequest, Protos.CMsgUseItem, {"itemId": item});
};

TeamFortress2.prototype.sortBackpack = function(sortType) {
	this._send(Language.SortItems, Protos.CMsgSortItems, {"sortType": sortType});
};

TeamFortress2.prototype.sendProfessorSpeks = function(steamID) {
	this._send(Language.FreeTrial_ChooseMostHelpfulFriend, Protos.CMsgTFFreeTrialChooseMostHelpfulFriend, {"accountIdFriend": new SteamID(steamID).accountid});
};

TeamFortress2.prototype.createServerIdentity = function() {
	this._send(Language.GameServer_CreateIdentity, Protos.CMsgGC_GameServer_CreateIdentity, {"accountId": new SteamID(this._steam.steamID).accountid});
};

TeamFortress2.prototype.getRegisteredServers = function() {
	this._send(Language.GameServer_List, Protos.CMsgGC_GameServer_List, {"accountId": new SteamID(this._steam.steamID).accountid});
};

TeamFortress2.prototype.resetServerIdentity = function(id) {
	this._send(Language.GameServer_ResetIdentity, Protos.CMsgGC_GameServer_ResetIdentity, {"gameServerAccountId": id});
};

TeamFortress2.prototype.openCrate = function(keyID, crateID) {
	var buffer = new ByteBuffer(16, ByteBuffer.LITTLE_ENDIAN);
	buffer.writeUint64(coerceToLong(keyID));
	buffer.writeUint64(coerceToLong(crateID));
	this._send(Language.UnlockCrate, null, buffer);
};

TeamFortress2.prototype.equipItem = function(itemID, classID, slot) {
	this._send(Language.AdjustItemEquippedState, Protos.CMsgAdjustItemEquippedState, {"itemId": itemID, "newClass": classID, "newSlot": slot});
};

TeamFortress2.prototype.requestSpyVsEngiWarStats = function() {
	this._send(Language.SpyVsEngyWar_RequestGlobalStats, Protos.CGCMsgGC_SpyVsEngyWar_RequestGlobalStats, {});
};

TeamFortress2.prototype._handlers = {};

function coerceToLong(num, signed) {
	return typeof num === 'string' ? new ByteBuffer.Long(num, !signed, 10) : num;
}

require('./enums.js');
require('./handlers.js');<commit_msg>I'm an idiot who needs to read documentation more carefully<commit_after>var vdf = require('vdf');
var fs = require('fs');
var SteamID = require('steamid');
var ByteBuffer = require('bytebuffer');

var protomask = 0x80000000;

var Language = require('./language.js');
var Protos = require('./protos.js');

module.exports = TeamFortress2;

require('util').inherits(TeamFortress2, require('events').EventEmitter);

function TeamFortress2(steam) {
	this._steam = steam;
	this.haveGCSession = false;
	this._hadGCSession = false;
	this._isInTF2 = false;

	var self = this;

	// "extend" the default steam.gamesPlayed function so we can catch when TF2 starts up
	var gamesPlayed = steam.gamesPlayed;
	steam.gamesPlayed = function(appids) {
		if(appids.indexOf(440) != -1) {
			self._isInTF2 = true;
			if(!self.haveGCSession) {
				self._connect();
			}
		} else {
			if(self._helloInterval) {
				clearInterval(self._helloInterval);
				self._helloInterval = null;
			}

			self._isInTF2 = false;
			self.haveGCSession = false;
			self._hadGCSession = false;
		}

		gamesPlayed.call(steam, appids);
	};

	steam.on('fromGC', function(appID, type, body) {
		if(appID != 440) {
			// Not from the TF2 GC
			return;
		}

		var protobuf = !!(type & protomask);
		type &= ~protomask;

		if(self._handlers[type]) {
			self._handlers[type].call(self, protobuf ? body : ByteBuffer.wrap(body, ByteBuffer.LITTLE_ENDIAN));
		} else {
			var msgName = type;
			for(var i in Language) {
				if(Language[i] == type) {
					msgName = i;
					break;
				}
			}

			self.emit('debug', "Got unhandled GC message " + msgName + (protobuf ? " (protobuf)" : ""));
		}
	});

	steam.on('loggedOff', function() {
		self._isInTF2 = false;
		self._hadGCSession = self.haveGCSession;
		if(self.haveGCSession) {
			self.emit('disconnectedFromGC', TeamFortress2.GCGoodbyeReason.NO_SESSION);
			self.haveGCSession = false;
		}
	});

	steam.on('error', function(e) {
		self._isInTF2 = false;
		self._hadGCSession = false;
		if(self.haveGCSession) {
			self.emit('disconnectedFromGC', TeamFortress2.GCGoodbyeReason.NO_SESSION);
			self.haveGCSession = false;
		}
	});

	steam.on('loggedOn', function() {
		if(self._hadGCSession) {
			self._connect();
			self._hadGCSession = false;
		}
	});
}

TeamFortress2.prototype._connect = function() {
	if(!this._isInTF2 || this._helloInterval) {
		return; // We're not in TF2 or we're already trying to connect
	}

	var self = this;
	this._helloInterval = setInterval(function() {
		if(self.haveGCSession) {
			clearInterval(self._helloInterval);
			self._helloInterval = null;
			return;
		}

		self._send(Language.ClientHello, Protos.CMsgClientHello, {});
	}, 5000);
};

TeamFortress2.prototype._send = function(type, protobuf, body) {
	if(!this._steam.loggedOn) {
		return false;
	}

	var msgName = type;
	for(var i in Language) {
		if(Language[i] == type) {
			msgName = i;
			break;
		}
	}

	this.emit('debug', "Sending GC message " + msgName);

	if(protobuf) {
		this._steam.toGC(440, type | protomask, (new protobuf(body)).toBuffer());
	} else {
		// This is a ByteBuffer
		this._steam.toGC(440, type, body.flip().toBuffer());
	}

	return true;
};

TeamFortress2.prototype.setLang = function(langFile) {
	var lang = vdf.parse(langFile);
	// The vdf parser appears to add some random characters and quotes to the root 'lang' key, so we'll just use a loop to find it
	for(var i in lang) {
		this.lang = lang[i].Tokens;
	}
};

TeamFortress2.prototype.craft = function(items, recipe) {
	var buffer = new ByteBuffer(2 + 2 + (8 * items.length), ByteBuffer.LITTLE_ENDIAN);
	buffer.writeInt16(recipe || -2); // -2 is wildcard
	buffer.writeInt16(items.length);
	for(var i = 0; i < items.length; i++) {
		buffer.writeUint64(coerceToLong(items[i]));
	}

	this._send(Language.Craft, null, buffer);
};

TeamFortress2.prototype.trade = function(steamID) {
	var buffer = new ByteBuffer(12, ByteBuffer.LITTLE_ENDIAN);
	buffer.writeUint32(0);
	buffer.writeUint64(coerceToLong(steamID));
	this._send(Language.Trading_InitiateTradeRequest, null, buffer);
};

TeamFortress2.prototype.cancelTradeRequest = function() {
	var buffer = new ByteBuffer(0, ByteBuffer.LITTLE_ENDIAN);
	this._send(Language.Trading_CancelSession, null, buffer);
};

TeamFortress2.prototype.respondToTrade = function(tradeID, accept) {
	var buffer = new ByteBuffer(8, ByteBuffer.LITTLE_ENDIAN);
	buffer.writeUint32(accept ? TeamFortress2.TradeResponse.Accepted : TeamFortress2.TradeResponse.Declined);
	buffer.writeUint32(tradeID);
	this._send(Language.Trading_InitiateTradeResponse, null, buffer);
};

TeamFortress2.prototype.setStyle = function(item, style) {
	var buffer = new ByteBuffer(12, ByteBuffer.LITTLE_ENDIAN);
	buffer.writeUint64(coerceToLong(item));
	buffer.writeUint32(style);
	this._send(Language.SetItemStyle, null, buffer);
};

TeamFortress2.prototype.setPosition = function(item, position) {
	var buffer = new ByteBuffer(16, ByteBuffer.LITTLE_ENDIAN);
	buffer.writeUint64(coerceToLong(item));
	buffer.writeUint64(coerceToLong(position));
	this._send(Language.SetSingleItemPosition, null, buffer);
};

TeamFortress2.prototype.setPositions = function(items) {
	this._send(Language.SetItemPositions, Protos.CMsgSetItemPositions, {"itemPositions": items});
};

TeamFortress2.prototype.deleteItem = function(item) {
	var buffer = new ByteBuffer(8, ByteBuffer.LITTLE_ENDIAN);
	buffer.writeUint64(coerceToLong(item));
	this._send(Language.Delete, null, buffer);
};

TeamFortress2.prototype.wrapItem = function(wrapID, itemID) {
	var buffer = new ByteBuffer(16, ByteBuffer.LITTLE_ENDIAN);
	buffer.writeUint64(coerceToLong(wrapID));
	buffer.writeUint64(coerceToLong(itemID));
	this._send(Language.GiftWrapItem, null, buffer);
};

TeamFortress2.prototype.deliverGift = function(gift, steamID) {
	var buffer = new ByteBuffer(16, ByteBuffer.LITTLE_ENDIAN);
	buffer.writeUint64(coerceToLong(gift));
	buffer.writeUint64(coerceToLong(steamID));
	this._send(Language.DeliverGift, null, buffer);
};

TeamFortress2.prototype.unwrapGift = function(gift) {
	var buffer = new ByteBuffer(8, ByteBuffer.LITTLE_ENDIAN);
	buffer.writeUint64(coerceToLong(gift));
	this._send(Language.UnwrapGiftRequest, null, buffer);
};

TeamFortress2.prototype.useItem = function(item) {
	this._send(Language.UseItemRequest, Protos.CMsgUseItem, {"itemId": item});
};

TeamFortress2.prototype.sortBackpack = function(sortType) {
	this._send(Language.SortItems, Protos.CMsgSortItems, {"sortType": sortType});
};

TeamFortress2.prototype.sendProfessorSpeks = function(steamID) {
	this._send(Language.FreeTrial_ChooseMostHelpfulFriend, Protos.CMsgTFFreeTrialChooseMostHelpfulFriend, {"accountIdFriend": new SteamID(steamID).accountid});
};

TeamFortress2.prototype.createServerIdentity = function() {
	this._send(Language.GameServer_CreateIdentity, Protos.CMsgGC_GameServer_CreateIdentity, {"accountId": new SteamID(this._steam.steamID).accountid});
};

TeamFortress2.prototype.getRegisteredServers = function() {
	this._send(Language.GameServer_List, Protos.CMsgGC_GameServer_List, {"accountId": new SteamID(this._steam.steamID).accountid});
};

TeamFortress2.prototype.resetServerIdentity = function(id) {
	this._send(Language.GameServer_ResetIdentity, Protos.CMsgGC_GameServer_ResetIdentity, {"gameServerAccountId": id});
};

TeamFortress2.prototype.openCrate = function(keyID, crateID) {
	var buffer = new ByteBuffer(16, ByteBuffer.LITTLE_ENDIAN);
	buffer.writeUint64(coerceToLong(keyID));
	buffer.writeUint64(coerceToLong(crateID));
	this._send(Language.UnlockCrate, null, buffer);
};

TeamFortress2.prototype.equipItem = function(itemID, classID, slot) {
	this._send(Language.AdjustItemEquippedState, Protos.CMsgAdjustItemEquippedState, {"itemId": itemID, "newClass": classID, "newSlot": slot});
};

TeamFortress2.prototype.requestSpyVsEngiWarStats = function() {
	this._send(Language.SpyVsEngyWar_RequestGlobalStats, Protos.CGCMsgGC_SpyVsEngyWar_RequestGlobalStats, {});
};

TeamFortress2.prototype._handlers = {};

function coerceToLong(num, signed) {
	return typeof num === 'string' ? new ByteBuffer.Long.fromString(num, !signed, 10) : num;
}

require('./enums.js');
require('./handlers.js');<|endoftext|>


<commit_before>/*!
 * hard <https://github.com/akileez/hard>
 *
 * Copyright (c) 2015 Keith Williams.
 * Licensed under the ISC license.
 */

function rendr (files, stack, globals, defaults, cb) {
  iterate.each(files, function (page, key, done) {
    var page = matter.read(page)
    var meta = page.data || {}
    var text = page.content || ''

    // check for and assign default layout
    if (isNullOrUndef(meta.layout) || !stack[meta.layout]) {
      meta.layout = defaults.defaultLayout
    }

    // merge context
    var context = extend({}, globals, stack[meta.layout].locals, meta)

    // apply layouts to content
    text = layouts(text, meta.layout, stack, {
      layoutDelims: ['{{=', '}}'],
      defaultLayout: [null]
    }).result

    // compile template
    var template = handlebars.compile(text, {
      noEscape: true,
      preventIndent: true,
      assumeObjects: true
    })

    // mkdir if non-existant, write file to dest and prettify rendered template
    return writeFile(meta.dest.fpath, template(context), function (err) {
      assert.ifError(err)
      logger.file(meta.dest.fpath, 'rendered')
      done(null, key)
    })
  }, function (err, result) {
    assert.ifError(err)
    cb()
  })
}

function rendr2 (files, stack, globals, defaults, cb) {
  iterate.each(files, function (page, key, done) {
    var page = matter.read(page)
    var meta = page.data || {}
    var text = page.content || ''

    // merge context
    var context = extend({}, globals, meta)

    // compile template
    var template = handlebars.compile(text, {
      noEscape: true,
      preventIndent: true,
      assumeObjects: true
    })

    // mkdir if non-existant, write file to dest and prettify rendered template
    return writeFile(meta.dest.fpath, template(context), function (err) {
      assert.ifError(err)
      logger.file(meta.dest.fpath, 'rendered')
      done(null, key)
    })
  }, function (err, result) {
    assert.ifError(err)
    cb()
  })
}
<commit_msg>update index -- install base render process<commit_after>//
//    █████╗ ██╗  ██╗██╗██╗     ███████╗███████╗███████╗
//   ██╔══██╗██║ ██╔╝██║██║     ██╔════╝██╔════╝╚══███╔╝
//   ███████║█████╔╝ ██║██║     █████╗  █████╗    ███╔╝
//   ██╔══██║██╔═██╗ ██║██║     ██╔══╝  ██╔══╝   ███╔╝
//   ██║  ██║██║  ██╗██║███████╗███████╗███████╗███████╗
//   ╚═╝  ╚═╝╚═╝  ╚═╝╚═╝╚══════╝╚══════╝╚══════╝╚══════╝
//
//   hard <https://github.com/akileez/hard>
//   Copyright (c) 2015 Keith Williams. Licensed under the ISC license.

// Rendr Requirements
// ///////////////////////////////////////////////////////////////////////////////

'use strict'

var argv             = require('argh').argv
var resolve          = require('resolve')
var handlebars       = require('handlebars')
var globby           = require('./app/src/globby')
var registrar        = require('./app/src/registrarHandlebars')
var rendr            = require('./app/rendr').rendr
var matter           = require('./app/rendr').matter
var buildLayoutStack = require('./app/rendr').buildLayoutStack
var readFile         = require('./app/rendr').readFile
var Config           = require('toolz/src/cache/cfg')
var iterate          = require('toolz/src/async/iterate')
var concurrent       = require('toolz/src/async/concurrent')
var contains         = require('toolz/src/array/contains')
var strContains      = require('toolz/src/string/contains')
var expand           = require('toolz/src/string/expand')
var keys             = require('toolz/src/object/keys')
var values           = require('toolz/src/object/values')
var union            = require('toolz/src/array/union')
var wrap             = require('toolz/src/async/wrap')
var getBaseDir       = require('./app/util/getBaseDir')
var logger           = require('./app/util/logger')
var ftree            = require('./app/util/fileTree')
var jcolz            = require('json-colorz')
var parsefm          = require('parse-yuf')
var path             = require('path')
var assert           = require('assert')

var config           = new Config()
var opts             = new Config()
var stack            = new Config()
var map              = new Config()
var page             = new Config()

var registrarhbs     = wrap(registrar)

function Rendr (initialConfig) {

  logger.datetime()

  // Application Switches
  // ///////////////////////////////////////////////////////////////////////////////

  // Build Environment : [development, production]
  // Build Stage       : [dev, test, prod]

  config.set({
    BUILD_ENV   : 'development',
    BUILD_STAGE : 'dev',
  })

  if (argv.test) {
    config.set('BUILD_STAGE', 'test')
    // opts.set('destination', 'dist') This test worked.
  }

  if (argv.stage) {
    config.set('BUILD_ENV', 'production')
    config.set('BUILD_STAGE', 'test')
  }

  if (argv.prod) {
    config.set('BUILD_ENV', 'production')
    config.set('BUILD_STAGE', 'prod')
  }

  if (argv.argv === undefined) argv.argv = 'rendr'

  // display summary of environment variables
  logger.infoDisplay(config.get(), argv)

  // Environment(env), Global(config) and Defaults(opts) configuration
  // ///////////////////////////////////////////////////////////////////////////////

  // initialize app with settings
  logger.ready('Reading', 'configuration')

  config.set(initialConfig.globals)
  opts.set(initialConfig.defaults)

  // Rendr Tasks
  // ///////////////////////////////////////////////////////////////////////////////
  // if no task name given, set default task name to `rendr`
  if (argv.argv == 'rendr') {
    argv.r = true

    var opsRendr = [
      register,
      configContext,
      loadTemplates,
      buildFileTree,
      pageMap,
      layoutStack,
      rendrTemplates,
      watch
    ]

    iterate.series(opsRendr, function (err) {
      assert.ifError(err)
    })
  }

  if (argv.argv == 'jobs') {
    logger.jobsDisplay()
  }

  // get initial settings read in from the initialConfig
  if (argv.argv == 'config') {
    if (argv.type == 'defaults') {
      logger.ready('displaying', 'defaults')
      jcolz(opts.get())
    }
    if (argv.type == 'globals') {
      logger.ready('displaying', 'globals')
      var opsConfig = [configContext]
      return iterate.series(opsConfig, function (err) {
        assert.ifError(err)
        jcolz(config.get())
      })
    }
  }

  // Core Functions
  // ///////////////////////////////////////////////////////////////////////////////

  // Register Handlebars Helpers and Partials
  function register (cb) {
    registrarhbs(handlebars, {
      bustCache: true,
      // parsePartialName: function (file) {
      //   return path.basename(file.shortPath)
      // },
      partials: [
        opts.get('partials')
      ],
      helpers: [
        opts.get('helpers')
      ]
    }, function () {
      cb(null, 'registrar')
    })
  }

  function configContext (cb) {
    iterate.each(globby.sync(opts.get('context')), function (val, key, done) {
      parsefm(val, function (err, res) {
        assert.ifError(err)
        config.set(expand(res.data))
        done(null, key)
      })
    }, function (err, res) {
      assert.ifError(err)
      // jcolz(config.get())
      cb(null, 'reData')
    })
  }

  // Normalized file object of Template Views and Sources
  // Map frontMatter (YAML) to normalized object for each template
  function loadTemplates (cb) {
    var nfmap // new front-matter map

    iterate.each(globby.sync(opts.get('templates')), function (val, key, done) {
      map.set(readFile(val))
      done(null, key)
    }, function (err, res) {
      assert.ifError(err)
      nfmap = {}

      matter(map.get(), false, opts.get(), function (err, res) {
        nfmap.map = res
        config.set(nfmap)

        if (argv.d) {
          iterate.each(globby.sync(opts.get('sources')), function (val, key, done) {
            map.set(readFile(val))
            done(null, key)
          }, function (err, res) {
            assert.ifError(err)
            cb(null, 'loadTemplates')
          })
        } else {
          cb(null, 'loadTemplates')
        }
      })
    })
  }

  // Generated a filepath object of static assets and attach to global data (`this`).
  // helpers use this object for lookup, navigation and relative path calculation.
  function buildFileTree (cb) {
    var items = {
      // glob of filenames and namespace for ftree
      templates : 'tmpls', // just for testing. remove later
      // modules   : '_',
      css       : 'css',
      js        : 'js',
      code      : 'code',
      ico       : 'ico',
      img       : 'img',
      pdf       : 'pdf'
    }

    iterate.each(items, function (val, key, done) {
      ftree(globby.sync(opts.get(key)), val, function (err, res) {
        config.set(res)
        done(null, key)
      })
    }, function (err, res) {
      assert.ifError(err)
      cb(null, 'ftree')
    })
  }

  // Map modules/pages to cache. Helpers read from cache as opposed to
  // reading from disk during render time.
  function pageMap (cb) {
    iterate.each(globby.sync(opts.get('modules')), function (val, key, done) {
      page.set(readFile(val, true))
      done(null, key)
    }, function (err, res) {
      assert.ifError(err)
      config.set('_', page.get())
      cb(null, 'pageMap')
    })
  }

  // Build the layout stack
  function layoutStack (cb) {
    // stack.del()
    buildLayoutStack(globby.sync(opts.get('layouts')), false, function (err, res) {
      stack.set(res)
      cb(null, 'refresh')
    })
  }

  // Rendr templates using caches
  // map    -- normalized template/source object
  // stack  -- normalized layout object
  // config -- global data (context)
  // opts   -- default options
  function rendrTemplates (cb) {
    if (argv.r) {
      logger.info('Begin', 'rendering')
      rendr(map.get(), stack.get(), config.get(), opts.get(), function () {
        logger.done('rendered', 'Templates')
        cb(null, 'rendrTemplates')
      })
    } else {
      cb(null, 'rendrTemplates')
    }
  }

  // Chokidar Watch Files
  // ///////////////////////////////////////////////////////////////////////////////

  // Large section of code which could use a consolidation of sorts into a plain function with
  // parameters passed to it for configuration. Still working on that part. Main logic of program
  // presented here running under toolz/src/async/iterate. Using flags via argh.argv to filter whether or not
  // watch will run.
  function watch (cb) {
    if (argv.w) {
      argv.r = true
      var chokidar = require(resolve.sync('chokidar', {basedir: '/usr/local/lib/node_modules'}))
      var watchOpts = {
        ignored: /[\/\\]\./,
        ignoreInitial: true,
        persistent: true,
        useFsEvents: false
      }

      var rndrSingleFile = function (path, cb) {
        // get updated template object.
        var pathObj = readFile(path)
        // reset the file cache and frontmatter
        if (strContains(path, 'views')) {
          map.set(pathObj)

          var nfmap = {}

          matter(map.get(pathObj), true, opts.get(), function (err, res) {
            // namespace the frontmatter object
            nfmap.map = res
            config.set(nfmap)
          })
        }

        // rendr only changed template
        rendr(pathObj, stack.get(), config.get(), opts.get(), function () {
          logger.done('rendered', 'Template')
          cb(null, 'rndr')
        })
      }

      var watch = {
        // Watch Templates Views.
        // /////////////////////////////////////////////////////////////////////////////////
        // This process will generate a YFM Map of all templates, re-generate only the file
        // which changed, and re-populate the file cache with a fresh copy. All other watch
        // processes will call this cache to re-generate files upon a change in their
        // respective operations.
        templates: chokidar.watch(opts.get('templates'), watchOpts)
          .on('change', function(path) {
            logger.changed(path)

            function rndrFilez (cb) {
              rndrSingleFile(path, function () {
                cb(null, 'rndr')
              })
            }

            var opsTemplates = [rndrFilez]

            iterate.series(opsTemplates, function(err, res) {
              assert.ifError(err)
            })
          })
          .on('ready', function() {
            logger.ready('Watching:', 'templates')
          }),

        // Watch Templates Source.
        // /////////////////////////////////////////////////////////////////////////////////
        // This process will re-generate only the file which changed, and re-populate
        // the file cache with a fresh copy. All other watch processes will call this
        // newly created cache to re-generate files upon a change in their
        // respective operations.
        sources: chokidar.watch(opts.get('sources'), watchOpts)
          .on('change', function(path) {
            logger.changed(path)

            function rndrFilez (cb) {
              rndrSingleFile(path, function () {
                cb(null, 'rndr')
              })
            }

            var opsTemplates = [rndrFilez]

            iterate.series(opsTemplates, function(err, res) {
              assert.ifError(err)
            })
          }),

        // Watch Layouts.
        // /////////////////////////////////////////////////////////////////////////////////
        layouts: chokidar.watch(opts.get('layouts'), watchOpts)
          .on('change', function(path) {
            logger.changed(path)

            function donemsg (cb) {
              logger.done('initialized', 'Stack')
              cb(null, 'doneMsg')
            }

            function rndrFilez (cb) {
              var fn = 'layouts/templates/src/sitemap.hbs'
              rndrSingleFile(fn, function () {
                cb(null, 'rndr')
              })
            }

            function reStack (cb) {
              buildLayoutStack(globby.sync(path), path, function (err, res) {
                stack.set(res)
                cb(null, 'reStack')
              })
            }

            if (getBaseDir(path, 'self') === 'layout-sitemap') {
              var opsLayouts = [reStack, donemsg, rndrFilez]
              iterate.series(opsLayouts, function (err, res) {
                assert.ifError(err)
              })
            } else {
              var opsLayouts = [reStack, donemsg, rendrTemplates]
              iterate.series(opsLayouts, function (err, res) {
                assert.ifError(err)
              })
            }
          })
          .on('ready', function() {
            logger.ready('Watching:', 'layouts')
          }),

        // Watch Helpers..
        // /////////////////////////////////////////////////////////////////////////////////
        helpers: chokidar.watch(opts.get('helpers'), watchOpts)
          .on('change', function(path) {
            logger.changed(path)

            // Register just the helpers
            function registerHelpers (cb) {
              registrarhbs(handlebars, {
                bustCache: true,
                helpers: [
                  opts.get('helpers')
                ]
              }, function () {
                logger.done('reloaded', 'Helpers')
                cb(null, 'helpers')
              })
            }

            var opsHelpers = [registerHelpers, rendrTemplates]
            iterate.series(opsHelpers, function (err, res) {
              assert.ifError(err)
            })
          })
          .on('ready', function() {
            logger.ready('Watching:', 'helpers')
          }),

        // Watch Partials.
        // /////////////////////////////////////////////////////////////////////////////////
        partials: chokidar.watch(opts.get('partials'), watchOpts)
          .on('change', function(path) {
            logger.changed(path)

            // Register just the partials
            function registerPartials (cb) {
              registrarhbs(handlebars, {
                bustCache: true,
                partials: [
                  opts.get('partials')
                ]
              }, function () {
                logger.done('reloaded', 'Partials')
                cb(null, 'partials')
              })
            }

            var opsPartials = [registerPartials, rendrTemplates]
            iterate.series(opsPartials, function (err, res) {
              assert.ifError(err)
            })
          })
          .on('ready', function() {
            logger.ready('Watching:', 'partials')
          }),

        // Watch Modules.
        // /////////////////////////////////////////////////////////////////////////////////
        modules: chokidar.watch(opts.get('modules'), watchOpts)
          .on('all', function(event, path) {

            function pageMapper (cb) {
              page.set(readFile(path, true))
              // config.set('_', page.get())
              cb(null, 'mapped')
            }

            if (event == 'change') {
              logger.changed(path)

              var opsMods = [pageMapper, rendrTemplates]
              iterate.series(opsMods, function(err, res) {
                assert.ifError(err)
              })
            }

            if (event == 'add') {
              logger.event('File', path, 'has been added')

              var opsMods = [pageMapper]
              iterate.series(opsMods, function (err, res) {
                assert.ifError(err)
              })
            }

            if (event == 'unlink') {
              logger.event('File', path, 'has been removed')

              // normalize key, remove it from page cache, reset global cache
              var fp = path.split(/[\/]/g).slice(-1).toString().replace(/.hbs$/, '')
              page.del(fp)
              config.set('_', page.get())

              var opsMods = [rendrTemplates]
              iterate.series(opsMods, function (err, res) {
                assert.ifError(err)
              })
            }
          })
          .on('ready', function() {
            logger.ready('Watching:', 'modules')
          }),

        // Watch Globals.
        // /////////////////////////////////////////////////////////////////////////////////
        globaldata: chokidar.watch(opts.get('context'), watchOpts)
          .on('change', function(fp) {
            logger.changed(fp)

            function reGdata (cb) {
              parsefm(fp, function (err, res) {
                config.set(expand(res.data))
                logger.done('changed', 'Global context')
                cb(null, 'gdata')
              })
            }

            var opsGdata = [reGdata, rendrTemplates]
            iterate.series(opsGdata, function (err, res) {
              assert.ifError(err)
            })
          })
          .on('unlink', function(fp) {
            logger.event('File', fp, 'has been removed.')

            function delGdata (cb) {
              config.del(path.basename(fp, path.extname(fp)))
              jcolz(config.get())
              cb(null, 'delGdata')
            }

            var opsGdata = [delGdata, rendrTemplates]
            iterate.series(opsGdata, function (err, res) {
              assert.ifError(err)
            })
          })
      }
    }
    cb(null, 'watch')
  }
}

module.exports = Rendr
module.exports.glob = globby
module.exports.handlebars = handlebars
module.exports.parsefm = parsefm.sync
<|endoftext|>


<commit_before>var WebGL = require("./lib/webgl"),
    SGEMMCalculator = require("./lib/sgemmcalculator"),
    test = require("./lib/test");

var gl = new WebGL(),
    gemm = new SGEMMCalculator(gl);

module.exports = {
    "sgemm" : gemm.calculate.bind(gemm),
    "saxpy" : saxpy,
    "gl" : gl,
    "util" : { "fromArray" : fromArray, "transpose" : transpose},
    "test" : test
};

function saxpy(n, a, x, y){
    var i = 0,
        result = new Float32Array(n);

    // assert n = a.length
    // assert a is scalar
    // assert x is Float32Array

    if(isNumeric(y)){
        // shortcut for scalar y
        for(; i < n; i++){
            result[i] = a * x[i] + y;
        }
    } else {

        for(; i < n; i++){
            result[i] = a * x[i] + y[i];
        }
    }

    return result;

}

// add a String.format method, if none exists
if (!String.prototype.format) {
  String.prototype.format = function() {
	var args = arguments;
	return this.replace(/{(\d+)}/g, function(match, number) {
	  return typeof args[number] != 'undefined'
		? args[number]
		: match
	  ;
	});
  };
}

function isNumeric( obj ) { return (obj - parseFloat( obj ) + 1) >= 0; }

/* create a typed array from a 2D javascript array */
function fromArray(array, type, tranpose) {
	var shape = [],
			data,
			c;   // number of columns

	if(!tranpose){
		shape[0] = array.length;
		shape[1] = array[0].length;
	} else {
		shape[1] = array.length;
		shape[0] = array[0].length;
	}
	c = shape[1];

	type = type || Float32Array;

	data = new type(shape[0]*shape[1]);

	for (var ii = 0; ii < shape[0]; ++ii)
		for (var jj = 0; jj < shape[1]; ++jj)
		if(!tranpose)
			data[ii*c + jj] = array[ii][jj];
		else
			data[ii*c + jj] = array[jj][ii];

	return data;
};

// tranpose a typed array in row major order, with the given row and column
// numers
function transpose(r, c, typedArray){
    var result = new typedArray.constructor(r*c);

    for(var i = 0; i < r; i++){
        for(var j = 0; j < c; j++){
            result[j * r + i] = typedArray[i * c + j];
        }
    }

    return result;
}
<commit_msg>basic GPU saxpy<commit_after>var WebGL = require("./lib/webgl"),
    SGEMMCalculator = require("./lib/sgemmcalculator"),
    SAXPYCalculator = require("./lib/saxpycalculator"),
    test = require("./lib/test");

var gl = new WebGL(),
    sgemm = new SGEMMCalculator(gl),
    saxpy = new SAXPYCalculator(gl);

module.exports = {
    "sgemm" : sgemm.calculate.bind(sgemm),
    "saxpy" : saxpy.calculate.bind(saxpy),
    "gl" : gl,
    "util" : { "fromArray" : fromArray, "transpose" : transpose},
    "test" : test
};
/*
function saxpy(n, a, x, y){
    var i = 0,
        result = new Float32Array(n);

    // assert n = x.length
    // assert a is scalar
    // assert x is Float32Array

    if(isNumeric(y)){
        // shortcut for scalar y
        for(; i < n; i++){
            result[i] = a * x[i] + y;
        }
    } else {

        for(; i < n; i++){
            result[i] = a * x[i] + y[i];
        }
    }

    return result;

}*/

// add a String.format method, if none exists
if (!String.prototype.format) {
  String.prototype.format = function() {
	var args = arguments;
	return this.replace(/{(\d+)}/g, function(match, number) {
	  return typeof args[number] != 'undefined'
		? args[number]
		: match
	  ;
	});
  };
}

function isNumeric( obj ) { return (obj - parseFloat( obj ) + 1) >= 0; }

/* create a typed array from a 2D javascript array */
function fromArray(array, type, tranpose) {
	var shape = [],
			data,
			c;   // number of columns

	if(!tranpose){
		shape[0] = array.length;
		shape[1] = array[0].length;
	} else {
		shape[1] = array.length;
		shape[0] = array[0].length;
	}
	c = shape[1];

	type = type || Float32Array;

	data = new type(shape[0]*shape[1]);

	for (var ii = 0; ii < shape[0]; ++ii)
		for (var jj = 0; jj < shape[1]; ++jj)
		if(!tranpose)
			data[ii*c + jj] = array[ii][jj];
		else
			data[ii*c + jj] = array[jj][ii];

	return data;
};

// tranpose a typed array in row major order, with the given row and column
// numers
function transpose(r, c, typedArray){
    var result = new typedArray.constructor(r*c);

    for(var i = 0; i < r; i++){
        for(var j = 0; j < c; j++){
            result[j * r + i] = typedArray[i * c + j];
        }
    }

    return result;
}
<|endoftext|>


<commit_before>console.clear();

const WebSocket = require('ws');

const port = 3000;

let SHOW_DEBUG_MESSAGES = true;
const log = (...args) => {
  if(SHOW_DEBUG_MESSAGES) {
    console.log(...args);
  }
}

const VISITOR = null;
const CLIENT = 1;
const HOST = 2;

const state = {
  connPool: new ConnectionPool(),
}

// ======================================================= //

function ConnectionPool() {
  this.hosts = [];
  this.nextHostID = 1; // not an index for array
}

ConnectionPool.prototype.addHost = function(conn) {
  this.hosts.push(conn);
  return this.nextHostID++;
}

ConnectionPool.prototype.removeHost = function(conn) {
  this.hosts.splice(this.hosts.indexOf(conn), 1);
}

ConnectionPool.prototype.getDisplayList = function() {
  return this.hosts.map(h => ({ hostID: h.hostID, hostName: h.hostName }));
}

// ======================================================= //

function Connection(state, ws) {
  this.state = state;
  this.ws = ws;
  this.type = VISITOR;
  this._handleMessage = this._onVisitorMessage;
  this.hostID;
}

Connection.prototype.onMessage = function(str) {
  this._handleMessage(str);
}

Connection.prototype._onVisitorMessage = function(str) {
  const req = JSON.parse(str);
  switch(req.type) {
    case 'HOST': //props: hostName
      this.type = HOST;
      this._handleMessage = this._onHostMessage;
      this.hostID = this.state.connPool.addHost(this);
      this.hostName = req.hostName;
      this.ws.send(JSON.stringify({
        type: 'REGISTERED',
        hostID: this.hostID,
        hostName: this.hostName,
      }));
      break;
    case 'LIST':
      this.ws.send(JSON.stringify({
        type: 'LIST',
        payload: this.state.connPool.getDisplayList(),
      }));
      break;
    default:
      log('Unknown request type:', req.type, 'for:', req);
  }
}

Connection.prototype._onHostMessage = function(str) {}

// ======================== Main ======================== //
const wss = new WebSocket.Server({ port: port });

console.log('Listening on port %d...', port);

try {
wss.on('connection', function connection(ws) {
  try {
    log('New Connection');

    const conn = new Connection(state, ws);

    ws.on('message', function incoming(msg) {
      log('Received: %s', msg);

      try {
        conn.onMessage(msg);
      } catch (e) {
        log('ERROR onMessage: ',e,'\n- Trying to Process: `'+msg+'`');
      }
    });

    ws.on('close', function() {
      log('* Lost Connection');
      state.connPool.removeHost(conn);
    });
  } catch(e) {
    log('ERROR on connection:\n',e);
  }
});
} catch(e) {
  log('ERROR listening for connections:\n', e);
}
<commit_msg>Convert server's prototype declarations to classes<commit_after>console.clear();

const WebSocket = require('ws');

const port = 3000;

let SHOW_DEBUG_MESSAGES = true;
const log = (...args) => {
  if(SHOW_DEBUG_MESSAGES) {
    console.log(...args);
  }
}

const VISITOR = null;
const CLIENT = 1;
const HOST = 2;

// ======================================================= //

class ConnectionPool {
  constructor() {
    this.hosts = [];
    this.nextHostID = 1; // not an index for array
  }

  addHost(conn) {
    this.hosts.push(conn);
    return this.nextHostID++;
  }

  removeHost(conn) {
    this.hosts.splice(this.hosts.indexOf(conn), 1);
  }

  getDisplayList() {
    return this.hosts.map(h => ({ hostID: h.hostID, hostName: h.hostName }));
  }
}

// ======================================================= //

class Connection {
  constructor(state, ws) {
    this.state = state;
    this.ws = ws;
    this.type = VISITOR;
    this._handleMessage = this._onVisitorMessage;
    this.hostID;
  }

  onMessage(str) {
    this._handleMessage(str);
  }

  _onVisitorMessage(str) {
    const req = JSON.parse(str);
    switch(req.type) {
      case 'HOST': //props: hostName
        this.type = HOST;
        this._handleMessage = this._onHostMessage;
        this.hostID = this.state.connPool.addHost(this);
        this.hostName = req.hostName;
        this.ws.send(JSON.stringify({
          type: 'REGISTERED',
          hostID: this.hostID,
          hostName: this.hostName,
        }));
        break;
      case 'LIST':
        this.ws.send(JSON.stringify({
          type: 'LIST',
          payload: this.state.connPool.getDisplayList(),
        }));
        break;
      default:
        log('Unknown request type:', req.type, 'for:', req);
    }
  }

  _onHostMessage(str) {}
}

// ======================== Main ======================== //

const state = {
  connPool: new ConnectionPool(),
}

const wss = new WebSocket.Server({ port: port });

console.log('Listening on port %d...', port);

try {
wss.on('connection', function connection(ws) {
  try {
    log('New Connection');

    const conn = new Connection(state, ws);

    ws.on('message', function incoming(msg) {
      log('Received: %s', msg);

      try {
        conn.onMessage(msg);
      } catch (e) {
        log('ERROR onMessage: ',e,'\n- Trying to Process: `'+msg+'`');
      }
    });

    ws.on('close', function() {
      log('* Lost Connection');
      state.connPool.removeHost(conn);
    });
  } catch(e) {
    log('ERROR on connection:\n',e);
  }
});
} catch(e) {
  log('ERROR listening for connections:\n', e);
}
<|endoftext|>


<commit_before>module.exports = merge

function merge() {
  var args = [].slice.call(arguments),
      l = args.length
  if (!l) return {}
  if (l == 1) return args[0]
  return parseObjects(args)
}

function parseObjects(objs) {
  var result = {},
      keys = []
  for (var i = 0, l = objs.length; i < l; ++i) {
    keys = keys.concat(Object.keys(objs[i]))
  }
  keys = keys.filter(function (k, idx, arr) { return arr.lastIndexOf(k) === idx })
  for (var k = 0, f = keys.length; k < f; ++k) {
    var keyResult = [],
        attr = keys[k],
        convert = false
    objs.map(function (el) {
      if (el.hasOwnProperty(attr)) {
        if (el[attr] instanceof Array) {
          keyResult = keyResult.concat(el[attr])
          return convert = true
        }
        keyResult.push(el[attr])
      }
    })
    if (keyResult.length == 1 && !convert) keyResult = keyResult[0]
    result[attr] = keyResult
  }
  return result
}
<commit_msg>dont need a second function, keeping this one level<commit_after>module.exports = merge

function merge() {
  var objs = [].slice.call(arguments),
      l = objs.length
  if (!l) return {}
  if (l == 1) return objs[0]
  var result = {},
      keys = []
  for (var i = 0; i < l; ++i) {
    keys = keys.concat(Object.keys(objs[i]))
  }
  keys = keys.filter(function (k, idx, arr) { return arr.lastIndexOf(k) === idx })
  for (var k = 0, f = keys.length; k < f; ++k) {
    var keyResult = [],
        attr = keys[k],
        convert = false
    objs.map(function (el) {
      if (el.hasOwnProperty(attr)) {
        if (el[attr] instanceof Array) {
          keyResult = keyResult.concat(el[attr])
          return convert = true
        }
        keyResult.push(el[attr])
      }
    })
    if (keyResult.length == 1 && !convert) keyResult = keyResult[0]
    result[attr] = keyResult
  }
  return result
}
<|endoftext|>