<commit_before>var util = require('util');
var debug = require('debug')('pigato:Broker');
var uuid = require('shortid');
var events = require('events');
var zmq = require('zmq');
var async = require('async');
var MDP = require('./mdp');

var HEARTBEAT_LIVENESS = 3;

var noop = function() {};

function Broker(endpoint, conf) {
  this.endpoint = endpoint;

  this.services = {};
  this.workers = {};

  this.conf = {
    heartbeat: 2500
  };

  var self = this;

  Object.keys(conf || {}).every(function(k) {
    self.conf[k] = conf[k];
  });

  this.ctrl = new Controller();

  events.EventEmitter.call(this);
}
util.inherits(Broker, events.EventEmitter);

Broker.prototype.start = function(cb) {
  this.name = 'B' + uuid.generate();
  this.socket = zmq.socket('router');
  this.socket.identity = new Buffer(this.name);

  var self = this;

  this.socket.on('message', function() {
    self.onMsg.call(self, arguments);
  });

  try {
    this.socket.bindSync(this.endpoint);
  } catch(e) {
    cb(e);
    return;
  }

  debug('B: broker started on %s', this.endpoint);

  this.hbTimer = setInterval(function() {
    self.workersCheck();
  }, this.conf.heartbeat);

  cb();
};

Broker.prototype.stop = function() {
  clearInterval(this.hbTimer);
  if (this.socket) {
    this.socket.close();
    delete this['socket'];
  }
};

Broker.prototype.send = function(msg) {
  this.socket.send(msg);
};

Broker.prototype.onMsg = function(msg) {
  var self = this;
  var header = msg[1].toString();

  if (header == MDP.CLIENT) {
    setImmediate(function() {
      self.onClient(msg);
    });
  } else if (header == MDP.WORKER) {
    setImmediate(function() {
      self.onWorker(msg);
    });
  } else {
    debug('(onMsg) Invalid message header \'' + header + '\'');
  }
};

Broker.prototype.emitErr = function(msg) {
  var self = this;

  setImmediate(function() {
    self.emit.apply(self, ['error', msg]);
  });
};

Broker.prototype.onClient = function(msg) {
  var self = this;
  var clientId = msg[0].toString();
  var type = msg[2];

  if (type == MDP.W_REQUEST) {
    var srvName = msg[3].toString();
    //debug("B: REQUEST from clientId: %s, service: %s", clientId, srvName);
    this.requestQueue(srvName, msg);
  } else if (type == MDP.W_HEARTBEAT) {
    if (msg.length === 4) {
      var rid = msg[3].toString();
      this.ctrl.rget(rid, function(err, req) {
        if (req && req.workerId) {
          self.send([req.workerId, MDP.WORKER, MDP.W_HEARTBEAT, clientId, '', rid]);
        }
      });
    }
  }
};

Broker.prototype.onWorker = function(msg) {
  var self = this;
  var workerId = msg[0].toString();
  var type = msg[2];

  var workerReady = (workerId in this.workers);
  var worker = this.workerRequire(workerId)

  if (type == MDP.W_READY) {
    var srvName = msg[3].toString();

    debug('B: register worker: %s, service: %s', workerId, srvName, workerReady ? 'R' : '');

    if (workerReady) {
      this.workerDelete(workerId, true);

    } else {
      this.serviceRequire(srvName);
      worker.service = srvName;
      this.serviceWorkerWait(srvName, workerId, true);
    }

    return;
  }

  if (!workerReady) {
    this.workerDelete(workerId, true);
    return;
  }

  worker.liveness = HEARTBEAT_LIVENESS;

  if (type == MDP.W_REPLY || type == MDP.W_REPLY_PARTIAL || type == MDP.W_REPLY_REJECT) {
    var clientId = msg[3].toString();
    var rid = msg[5].toString();

    if (rid !== worker.rid) {
      debug("B: FATAL from worker '%s' (%s), rid mismatch '%s'!='%s'", workerId, worker.service, worker.rid, rid);
      this.workerDelete(workerId, true);
      return;
    }

    self.ctrl.rget(rid, function (err, req) {
      if (!req) {
        debug("B: FATAL from worker '%s' (%s), req not found", workerId, worker.service, rid);
        self.workerDelete(workerId, true);
        return;
      }

      if (type == MDP.W_REPLY_REJECT) {
        debug("B: REJECT from worker '%s' (%s) for req '%s'", workerId, worker.service, rid);

        req.rejects.push(workerId);
        delete req.workerId;

        self.ctrl.rset(rid, req, function() {
          self.ctrl.runshift(worker.service, rid, function() {
            delete worker.rid;
            self.serviceWorkerWait(worker.service, workerId, true);
          });
        });
      } else if (type == MDP.W_REPLY || type == MDP.W_REPLY_PARTIAL) {
        debug("B: REPLY from worker '%s' (%s)", workerId, worker.service);

        var obj = [clientId, MDP.CLIENT, type];
        for (var i = 4; i < msg.length; i++) {
          obj.push(msg[i]);
        }

        self.send(obj);

        if (type == MDP.W_REPLY) {
          delete worker.rid;
          self.serviceWorkerWait(worker.service, workerId, true);
          self.ctrl.rdel(rid);
        }
      }
    });
  } else {
    if (type == MDP.W_DISCONNECT) {
      this.workerDelete(workerId);
    }
  }
};

Broker.prototype.requestQueue = function(srvName, msg) {
  var self = this;
  var clientId = msg[0].toString();
  var rid = msg[4].toString();
  var opts = msg[6] ? msg[6].toString() : null;

  try {
    opts = JSON.parse(opts) || {};
  } catch(e) {
    opts = null;
  }

  if (typeof opts !== 'object') {
    opts = {};
  }

  var req = {
    service: srvName,
    clientId: clientId,
    rid: rid,
    timeout: opts.timeout || 60000,
    ts: (new Date()).getTime(),
    rejects: [],
    msg: msg,
    opts: opts
  };

  async.series([
    function(next) {
    self.ctrl.rset(rid, req, next);
  },
  function(next) {
    self.ctrl.rpush(srvName, rid, next);
  },
  function(next) {
    self.dispatch(srvName, next);
  }
  ]);
};

Broker.prototype.requestValidate = function(req) {
  if (!req) {
    return false;
  }

  if (req.timeout > -1 && ((new Date()).getTime() > req.ts + req.timeout)) {
    return false;
  }

  return true;
};

Broker.prototype.workerRequire = function(workerId) {
  if (workerId in this.workers) {
    return this.workers[workerId];
  }

  var worker = {
    workerId: workerId,
    liveness: HEARTBEAT_LIVENESS
  };

  this.workers[workerId] = worker;
  return worker;
};

Broker.prototype.workerDelete = function(workerId, disconnect) {
  var worker = this.workers[workerId];

  if (!worker) {
    return;
  }

  debug('workerDelete \'%s\'%s (%s)', workerId, disconnect);

  if (disconnect) {
    this.send([workerId, MDP.WORKER, MDP.W_DISCONNECT]);
  }

  if (worker.service) {
    var service = this.serviceRequire(worker.service);
    for (var i = 0; i < service.waiting.length; i++) {
      if (workerId !== service.waiting[i]) {
        continue;
      }

      service.waiting.splice(i, 1);
      break;
    }
  }

  delete this.workers[workerId];
};

Broker.prototype.workersCheck = function() {
  var self = this;

  Object.keys(this.workers).every(function(workerId) {
    var worker = self.workers[workerId];
    worker.liveness--;

    if (worker.liveness < 0) {
      debug('B: workerPurge \'%s\'', workerId);
      self.workerDelete(workerId, true);
      return true;
    }

    self.send([workerId, MDP.WORKER, MDP.W_HEARTBEAT]);

    return true;
  });
};

Broker.prototype.serviceRequire = function(srvName) {
  if (srvName in this.services) {
    return this.services[srvName];
  }

  var service = {
    name: srvName,
    waiting: []
  };

  this.services[srvName] = service;
  return service;
};

Broker.prototype.serviceWorkerWait = function(srvName, workerId, dispatch) {
  var self = this;
  var service = this.serviceRequire(srvName);
  var worker = this.workers[workerId];

  if (!worker || !worker.service || service.waiting.indexOf(workerId) > -1) {
    this.workerDelete(workerId, true);
    return;
  }

  service.waiting.push(workerId);

  if (dispatch) {
    setImmediate(function() {
      self.dispatch(srvName);
    });
  }
};

Broker.prototype.serviceWorkerUnwait = function(srvName) {
  var service = this.serviceRequire(srvName);
  if (service.waiting.length) {
    return service.waiting.shift();
  }
  return null;
};

Broker.prototype.dispatch = function(srvName) {
  var self = this;
  var service = this.serviceRequire(srvName);
  var rcnt = 0;

  var handle = function(workerId, worker, next) {
    self.ctrl.rpop(srvName, function(err, req) {
      if (!self.requestValidate(req)) {
        if (req) {
          self.ctrl.rdel(req.rid);
          rcnt++;
        }
        self.serviceWorkerWait(srvName, workerId);
        next();
        return;
      }

      if (req.rejects.indexOf(workerId) !== -1) {
        self.ctrl.runshift(srvName, req.rid, next);
        return;
      }

      req.workerId = workerId;
      worker.rid = req.rid;

      self.ctrl.rset(req.rid, req);

      var obj = [
        workerId, MDP.WORKER, MDP.W_REQUEST, req.clientId, ''
      ];

      for (var i = 4; i < req.msg.length; i++) {
        obj.push(req.msg[i]);
      }

      self.send(obj);
      rcnt++;
      next();
    });
  };

  var swcnt = service.waiting.length;
  var queue = [];

  for (var service_index = 0; service_index < swcnt; service_index++) {
    queue.push(function(next) {
      var workerId = self.serviceWorkerUnwait(srvName);
      if (!workerId) {
        next();
        return;
      }

      var worker = self.workers[workerId];
      if (!worker) {
        next();
        return;
      }

      handle(workerId, worker, next);
    });
  }

  async.series(queue, function() {
    if (rcnt) {
      setImmediate(function() {
        self.dispatch(srvName);
      });
    }
  });
};

function Controller() {
  this.reqs = {};
  this.srq = {};
};

Controller.prototype.rset = function(rid, req, callback) {
  this.reqs[rid] = req;

  if (callback) {
    callback();
  }
};

Controller.prototype.rpush = function(srv, rid, callback) {
  if (!this.srq[srv]) {
    this.srq[srv] = [];
  }

  var srq = this.srq[srv];
  srq.push(rid);

  if (callback) {
    callback();
  }
};

// adds a request to the front of a queue
// used for retry logic
Controller.prototype.runshift = function(srv, rid, callback) {
  if (!this.srq[srv]) {
    this.srq[srv] = [];
  }

  var srq = this.srq[srv];
  srq.unshift(rid);

  if (callback) {
    callback();
  }
};

Controller.prototype.rget = function(rid, callback) {
  var self = this;

  if (callback) {
    setImmediate(function() {
      callback(null, self.reqs[rid]);
    });
  }
};

Controller.prototype.rpop = function(srv, callback) {
  var srq = this.srq[srv];

  if (!srq) {
    callback();
    return;
  }

  this.rget(srq.shift(), callback);
};

Controller.prototype.rdel = function(rid) {
  delete this.reqs[rid];
};

module.exports = Broker;
<commit_msg>Basic Cache class<commit_after>var util = require('util');
var debug = require('debug')('pigato:Broker');
var uuid = require('shortid');
var events = require('events');
var zmq = require('zmq');
var async = require('async');
var MDP = require('./mdp');

var HEARTBEAT_LIVENESS = 3;

var noop = function() {};

function Broker(endpoint, conf) {
  this.endpoint = endpoint;

  this.services = {};
  this.workers = {};

  this.conf = {
    heartbeat: 2500
  };

  var self = this;

  Object.keys(conf || {}).every(function(k) {
    self.conf[k] = conf[k];
  });

  this.ctrl = new Controller();

  events.EventEmitter.call(this);
}
util.inherits(Broker, events.EventEmitter);

Broker.prototype.start = function(cb) {
  this.name = 'B' + uuid.generate();
  this.socket = zmq.socket('router');
  this.socket.identity = new Buffer(this.name);

  var self = this;

  this.socket.on('message', function() {
    self.onMsg.call(self, arguments);
  });

  try {
    this.socket.bindSync(this.endpoint);
  } catch(e) {
    cb(e);
    return;
  }

  debug('B: broker started on %s', this.endpoint);

  this.hbTimer = setInterval(function() {
    self.workersCheck();
  }, this.conf.heartbeat);

  cb();
};

Broker.prototype.stop = function() {
  clearInterval(this.hbTimer);
  if (this.socket) {
    this.socket.close();
    delete this['socket'];
  }
};

Broker.prototype.send = function(msg) {
  this.socket.send(msg);
};

Broker.prototype.onMsg = function(msg) {
  var self = this;
  var header = msg[1].toString();

  if (header == MDP.CLIENT) {
    setImmediate(function() {
      self.onClient(msg);
    });
  } else if (header == MDP.WORKER) {
    setImmediate(function() {
      self.onWorker(msg);
    });
  } else {
    debug('(onMsg) Invalid message header \'' + header + '\'');
  }
};

Broker.prototype.emitErr = function(msg) {
  var self = this;

  setImmediate(function() {
    self.emit.apply(self, ['error', msg]);
  });
};

Broker.prototype.onClient = function(msg) {
  var self = this;
  var clientId = msg[0].toString();
  var type = msg[2];

  if (type == MDP.W_REQUEST) {
    var srvName = msg[3].toString();
    //debug("B: REQUEST from clientId: %s, service: %s", clientId, srvName);
    this.requestQueue(srvName, msg);
  } else if (type == MDP.W_HEARTBEAT) {
    if (msg.length === 4) {
      var rid = msg[3].toString();
      this.ctrl.rget(rid, function(err, req) {
        if (req && req.workerId) {
          self.send([req.workerId, MDP.WORKER, MDP.W_HEARTBEAT, clientId, '', rid]);
        }
      });
    }
  }
};

Broker.prototype.onWorker = function(msg) {
  var self = this;
  var workerId = msg[0].toString();
  var type = msg[2];

  var workerReady = (workerId in this.workers);
  var worker = this.workerRequire(workerId)

  if (type == MDP.W_READY) {
    var srvName = msg[3].toString();

    debug('B: register worker: %s, service: %s', workerId, srvName, workerReady ? 'R' : '');

    if (workerReady) {
      this.workerDelete(workerId, true);

    } else {
      this.serviceRequire(srvName);
      worker.service = srvName;
      this.serviceWorkerWait(srvName, workerId, true);
    }

    return;
  }

  if (!workerReady) {
    this.workerDelete(workerId, true);
    return;
  }

  worker.liveness = HEARTBEAT_LIVENESS;

  if (type == MDP.W_REPLY || type == MDP.W_REPLY_PARTIAL || type == MDP.W_REPLY_REJECT) {
    var clientId = msg[3].toString();
    var rid = msg[5].toString();

    if (rid !== worker.rid) {
      debug("B: FATAL from worker '%s' (%s), rid mismatch '%s'!='%s'", workerId, worker.service, worker.rid, rid);
      this.workerDelete(workerId, true);
      return;
    }

    self.ctrl.rget(rid, function (err, req) {
      if (!req) {
        debug("B: FATAL from worker '%s' (%s), req not found", workerId, worker.service, rid);
        self.workerDelete(workerId, true);
        return;
      }

      if (type == MDP.W_REPLY_REJECT) {
        debug("B: REJECT from worker '%s' (%s) for req '%s'", workerId, worker.service, rid);

        req.rejects.push(workerId);
        delete req.workerId;

        self.ctrl.rset(rid, req, function() {
          self.ctrl.runshift(worker.service, rid, function() {
            delete worker.rid;
            self.serviceWorkerWait(worker.service, workerId, true);
          });
        });
      } else if (type == MDP.W_REPLY || type == MDP.W_REPLY_PARTIAL) {
        debug("B: REPLY from worker '%s' (%s)", workerId, worker.service);

        var obj = [clientId, MDP.CLIENT, type];
        for (var i = 4; i < msg.length; i++) {
          obj.push(msg[i]);
        }

        self.send(obj);

        if (type == MDP.W_REPLY) {
          delete worker.rid;
          self.serviceWorkerWait(worker.service, workerId, true);
          self.ctrl.rdel(rid);
        }
      }
    });
  } else {
    if (type == MDP.W_DISCONNECT) {
      this.workerDelete(workerId);
    }
  }
};

Broker.prototype.requestQueue = function(srvName, msg) {
  var self = this;
  var clientId = msg[0].toString();
  var rid = msg[4].toString();
  var opts = msg[6] ? msg[6].toString() : null;

  try {
    opts = JSON.parse(opts) || {};
  } catch(e) {
    opts = null;
  }

  if (typeof opts !== 'object') {
    opts = {};
  }

  var req = {
    service: srvName,
    clientId: clientId,
    rid: rid,
    timeout: opts.timeout || 60000,
    ts: (new Date()).getTime(),
    rejects: [],
    msg: msg,
    opts: opts
  };

  async.series([
    function(next) {
    self.ctrl.rset(rid, req, next);
  },
  function(next) {
    self.ctrl.rpush(srvName, rid, next);
  },
  function(next) {
    self.dispatch(srvName, next);
  }
  ]);
};

Broker.prototype.requestValidate = function(req) {
  if (!req) {
    return false;
  }

  if (req.timeout > -1 && ((new Date()).getTime() > req.ts + req.timeout)) {
    return false;
  }

  return true;
};

Broker.prototype.workerRequire = function(workerId) {
  if (workerId in this.workers) {
    return this.workers[workerId];
  }

  var worker = {
    workerId: workerId,
    liveness: HEARTBEAT_LIVENESS
  };

  this.workers[workerId] = worker;
  return worker;
};

Broker.prototype.workerDelete = function(workerId, disconnect) {
  var worker = this.workers[workerId];

  if (!worker) {
    return;
  }

  debug('workerDelete \'%s\'%s (%s)', workerId, disconnect);

  if (disconnect) {
    this.send([workerId, MDP.WORKER, MDP.W_DISCONNECT]);
  }

  if (worker.service) {
    var service = this.serviceRequire(worker.service);
    for (var i = 0; i < service.waiting.length; i++) {
      if (workerId !== service.waiting[i]) {
        continue;
      }

      service.waiting.splice(i, 1);
      break;
    }
  }

  delete this.workers[workerId];
};

Broker.prototype.workersCheck = function() {
  var self = this;

  Object.keys(this.workers).every(function(workerId) {
    var worker = self.workers[workerId];
    worker.liveness--;

    if (worker.liveness < 0) {
      debug('B: workerPurge \'%s\'', workerId);
      self.workerDelete(workerId, true);
      return true;
    }

    self.send([workerId, MDP.WORKER, MDP.W_HEARTBEAT]);

    return true;
  });
};

Broker.prototype.serviceRequire = function(srvName) {
  if (srvName in this.services) {
    return this.services[srvName];
  }

  var service = {
    name: srvName,
    waiting: []
  };

  this.services[srvName] = service;
  return service;
};

Broker.prototype.serviceWorkerWait = function(srvName, workerId, dispatch) {
  var self = this;
  var service = this.serviceRequire(srvName);
  var worker = this.workers[workerId];

  if (!worker || !worker.service || service.waiting.indexOf(workerId) > -1) {
    this.workerDelete(workerId, true);
    return;
  }

  service.waiting.push(workerId);

  if (dispatch) {
    setImmediate(function() {
      self.dispatch(srvName);
    });
  }
};

Broker.prototype.serviceWorkerUnwait = function(srvName) {
  var service = this.serviceRequire(srvName);
  if (service.waiting.length) {
    return service.waiting.shift();
  }
  return null;
};

Broker.prototype.dispatch = function(srvName) {
  var self = this;
  var service = this.serviceRequire(srvName);
  var rcnt = 0;

  var handle = function(workerId, worker, next) {
    self.ctrl.rpop(srvName, function(err, req) {
      if (!self.requestValidate(req)) {
        if (req) {
          self.ctrl.rdel(req.rid);
          rcnt++;
        }
        self.serviceWorkerWait(srvName, workerId);
        next();
        return;
      }

      if (req.rejects.indexOf(workerId) !== -1) {
        self.ctrl.runshift(srvName, req.rid, next);
        return;
      }

      req.workerId = workerId;
      worker.rid = req.rid;

      self.ctrl.rset(req.rid, req);

      var obj = [
        workerId, MDP.WORKER, MDP.W_REQUEST, req.clientId, ''
      ];

      for (var i = 4; i < req.msg.length; i++) {
        obj.push(req.msg[i]);
      }

      self.send(obj);
      rcnt++;
      next();
    });
  };

  var swcnt = service.waiting.length;
  var queue = [];

  for (var service_index = 0; service_index < swcnt; service_index++) {
    queue.push(function(next) {
      var workerId = self.serviceWorkerUnwait(srvName);
      if (!workerId) {
        next();
        return;
      }

      var worker = self.workers[workerId];
      if (!worker) {
        next();
        return;
      }

      handle(workerId, worker, next);
    });
  }

  async.series(queue, function() {
    if (rcnt) {
      setImmediate(function() {
        self.dispatch(srvName);
      });
    }
  });
};

function Controller() {
  this.reqs = {};
  this.srq = {};
};

Controller.prototype.rset = function(rid, req, callback) {
  this.reqs[rid] = req;

  if (callback) {
    callback();
  }
};

Controller.prototype.rpush = function(srv, rid, callback) {
  if (!this.srq[srv]) {
    this.srq[srv] = [];
  }

  var srq = this.srq[srv];
  srq.push(rid);

  if (callback) {
    callback();
  }
};

// adds a request to the front of a queue
// used for retry logic
Controller.prototype.runshift = function(srv, rid, callback) {
  if (!this.srq[srv]) {
    this.srq[srv] = [];
  }

  var srq = this.srq[srv];
  srq.unshift(rid);

  if (callback) {
    callback();
  }
};

Controller.prototype.rget = function(rid, callback) {
  var self = this;

  if (callback) {
    setImmediate(function() {
      callback(null, self.reqs[rid]);
    });
  }
};

Controller.prototype.rpop = function(srv, callback) {
  var srq = this.srq[srv];

  if (!srq) {
    callback();
    return;
  }

  this.rget(srq.shift(), callback);
};

Controller.prototype.rdel = function(rid) {
  delete this.reqs[rid];
};

function Cache() {
  this.m = {};

  var self = this;

  setInterval(function() {
    self.prune();
  }, 10000);
};

Cache.prototype.prune = function() {
  var self = this;

  Object.keys(this.m).every(function(hash) {
    var entry = self.m[hash];
    if (entry.expire > -1) {
      if (entry.expire < (new Date()).getTime()) {
        delete self.m[hash];
      }
    }

    return true;
  });
};

Cache.prototype.get = function(hash, callback) {
  var self = this;

  setImmediate(function() {
    var entry = self.m[hash];
    callback(null, entry ? entry.data : null);
  });
};

Cache.prototype.set = function(hash, data, opts, callback) {
  this.m[hash] = {
    data: data,
    expire: opts.expire ? (new Date()).getTime() + opts.expire : -1
  };

  if (callback) {
    callback();
  }
};

module.exports = Broker;
<|endoftext|>


<commit_before>function exposeRegistryMethodsWithoutDeprecations(container) {
  var methods = [
    'register',
    'unregister',
    'resolve',
    'normalize',
    'typeInjection',
    'injection',
    'factoryInjection',
    'factoryTypeInjection',
    'has',
    'options',
    'optionsForType'
  ];

  function exposeRegistryMethod(container, method) {
    container[method] = function() {
      return container._registry[method].apply(container._registry, arguments);
    };
  }

  for (var i = 0, l = methods.length; i < l; i++) {
    exposeRegistryMethod(container, methods[i]);
  }
}

export default function(resolver) {
  var registry, container;
  var namespace = Ember.Object.create({
    Resolver: { create: function() { return resolver; } }
  });

  function register(name, factory) {
    var thingToRegisterWith = registry || container;

    if (!container.lookupFactory(name)) {
      thingToRegisterWith.register(name, factory);
    }
  }

  if (Ember.Application.buildRegistry) {
    registry = Ember.Application.buildRegistry(namespace);
    registry.register('component-lookup:main', Ember.ComponentLookup);

    registry = registry;
    container = registry.container();
    exposeRegistryMethodsWithoutDeprecations(container);
  } else {
    container = Ember.Application.buildContainer(namespace);
    container.register('component-lookup:main', Ember.ComponentLookup);
  }

  // Ember 1.10.0 did not properly add `view:toplevel` or `view:default`
  // to the registry in Ember.Application.buildRegistry :(
  //
  // Ember 2.0.0 removed Ember.View as public API, so only do this when
  // Ember.View is present
  if (Ember.View) {
    register('view:toplevel', Ember.View.extend());
  }

  // Ember 2.0.0 removed Ember._MetamorphView from the Ember global, so only
  // do this when present
  if (Ember._MetamorphView) {
    register('view:default', Ember._MetamorphView);
  }

  var globalContext = typeof global === 'object' && global || self;
  if (globalContext.DS) {
    var DS = globalContext.DS;
    if (DS._setupContainer) {
      DS._setupContainer(registry || container);
    } else {
      register('transform:boolean', DS.BooleanTransform);
      register('transform:date', DS.DateTransform);
      register('transform:number', DS.NumberTransform);
      register('transform:string', DS.StringTransform);
      register('serializer:-default', DS.JSONSerializer);
      register('serializer:-rest', DS.RESTSerializer);
      register('adapter:-rest', DS.RESTAdapter);
    }
  }

  return {
    registry: registry,
    container: container
  };
}
<commit_msg>Only override container methods if present.<commit_after>function exposeRegistryMethodsWithoutDeprecations(container) {
  var methods = [
    'register',
    'unregister',
    'resolve',
    'normalize',
    'typeInjection',
    'injection',
    'factoryInjection',
    'factoryTypeInjection',
    'has',
    'options',
    'optionsForType'
  ];

  function exposeRegistryMethod(container, method) {
    if (method in container) {
      container[method] = function() {
        return container._registry[method].apply(container._registry, arguments);
      };
    }
  }

  for (var i = 0, l = methods.length; i < l; i++) {
    exposeRegistryMethod(container, methods[i]);
  }
}

export default function(resolver) {
  var registry, container;
  var namespace = Ember.Object.create({
    Resolver: { create: function() { return resolver; } }
  });

  function register(name, factory) {
    var thingToRegisterWith = registry || container;

    if (!container.lookupFactory(name)) {
      thingToRegisterWith.register(name, factory);
    }
  }

  if (Ember.Application.buildRegistry) {
    registry = Ember.Application.buildRegistry(namespace);
    registry.register('component-lookup:main', Ember.ComponentLookup);

    registry = registry;
    container = registry.container();
    exposeRegistryMethodsWithoutDeprecations(container);
  } else {
    container = Ember.Application.buildContainer(namespace);
    container.register('component-lookup:main', Ember.ComponentLookup);
  }

  // Ember 1.10.0 did not properly add `view:toplevel` or `view:default`
  // to the registry in Ember.Application.buildRegistry :(
  //
  // Ember 2.0.0 removed Ember.View as public API, so only do this when
  // Ember.View is present
  if (Ember.View) {
    register('view:toplevel', Ember.View.extend());
  }

  // Ember 2.0.0 removed Ember._MetamorphView from the Ember global, so only
  // do this when present
  if (Ember._MetamorphView) {
    register('view:default', Ember._MetamorphView);
  }

  var globalContext = typeof global === 'object' && global || self;
  if (globalContext.DS) {
    var DS = globalContext.DS;
    if (DS._setupContainer) {
      DS._setupContainer(registry || container);
    } else {
      register('transform:boolean', DS.BooleanTransform);
      register('transform:date', DS.DateTransform);
      register('transform:number', DS.NumberTransform);
      register('transform:string', DS.StringTransform);
      register('serializer:-default', DS.JSONSerializer);
      register('serializer:-rest', DS.RESTSerializer);
      register('adapter:-rest', DS.RESTAdapter);
    }
  }

  return {
    registry: registry,
    container: container
  };
}
<|endoftext|>


<commit_before>import React from 'react';
import {shallow} from 'enzyme';
import {QueryRenderer} from 'react-relay';

import ReviewsContainer from '../../lib/containers/reviews-container';
import Repository from '../../lib/models/repository';
import {InMemoryStrategy, UNAUTHENTICATED, INSUFFICIENT} from '../../lib/shared/keytar-strategy';
import GithubLoginModel from '../../lib/models/github-login-model';
import {getEndpoint} from '../../lib/models/endpoint';
import {multiFilePatchBuilder} from '../builder/patch';
import {cloneRepository} from '../helpers';

describe('ReviewsContainer', function() {
  let atomEnv, repository, loginModel, repoData, queryData;

  beforeEach(async function() {
    atomEnv = global.buildAtomEnvironment();
    const workdir = await cloneRepository();
    repository = new Repository(workdir);
    await repository.getLoadPromise();
    loginModel = new GithubLoginModel(InMemoryStrategy);
    sinon.stub(loginModel, 'getScopes').resolves(GithubLoginModel.REQUIRED_SCOPES);

    repoData = {
      branches: await repository.getBranches(),
      remotes: await repository.getRemotes(),
      isAbsent: repository.isAbsent(),
      isLoading: repository.isLoading(),
      isPresent: repository.isPresent(),
      isMerging: await repository.isMerging(),
      isRebasing: await repository.isRebasing(),
    };

    queryData = {
      repository: {
        pullRequest: {},
      },
    };
  });

  afterEach(function() {
    atomEnv.destroy();
  });

  function buildApp(override = {}) {
    const props = {
      endpoint: getEndpoint('github.com'),

      owner: 'atom',
      repo: 'github',
      number: 1234,
      workdir: repository.getWorkingDirectoryPath(),

      repository,
      loginModel,

      workspace: atomEnv.workspace,
      config: atomEnv.config,
      commands: atomEnv.commands,

      ...override,
    };

    return <ReviewsContainer {...props} />;
  }

  it('renders a loading spinner while the token is loading', function() {
    const wrapper = shallow(buildApp());
    const tokenWrapper = wrapper.find('ObserveModel').renderProp('children')(null);
    assert.isTrue(tokenWrapper.exists('LoadingView'));
  });

  it('shows a login form if no token is available', function() {
    const wrapper = shallow(buildApp());
    const tokenWrapper = wrapper.find('ObserveModel').renderProp('children')(UNAUTHENTICATED);
    assert.isTrue(tokenWrapper.exists('GithubLoginView'));
  });

  it('shows a login form if the token is outdated', function() {
    const wrapper = shallow(buildApp());
    const tokenWrapper = wrapper.find('ObserveModel').renderProp('children')(INSUFFICIENT);

    assert.isTrue(tokenWrapper.exists('GithubLoginView'));
    assert.match(tokenWrapper.find('GithubLoginView > p').text(), /re-authenticate/);
  });

  it('gets the token from the login model', async function() {
    await loginModel.setToken('https://github.enterprise.horse', 'neigh');

    const wrapper = shallow(buildApp({
      loginModel,
      endpoint: getEndpoint('github.enterprise.horse'),
    }));

    assert.strictEqual(wrapper.find('ObserveModel').prop('model'), loginModel);
    assert.strictEqual(await wrapper.find('ObserveModel').prop('fetchData')(loginModel), 'neigh');
  });

  it('shows a loading spinner if the patch is being fetched', function() {
    const wrapper = shallow(buildApp());
    const tokenWrapper = wrapper.find('ObserveModel').renderProp('children')('shhh');
    const patchWrapper = tokenWrapper.find('PullRequestPatchContainer').renderProp('children')(null, null);
    const repoWrapper = patchWrapper.find('ObserveModel').renderProp('children')(repoData);
    const resultWrapper = repoWrapper.find(QueryRenderer).renderProp('render')({error: null, props: queryData, retry: () => {}});

    assert.isTrue(resultWrapper.exists('LoadingView'));
  });

  it('shows a loading spinner if the repository data is being fetched', function() {
    const wrapper = shallow(buildApp());
    const tokenWrapper = wrapper.find('ObserveModel').renderProp('children')('shhh');
    const patchWrapper = tokenWrapper.find('PullRequestPatchContainer').renderProp('children')(null, {});
    const repoWrapper = patchWrapper.find('ObserveModel').renderProp('children')(null);
    const resultWrapper = repoWrapper.find(QueryRenderer).renderProp('render')({error: null, props: queryData, retry: () => {}});

    assert.isTrue(resultWrapper.exists('LoadingView'));
  });

  it('shows a loading spinner if the GraphQL query is still being performed', function() {
    const wrapper = shallow(buildApp());
    const tokenWrapper = wrapper.find('ObserveModel').renderProp('children')('shhh');
    const patchWrapper = tokenWrapper.find('PullRequestPatchContainer').renderProp('children')(null, {});
    const repoWrapper = patchWrapper.find('ObserveModel').renderProp('children')(repoData);
    const resultWrapper = repoWrapper.find(QueryRenderer).renderProp('render')({error: null, props: null, retry: () => {}});

    assert.isTrue(resultWrapper.exists('LoadingView'));
  });

  it('passes the patch to the controller', function() {
    const wrapper = shallow(buildApp({
      owner: 'secret',
      repo: 'squirrel',
      number: 123,
      endpoint: getEndpoint('github.enterprise.com'),
    }));

    const {multiFilePatch} = multiFilePatchBuilder().build();

    const tokenWrapper = wrapper.find('ObserveModel').renderProp('children')('shhh');

    assert.strictEqual(tokenWrapper.find('PullRequestPatchContainer').prop('owner'), 'secret');
    assert.strictEqual(tokenWrapper.find('PullRequestPatchContainer').prop('repo'), 'squirrel');
    assert.strictEqual(tokenWrapper.find('PullRequestPatchContainer').prop('number'), 123);
    assert.strictEqual(tokenWrapper.find('PullRequestPatchContainer').prop('endpoint').getHost(), 'github.enterprise.com');
    assert.strictEqual(tokenWrapper.find('PullRequestPatchContainer').prop('token'), 'shhh');
    const patchWrapper = tokenWrapper.find('PullRequestPatchContainer').renderProp('children')(null, multiFilePatch);

    const repoWrapper = patchWrapper.find('ObserveModel').renderProp('children')(repoData);
    const resultWrapper = repoWrapper.find(QueryRenderer).renderProp('render')({error: null, props: queryData, retry: () => {}});

    assert.strictEqual(resultWrapper.find('ReviewsController').prop('multiFilePatch'), multiFilePatch);
  });

  it('passes loaded repository data to the controller', async function() {
    const wrapper = shallow(buildApp());

    const extraRepoData = {...repoData, one: Symbol('one'), two: Symbol('two')};

    const tokenWrapper = wrapper.find('ObserveModel').renderProp('children')('shhh');
    const patchWrapper = tokenWrapper.find('PullRequestPatchContainer').renderProp('children')(null, {});

    assert.strictEqual(patchWrapper.find('ObserveModel').prop('model'), repository);
    assert.deepEqual(await patchWrapper.find('ObserveModel').prop('fetchData')(repository), repoData);
    const repoWrapper = patchWrapper.find('ObserveModel').renderProp('children')(extraRepoData);

    const resultWrapper = repoWrapper.find(QueryRenderer).renderProp('render')({error: null, props: queryData, retry: () => {}});

    assert.strictEqual(resultWrapper.find('ReviewsController').prop('one'), extraRepoData.one);
    assert.strictEqual(resultWrapper.find('ReviewsController').prop('two'), extraRepoData.two);
  });

  it('passes extra properties to the controller', function() {
    const extra = Symbol('extra');
    const wrapper = shallow(buildApp({extra}));

    const tokenWrapper = wrapper.find('ObserveModel').renderProp('children')('shhh');
    const patchWrapper = tokenWrapper.find('PullRequestPatchContainer').renderProp('children')(null, {});

    assert.strictEqual(patchWrapper.find('ObserveModel').prop('model'), repository);
    const repoWrapper = patchWrapper.find('ObserveModel').renderProp('children')(repoData);

    const resultWrapper = repoWrapper.find(QueryRenderer).renderProp('render')({error: null, props: queryData, retry: () => {}});

    assert.strictEqual(resultWrapper.find('ReviewsController').prop('extra'), extra);
  });

  it('shows an error if the patch cannot be fetched', function() {
    const wrapper = shallow(buildApp());

    const tokenWrapper = wrapper.find('ObserveModel').renderProp('children')('shhh');
    const patchWrapper = tokenWrapper.find('PullRequestPatchContainer').renderProp('children')('[errors intensify]', null);
    assert.deepEqual(patchWrapper.find('ErrorView').prop('descriptions'), ['[errors intensify]']);
  });

  it('shows an error if the GraphQL query fails', async function() {
    const wrapper = shallow(buildApp({
      endpoint: getEndpoint('github.enterprise.horse'),
    }));

    const err = new Error("just didn't feel like it");
    const retry = sinon.spy();

    const tokenWrapper = wrapper.find('ObserveModel').renderProp('children')('shhh');
    const patchWrapper = tokenWrapper.find('PullRequestPatchContainer').renderProp('children')(null, {});
    const repoWrapper = patchWrapper.find('ObserveModel').renderProp('children')(repoData);
    const resultWrapper = repoWrapper.find(QueryRenderer).renderProp('render')({error: err, props: null, retry});

    assert.strictEqual(resultWrapper.find('QueryErrorView').prop('error'), err);

    await resultWrapper.find('QueryErrorView').prop('login')('different');
    assert.strictEqual(await loginModel.getToken('https://github.enterprise.horse'), 'different');

    await resultWrapper.find('QueryErrorView').prop('logout')();
    assert.strictEqual(await loginModel.getToken('https://github.enterprise.horse'), UNAUTHENTICATED);

    resultWrapper.find('QueryErrorView').prop('retry')();
    assert.isTrue(retry.called);
  });
});
<commit_msg>ReviewsContainer tests :white_check_mark: + :100:<commit_after>import React from 'react';
import {shallow} from 'enzyme';
import {QueryRenderer} from 'react-relay';

import ReviewsContainer from '../../lib/containers/reviews-container';
import ReviewsController from '../../lib/controllers/reviews-controller';
import {InMemoryStrategy, UNAUTHENTICATED, INSUFFICIENT} from '../../lib/shared/keytar-strategy';
import GithubLoginModel from '../../lib/models/github-login-model';
import WorkdirContextPool from '../../lib/models/workdir-context-pool';
import {getEndpoint} from '../../lib/models/endpoint';
import {multiFilePatchBuilder} from '../builder/patch';
import {cloneRepository} from '../helpers';

describe('ReviewsContainer', function() {
  let atomEnv, workdirContextPool, repository, loginModel, repoData, queryData;

  beforeEach(async function() {
    atomEnv = global.buildAtomEnvironment();

    workdirContextPool = new WorkdirContextPool();

    const workdir = await cloneRepository();
    repository = workdirContextPool.add(workdir).getRepository();
    await repository.getLoadPromise();
    loginModel = new GithubLoginModel(InMemoryStrategy);
    sinon.stub(loginModel, 'getScopes').resolves(GithubLoginModel.REQUIRED_SCOPES);

    repoData = {
      branches: await repository.getBranches(),
      remotes: await repository.getRemotes(),
      isAbsent: repository.isAbsent(),
      isLoading: repository.isLoading(),
      isPresent: repository.isPresent(),
      isMerging: await repository.isMerging(),
      isRebasing: await repository.isRebasing(),
    };

    queryData = {
      repository: {
        pullRequest: {},
      },
    };
  });

  afterEach(function() {
    atomEnv.destroy();
  });

  function buildApp(override = {}) {
    const props = {
      endpoint: getEndpoint('github.com'),

      owner: 'atom',
      repo: 'github',
      number: 1234,
      workdir: repository.getWorkingDirectoryPath(),

      repository,
      loginModel,
      workdirContextPool,

      workspace: atomEnv.workspace,
      config: atomEnv.config,
      commands: atomEnv.commands,
      tooltips: atomEnv.tooltips,

      ...override,
    };

    return <ReviewsContainer {...props} />;
  }

  it('renders a loading spinner while the token is loading', function() {
    const wrapper = shallow(buildApp());
    const tokenWrapper = wrapper.find('ObserveModel').renderProp('children')(null);
    assert.isTrue(tokenWrapper.exists('LoadingView'));
  });

  it('shows a login form if no token is available', function() {
    const wrapper = shallow(buildApp());
    const tokenWrapper = wrapper.find('ObserveModel').renderProp('children')(UNAUTHENTICATED);
    assert.isTrue(tokenWrapper.exists('GithubLoginView'));
  });

  it('shows a login form if the token is outdated', function() {
    const wrapper = shallow(buildApp());
    const tokenWrapper = wrapper.find('ObserveModel').renderProp('children')(INSUFFICIENT);

    assert.isTrue(tokenWrapper.exists('GithubLoginView'));
    assert.match(tokenWrapper.find('GithubLoginView > p').text(), /re-authenticate/);
  });

  it('gets the token from the login model', async function() {
    await loginModel.setToken('https://github.enterprise.horse', 'neigh');

    const wrapper = shallow(buildApp({
      loginModel,
      endpoint: getEndpoint('github.enterprise.horse'),
    }));

    assert.strictEqual(wrapper.find('ObserveModel').prop('model'), loginModel);
    assert.strictEqual(await wrapper.find('ObserveModel').prop('fetchData')(loginModel), 'neigh');
  });

  it('shows a loading spinner if the patch is being fetched', function() {
    const wrapper = shallow(buildApp());
    const tokenWrapper = wrapper.find('ObserveModel').renderProp('children')('shhh');
    const patchWrapper = tokenWrapper.find('PullRequestPatchContainer').renderProp('children')(null, null);
    const repoWrapper = patchWrapper.find('ObserveModel').renderProp('children')(repoData);
    const resultWrapper = repoWrapper.find(QueryRenderer).renderProp('render')({error: null, props: queryData, retry: () => {}});

    assert.isTrue(resultWrapper.exists('LoadingView'));
  });

  it('shows a loading spinner if the repository data is being fetched', function() {
    const wrapper = shallow(buildApp());
    const tokenWrapper = wrapper.find('ObserveModel').renderProp('children')('shhh');
    const patchWrapper = tokenWrapper.find('PullRequestPatchContainer').renderProp('children')(null, {});
    const repoWrapper = patchWrapper.find('ObserveModel').renderProp('children')(null);
    const resultWrapper = repoWrapper.find(QueryRenderer).renderProp('render')({error: null, props: queryData, retry: () => {}});

    assert.isTrue(resultWrapper.exists('LoadingView'));
  });

  it('shows a loading spinner if the GraphQL query is still being performed', function() {
    const wrapper = shallow(buildApp());
    const tokenWrapper = wrapper.find('ObserveModel').renderProp('children')('shhh');
    const patchWrapper = tokenWrapper.find('PullRequestPatchContainer').renderProp('children')(null, {});
    const repoWrapper = patchWrapper.find('ObserveModel').renderProp('children')(repoData);
    const resultWrapper = repoWrapper.find(QueryRenderer).renderProp('render')({error: null, props: null, retry: () => {}});

    assert.isTrue(resultWrapper.exists('LoadingView'));
  });

  it('passes the patch to the controller', function() {
    const wrapper = shallow(buildApp({
      owner: 'secret',
      repo: 'squirrel',
      number: 123,
      endpoint: getEndpoint('github.enterprise.com'),
    }));

    const {multiFilePatch} = multiFilePatchBuilder().build();

    const tokenWrapper = wrapper.find('ObserveModel').renderProp('children')('shhh');

    assert.strictEqual(tokenWrapper.find('PullRequestPatchContainer').prop('owner'), 'secret');
    assert.strictEqual(tokenWrapper.find('PullRequestPatchContainer').prop('repo'), 'squirrel');
    assert.strictEqual(tokenWrapper.find('PullRequestPatchContainer').prop('number'), 123);
    assert.strictEqual(tokenWrapper.find('PullRequestPatchContainer').prop('endpoint').getHost(), 'github.enterprise.com');
    assert.strictEqual(tokenWrapper.find('PullRequestPatchContainer').prop('token'), 'shhh');
    const patchWrapper = tokenWrapper.find('PullRequestPatchContainer').renderProp('children')(null, multiFilePatch);

    const repoWrapper = patchWrapper.find('ObserveModel').renderProp('children')(repoData);
    const resultWrapper = repoWrapper.find(QueryRenderer).renderProp('render')({error: null, props: queryData, retry: () => {}});

    assert.strictEqual(resultWrapper.find(ReviewsController).prop('multiFilePatch'), multiFilePatch);
  });

  it('passes loaded repository data to the controller', async function() {
    const wrapper = shallow(buildApp());

    const extraRepoData = {...repoData, one: Symbol('one'), two: Symbol('two')};

    const tokenWrapper = wrapper.find('ObserveModel').renderProp('children')('shhh');
    const patchWrapper = tokenWrapper.find('PullRequestPatchContainer').renderProp('children')(null, {});

    assert.strictEqual(patchWrapper.find('ObserveModel').prop('model'), repository);
    assert.deepEqual(await patchWrapper.find('ObserveModel').prop('fetchData')(repository), repoData);
    const repoWrapper = patchWrapper.find('ObserveModel').renderProp('children')(extraRepoData);

    const resultWrapper = repoWrapper.find(QueryRenderer).renderProp('render')({error: null, props: queryData, retry: () => {}});

    assert.strictEqual(resultWrapper.find(ReviewsController).prop('one'), extraRepoData.one);
    assert.strictEqual(resultWrapper.find(ReviewsController).prop('two'), extraRepoData.two);
  });

  it('passes extra properties to the controller', function() {
    const extra = Symbol('extra');
    const wrapper = shallow(buildApp({extra}));

    const tokenWrapper = wrapper.find('ObserveModel').renderProp('children')('shhh');
    const patchWrapper = tokenWrapper.find('PullRequestPatchContainer').renderProp('children')(null, {});

    assert.strictEqual(patchWrapper.find('ObserveModel').prop('model'), repository);
    const repoWrapper = patchWrapper.find('ObserveModel').renderProp('children')(repoData);

    const resultWrapper = repoWrapper.find(QueryRenderer).renderProp('render')({error: null, props: queryData, retry: () => {}});

    assert.strictEqual(resultWrapper.find(ReviewsController).prop('extra'), extra);
  });

  it('shows an error if the patch cannot be fetched', function() {
    const wrapper = shallow(buildApp());

    const tokenWrapper = wrapper.find('ObserveModel').renderProp('children')('shhh');
    const patchWrapper = tokenWrapper.find('PullRequestPatchContainer').renderProp('children')('[errors intensify]', null);
    assert.deepEqual(patchWrapper.find('ErrorView').prop('descriptions'), ['[errors intensify]']);
  });

  it('shows an error if the GraphQL query fails', async function() {
    const wrapper = shallow(buildApp({
      endpoint: getEndpoint('github.enterprise.horse'),
    }));

    const err = new Error("just didn't feel like it");
    const retry = sinon.spy();

    const tokenWrapper = wrapper.find('ObserveModel').renderProp('children')('shhh');
    const patchWrapper = tokenWrapper.find('PullRequestPatchContainer').renderProp('children')(null, {});
    const repoWrapper = patchWrapper.find('ObserveModel').renderProp('children')(repoData);
    const resultWrapper = repoWrapper.find(QueryRenderer).renderProp('render')({error: err, props: null, retry});

    assert.strictEqual(resultWrapper.find('QueryErrorView').prop('error'), err);

    await resultWrapper.find('QueryErrorView').prop('login')('different');
    assert.strictEqual(await loginModel.getToken('https://github.enterprise.horse'), 'different');

    await resultWrapper.find('QueryErrorView').prop('logout')();
    assert.strictEqual(await loginModel.getToken('https://github.enterprise.horse'), UNAUTHENTICATED);

    resultWrapper.find('QueryErrorView').prop('retry')();
    assert.isTrue(retry.called);
  });
});
<|endoftext|>


<commit_before>'use strict'
const log = require('debug')
var debug = log('netcat:client')
const Netcat = require('./Netcat')
const util = require('./util')
const net = require('net')

function noop () {}

class Client extends Netcat {

  constructor (opts) {
    opts = opts || {}
    super(opts)

    this.debug = debug
    this._address = opts.address || '127.0.0.1'
    this._interval = opts.interval || false
    this._timeout = opts.timeout || null
  }

  timeout (ms) {
    debug('setting timeout', ms, 'ms')
    this._timeout = ms
  }

  interval (secs) {
    debug('setting interval to', secs, 'seconds')
    if (!Number.isInteger(secs)) throw Error('Please provide a valid number')
    this._interval = Math.round(secs)
    return this
  }

  i (s) { /* alias for interval */
    this.interval(s)
  }

  connect (cb) {
    debug('connect() called')
    var self = this
    cb = cb || noop

    function data (d) {
      debug('got data', d)
      self.emit('data', d)
    }

    function error (err) {
      debug('got error', err)
      self.emit('err', err)
    }

    function timeout () {
      debug('got timeout')
      self.client.destroy()
      self.emit('timeout')
    }

    function close () {
      debug('Connection closed')
      if (self._retry) {
        debug('Retrying connection in', (self._retry / 1000).toFixed(2), 'seconds')
        setTimeout(function () {
          self.client.connect({host: self._address, port: self._port})
        }, self._retry)
      }
      self.emit('close')
    }

    function connect () {
      debug('Connected to %s:%d', self._address, self._port)
      /* spawn exec */
      util.spawnProcess.call(self, self.client)

      self.client.pipe(self.passThrough, { end: false })
      cb.call(self)
    }

    // create TCP client
    this.client = net.connect({host: this._address, port: this._port})

    if (this._timeout) this.client.setTimeout(this._timeout)

    process.nextTick(function () {
      self.client.on('data', data)
      self.client.on('error', error)
      self.client.on('timeout', timeout)
      self.client.on('close', close)
      self.client.on('connect', connect)
    })

    return this
  }

  retry (ms) {
    if (!Number.isInteger(ms)) throw Error('Retry should be a positive integer!')
    this._retry = ms
    return this /* chainable method */
  }

  stream () {
    debug('Returning stream reference')
    return this.client /* return stream */
  }

  pipe (outStream) {
    debug('Piping data from socket to the given outStream')
    this.passThrough.pipe(outStream) /* incoming */
    return this
  }

  send (data, cb) {
    cb = cb || noop
    if (data && !Buffer.isBuffer(data)) {
      data = Buffer.from(data)
    }
    debug('Client sending data', data)
    var self = this
    if (!this.client) return this
    if (this._interval) { /* delay */
      setTimeout(function () {
        this.client.write(data, cb)
      }, self._interval * 1000)
    } else {
      this.client.write(data, cb)
    }
    return this
  }

  end (d) {
    if (this.client) this.client.end(d) /* send data + EOF */
    return this
  }

  close (cb) {
    debug('client: closing socket.')
    cb = cb || noop
    this.on('close', cb)
    return this.end()
  }

}

module.exports = Client

if (!module.parent) {
  // const fs = require('fs')
  const nc2 = new Client()
  nc2.port(2389).retry(5000).connect().exec('/bin/sh')
}
<commit_msg>HACK to keep the stream open when in retry mode<commit_after>'use strict'
const log = require('debug')
var debug = log('netcat:client')
const Netcat = require('./Netcat')
const util = require('./util')
const net = require('net')

function noop () {}

class Client extends Netcat {

  constructor (opts) {
    opts = opts || {}
    super(opts)

    this.debug = debug
    this._address = opts.address || '127.0.0.1'
    this._interval = opts.interval || false
    this._timeout = opts.timeout || null
  }

  timeout (ms) {
    debug('setting timeout', ms, 'ms')
    this._timeout = ms
  }

  interval (secs) {
    debug('setting interval to', secs, 'seconds')
    if (!Number.isInteger(secs)) throw Error('Please provide a valid number')
    this._interval = Math.round(secs)
    return this
  }

  i (s) { /* alias for interval */
    this.interval(s)
  }

  connect (cb) {
    debug('connect() called')
    var self = this
    cb = cb || noop

    function data (d) {
      debug('got data', d)
      self.emit('data', d)
    }

    function error (err) {
      debug('got error', err)
      self.emit('err', err)
    }

    function timeout () {
      debug('got timeout')
      self.client.destroy()
      self.emit('timeout')
    }

    function close () {
      debug('Connection closed')
      if (self._retry) {
        debug('Retrying connection in', (self._retry / 1000).toFixed(2), 'seconds')
        setTimeout(function () {
          self.client.connect({host: self._address, port: self._port})
        }, self._retry)
      }
      self.emit('close')
    }

    function connect () {
      debug('Connected to %s:%d', self._address, self._port)
      /* spawn exec */
      util.spawnProcess.call(self, self.client)

      self.client.pipe(self.passThrough, { end: !self._retry }) /* HACK: kept open when retrying */
      cb.call(self)
    }

    // create TCP client
    this.client = net.connect({host: this._address, port: this._port})

    if (this._timeout) this.client.setTimeout(this._timeout)

    process.nextTick(function () {
      self.client.on('data', data)
      self.client.on('error', error)
      self.client.on('timeout', timeout)
      self.client.on('close', close)
      self.client.on('connect', connect)
    })

    return this
  }

  retry (ms) {
    if (!Number.isInteger(ms)) throw Error('Retry should be a positive integer!')
    this._retry = ms
    return this /* chainable method */
  }

  stream () {
    debug('Returning stream reference')
    return this.client /* return stream */
  }

  pipe (outStream) {
    debug('Piping data from socket to the given outStream')
    this.passThrough.pipe(outStream) /* incoming */
    return this
  }

  send (data, cb) {
    cb = cb || noop
    if (data && !Buffer.isBuffer(data)) {
      data = Buffer.from(data)
    }
    debug('Client sending data', data)
    var self = this
    if (!this.client) return this
    if (this._interval) { /* delay */
      setTimeout(function () {
        this.client.write(data, cb)
      }, self._interval * 1000)
    } else {
      this.client.write(data, cb)
    }
    return this
  }

  end (d) {
    if (this.client) this.client.end(d) /* send data + EOF */
    return this
  }

  close (cb) {
    debug('client: closing socket.')
    cb = cb || noop
    this.on('close', cb)
    return this.end()
  }

}

module.exports = Client

if (!module.parent) {
  // const fs = require('fs')
  const nc2 = new Client()
  nc2.port(2389).retry(5000).connect().exec('/bin/sh')
}
<|endoftext|>


<commit_before>import React from 'react';
import Relay from 'react-relay';
import GroupCallInvitationCreationForm from './GroupCallInvitationCreationForm'
import {Nav, NavItem} from "react-bootstrap";

export class GroupCallInvitationList extends React.Component {

  state = {
    isCreating: false
  }

  handleCreateCall = (event) => {
    this.setState({isCreating: true})
  }

  renderGroupCallInvitations() {
    return this.props.viewer.groupCallInvitationList.edges.map(invitation =>
      <NavItem>
        {invitation.node.topic}
      </NavItem>
    );
  }

  render() {
    var callCreationComponent;
    if (!this.state.isCreating)
      callCreationComponent = <button onClick={this.handleCreateCall}>New Call</button>;
    else
      callCreationComponent = <GroupCallInvitationCreationForm viewer={this.props.viewer} />
    return (

            <NavItem>Test 1</NavItem>
            <NavItem>Test 2</NavItem>

          {callCreationComponent}

    );
  }
}

export const GroupCallInvitationListRelay = Relay.createContainer(GroupCallInvitationList, {
  fragments: {
    viewer: () => Relay.QL`
      fragment on Viewer {
        ${GroupCallInvitationCreationForm.getFragment('viewer')},
        groupCallInvitationList(first:10) {
          edges {
            node {
              id,
              topic,
              groupCallList(first:10) {
                edges {
                  node {
                    scheduledTime
                  }
                }
              }
            }
          }
        }
      }
    `,
  },
});

<commit_msg>Add list of calls<commit_after>import React from 'react';
import Relay from 'react-relay';
import GroupCallInvitationCreationForm from './GroupCallInvitationCreationForm'
import {Nav, NavItem} from "react-bootstrap";

export class GroupCallInvitationList extends React.Component {

  state = {
    isCreating: false
  }

  handleCreateCall = (event) => {
    this.setState({isCreating: true})
  }

  renderGroupCallInvitations() {
    return this.props.viewer.groupCallInvitationList.edges.map(invitation =>
      <NavItem>
        {invitation.node.topic}
      </NavItem>
    );
  }

  render() {
    var callCreationComponent;
    if (!this.state.isCreating)
      callCreationComponent = <button onClick={this.handleCreateCall}>New Call</button>;
    else
      callCreationComponent = <GroupCallInvitationCreationForm viewer={this.props.viewer} />
    return (

            {this.renderGroupCallInvitations()}

          {callCreationComponent}

    );
  }
}

export const GroupCallInvitationListRelay = Relay.createContainer(GroupCallInvitationList, {
  fragments: {
    viewer: () => Relay.QL`
      fragment on Viewer {
        ${GroupCallInvitationCreationForm.getFragment('viewer')},
        groupCallInvitationList(first:10) {
          edges {
            node {
              id,
              topic,
              groupCallList(first:10) {
                edges {
                  node {
                    scheduledTime
                  }
                }
              }
            }
          }
        }
      }
    `,
  },
});

<|endoftext|>


<commit_before>import $ from 'blingblingjs'

export const getSide = direction => {
  let start = direction.split('+').pop().replace(/^\w/, c => c.toUpperCase())
  if (start == 'Up') start = 'Top'
  if (start == 'Down') start = 'Bottom'
  return start
}

let timeoutMap = {}
export const showHideSelected = (el, duration = 750) => {
  el.setAttribute('data-selected-hide', true)
  showHideNodeLabel(el, true)

  if (timeoutMap[nodeKey(el)])
    clearTimeout(timeoutMap[nodeKey(el)])

  timeoutMap[nodeKey(el)] = setTimeout(_ => {
    el.removeAttribute('data-selected-hide')
    showHideNodeLabel(el, false)
  }, duration)

  return el
}

export const showHideNodeLabel = (el, show = false) => {
  if (!el.hasAttribute('data-label-id'))
    return

  const nodes = $(`
    pb-label[data-label-id="${el.getAttribute('data-label-id')}"],
    pb-handles[data-label-id="${el.getAttribute('data-label-id')}"]
  `)

  nodes.length && show
    ? nodes.forEach(el =>
      el.style.display = 'none')
    : nodes.forEach(el =>
      el.style.display = null)
}

export const htmlStringToDom = (htmlString = "") =>
  (new DOMParser().parseFromString(htmlString, 'text/html'))
    .body.firstChild

export const isOffBounds = node =>
  node.closest &&
  (node.closest('tool-pallete')
  || node.closest('hotkey-map')
  || node.closest('pb-metatip')
  || node.closest('pb-ally')
  || node.closest('pb-label')
  || node.closest('pb-handles')
  || node.closest('pb-gridlines')
  )<commit_msg>fixes miss dep after refactor<commit_after>import $ from 'blingblingjs'
import { nodeKey } from './strings'

export const getSide = direction => {
  let start = direction.split('+').pop().replace(/^\w/, c => c.toUpperCase())
  if (start == 'Up') start = 'Top'
  if (start == 'Down') start = 'Bottom'
  return start
}

let timeoutMap = {}
export const showHideSelected = (el, duration = 750) => {
  el.setAttribute('data-selected-hide', true)
  showHideNodeLabel(el, true)

  if (timeoutMap[nodeKey(el)])
    clearTimeout(timeoutMap[nodeKey(el)])

  timeoutMap[nodeKey(el)] = setTimeout(_ => {
    el.removeAttribute('data-selected-hide')
    showHideNodeLabel(el, false)
  }, duration)

  return el
}

export const showHideNodeLabel = (el, show = false) => {
  if (!el.hasAttribute('data-label-id'))
    return

  const nodes = $(`
    pb-label[data-label-id="${el.getAttribute('data-label-id')}"],
    pb-handles[data-label-id="${el.getAttribute('data-label-id')}"]
  `)

  nodes.length && show
    ? nodes.forEach(el =>
      el.style.display = 'none')
    : nodes.forEach(el =>
      el.style.display = null)
}

export const htmlStringToDom = (htmlString = "") =>
  (new DOMParser().parseFromString(htmlString, 'text/html'))
    .body.firstChild

export const isOffBounds = node =>
  node.closest &&
  (node.closest('tool-pallete')
  || node.closest('hotkey-map')
  || node.closest('pb-metatip')
  || node.closest('pb-ally')
  || node.closest('pb-label')
  || node.closest('pb-handles')
  || node.closest('pb-gridlines')
  )<|endoftext|>


<commit_before>const mix = require('merge-descriptors');

function ChatError(message) {
    this.name = 'ChatError';
    this.message = message || '';
}

mix(ChatError.prototype, Error.prototype);

module.exports = {ChatError};
<commit_msg>Object#assign<commit_after>function ChatError(message) {
    this.name = 'ChatError';
    this.message = message || '';
}

Object.assign(ChatError, Error.prototype);

module.exports = {ChatError};
<|endoftext|>


<commit_before>var log = require('util/log');

function attachMiddleware(maxSize) {
  return function bodyDecoder(req, res, next) {
    var cl, bodyLen = 0;
    cl = req.headers['content-length'];

    if (cl) {
      cl = parseInt(cl, 10);
      if (cl >= maxSize) {
        log.info('Denying client for too large content length');
        res.writeHead(413, {Connection: 'close'});
        res.end();
        req.socket.destroy();
      }
    }

    req.setEncoding('utf8');
    req.on('data', function(chunk) {
      bodyLen += chunk.length;
      if (bodyLen >= maxSize) {
        log.info('Denying client for body too large');
        res.writeHead(413, {Connection: 'close'});
        res.end();
        req.socket.destroy();
      }
    });

    next();
  };
}

exports.attachMiddleware = attachMiddleware;
<commit_msg>Buffer incoming data in memory and only call next if request was not aborted.<commit_after>var log = require('util/log');

function attachMiddleware(maxSize) {
  return function bodyDecoder(req, res, next) {
    var cl, bodyLen = 0;
    req.buffer = '';
    cl = req.headers['content-length'];

    if (cl) {
      cl = parseInt(cl, 10);
      if (cl >= maxSize) {
        log.info('Denying client for too large content length');
        res.writeHead(413, {Connection: 'close'});
        res.end();
      }
    }

    function onData(chunk) {
      req.buffer += chunk;
      bodyLen += chunk.length;
      if (bodyLen >= maxSize) {
        log.info('Denying client for body too large');
        res.writeHead(413, {Connection: 'close'});
        res.end();
        req.removeListener('data', onData);
      }
    }

    req.setEncoding('utf8');
    req.on('data', onData);
    req.on('end', next);
  };
}

exports.attachMiddleware = attachMiddleware;
<|endoftext|>


<commit_before>/**
* @jest-environment node
*
* Theese test checks that the examples installs with packages from npm,
* that they build, the dev server runs as expected and is reachable at port 3000
*/
'use strict';
//
//
//
// require('leaked-handles').set({
//     fullStack: true, // use full stack traces
//     timeout: 30000, // run every 30 seconds instead of 5.
//     debugSockets: true // pretty print tcp thrown exceptions.
// });

const puppeteer = require('puppeteer');
const terminate = require('terminate');

const assert = require('assert');
const os = require('os');
const fs = require('fs-extra');
const rfs = require('fs');
const execa = require('execa');
const util = require('util');
const glob = util.promisify(require('glob'));
const axios = require('axios');
const isDocker = require('is-docker');
const razzleUtil = require('../fixtures/util');

const path = require("path");
const copy = require('recursive-copy');
const mkdtemp = util.promisify(fs.mkdtemp);
const mkdtempTpl = path.join(os.tmpdir(), 'example-');

const directoryExists = (dirPath) => fs.existsSync(dirPath) && fs.lstatSync(dirPath).isDirectory();
const fileExists = (dirPath) => fs.existsSync(dirPath);

const rootDir = path.join(path.resolve(__dirname), '..', '..');
const testArtifactsDir = path.join(rootDir, 'test-artifacts');

const silent = !process.env.NOISY_TESTS;
const stdio = 'pipe';

const useCra = process.env.NPM_TAG !== 'development';

const use_package_manager = typeof process.env.PACKAGE_MANAGER === 'undefined' ? 'default' : process.env.PACKAGE_MANAGER;

const useYalc = use_package_manager === 'yalc';

const package_manager = use_package_manager === 'default' || useYalc ? 'yarn' : use_package_manager;

const cra_package_manager = use_package_manager === 'default' ? false : use_package_manager;

const install_deps_args = ['yarn', 'yalc'].indexOf(package_manager) !== -1 ?
[ "install", "--ignore-engines" ] :
[ "install" ];

const webpack_deps = typeof process.env.WEBPACK_DEPS !== 'undefined' ? process.env.WEBPACK_DEPS.split(' ') : false;

const add_webpack_deps_args = package_manager === 'yarn' ?
[ "add", "--dev", "-W"].concat(webpack_deps).concat([ "--ignore-engines" ]) :
[ "install", "--save-dev"].concat(webpack_deps);

const use_npm_tag = typeof process.env.NPM_TAG === 'undefined' ? '' : `@${process.env.NPM_TAG}`;

const writeLogs = true;

let examples =
    { simple: [
      { example: 'basic', path: 'examples/basic' },
      { example: 'basic-server', path: 'examples/basic-server' },
      { example: 'basic-spa', path: 'examples/basic-spa' },
      {
        example: 'with-custom-babel-config',
        path: 'examples/with-custom-babel-config'
      },
      {
        example: 'with-custom-devserver-options',
        path: 'examples/with-custom-devserver-options'
      },
      {
        example: 'with-custom-environment-variables',
        path: 'examples/with-custom-environment-variables'
      },
      {
        example: 'with-custom-target-babel-config',
        path: 'examples/with-custom-target-babel-config'
      },
      {
        example: 'with-custom-webpack-config',
        path: 'examples/with-custom-webpack-config'
      },
      { example: 'with-eslint', path: 'examples/with-eslint' },
      {
        example: 'with-experimental-refresh',
        path: 'examples/with-experimental-refresh'
      },
      {
        example: 'with-firebase-functions',
        path: 'examples/with-firebase-functions'
      },
      { example: 'with-heroku', path: 'examples/with-heroku' },
      { example: 'with-hyperapp', path: 'examples/with-hyperapp' },
      { example: 'with-inferno', path: 'examples/with-inferno' },
      {
        example: 'with-jest-snapshots',
        path: 'examples/with-jest-snapshots'
      },
      {
        example: 'with-jsconfig-paths',
        path: 'examples/with-jsconfig-paths'
      },
      { example: 'with-jsxstyle', path: 'examples/with-jsxstyle' },
      { example: 'with-koa', path: 'examples/with-koa' },
      { example: 'with-less', path: 'examples/with-less' },
      {
        example: 'with-loadable-components',
        path: 'examples/with-loadable-components'
      },
      { example: 'with-material-ui', path: 'examples/with-material-ui' },
      { example: 'with-mdx', path: 'examples/with-mdx' },
      { example: 'with-now', path: 'examples/with-now' },
      { example: 'with-now-v2', path: 'examples/with-now-v2' },
      { example: 'with-polka', path: 'examples/with-polka' },
      { example: 'with-preact', path: 'examples/with-preact' },
      {
        example: 'with-promise-config',
        path: 'examples/with-promise-config'
      },
      {
        example: 'with-react-native-web',
        path: 'examples/with-react-native-web'
      },
      { example: 'with-react-router', path: 'examples/with-react-router' },
      {
        example: 'with-react-server-components',
        path: 'examples/with-react-server-components'
      },
      { example: 'with-redux', path: 'examples/with-redux' },
      { example: 'with-scss', path: 'examples/with-scss' },
      { example: 'with-scss-options', path: 'examples/with-scss-options' },
      {
        example: 'with-single-exposed-port',
        path: 'examples/with-single-exposed-port'
      },
      {
        example: 'with-styled-components',
        path: 'examples/with-styled-components'
      },
      { example: 'with-svelte', path: 'examples/with-svelte' },
      { example: 'with-tailwindcss', path: 'examples/with-tailwindcss' },
      { example: 'with-typescript', path: 'examples/with-typescript' },
      {
        example: 'with-typescript-plugin',
        path: 'examples/with-typescript-plugin'
      },
      {
        example: 'with-vendor-bundle',
        path: 'examples/with-vendor-bundle'
      },
      { example: 'with-vue', path: 'examples/with-vue' },
      { example: 'with-vue-router', path: 'examples/with-vue-router' },
      {
        example: 'with-webpack-public-path',
        path: 'examples/with-webpack-public-path'
      }
    ], complex: [
    { example: 'with-monorepo', path: 'examples/with-monorepo' }, // test timing ssues
    {
      example: 'with-module-federation', // test timing ssues
      path: 'examples/with-module-federation'
    },
    { example: 'with-reason-react', path: 'examples/with-reason-react' }, // test timing ssues
    {
      example: 'with-typeorm-graphql', // test timing ssues
      path: 'examples/with-typeorm-graphql'
    },
    // { example: 'with-elm', path: 'examples/with-elm' }, // requires elm binary
    // {
    //   example: 'with-devcert-https', // may not be possible to test
    //   path: 'examples/with-devcert-https'
    // }
  ]
};

let browser;
let page;

beforeAll(async function(done) {
  if (isDocker()) {
    const response = await axios.get(
      "http://localhost:9222/json/version"
    );
    const browserWSEndpoint = response.data.webSocketDebuggerUrl;
    browser = await puppeteer.connect({ browserWSEndpoint  });
  } else {
    browser = await puppeteer.launch({ headless: process.env.HEADLESS !== "false"  });
  }
  page = await browser.newPage();
  await fs.ensureDir(testArtifactsDir);

  if (useYalc) {
    razzleUtil.yalcPublishAll();
  }
  // const res = await glob('examples/*')
  // examples=res.map(ex=>({example: ex.split('/')[1], path: ex}))
  // console.log(examples)
  done();
});

afterAll(async function(done) {
  if (!isDocker()) {
    await browser.close();
  }
  await new Promise((r) => setTimeout(r, 3000));
  done();
});
Object.keys(examples).forEach((exampleType) => {

  describe(`tests for ${exampleType} isomorphic examples`, () => {

    examples[exampleType].forEach(exampleinfo => {
      const example=exampleinfo.example;

      describe(`tests for the ${example} example`, () => {
        let tempDir;
        let craDir;
        let razzleMeta;

        beforeAll(async function(done) {

          razzleMeta = JSON.parse(await fs.readFile(
            path.join(rootDir, exampleinfo.path, 'package.json'))).razzle_meta||{};

          mkdtemp(mkdtempTpl, (err, directory) => {
            tempDir = directory;
            craDir = path.join(directory, 'example');
            console.log('Using tempdir: ' + tempDir);

            if (!useCra) {
              copy(path.join(rootDir, exampleinfo.path), tempDir, { dot: true },async function(error, results) {
                if (error) {
                  console.error('Copy failed: ' + error);
                } else {
                  // console.info('Copied ' + results.length + ' files');
                }
                if (useYalc) {
                  const packages = razzleUtil.removeWorkspacePackages(tempDir);
                  razzleUtil.yalcAddAll(packages, tempDir);
                }
                done();
              })
            } else {
              done();
            }
          })
        });

        afterAll(async function(done) {
          fs.remove(tempDir, err => {
            assert(!err)
            done();
          });
        });

        jest.setTimeout(300000);

        it(`should install packages`, async function(done) {
          if (!useCra) {
            const subprocess = execa(package_manager,
              install_deps_args,
              {stdio: stdio, cwd: tempDir, all: writeLogs })

            if (writeLogs) {
              const write = rfs.createWriteStream(
                path.join(testArtifactsDir, `${example}-${package_manager}-install.txt`));
              subprocess.all.pipe(write);
            }

            subprocess.then(({exitCode})=>{
              assert.equal(exitCode, 0)
              done();
            })
            await subprocess;
          } else {
            console.log("Skipped install packages");
            done();
          }
        }, 300000);

        it(`should run create-razzle-app successfully`, async function(done) {

          if (useCra) {
            const subprocess = execa("npx", [
              `create-razzle-app${use_npm_tag}`,,
              cra_package_manager && `--${cra_package_manager}`,
              "--verbose",
              "--example",
              example,
              "example"
            ].filter(x=>x), {stdio: stdio, cwd: tempDir, all: writeLogs });
            if (writeLogs) {
              const write = rfs.createWriteStream(
                path.join(testArtifactsDir, `${example}-create-razzle-app.txt`));
              subprocess.all.pipe(write);
            }

            subprocess.then(async ({exitCode})=>{
              assert.equal(exitCode, 0)
              done();
            })
            await subprocess;
          } else {
            console.log("Skipped run create-razzle-app successfully");
            done();
          }
        }, 300000);

        jest.setTimeout(300000);

        it(`should use specific webpack and html-webpack-plugin`, async function(done) {
          if (webpack_deps && !razzleMeta.forceWebpack) {
            console.log(`Installing ${webpack_deps.join(' ')} using ${package_manager}`);
            const subprocess = execa(package_manager,
              add_webpack_deps_args
            , {stdio: stdio, cwd: useCra ? craDir : tempDir, all: writeLogs });
            if (writeLogs) {
              const write = rfs.createWriteStream(
                path.join(testArtifactsDir, `${example}-add-deps.txt`));
              subprocess.all.pipe(write);
            }

            subprocess.then(({exitCode})=>{
              assert.equal(exitCode, 0)
              done();
            })
            await subprocess;
          } else {
            console.log("Skipped use specific webpack and html-webpack-plugin");
            done();
          }
        }, 300000);

        jest.setTimeout(300000);

        it(`should build successfully`, async function(done) {
          const subprocess = execa(package_manager, ["build", "--noninteractive"],
          {stdio: stdio, cwd: useCra ? craDir : tempDir, all: writeLogs })

          if (writeLogs) {
            const write = rfs.createWriteStream(
              path.join(testArtifactsDir, `${example}-${package_manager}-build.txt`));
            subprocess.all.pipe(write);
          }

          subprocess.then(({exitCode})=>{
            assert.equal(exitCode, 0)
            done();
          })
          await subprocess;
        }, 300000);

        jest.setTimeout(300000);

        it(`should start devserver and exit`, async function(done) {

          const subprocess = execa(package_manager, ["start"],
          {stdio: stdio, cwd: useCra ? craDir : tempDir, all: writeLogs })

          if (writeLogs) {
            const write = rfs.createWriteStream(
              path.join(testArtifactsDir, `${example}-${package_manager}-start.txt`));
            subprocess.all.pipe(write);
          }

          let resolved = false;
          let timer;

          try {
            await new Promise(async (resolve, reject) =>{
              console.info(`${package_manager} start for ${example} `);
              const waitForData = data => {
                if (data.toString().includes('Server-side HMR Enabled!') || data.toString().includes('> SPA Started on port')) {
                  resolved = true;
                  subprocess.off('data', waitForData)
                  clearTimeout(timer);
                  resolve();
                }
              }
              timer = setTimeout(function() {
                subprocess.off('data', waitForData)
                reject();
              }, 30000)
              subprocess.stdout.on('data', waitForData);
            })
          } catch {
          }
          if (razzleMeta.yarnStartDelay) {
            await new Promise((r) => setTimeout(r, razzleMeta.yarnStartDelay));
          }
          if (resolved) {
            try {
              await page.goto(`${razzleMeta.protocol||'http'}://localhost:${razzleMeta.port||'3000'}/`);
              await page.screenshot({ path: path.join(testArtifactsDir, `${example}.png`) });
            } catch {

            }
          }

          await new Promise((r) => setTimeout(r, 2000));

          terminate(subprocess.pid, 'SIGINT', { timeout: 3000 }, async () => {
            terminate(subprocess.pid);
            assert.ok(resolved, `yarn start for ${example} failed`);
            done();
          });

        }, 300000);

      });
    });
  });

});
<commit_msg>dev-infra: skip some tests on node 10 and 13<commit_after>/**
* @jest-environment node
*
* Theese test checks that the examples installs with packages from npm,
* that they build, the dev server runs as expected and is reachable at port 3000
*/
'use strict';
//
//
//
// require('leaked-handles').set({
//     fullStack: true, // use full stack traces
//     timeout: 30000, // run every 30 seconds instead of 5.
//     debugSockets: true // pretty print tcp thrown exceptions.
// });

const puppeteer = require('puppeteer');
const terminate = require('terminate');
const semver = require('semver');
const assert = require('assert');
const os = require('os');
const fs = require('fs-extra');
const rfs = require('fs');
const execa = require('execa');
const util = require('util');
const glob = util.promisify(require('glob'));
const axios = require('axios');
const isDocker = require('is-docker');
const razzleUtil = require('../fixtures/util');

const path = require("path");
const copy = require('recursive-copy');
const mkdtemp = util.promisify(fs.mkdtemp);
const mkdtempTpl = path.join(os.tmpdir(), 'example-');

const directoryExists = (dirPath) => fs.existsSync(dirPath) && fs.lstatSync(dirPath).isDirectory();
const fileExists = (dirPath) => fs.existsSync(dirPath);

const rootDir = path.join(path.resolve(__dirname), '..', '..');
const testArtifactsDir = path.join(rootDir, 'test-artifacts');

const silent = !process.env.NOISY_TESTS;
const stdio = 'pipe';

const useCra = process.env.NPM_TAG !== 'development';

const use_package_manager = typeof process.env.PACKAGE_MANAGER === 'undefined' ? 'default' : process.env.PACKAGE_MANAGER;

const useYalc = use_package_manager === 'yalc';

const package_manager = use_package_manager === 'default' || useYalc ? 'yarn' : use_package_manager;

const cra_package_manager = use_package_manager === 'default' ? false : use_package_manager;

const install_deps_args = ['yarn', 'yalc'].indexOf(package_manager) !== -1 ?
[ "install", "--ignore-engines" ] :
[ "install" ];

const webpack_deps = typeof process.env.WEBPACK_DEPS !== 'undefined' ? process.env.WEBPACK_DEPS.split(' ') : false;

const add_webpack_deps_args = package_manager === 'yarn' ?
[ "add", "--dev", "-W"].concat(webpack_deps).concat([ "--ignore-engines" ]) :
[ "install", "--save-dev"].concat(webpack_deps);

const use_npm_tag = typeof process.env.NPM_TAG === 'undefined' ? '' : `@${process.env.NPM_TAG}`;

const writeLogs = true;

let examples =
    { simple: [
      { example: 'basic', path: 'examples/basic' },
      { example: 'basic-server', path: 'examples/basic-server' },
      { example: 'basic-spa', path: 'examples/basic-spa' },
      {
        example: 'with-custom-babel-config',
        path: 'examples/with-custom-babel-config'
      },
      {
        example: 'with-custom-devserver-options',
        path: 'examples/with-custom-devserver-options'
      },
      {
        example: 'with-custom-environment-variables',
        path: 'examples/with-custom-environment-variables'
      },
      {
        example: 'with-custom-target-babel-config',
        path: 'examples/with-custom-target-babel-config'
      },
      {
        example: 'with-custom-webpack-config',
        path: 'examples/with-custom-webpack-config'
      },
      { example: 'with-eslint', path: 'examples/with-eslint' },
      {
        example: 'with-experimental-refresh',
        path: 'examples/with-experimental-refresh'
      },
      {
        example: 'with-firebase-functions',
        path: 'examples/with-firebase-functions'
      },
      { example: 'with-heroku', path: 'examples/with-heroku' },
      { example: 'with-hyperapp', path: 'examples/with-hyperapp' },
      { example: 'with-inferno', path: 'examples/with-inferno' },
      {
        example: 'with-jest-snapshots',
        path: 'examples/with-jest-snapshots'
      },
      {
        example: 'with-jsconfig-paths',
        path: 'examples/with-jsconfig-paths'
      },
      { example: 'with-jsxstyle', path: 'examples/with-jsxstyle' },
      { example: 'with-koa', path: 'examples/with-koa' },
      { example: 'with-less', path: 'examples/with-less' },
      {
        example: 'with-loadable-components',
        path: 'examples/with-loadable-components'
      },
      { example: 'with-material-ui', path: 'examples/with-material-ui' },
      { example: 'with-mdx', path: 'examples/with-mdx' },
      { example: 'with-now', path: 'examples/with-now' },
      { example: 'with-now-v2', path: 'examples/with-now-v2' },
      { example: 'with-polka', path: 'examples/with-polka' },
      { example: 'with-preact', path: 'examples/with-preact' },
      {
        example: 'with-promise-config',
        path: 'examples/with-promise-config'
      },
      {
        example: 'with-react-native-web',
        path: 'examples/with-react-native-web'
      },
      { example: 'with-react-router', path: 'examples/with-react-router' },
      !semver.satisfies(process.version, '~10||~13') && {
        example: 'with-react-server-components',
        path: 'examples/with-react-server-components'
      },
      { example: 'with-redux', path: 'examples/with-redux' },
      { example: 'with-scss', path: 'examples/with-scss' },
      { example: 'with-scss-options', path: 'examples/with-scss-options' },
      {
        example: 'with-single-exposed-port',
        path: 'examples/with-single-exposed-port'
      },
      {
        example: 'with-styled-components',
        path: 'examples/with-styled-components'
      },
      { example: 'with-svelte', path: 'examples/with-svelte' },
      !semver.satisfies(process.version, '~10') && {
        example: 'with-tailwindcss', path: 'examples/with-tailwindcss' },
      { example: 'with-typescript', path: 'examples/with-typescript' },
      {
        example: 'with-typescript-plugin',
        path: 'examples/with-typescript-plugin'
      },
      {
        example: 'with-vendor-bundle',
        path: 'examples/with-vendor-bundle'
      },
      { example: 'with-vue', path: 'examples/with-vue' },
      { example: 'with-vue-router', path: 'examples/with-vue-router' },
      {
        example: 'with-webpack-public-path',
        path: 'examples/with-webpack-public-path'
      }
    ].filter(x=>x), complex: [
    { example: 'with-monorepo', path: 'examples/with-monorepo' }, // test timing ssues
    {
      example: 'with-module-federation', // test timing ssues
      path: 'examples/with-module-federation'
    },
    { example: 'with-reason-react', path: 'examples/with-reason-react' }, // test timing ssues
    {
      example: 'with-typeorm-graphql', // test timing ssues
      path: 'examples/with-typeorm-graphql'
    },
    // { example: 'with-elm', path: 'examples/with-elm' }, // requires elm binary
    // {
    //   example: 'with-devcert-https', // may not be possible to test
    //   path: 'examples/with-devcert-https'
    // }
  ]
};

let browser;
let page;

beforeAll(async function(done) {
  if (isDocker()) {
    const response = await axios.get(
      "http://localhost:9222/json/version"
    );
    const browserWSEndpoint = response.data.webSocketDebuggerUrl;
    browser = await puppeteer.connect({ browserWSEndpoint  });
  } else {
    browser = await puppeteer.launch({ headless: process.env.HEADLESS !== "false"  });
  }
  page = await browser.newPage();
  await fs.ensureDir(testArtifactsDir);

  if (useYalc) {
    razzleUtil.yalcPublishAll();
  }
  // const res = await glob('examples/*')
  // examples=res.map(ex=>({example: ex.split('/')[1], path: ex}))
  // console.log(examples)
  done();
});

afterAll(async function(done) {
  if (!isDocker()) {
    await browser.close();
  }
  await new Promise((r) => setTimeout(r, 3000));
  done();
});
Object.keys(examples).forEach((exampleType) => {

  describe(`tests for ${exampleType} isomorphic examples`, () => {

    examples[exampleType].forEach(exampleinfo => {
      const example=exampleinfo.example;

      describe(`tests for the ${example} example`, () => {
        let tempDir;
        let craDir;
        let razzleMeta;

        beforeAll(async function(done) {

          razzleMeta = JSON.parse(await fs.readFile(
            path.join(rootDir, exampleinfo.path, 'package.json'))).razzle_meta||{};

          mkdtemp(mkdtempTpl, (err, directory) => {
            tempDir = directory;
            craDir = path.join(directory, 'example');
            console.log('Using tempdir: ' + tempDir);

            if (!useCra) {
              copy(path.join(rootDir, exampleinfo.path), tempDir, { dot: true },async function(error, results) {
                if (error) {
                  console.error('Copy failed: ' + error);
                } else {
                  // console.info('Copied ' + results.length + ' files');
                }
                if (useYalc) {
                  const packages = razzleUtil.removeWorkspacePackages(tempDir);
                  razzleUtil.yalcAddAll(packages, tempDir);
                }
                done();
              })
            } else {
              done();
            }
          })
        });

        afterAll(async function(done) {
          fs.remove(tempDir, err => {
            assert(!err)
            done();
          });
        });

        jest.setTimeout(300000);

        it(`should install packages`, async function(done) {
          if (!useCra) {
            const subprocess = execa(package_manager,
              install_deps_args,
              {stdio: stdio, cwd: tempDir, all: writeLogs })

            if (writeLogs) {
              const write = rfs.createWriteStream(
                path.join(testArtifactsDir, `${example}-${package_manager}-install.txt`));
              subprocess.all.pipe(write);
            }

            subprocess.then(({exitCode})=>{
              assert.equal(exitCode, 0)
              done();
            })
            await subprocess;
          } else {
            console.log("Skipped install packages");
            done();
          }
        }, 300000);

        it(`should run create-razzle-app successfully`, async function(done) {

          if (useCra) {
            const subprocess = execa("npx", [
              `create-razzle-app${use_npm_tag}`,,
              cra_package_manager && `--${cra_package_manager}`,
              "--verbose",
              "--example",
              example,
              "example"
            ].filter(x=>x), {stdio: stdio, cwd: tempDir, all: writeLogs });
            if (writeLogs) {
              const write = rfs.createWriteStream(
                path.join(testArtifactsDir, `${example}-create-razzle-app.txt`));
              subprocess.all.pipe(write);
            }

            subprocess.then(async ({exitCode})=>{
              assert.equal(exitCode, 0)
              done();
            })
            await subprocess;
          } else {
            console.log("Skipped run create-razzle-app successfully");
            done();
          }
        }, 300000);

        jest.setTimeout(300000);

        it(`should use specific webpack and html-webpack-plugin`, async function(done) {
          if (webpack_deps && !razzleMeta.forceWebpack) {
            console.log(`Installing ${webpack_deps.join(' ')} using ${package_manager}`);
            const subprocess = execa(package_manager,
              add_webpack_deps_args
            , {stdio: stdio, cwd: useCra ? craDir : tempDir, all: writeLogs });
            if (writeLogs) {
              const write = rfs.createWriteStream(
                path.join(testArtifactsDir, `${example}-add-deps.txt`));
              subprocess.all.pipe(write);
            }

            subprocess.then(({exitCode})=>{
              assert.equal(exitCode, 0)
              done();
            })
            await subprocess;
          } else {
            console.log("Skipped use specific webpack and html-webpack-plugin");
            done();
          }
        }, 300000);

        jest.setTimeout(300000);

        it(`should build successfully`, async function(done) {
          const subprocess = execa(package_manager, ["build", "--noninteractive"],
          {stdio: stdio, cwd: useCra ? craDir : tempDir, all: writeLogs })

          if (writeLogs) {
            const write = rfs.createWriteStream(
              path.join(testArtifactsDir, `${example}-${package_manager}-build.txt`));
            subprocess.all.pipe(write);
          }

          subprocess.then(({exitCode})=>{
            assert.equal(exitCode, 0)
            done();
          })
          await subprocess;
        }, 300000);

        jest.setTimeout(300000);

        it(`should start devserver and exit`, async function(done) {

          const subprocess = execa(package_manager, ["start"],
          {stdio: stdio, cwd: useCra ? craDir : tempDir, all: writeLogs })

          if (writeLogs) {
            const write = rfs.createWriteStream(
              path.join(testArtifactsDir, `${example}-${package_manager}-start.txt`));
            subprocess.all.pipe(write);
          }

          let resolved = false;
          let timer;

          try {
            await new Promise(async (resolve, reject) =>{
              console.info(`${package_manager} start for ${example} `);
              const waitForData = data => {
                if (data.toString().includes('Server-side HMR Enabled!') || data.toString().includes('> SPA Started on port')) {
                  resolved = true;
                  subprocess.off('data', waitForData)
                  clearTimeout(timer);
                  resolve();
                }
              }
              timer = setTimeout(function() {
                subprocess.off('data', waitForData)
                reject();
              }, 30000)
              subprocess.stdout.on('data', waitForData);
            })
          } catch {
          }
          if (razzleMeta.yarnStartDelay) {
            await new Promise((r) => setTimeout(r, razzleMeta.yarnStartDelay));
          }
          if (resolved) {
            try {
              await page.goto(`${razzleMeta.protocol||'http'}://localhost:${razzleMeta.port||'3000'}/`);
              await page.screenshot({ path: path.join(testArtifactsDir, `${example}.png`) });
            } catch {

            }
          }

          await new Promise((r) => setTimeout(r, 2000));

          terminate(subprocess.pid, 'SIGINT', { timeout: 3000 }, async () => {
            terminate(subprocess.pid);
            assert.ok(resolved, `yarn start for ${example} failed`);
            done();
          });

        }, 300000);

      });
    });
  });

});
<|endoftext|>