<commit_before>// Setup basic express server
var fs = require('fs');
var express = require('express');
var app = express();
var options = {
    key: fs.readFileSync('/etc/ssl/rtloc.tk/private.key'),
    cert: fs.readFileSync('/etc/ssl/rtloc.tk/public.crt'),
    ca: fs.readFileSync('/etc/ssl/rtloc.tk/ca.pem')
}
var server = require('https').createServer(options,app);
var io = require('socket.io')(server);
var sPort = 443;//process.env.PORT || 443;
var nPort = 80;//process.env.PORT || 80;
var http = require('http');

var allusers = new Array();

server.listen(sPort, function () {
  console.log('Server listening at port %d', sPort);
});

var httpserver = http.createServer(function(req, res) {
  var output = "";
  switch(req.url){
    case '/track' :
    case '/track/' :
      output +=('
');
      output +=('
Username	Latitude	Longitude
');
      for ( var tuser in allusers ){
        output +=('
');
        output +=('' + allusers[tuser].unm + '	');
        output +=('' + allusers[tuser].lat + '	');
        output +=('' + allusers[tuser].lng + '	');
        output +=('
');
      }
      output +=('
');
      fs.writeFile('public/logs/' + new Date().getTime() + '.log', output, 'utf8');
      res.write(output);
    break;
    case '/logs' :
    case '/logs/' :
    console.log(__dirname+'/public/logs/');
      fs.readdir(__dirname+'/public/logs/', function(err, items) {
          output +=('
');
          output +=('
Sl No	Item
');
          for (var i=0; i<items.length; i++) {
            output +=('
');
            output +=('' + (i+1) + '	');
            output +=(''+items[i]+'	');
            output +=('
');
          }
          output +=('
');
          console.log(output);
          res.write(output);
      });
    default :
      res.writeHead(302, {'Location': 'https://rtloc.tk' + req.url});
    break;
  }
  res.end();
});

httpserver.listen(nPort, function () {
  console.log('Server listening at port %d', nPort);
});

// Routing
app.use(express.static(__dirname + '/public'));

// Chatroom

var numUsers = 0;

io.on('connection', function (socket) {
  var addedUser = false;

  // when the client emits 'new message', this listens and executes
  socket.on('new location', function (data) {
    // we tell the client to execute 'new message'
    socket.broadcast.emit('new location', {
      uname: data.uname,
      tyLat: data.tyLat,
      tyLng: data.tyLng
    });
    //console.log(data.uname+"@"+data.tyLat+","+data.tyLng);
    if(!( data.uname in allusers )){
      console.log("Creating " + data.uname + "...");
      allusers[data.uname] = new Object();
      allusers[data.uname].lat = data.tyLat;
      allusers[data.uname].lng = data.tyLng;
      allusers[data.uname].unm = data.uname;
      //allusers[data.uname] = node;
    }else{
      allusers[data.uname].lat = data.tyLat;
      allusers[data.uname].lng = data.tyLng;
    }
  });

  // when the client emits 'add user', this listens and executes
  socket.on('add user', function (username) {
    if (addedUser) return;

    // we store the username in the socket session for this client
    socket.username = username;
    ++numUsers;
    addedUser = true;
    socket.emit('login', {
      numUsers: numUsers
    });
    // echo globally (all clients) that a person has connected
    socket.broadcast.emit('user joined', {
      username: socket.username,
      numUsers: numUsers
    });
  });

  // when the user disconnects.. perform this
  socket.on('disconnect', function () {
    if (addedUser) {
      --numUsers;

      // echo globally that this client has left
      socket.broadcast.emit('user left', {
        username: socket.username,
        numUsers: numUsers
      });
    }
  });

});
<commit_msg>Automatic commit from server<commit_after>// Setup basic express server
var fs = require('fs');
var express = require('express');
var app = express();
var options = {
    key: fs.readFileSync('/etc/ssl/rtloc.tk/private.key'),
    cert: fs.readFileSync('/etc/ssl/rtloc.tk/public.crt'),
    ca: fs.readFileSync('/etc/ssl/rtloc.tk/ca.pem')
}
var server = require('https').createServer(options,app);
var io = require('socket.io')(server);
var sPort = 443;//process.env.PORT || 443;
var nPort = 80;//process.env.PORT || 80;
var http = require('http');

var allusers = new Array();

server.listen(sPort, function () {
  console.log('Server listening at port %d', sPort);
});

var httpserver = http.createServer(function(req, res) {
  var output = "";
  switch(req.url){
    case '/track' :
    case '/track/' :
      output +=('
');
      output +=('
Username	Latitude	Longitude
');
      for ( var tuser in allusers ){
        output +=('
');
        output +=('' + allusers[tuser].unm + '	');
        output +=('' + allusers[tuser].lat + '	');
        output +=('' + allusers[tuser].lng + '	');
        output +=('
');
      }
      output +=('
');
      fs.writeFile('public/logs/' + new Date().getTime() + '.log', output, 'utf8');
      res.write(output);
    break;
    case '/logs' :
    case '/logs/' :
    console.log(__dirname+'/public/logs/');
      fs.readdir(__dirname+'/public/logs/', function(err, items) {
          output +=('
');
          output +=('
Sl No	Item
');
          for (var i=0; i<items.length; i++) {
            output +=('
');
            output +=('' + (i+1) + '	');
            output +=(''+items[i]+'	');
            output +=('
');
          }
          output +=('
');
          console.log(output);
          res.write(output);
      });
    break;
    default :
      res.writeHead(302, {'Location': 'https://rtloc.tk' + req.url});
    break;
  }
  res.end();
});

httpserver.listen(nPort, function () {
  console.log('Server listening at port %d', nPort);
});

// Routing
app.use(express.static(__dirname + '/public'));

// Chatroom

var numUsers = 0;

io.on('connection', function (socket) {
  var addedUser = false;

  // when the client emits 'new message', this listens and executes
  socket.on('new location', function (data) {
    // we tell the client to execute 'new message'
    socket.broadcast.emit('new location', {
      uname: data.uname,
      tyLat: data.tyLat,
      tyLng: data.tyLng
    });
    //console.log(data.uname+"@"+data.tyLat+","+data.tyLng);
    if(!( data.uname in allusers )){
      console.log("Creating " + data.uname + "...");
      allusers[data.uname] = new Object();
      allusers[data.uname].lat = data.tyLat;
      allusers[data.uname].lng = data.tyLng;
      allusers[data.uname].unm = data.uname;
      //allusers[data.uname] = node;
    }else{
      allusers[data.uname].lat = data.tyLat;
      allusers[data.uname].lng = data.tyLng;
    }
  });

  // when the client emits 'add user', this listens and executes
  socket.on('add user', function (username) {
    if (addedUser) return;

    // we store the username in the socket session for this client
    socket.username = username;
    ++numUsers;
    addedUser = true;
    socket.emit('login', {
      numUsers: numUsers
    });
    // echo globally (all clients) that a person has connected
    socket.broadcast.emit('user joined', {
      username: socket.username,
      numUsers: numUsers
    });
  });

  // when the user disconnects.. perform this
  socket.on('disconnect', function () {
    if (addedUser) {
      --numUsers;

      // echo globally that this client has left
      socket.broadcast.emit('user left', {
        username: socket.username,
        numUsers: numUsers
      });
    }
  });

});
<|endoftext|>


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

var textos = ["q?","Q?"];
var nasus_quotes = [
"Who let the dogs out? Woof. Woof. Woof.",
"No, I will not fetch the ball.",
"My bite is worse than my bark.",
"The cycle of life and death continues. We will live, they will die.",
"Do not try my patience.",
"Life is part of a cycle. Yours is over.",
"Your soul will be measured.",
"Return to the dust."
];

var nasus = exec('tweet stream "nasus" --json');
console.log("Reading 'nasus' tweets");
nasus.stdout.on('data', function(data) {
    var dados = JSON.parse(data);
    console.log("@"+dados.user.screen_name+": "+dados.text);
    var textoAleatorio = textos[Math.floor(Math.random()*textos.length)];
    var comando = 'tweet new "@'+dados.user.screen_name+' '+textoAleatorio+'"';
    var newTweet = exec(comando);
    console.log(comando);
    newTweet.stdout.on('data', function(nasusData) {
      console.log(nasusData);
    });
    newTweet.stderr.on('data', function(data) {
      console.log(data);
    });
});
nasus.stdout.on('exit', function(data) {
  console.log(data);
});
nasus.stderr.on('data', function(data) {
  console.log(data);
});

var reply = exec('tweet stream "@such_nasus" --json');
console.log("Reading '@such_nasus' tweets");
reply.stdout.on('data', function(data) {
    var dados = JSON.parse(data);
    console.log("@"+dados.user.screen_name+": "+dados.text);
    var quoteAleatorio = nasus_quotes[Math.floor(Math.random()*nasus_quotes.length)];
    var comando = 'tweet new "@'+dados.user.screen_name+' '+quoteAleatorio+'"';
    var newTweet = exec(comando);
    console.log(comando);
    newTweet.stdout.on('data', function(nasusData) {
      console.log(nasusData);
    });
    newTweet.stderr.on('data', function(nasusData) {
      console.log(nasusData);
    });
});
reply.stdout.on('exit', function(data) {
  console.log(data);
});
reply.stderr.on('data', function(data) {
  console.log(data);
});
<commit_msg>way to diferenciate when an error occours<commit_after>var exec = require('child_process').exec;

var textos = ["q?","Q?"];
var nasus_quotes = [
"Who let the dogs out? Woof. Woof. Woof.",
"No, I will not fetch the ball.",
"My bite is worse than my bark.",
"The cycle of life and death continues. We will live, they will die.",
"Do not try my patience.",
"Life is part of a cycle. Yours is over.",
"Your soul will be measured.",
"Return to the dust."
];

var nasus = exec('tweet stream "nasus" --json');
console.log("Reading 'nasus' tweets");
nasus.stdout.on('data', function(data) {
    var dados = JSON.parse(data);
    console.log("@"+dados.user.screen_name+": "+dados.text);
    var textoAleatorio = textos[Math.floor(Math.random()*textos.length)];
    var comando = 'tweet new "@'+dados.user.screen_name+' '+textoAleatorio+'"';
    var newTweet = exec(comando);
    console.log(comando);
    newTweet.stdout.on('data', function(nasusData) {
      console.log(nasusData);
    });
    newTweet.stderr.on('data', function(data) {
      console.log(data);
    });
});
nasus.stdout.on('exit', function(data) {
  console.log("stream 'nasus': "+data);
});
nasus.stderr.on('data', function(data) {
  console.log("stream 'nasus': "+data);
});

var reply = exec('tweet stream "@such_nasus" --json');
console.log("Reading '@such_nasus' tweets");
reply.stdout.on('data', function(data) {
    var dados = JSON.parse(data);
    console.log("@"+dados.user.screen_name+": "+dados.text);
    var quoteAleatorio = nasus_quotes[Math.floor(Math.random()*nasus_quotes.length)];
    var comando = 'tweet new "@'+dados.user.screen_name+' '+quoteAleatorio+'"';
    var newTweet = exec(comando);
    console.log(comando);
    newTweet.stdout.on('data', function(nasusData) {
      console.log(nasusData);
    });
    newTweet.stderr.on('data', function(nasusData) {
      console.log(nasusData);
    });
});
reply.stdout.on('exit', function(data) {
  console.log("stream '@such_nasus': "+data);
});
reply.stderr.on('data', function(data) {
  console.log("stream '@such_nasus': "+data);
});
<|endoftext|>


<commit_before>'use strict';

const {promisify} = require('util');
const {readFile} = require('fs');

const inspectWithKind = require('inspect-with-kind');
const Observable = require('zen-observable');

const promisifiedReadFile = promisify(readFile);

module.exports = function readMultipleFiles(...args) {
	return new Observable(observer => {
		const argLen = args.length;

		if (argLen !== 1 && argLen !== 2) {
			throw new RangeError(`Expected 1 or 2 arguments (paths: <Array|Set>[, options: <Object>]), but got ${
				argLen === 0 ? 'no' : argLen
			} arguments instead.`);
		}

		const [paths, options] = args;

		if (!Array.isArray(paths) && !(paths instanceof Set)) {
			const error = new TypeError(`Expected file paths (<Array> or <Set>), but got ${
				inspectWithKind(paths)
			} instead.`);

			error.code = 'ERR_INVALID_ARG_TYPE';
			throw error;
		}

		(async () => {
			try {
				await Promise.all([...paths].map(async path => observer.next({
					path,
					contents: await promisifiedReadFile(path, options)
				})));
			} catch (err) {
				observer.error(err);
			}

			observer.complete();
		})();
	});
};
<commit_msg>make use of util.types<commit_after>'use strict';

const {types: {isSet}, promisify} = require('util');
const {readFile} = require('fs');

const inspectWithKind = require('inspect-with-kind');
const Observable = require('zen-observable');

const promisifiedReadFile = promisify(readFile);

module.exports = function readMultipleFiles(...args) {
	return new Observable(observer => {
		const argLen = args.length;

		if (argLen !== 1 && argLen !== 2) {
			throw new RangeError(`Expected 1 or 2 arguments (paths: <Array|Set>[, options: <Object>]), but got ${
				argLen === 0 ? 'no' : argLen
			} arguments instead.`);
		}

		const [paths, options] = args;

		if (!Array.isArray(paths) && !isSet(paths)) {
			const error = new TypeError(`Expected file paths (<Array> or <Set>), but got ${
				inspectWithKind(paths)
			} instead.`);

			error.code = 'ERR_INVALID_ARG_TYPE';
			throw error;
		}

		(async () => {
			try {
				await Promise.all([...paths].map(async path => observer.next({
					path,
					contents: await promisifiedReadFile(path, options)
				})));
			} catch (err) {
				observer.error(err);
			}

			observer.complete();
		})();
	});
};
<|endoftext|>


<commit_before>'use strict'

// setup
const http = require('http')
const port = process.env.PORT || process.env.port || 8091
const scrud = {
  GET: 'search',
  'GET?': 'search',
  POST: 'create',
  'POST/': 'create',
  'GET/': 'read',
  'PUT/': 'update',
  'DELETE/': 'delete'
}

// globals
let server
let base = ''
let baseRgx = new RegExp(`^/?${base}/`)
let resources = {}

// helpers
const cleanPath = (url) => {
  return decodeURIComponent(url).replace(baseRgx, '').replace(/\/$/, '')
}

// exports
module.exports = {register, start, logger, _find, _findAll, _create, _save}

// register resource
function register (name, opts) {
  if (!name) return Promise.reject(new Error(`no name specified in register`))
  return new Promise((resolve, reject) => {
    let r = resources[name] = {name}
    return resolve(r)
  })
}

// start server
function start (opts = {}) {
  base = opts.base
  baseRgx = new RegExp(`^/?${base}/`)
  return new Promise((resolve, reject) => {
    server = http.createServer(handleRequest)
    server.listen(opts.port || port)
    return resolve(server)
  })
}

// handle 404
function fourOhFour (res) {
  res.statusCode = 404
  res.end('no match for requested route')
}

// request handler
function handleRequest (req, res) {
  if (!baseRgx.test(req.url)) return fourOhFour(res)
  let url = cleanPath(req.url)
  let matches = url.match(/^\/?(.+?)(\/|\?|$)/) || []
  let resource = resources[matches[1] || '']
  let modifier = matches[2]
  let action = scrud[`${req.method}${modifier}`]
  if (!resource || !action) return fourOhFour(res)
  res.setHeader('SCRUD', `${resource.name}:${action}`)
  res.end('{}')
}

// return global logger
function logger () { return null }

// helper: find resource
function _find () { return null }

// helper: find set of resources
function _findAll () { return null }

// helper: create resource
function _create () { return null }

// helper: update resource
function _save () { return null }
<commit_msg>Start scaffolding default handlers<commit_after>'use strict'

// setup
const http = require('http')
const port = process.env.PORT || process.env.port || 8091
const handlers = {
  search: resourceSearch,
  create: resourceCreate,
  read: resourceRead,
  update: resourceUpdate,
  delete: resourceDelete
}
const scrud = {
  GET: 'search',
  'GET?': 'search',
  POST: 'create',
  'POST/': 'create',
  'GET/': 'read',
  'PUT/': 'update',
  'DELETE/': 'delete'
}

// globals
let server
let base = ''
let baseRgx = new RegExp(`^/?${base}/`)
let resources = {}

// helpers
const cleanPath = (url) => {
  return decodeURIComponent(url).replace(baseRgx, '').replace(/\/$/, '')
}

// exports
module.exports = {register, start, logger, _find, _findAll, _create, _save}

// register resource
function register (name, opts) {
  if (!name) return Promise.reject(new Error(`no name specified in register`))
  return new Promise((resolve, reject) => {
    let r = resources[name] = {name}
    return resolve(r)
  })
}

// start server
function start (opts = {}) {
  base = opts.base
  baseRgx = new RegExp(`^/?${base}/`)
  return new Promise((resolve, reject) => {
    server = http.createServer(handleRequest)
    server.listen(opts.port || port)
    return resolve(server)
  })
}

// handle 404
function fourOhFour (res) {
  res.statusCode = 404
  res.end('no match for requested route')
}

// request handler
function handleRequest (req, res) {
  if (!baseRgx.test(req.url)) return fourOhFour(res)
  let url = cleanPath(req.url)
  let matches = url.match(/^\/?(.+?)(\/|\?|$)/) || []
  let resource = resources[matches[1] || '']
  let modifier = matches[2]
  let action = scrud[`${req.method}${modifier}`]
  if (!resource || !action) return fourOhFour(res)
  res.setHeader('SCRUD', `${resource.name}:${action}`)
  return (resource[action] || handlers[action])(req, res, resource.name)
}

// return global logger
function logger () { return null }

// helper: find resource
function _find () { return null }

// helper: find set of resources
function _findAll () { return null }

// helper: create resource
function _create () { return null }

// helper: update resource
function _save () { return null }

// resource method: search
function resourceSearch (req, res, name) { return res.end('{}') }

// resource method: create
function resourceCreate (req, res, name) { return res.end('{}') }

// resource method: read
function resourceRead (req, res, name) { return res.end('{}') }

// resource method: update
function resourceUpdate (req, res, name) { return res.end('{}') }

// resource method: delete
function resourceDelete (req, res, name) { return res.end('{}') }
<|endoftext|>


<commit_before>'use strict';

//
// Plugin name.
//
exports.name = 'async';

/**
 * The client-side plugin for BigPipe which adds XHR functionality.
 *
 * @param {BigPipe} pipe The BigPipe instance.
 * @param {Object} options .
 * @api public
 */
exports.client = function client(pipe, options) {
  var xhr = require('xhr')
    , async = pipe.xhr = {};

  /**
   * GET request via xhr.
   *
   * @param {String} uri Target url.
   * @param {Function} done Completion callback.
   * @api public
   */
  async.get = function get(uri, done) {
    xhr({ method: 'get', uri: uri }, done);
  };

  /**
   * POST request via xhr.
   *
   * @param {String} uri Target url.
   * @param {Object} data Optional data.
   * @param {Function} done Completion callback.
   * @api public
   */
  async.post = function post(uri, data, done) {
    if ('function' !== typeof done) {
      done = data;
      data = {};
    }

    xhr({ method: 'post', body: data, uri: uri }, done);
  };
};<commit_msg>[fix] post json if object<commit_after>'use strict';

//
// Plugin name.
//
exports.name = 'async';

/**
 * The client-side plugin for BigPipe which adds XHR functionality.
 *
 * @param {BigPipe} pipe The BigPipe instance.
 * @param {Object} options .
 * @api public
 */
exports.client = function client(pipe, options) {
  var xhr = require('xhr')
    , async = pipe.xhr = {};

  /**
   * GET request via xhr.
   *
   * @param {String} uri Target url.
   * @param {Function} done Completion callback.
   * @api public
   */
  async.get = function get(uri, done) {
    xhr({ method: 'get', uri: uri }, done);
  };

  /**
   * POST request via xhr.
   *
   * @param {String} uri Target url.
   * @param {Object} data Optional data.
   * @param {Function} done Completion callback.
   * @api public
   */
  async.post = function post(uri, data, done) {
    if ('function' !== typeof done) {
      done = data;
      data = {};
    }

    var object = {
      method: 'post',
      uri: uri
    };

    object['string' === typeof data ? 'body' : 'json'] = data;
    xhr(object, done);
  };
};<|endoftext|>


<commit_before>/**
 * share-url v1.1.0
 * @link https://github.com/noeldelgado/share-url
 * @license MIT
 */
(function(root, factory) {
  if (typeof exports === 'object') module.exports = factory(root);
  else root.ShareUrl = factory(root);
}(this, function factory(root) {
  var ENDPOINTS = {
    facebook    : 'https://www.facebook.com/sharer/sharer.php?',
    twitter     : 'https://twitter.com/share?',
    pinterest   : 'https://pinterest.com/pin/create/button/?',
    reddit      : 'http://www.reddit.com/submit?',
    linkedin    : 'https://linkedin.com/sharing/share-offsite/?',
    whatsapp    : 'https://api.whatsapp.com/send?',
    telegram    : 'https://t.me/share/url?',
  };

  return {
    facebook    : facebook,
    twitter     : twitter,
    pinterest   : pinterest,
    reddit      : reddit,
    linkedin    : linkedin,
    whatsapp    : whatsapp,
    telegram    : telegram,
    email       : email,
  };

  function _generateUrlParams(data) {
    return Object.keys(data || {}).map(function(propertyName) {
      return propertyName + '=' + encodeURIComponent(data[propertyName]);
    }).join('&');
  }

  /* Compose the share on facebook url string.
   * @argument data [Object] <required>
   * @argument data.u [String] <required>
   * @return url
   */
  function facebook(data) {
    return ENDPOINTS.facebook + _generateUrlParams(data);
  }

  /* Compose the share on whatsapp url string
   * @argument data [Object] <required>
   * @argument data.text [String] <required>
   * @return url
   */
  function whatsapp(data) {
    return ENDPOINTS.whatsapp + _generateUrlParams(data);
  }

  /* Compose the share on telegram url string
   * @argument data [Object] <required>
   * @argument data.url [String] <required>
   * @argument data.text [String] <optional>
   * @return url
   */
  function telegram(data) {
    return ENDPOINTS.telegram + _generateUrlParams(data);
  }

  /* Compose the share on twitter url string.
   * @argument data [Object] <required>
   * @argument data.text [String] <optional> Pre-populated text highlighted in the Tweet composer.
   * @argument data.in_reply_to [String] <optional> Status ID string of a parent Tweet such as a Tweet from your account (if applicable).
   * @argument data.url [String] <optional> URL included with the Tweet.
   * @argument data.hashtags [String] <optional> A comma-separated list of hashtags to be appended to default Tweet text.
   * @argument data.via [String] <optional> Attribute the source of a Tweet to a Twitter username.
   * @argument data.related [String] <optional> A comma-separated list of accounts related to the content of the shared URI.
   * @info https://dev.twitter.com/web/tweet-button/parameters
   * @return url
   */
  function twitter(data) {
    return ENDPOINTS.twitter + _generateUrlParams(data);
  }

  /* Compose the share on pinterest url string.
   * @argument data [Object] <required>
   * @argument data.url <required>
   * @argument data.media <required>
   * @argument data.description <required>
   * @info https://developers.pinterest.com/pin_it/
   * @return url
   */
  function pinterest(data) {
    return ENDPOINTS.pinterest + _generateUrlParams(data);
  }

  /* Compose the submit to reddit url string.
   * @argument data [Object] <required>
   * @argument data.url <required>
   * @argument data.title <optional>
   * @argument data.text <optional>
   * @info http://www.reddit.com/buttons/
   * @return url
   */
  function reddit(data) {
    return ENDPOINTS.reddit + _generateUrlParams(data);
  }

  /* Compose the share article on linkedin url string.
   * @argument data [Object] <required>
   * @argument data.url [String, 1024] <required> The url-encoded URL of the page that you wish to share.
   * @info https://developer.linkedin.com/docs/share-on-linkedin
   * @return url
   */
  function linkedin(data) {
    return ENDPOINTS.linkedin + _generateUrlParams(data);
  }

  /* Compose the send email url string.
   * @argument data [Object] <required>
   * @argument to [String] <required>
   * @argument subject [String] <optional>
   * @argument cc [String] <optional>
   * @argument bcc [String] <optional>
   * @argument body [String] <optional>
   * @info https://developer.mozilla.org/en-US/docs/Web/Guide/HTML/Email_links
   * @return url
   */
  function email(data) {
    var to = data.to;
    delete data.to;
    var params = _generateUrlParams(data);
    return 'mailto:' + (params.length ? (to + '?' + params) : to);
  }
}));
<commit_msg>feat(lib) add static version field<commit_after>/**
 * share-url v1.1.0
 * @link https://github.com/noeldelgado/share-url
 * @license MIT
 */
(function(root, factory) {
  if (typeof exports === 'object') module.exports = factory(root);
  else root.ShareUrl = factory(root);
}(this, function factory(root) {
  var ENDPOINTS = {
    facebook    : 'https://www.facebook.com/sharer/sharer.php?',
    twitter     : 'https://twitter.com/share?',
    pinterest   : 'https://pinterest.com/pin/create/button/?',
    reddit      : 'http://www.reddit.com/submit?',
    linkedin    : 'https://linkedin.com/sharing/share-offsite/?',
    whatsapp    : 'https://api.whatsapp.com/send?',
    telegram    : 'https://t.me/share/url?',
  };

  return {
    VERSION     : '1.1.0',
    facebook    : facebook,
    twitter     : twitter,
    pinterest   : pinterest,
    reddit      : reddit,
    linkedin    : linkedin,
    whatsapp    : whatsapp,
    telegram    : telegram,
    email       : email,
  };

  function _generateUrlParams(data) {
    return Object.keys(data || {}).map(function(propertyName) {
      return propertyName + '=' + encodeURIComponent(data[propertyName]);
    }).join('&');
  }

  /* Compose the share on facebook url string.
   * @argument data [Object] <required>
   * @argument data.u [String] <required>
   * @return url
   */
  function facebook(data) {
    return ENDPOINTS.facebook + _generateUrlParams(data);
  }

  /* Compose the share on whatsapp url string
   * @argument data [Object] <required>
   * @argument data.text [String] <required>
   * @return url
   */
  function whatsapp(data) {
    return ENDPOINTS.whatsapp + _generateUrlParams(data);
  }

  /* Compose the share on telegram url string
   * @argument data [Object] <required>
   * @argument data.url [String] <required>
   * @argument data.text [String] <optional>
   * @return url
   */
  function telegram(data) {
    return ENDPOINTS.telegram + _generateUrlParams(data);
  }

  /* Compose the share on twitter url string.
   * @argument data [Object] <required>
   * @argument data.text [String] <optional> Pre-populated text highlighted in the Tweet composer.
   * @argument data.in_reply_to [String] <optional> Status ID string of a parent Tweet such as a Tweet from your account (if applicable).
   * @argument data.url [String] <optional> URL included with the Tweet.
   * @argument data.hashtags [String] <optional> A comma-separated list of hashtags to be appended to default Tweet text.
   * @argument data.via [String] <optional> Attribute the source of a Tweet to a Twitter username.
   * @argument data.related [String] <optional> A comma-separated list of accounts related to the content of the shared URI.
   * @info https://dev.twitter.com/web/tweet-button/parameters
   * @return url
   */
  function twitter(data) {
    return ENDPOINTS.twitter + _generateUrlParams(data);
  }

  /* Compose the share on pinterest url string.
   * @argument data [Object] <required>
   * @argument data.url <required>
   * @argument data.media <required>
   * @argument data.description <required>
   * @info https://developers.pinterest.com/pin_it/
   * @return url
   */
  function pinterest(data) {
    return ENDPOINTS.pinterest + _generateUrlParams(data);
  }

  /* Compose the submit to reddit url string.
   * @argument data [Object] <required>
   * @argument data.url <required>
   * @argument data.title <optional>
   * @argument data.text <optional>
   * @info http://www.reddit.com/buttons/
   * @return url
   */
  function reddit(data) {
    return ENDPOINTS.reddit + _generateUrlParams(data);
  }

  /* Compose the share article on linkedin url string.
   * @argument data [Object] <required>
   * @argument data.url [String, 1024] <required> The url-encoded URL of the page that you wish to share.
   * @info https://developer.linkedin.com/docs/share-on-linkedin
   * @return url
   */
  function linkedin(data) {
    return ENDPOINTS.linkedin + _generateUrlParams(data);
  }

  /* Compose the send email url string.
   * @argument data [Object] <required>
   * @argument to [String] <required>
   * @argument subject [String] <optional>
   * @argument cc [String] <optional>
   * @argument bcc [String] <optional>
   * @argument body [String] <optional>
   * @info https://developer.mozilla.org/en-US/docs/Web/Guide/HTML/Email_links
   * @return url
   */
  function email(data) {
    var to = data.to;
    delete data.to;
    var params = _generateUrlParams(data);
    return 'mailto:' + (params.length ? (to + '?' + params) : to);
  }
}));
<|endoftext|>


<commit_before>/**
 * unassertify
 *   Browserify transform to remove assertions on production build
 *
 * https://github.com/twada/unassertify
 *
 * Copyright (c) 2015 Takuto Wada
 * Licensed under the MIT license.
 *   http://twada.mit-license.org/
 */
'use strict';

var through = require('through');
var esprima = require('esprima');
var escodegen = require('escodegen');
var unassert = require('unassert');

function isDebugMode (options) {
    return (options && options._flags && options._flags.debug);
}

function applyUnassert (code, options) {
    var ast = esprima.parse(code);
    return escodegen.generate(unassert(ast));
}

module.exports = function unassertify (filepath, options) {
    if (isDebugMode(options)) {
        return through();
    }

    var data = '',
        stream = through(write, end);

    function write(buf) {
        data += buf;
    }

    function end() {
        stream.queue(applyUnassert(data, options));
        stream.queue(null);
    }

    return stream;
};
<commit_msg>chore(unassertify): add sourceType option<commit_after>/**
 * unassertify
 *   Browserify transform to remove assertions on production build
 *
 * https://github.com/twada/unassertify
 *
 * Copyright (c) 2015 Takuto Wada
 * Licensed under the MIT license.
 *   http://twada.mit-license.org/
 */
'use strict';

var through = require('through');
var esprima = require('esprima');
var escodegen = require('escodegen');
var unassert = require('unassert');

function isDebugMode (options) {
    return (options && options._flags && options._flags.debug);
}

function applyUnassert (code, options) {
    var ast = esprima.parse(code, { sourceType: 'module' });
    return escodegen.generate(unassert(ast));
}

module.exports = function unassertify (filepath, options) {
    if (isDebugMode(options)) {
        return through();
    }

    var data = '',
        stream = through(write, end);

    function write(buf) {
        data += buf;
    }

    function end() {
        stream.queue(applyUnassert(data, options));
        stream.queue(null);
    }

    return stream;
};
<|endoftext|>


<commit_before>var /**
     * @private
     * @type {Object}
     */
    db = require('./db.json'),
    /**
     * @private
     * @const
     * @type {String}
     */
    SEP = '/';

module.exports = {
    /**
     * @param {String} mime - contentType header value
     * @returns {String} - 'text', 'application', 'image', 'video', 'audio' or false
     */
    lookup: function mimeFormatLookup (mime) {
        return mime && (mime = String(mime)) && (mime = mime.replace(/^\s*?([^;\s]+).*$/g, '$1')) && db[mime] || {
            type: (mime = mime.split(SEP)) && mime[0],
            format: 'raw'
        };
    }
};
<commit_msg>Added a `guess` function to guess format when lookup failed<commit_after>var /**
     * @private
     * @type {Object}
     */
    db = require('./db.json'),
    /**
     * @private
     * @const
     * @type {String}
     */
    SEP = '/';

module.exports = {
    /**
     * Attempts to guess the format by analysing mime type and not a db lookup
     *
     * @param {String} mime - contentType header value
     *
     * @returns {Object}
     */
    guess: function (mime) {
        var match = mime.match(/(jsonp|json|[a-z]{1,2}ml|script)/),
            format = match && match[1];

        return format ? {
            type: 'text',
            format: format,
            guessed: true
        } : { // default is `raw` for all unknown stuff
            type: (mime = mime.split(SEP)) && mime[0],
            format: 'raw',
            guessed: true
        };
    },
    /**
     * @param {String} mime - contentType header value
     * @returns {Object}
     */
    lookup: function mimeFormatLookup (mime) {
        return mime && (mime = String(mime)) && (mime = mime.replace(/^\s*?([^;\s]+).*$/g, '$1')) && db[mime] ||
            module.exports.guess(mime);
    }
};
<|endoftext|>


<commit_before>module.exports = function (config) {
    'use strict';
    var gutil = require('gulp-util');

    let _createBlockClass,
        _createElemClass,
        _createModClass,
        _createMixClass,
        _createClassList,
        _assignClassList;

    config = config ||
        {
            elemPrefix: '__',
            modPrefix: '_',
            modDlmtr: '_'
        };

    _createBlockClass = function (block) {
        return block;
    };

    _createElemClass = function (blockClass, elemName) {
        return blockClass + config.elemPrefix + elemName;
    };

    _createModClass = function (baseClass, mods) {
        var className = '',
            modClass;
        mods
            .replace(/\s{2,}/g, ' ') // remove more than one whitespace
            .replace(/\:\s?/g, config.modDlmtr) // remove whitespace after the semicolon
            .split(' ')
            .forEach(function (mod) {
                modClass = baseClass + config.modPrefix + mod;
                className += ' ' + modClass;
            });
        return className;
    };

    _createMixClass = function (baseClass, mix) {
        let mixClass = '',
            block,
            elem,
            mods,
            mixes,
            blockRegExp = /block\:([\S]*)\b/g,
            elemRegExp = /elem\:([\S]*)\b/g,
            modRegExp = /mods\:\[(.*)\]/g;

        mixes = mix
                .replace(/\s{2,}/g, ' ') // remove more than one whitespace
                .replace(/\:\s/g, ':'); // remove whitespace after the semicolon

            block = blockRegExp.exec(mixes) || [];
            elem = elemRegExp.exec(mixes) || [];
            mods = modRegExp.exec(mixes) || [];

            if (!block) {
                gutil.log("Please add block attribute to a mix definition: ", mixes);
            }

            mixClass = _createClassList({
                block: block[1],
                elem: elem[1],
                mods: mods[1],
                mix: ''
            });

            return ' ' + mixClass;
    };

    _createClassList = function (selector) {
        var result = '',
            block,
            elem;

        if (selector.block && !selector.elem) {
            block = _createBlockClass(selector.block);
            result = block;
        }

        if (selector.block && selector.elem) {
            elem = _createElemClass(selector.block, selector.elem);
            result = elem;
        }

        if (selector.mods) {
            result += _createModClass(result, selector.mods);
        }

        if (selector.mix) {
            result += _createMixClass(result, selector.mix);
        }

        return result;
    };

    _assignClassList = function (attributes, node) {
        var classes,
            classSet = {
                        block: '',
                        elem: '',
                        mod: '',
                        mix: ''
                    };

        ['block', 'elem', 'mods', 'mix'].forEach(function (attr) {
            if (attr in attributes) {
                classSet[attr] = attributes[attr];
                delete node.attrs[attr];
            }
        });

        classes = _createClassList(classSet);

        if (classes) {
            node.attrs.class = classes;
            return classSet;
        };
    };

    return function posthtmlBem(tree) {
        tree.match({attrs: {block: true}}, function (node) {
            var nodeAttrs;

            nodeAttrs = _assignClassList(node.attrs, node);

            if (node.content && Array.isArray(node.content)) {
                node.content.forEach(function (children) {
                    if (children.tag && children.attrs.elem && !children.attrs.block) {
                        children.attrs.block = nodeAttrs.block;
                    }
                });
                return node;
            }
            return node;
        });
        return tree;
    };
};
<commit_msg>excess return<commit_after>module.exports = function (config) {
    'use strict';
    var gutil = require('gulp-util');

    let _createBlockClass,
        _createElemClass,
        _createModClass,
        _createMixClass,
        _createClassList,
        _assignClassList;

    config = config ||
        {
            elemPrefix: '__',
            modPrefix: '_',
            modDlmtr: '_'
        };

    _createBlockClass = function (block) {
        return block;
    };

    _createElemClass = function (blockClass, elemName) {
        return blockClass + config.elemPrefix + elemName;
    };

    _createModClass = function (baseClass, mods) {
        var className = '',
            modClass;
        mods
            .replace(/\s{2,}/g, ' ') // remove more than one whitespace
            .replace(/\:\s?/g, config.modDlmtr) // remove whitespace after the semicolon
            .split(' ')
            .forEach(function (mod) {
                modClass = baseClass + config.modPrefix + mod;
                className += ' ' + modClass;
            });
        return className;
    };

    _createMixClass = function (baseClass, mix) {
        let mixClass = '',
            block,
            elem,
            mods,
            mixes,
            blockRegExp = /block\:([\S]*)\b/g,
            elemRegExp = /elem\:([\S]*)\b/g,
            modRegExp = /mods\:\[(.*)\]/g;

        mixes = mix
                .replace(/\s{2,}/g, ' ') // remove more than one whitespace
                .replace(/\:\s/g, ':'); // remove whitespace after the semicolon

            block = blockRegExp.exec(mixes) || [];
            elem = elemRegExp.exec(mixes) || [];
            mods = modRegExp.exec(mixes) || [];

            if (!block) {
                gutil.log("Please add block attribute to a mix definition: ", mixes);
            }

            mixClass = _createClassList({
                block: block[1],
                elem: elem[1],
                mods: mods[1],
                mix: ''
            });

            return ' ' + mixClass;
    };

    _createClassList = function (selector) {
        var result = '',
            block,
            elem;

        if (selector.block && !selector.elem) {
            block = _createBlockClass(selector.block);
            result = block;
        }

        if (selector.block && selector.elem) {
            elem = _createElemClass(selector.block, selector.elem);
            result = elem;
        }

        if (selector.mods) {
            result += _createModClass(result, selector.mods);
        }

        if (selector.mix) {
            result += _createMixClass(result, selector.mix);
        }

        return result;
    };

    _assignClassList = function (attributes, node) {
        var classes,
            classSet = {
                        block: '',
                        elem: '',
                        mod: '',
                        mix: ''
                    };

        ['block', 'elem', 'mods', 'mix'].forEach(function (attr) {
            if (attr in attributes) {
                classSet[attr] = attributes[attr];
                delete node.attrs[attr];
            }
        });

        classes = _createClassList(classSet);

        if (classes) {
            node.attrs.class = classes;
            return classSet;
        };
    };

    return function posthtmlBem(tree) {
        tree.match({attrs: {block: true}}, function (node) {
            var nodeAttrs;

            nodeAttrs = _assignClassList(node.attrs, node);

            if (node.content && Array.isArray(node.content)) {
                node.content.forEach(function (children) {
                    if (children.tag && children.attrs.elem && !children.attrs.block) {
                        children.attrs.block = nodeAttrs.block;
                    }
                });
            }
            return node;
        });
        return tree;
    };
};
<|endoftext|>


<commit_before>var through = require('through2');
var gutil = require('gulp-util');
var pathModule = require('path');
var jsStringEscape = require('js-string-escape');
var fs = require('fs');
var PluginError = gutil.PluginError;
var Minimize = require('minimize');

// Constants
const PLUGIN_NAME = 'angular-include-template';

module.exports = function (options) {
    options = options || {};
    if (!options.minimize) {
        options.minimize = {};
    }
    if (options.brakeOnErrors === undefined) {
        options.brakeOnErrors = true;
    }

    const DIRECTIVE_SUFFIX = 'r-directive.js';

    function isDirective(filename) {
        var position = filename.length - DIRECTIVE_SUFFIX.length;
        var lastIndex = filename.indexOf(DIRECTIVE_SUFFIX, position);
        return lastIndex !== -1 && lastIndex === position;
    }

    var minimizer = new Minimize(options.minimize);

    const TEMPLATE_PATTERN = /templateUrl:[\W]*['"]([^'"]+)['"]/;
    const CODE_EXIT = 0;
    const CODE_CAN_GO_NEXT = 1;

    /**
     * replace one template url with minified template text
     * @param {String} base
     * @param {String} content
     * @param {Function} cb
     */
    function replace(base, content, cb) {
        var matches = TEMPLATE_PATTERN.exec(content);

        console.log('matches: ' + matches);

        if (matches === null) {
            cb(CODE_EXIT, content);
            return;
        }

        var relativeTemplatePath = matches[1];
        var path = pathModule.join(base, relativeTemplatePath);

        console.log('template path: ' + path);

        fs.readFile(path, {encoding: 'utf8'}, function(err, templateContent) {
            if (err) {
                var errMsg = 'Can\'t open file: ' + path + ', error: ' + err;
                if (options.brakeOnErrors) {
                    // TODO: check
                    throw new PluginError(PLUGIN_NAME, errMsg);
                } else {
                    gutil.log(PLUGIN_NAME, '[WARN]', gutil.colors.magenta(errMsg));
                    cb(CODE_EXIT, content);
                    return;
                }
            }

            console.log('templateContent: ' + templateContent);

            minimizer.parse(templateContent, function (err, minifiedContent) {
                if (err) {
                    var errMsg = 'error while minifying ' + path + '. Error from minimize plugin: ' + err;
                    if (options.brakeOnErrors) {
                        throw new PluginError(PLUGIN_NAME, errMsg);
                    } else {
                        gutil.log(PLUGIN_NAME, '[WARN]', gutil.colors.magenta(errMsg));
                        cb(CODE_EXIT, content);
                        return;
                    }
                }

                var before = content.substr(0, matches.index);
                var template = jsStringEscape(minifiedContent);
                var after = content.substr(matches.index + matches[0].length);
                var newContent = before + 'template:\'' + template + '\'' + after;

                console.log('newContent: ' + newContent);

                cb(CODE_CAN_GO_NEXT, newContent);
            });
        });
    }

    function transform(file, enc, cb) {
        // ignore empty files
        if (file.isNull()) {
            cb(null, file);
            return;
        }

        if (file.isStream()) {
            throw new PluginError(PLUGIN_NAME, 'Streaming not supported. particular file: ' + file.path);
        }

        // check that file name ends with '-directive.js'
        if (!isDirective(file.path)) {
            cb(null, file);
            return;
        }

        console.log('file.path: ' + file.path);

        var content = file.contents.toString('utf8');
        var base = pathModule.dirname(file.path);
        replace(base, content, replaceCallback);

        function replaceCallback(code, content) {
            if (code === CODE_CAN_GO_NEXT) {
                replace(base, content, replaceCallback);
                return;
            }
            // code === CODE_EXIT
            file.contents = new Buffer(content);
            cb(null, file);
        }
    }

    return through.obj(transform);
};<commit_msg>improved performance moving from string concatenation to Buffer.concat<commit_after>var through = require('through2');
var gutil = require('gulp-util');
var pathModule = require('path');
var jsStringEscape = require('js-string-escape');
var fs = require('fs');
var PluginError = gutil.PluginError;
var Minimize = require('minimize');

// Constants
const PLUGIN_NAME = 'angular-include-template';

module.exports = function (options) {
    options = options || {};
    if (!options.minimize) {
        options.minimize = {};
    }
    if (options.brakeOnErrors === undefined) {
        options.brakeOnErrors = true;
    }

    var minimizer = new Minimize(options.minimize);

    // regexp uses 'g' flag to be able to match several occurrences
    // so it should be reset for each file
    const TEMPLATE_URL_PATTERN = 'templateUrl:[\\s]*[\'"]([^\'"]+)[\'"]';

    // variables which reset for each file
    var content;
    var templateUrlRegexp;

    const FOUND_SUCCESS = {};
    const FOUND_ERROR = {};
    const CODE_EXIT = {};

    const TEMPLATE_BEGIN = Buffer('template:\'');
    const TEMPLATE_END = Buffer('\'');

    /**
     * replace one template url with minified template text
     * @param {String} filePath
     * @param {Function} cb
     */
    function replace(filePath, cb) {
        var matches = templateUrlRegexp.exec(content);

        console.log('matches: ' + matches);

        if (matches === null) {
            cb(CODE_EXIT);
            return;
        }

        var relativeTemplatePath = matches[1];
        var path = pathModule.join(filePath, relativeTemplatePath);

        console.log('template path: ' + path);

        fs.readFile(path, {encoding: 'utf8'}, function(err, templateContent) {
            if (err) {
                var errMsg = 'Can\'t open file: ' + path + ', error: ' + err;
                if (options.brakeOnErrors) {
                    // TODO: check
                    throw new PluginError(PLUGIN_NAME, errMsg);
                } else {
                    gutil.log(PLUGIN_NAME, '[WARN]', gutil.colors.magenta(errMsg));
                    cb(FOUND_ERROR);
                    return;
                }
            }

            minimizer.parse(templateContent, function (err, minifiedContent) {
                if (err) {
                    var errMsg = 'error while minifying ' + path + '. Error from minimize plugin: ' + err;
                    if (options.brakeOnErrors) {
                        throw new PluginError(PLUGIN_NAME, errMsg);
                    } else {
                        gutil.log(PLUGIN_NAME, '[WARN]', gutil.colors.magenta(errMsg));
                        cb(FOUND_ERROR);
                        return;
                    }
                }

                cb(FOUND_SUCCESS, {
                    regexpMatch : matches,
                    template: minifiedContent
                });
            });
        });
    }

    function joinParts(entrances) {
        var parts = [];
        var index = 0;
        for (var i=0; i<entrances.length; i++) {
            var entrance = entrances[i];
            var matches = entrance.regexpMatch;

            parts.push(Buffer(content.substring(index, matches.index)));
            parts.push(TEMPLATE_BEGIN);
            parts.push(Buffer(jsStringEscape(entrance.template)));
            parts.push(TEMPLATE_END);

            index = matches.index + matches[0].length;
        }
        parts.push(Buffer(content.substr(index)));
        return Buffer.concat(parts);
    }

    function transform(file, enc, cb) {
        // ignore empty files
        if (file.isNull()) {
            cb(null, file);
            return;
        }

        if (file.isStream()) {
            throw new PluginError(PLUGIN_NAME, 'Streaming not supported. particular file: ' + file.path);
        }

        content = file.contents.toString('utf8');
        templateUrlRegexp = new RegExp(TEMPLATE_URL_PATTERN, 'g');
        var entrances = [];

        console.log('file.path: ' + file.path);

        var base = pathModule.dirname(file.path);
        replace(base, replaceCallback);

        function replaceCallback(code, entrance) {
            if (code === FOUND_SUCCESS) {
                entrances.push(entrance);
                replace(base, replaceCallback);
                return;
            }

            if (code === FOUND_ERROR) {
                replace(base, replaceCallback);
                return
            }

            /* if (code === CODE_EXIT) */
            if (entrances.length) {
                file.contents = joinParts(entrances);
            }

            cb(null, file);
        }
    }

    return through.obj(transform);
};<|endoftext|>


<commit_before>'use strict';

const recast = require(`recast`);
const bluebird = require(`bluebird`);
const fs = bluebird.promisifyAll(require(`fs`));
const path = require(`path`);
const builders = recast.types.builders;

function processScript(script) {
    const includeNodes = [];
    const ast = recast.parse(script);

    recast.visit(ast, {
        visitExpressionStatement: function(p) {
            if (
                p.node.expression &&
                p.node.expression.callee &&
                p.node.expression.callee.name === 'include'
            ) {
                includeNodes.push(p);
            }

            this.traverse(p);
        }
    });

    const includePromises = includeNodes.map((p) => {
        const filePath = path.join(path.dirname(process.argv[2]), p.node.expression.arguments[0].value);

        return fs.readFileAsync(filePath, `utf8`).catch((err) => {
            return bluebird.reject(new Error(`Error when reading ${filePath}. Error given: ${err}`));
        }).then((file) => {
            return processScript(file);
        }).then(({ast: subAst, includes: subIncludes}) => {
            p.replace(
                builders.expressionStatement(
                    builders.callExpression(
                        builders.functionExpression(
                            null,
                            [],
                            builders.blockStatement(subAst.program.body),
                            false,
                            false
                        ),
                        []
                    )
                )
            );

            return [filePath, ...subIncludes];
        });
    });

    return bluebird.all(includePromises).reduce((includes = [], subIncludes) => {
        return includes.concat(...subIncludes);
    }).then((includes = []) => {
        return {ast, includes};
    });
}

module.exports = {
    run: (script, callback) => {
        const newScript = processScript(script).then(({ast, includes}) => {
            return {
                code: recast.print(ast).code,
                includes
            };
        });

        if (typeof callback === `undefined`) {
            return newScript;
        }

        newScript.then(({code, includes}) => {
            callback(null, includes, code)
        }).catch((err) => {
            callback(err);
        });
    },

    runFile: (path, outputPath, callback) => {
        if (typeof outputPath === `function`) {
            callback = options;
            outputPath = undefined;
        }

        const runFilePromise = fs.readFileAsync(path, `utf8`).catch((err) => {
            return bluebird.reject(new Error(`Error when reading ${path}. Error given: ${err}`));
        }).then((script) => {
            return processScript(script);
        }).then(({ast, includes}) => {
            const code = recast.print(ast).code
            if (!outputPath) {
                return bluebird.resolve([includes, code]);
            }

            return bluebird.all([
                includes,
                code,
                fs.writeFileAsync(outputPath, code).catch((err) => {
                    return bluebird.reject(new Error(`Error when writing ${outputPath}. Error given: ${err}`));
                })
            ]);
        }).then(([includes, code]) => {
            return bluebird.resolve({includes, code});
        });

        if (typeof callback === `undefined`) {
            return runFilePromise;
        }

        runFilePromise.then(({includes, code}) => {
            callback(null, includes, code);
        }).catch((err) => {
            callback(err);
        })
    }
}
<commit_msg>Remove accidental process.argv[2] and add a basepath<commit_after>'use strict';

const recast = require(`recast`);
const bluebird = require(`bluebird`);
const fs = bluebird.promisifyAll(require(`fs`));
const path = require(`path`);
const builders = recast.types.builders;

function processScript(script, basePath) {
    const includeNodes = [];
    const ast = recast.parse(script);

    recast.visit(ast, {
        visitExpressionStatement: function(p) {
            if (
                p.node.expression &&
                p.node.expression.callee &&
                p.node.expression.callee.name === 'include'
            ) {
                includeNodes.push(p);
            }

            this.traverse(p);
        }
    });

    const includePromises = includeNodes.map((p) => {
        const filePath = path.join(basePath, p.node.expression.arguments[0].value);

        return fs.readFileAsync(filePath, `utf8`).catch((err) => {
            return bluebird.reject(new Error(`Error when reading ${filePath}. Error given: ${err}`));
        }).then((file) => {
            return processScript(file, basePath);
        }).then(({ast: subAst, includes: subIncludes}) => {
            p.replace(
                builders.expressionStatement(
                    builders.callExpression(
                        builders.functionExpression(
                            null,
                            [],
                            builders.blockStatement(subAst.program.body),
                            false,
                            false
                        ),
                        []
                    )
                )
            );

            return [filePath, ...subIncludes];
        });
    });

    return bluebird.all(includePromises).reduce((includes = [], subIncludes) => {
        return includes.concat(...subIncludes);
    }).then((includes = []) => {
        return {ast, includes};
    });
}

module.exports = {
    run: (script, basePath, callback) => {
        if (typeof basePath === `function`) {
            callback = basePath;
            basePath = ``;
        }

        const newScript = processScript(script, basePath).then(({ast, includes}) => {
            return {
                code: recast.print(ast).code,
                includes
            };
        });

        if (typeof callback === `undefined`) {
            return newScript;
        }

        newScript.then(({code, includes}) => {
            callback(null, includes, code)
        }).catch((err) => {
            callback(err);
        });
    },

    runFile: (inputPath, outputPath, callback) => {
        if (typeof outputPath === `function`) {
            callback = outputPath;
            outputPath = undefined;
        }

        const runFilePromise = fs.readFileAsync(inputPath, `utf8`).catch((err) => {
            return bluebird.reject(new Error(`Error when reading ${inputPath}. Error given: ${err}`));
        }).then((script) => {
            return processScript(script, path.dirname(inputPath));
        }).then(({ast, includes}) => {
            const code = recast.print(ast).code
            if (!outputPath) {
                return bluebird.resolve([includes, code]);
            }

            return bluebird.all([
                includes,
                code,
                fs.writeFileAsync(outputPath, code).catch((err) => {
                    return bluebird.reject(new Error(`Error when writing ${outputPath}. Error given: ${err}`));
                })
            ]);
        }).then(([includes, code]) => {
            return bluebird.resolve({includes, code});
        });

        if (typeof callback === `undefined`) {
            return runFilePromise;
        }

        runFilePromise.then(({includes, code}) => {
            callback(null, includes, code);
        }).catch((err) => {
            callback(err);
        })
    }
}
<|endoftext|>


<commit_before>const server = require('./server');
const registerCron = require('./cron');

const port = process.env.PORT || 3000;
server.init().listen(port, () => {
	console.log(`Server is up! Listening on ${port}.`);
	registerCron();
});<commit_msg>fixup! added a cron job to crawl headlines every hour<commit_after>require('./cron')();
const server = require('./server');

const port = process.env.PORT || 3000;
server.init().listen(port, () => {
	console.log(`Server is up! Listening on ${port}.`);
});<|endoftext|>


<commit_before>'use strict';

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

exports.errors = require('./lib/errors');

exports.inprocessTransport = require('./lib/inprocess_transport');

exports.channelPrototype = function () {
	var self = Object.create(EventEmitter.prototype);
	EventEmitter.init.call(self);
	var transportMatcher = exports.createSingleMatcher();
	var singleHandlerMatchers = Object.create(null);
	var multiHandlerMatchers = Object.create(null);

	self.use = function (pattern, transportFactory) {
		var transport = transportFactory(self);
		transportMatcher.add(pattern, transport);
	};

	self.findSingle = function (key, pattern) {
		var matcher = singleHandlerMatchers[key];
		if (!matcher) {
			return null;
		}
		return matcher.find(pattern);
	};

	self.addSingle = function (key, pattern, fn) {
		var matcher = singleHandlerMatchers[key];
		if (!matcher) {
			matcher = singleHandlerMatchers[key] = exports.createSingleMatcher();
		}
		if (matcher.find(pattern)) {
			return false;
		}
		matcher.add(pattern, fn);
		return true;
	};

	self.removeSingle = function (key, pattern) {
		var matcher = singleHandlerMatchers[key];
		if (!matcher) {
			return false;
		}
		if (matcher.find(pattern)) {
			matcher.remove(pattern);
			return true;
		}
		return false;
	};

	self.findMulti = function (key, pattern) {
		var matcher = multiHandlerMatchers[key];
		if (!matcher) {
			return [];
		}
		return matcher.find(pattern) || [];
	};

	self.addMulti = function (key, pattern, fn) {
		var matcher = multiHandlerMatchers[key];
		if (!matcher) {
			matcher = multiHandlerMatchers[key] = exports.createMultiMatcher();
		}
		matcher.add(pattern, fn);
		return true;
	};

	self.removeMulti = function (key, pattern, fn) {
		var i;
		var matcher = multiHandlerMatchers[key];
		if (!matcher) {
			return false;
		}
		var handlers = matcher.find(pattern);
		if (!handlers) {
			return false;
		}
		i = handlers.indexOf(fn);
		if (i < 0) {
			return false;
		}
		handlers.splice(i, 1);
		return true;
	};

	self.findTransport = function (pattern) {
		return transportMatcher.find(pattern);
	};

	self.notifyError = function (err) {
		self.emit('error', err);
	};

	return self;
};

exports.eventChannel = function () {
	var self = Object.create(exports.channelPrototype());

	self.broadcast = function (pattern, payload) {
		var transport = self.findTransport(pattern);
		return transport.broadcast(pattern, payload);
	};

	self.observe = function (pattern, observer) {
		if (typeof observer !== 'function') {
			throw new Error('observe() expects a function as the second argument.');
		}
		var transport = self.findTransport(pattern);
		return transport.observe(pattern, observer);
	};

	self.remove = function (pattern, observer) {
		var transport = self.findTransport(pattern);
		return transport.removeObserver(pattern, observer);
	};

	return self;
};

exports.commandChannel = function () {
	var self = Object.create(exports.channelPrototype());

	self.send = function (pattern, payload) {
		var transport = self.findTransport(pattern);
		return transport.send(pattern, payload);
	};

	self.receive = function (pattern, handler) {
		if (typeof handler !== 'function') {
			throw new Error('receive() expects a function as the second argument.');
		}
		var transport = self.findTransport(pattern);
		return transport.addHandler(pattern, handler);
	};

	self.remove = function (pattern, handler) {
		var transport = self.findTransport(pattern);
		return transport.removeHandler(pattern, handler);
	};

	return self;
};

exports.requestChannel = function () {
	var self = Object.create(exports.channelPrototype());

	self.request = function (pattern, payload) {
		var transport = self.findTransport(pattern);
		return transport.request(pattern, payload);
	};

	self.reply = function (pattern, handler) {
		if (typeof handler !== 'function') {
			throw new Error('reply() expects a function as the second argument.');
		}
		var transport = self.findTransport(pattern);
		return transport.registerHandler(pattern, handler);
	};

	self.remove = function (pattern, handler) {
		var transport = self.findTransport(pattern);
		return transport.unregisterHandler(pattern, handler);
	};

	return self;
};

exports.createSingleMatcher = function () {
	return patrun({gex: true});
};

exports.createMultiMatcher = function () {
	return patrun(function (pattern, fn) {
		var api = Object.create(null);
		var keyLength = Object.keys(pattern).length;
		var items = this.find(pattern) || [];
		items.push(fn);

		api.find = function (pat) {
			if (Object.keys(pat).length > keyLength) {
				return null;
			}
			return items.length > 0 ? items : null;
		};

		api.remove = function () {
			items.pop();
			return items.length === 0;
		};

		return api;
	});
};
<commit_msg>new pattern matching is not working yet<commit_after>'use strict';

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

exports.errors = require('./lib/errors');

exports.inprocessTransport = require('./lib/inprocess_transport');

exports.channelPrototype = function () {
	var self = Object.create(EventEmitter.prototype);
	EventEmitter.init.call(self);
	var transportMatcher = exports.createSingleMatcher();
	var singleHandlerMatchers = Object.create(null);
	var multiHandlerMatchers = Object.create(null);

	self.use = function (pattern, transportFactory) {
		var transport = transportFactory(self);
		transportMatcher.add(pattern, transport);
	};

	self.findSingle = function (key, pattern) {
		var matcher = singleHandlerMatchers[key];
		if (!matcher) {
			return null;
		}
		return matcher.find(pattern)[0];
	};

	self.addSingle = function (key, pattern, fn) {
		var matcher = singleHandlerMatchers[key];
		if (!matcher) {
			matcher = singleHandlerMatchers[key] = exports.PatternMatcher.create();
		}
		if (matcher.exists(pattern)) {
			return false;
		}
		matcher.add(pattern, fn);
		return true;
	};

	self.removeSingle = function (key, pattern) {
		var matcher = singleHandlerMatchers[key];
		if (!matcher) {
			return false;
		}
		if (matcher.exists(pattern)) {
			matcher.remove(pattern);
			return true;
		}
		return false;
	};

	self.findMulti = function (key, pattern) {
		var matcher = multiHandlerMatchers[key];
		if (!matcher) {
			return [];
		}
		return matcher.find(pattern);
	};

	self.addMulti = function (key, pattern, fn) {
		var matcher = multiHandlerMatchers[key];
		if (!matcher) {
			matcher = multiHandlerMatchers[key] = exports.PatternMatcher.create();
		}
		matcher.add(pattern, fn);
		return true;
	};

	self.removeMulti = function (key, pattern, fn) {
		var matcher = multiHandlerMatchers[key];
		if (!matcher) {
			return false;
		}
		return matcher.remove(pattern, fn);
	};

	self.findTransport = function (pattern) {
		return transportMatcher.find(pattern);
	};

	self.notifyError = function (err) {
		self.emit('error', err);
	};

	return self;
};

exports.eventChannel = function () {
	var self = Object.create(exports.channelPrototype());

	self.broadcast = function (pattern, payload) {
		var transport = self.findTransport(pattern);
		return transport.broadcast(pattern, payload);
	};

	self.observe = function (pattern, observer) {
		if (typeof observer !== 'function') {
			throw new Error('observe() expects a function as the second argument.');
		}
		var transport = self.findTransport(pattern);
		return transport.observe(pattern, observer);
	};

	self.remove = function (pattern, observer) {
		var transport = self.findTransport(pattern);
		return transport.removeObserver(pattern, observer);
	};

	return self;
};

exports.commandChannel = function () {
	var self = Object.create(exports.channelPrototype());

	self.send = function (pattern, payload) {
		var transport = self.findTransport(pattern);
		return transport.send(pattern, payload);
	};

	self.receive = function (pattern, handler) {
		if (typeof handler !== 'function') {
			throw new Error('receive() expects a function as the second argument.');
		}
		var transport = self.findTransport(pattern);
		return transport.addHandler(pattern, handler);
	};

	self.remove = function (pattern, handler) {
		var transport = self.findTransport(pattern);
		return transport.removeHandler(pattern, handler);
	};

	return self;
};

exports.requestChannel = function () {
	var self = Object.create(exports.channelPrototype());

	self.request = function (pattern, payload) {
		var transport = self.findTransport(pattern);
		return transport.request(pattern, payload);
	};

	self.reply = function (pattern, handler) {
		if (typeof handler !== 'function') {
			throw new Error('reply() expects a function as the second argument.');
		}
		var transport = self.findTransport(pattern);
		return transport.registerHandler(pattern, handler);
	};

	self.remove = function (pattern, handler) {
		var transport = self.findTransport(pattern);
		return transport.unregisterHandler(pattern, handler);
	};

	return self;
};

exports.createSingleMatcher = function () {
	return patrun({gex: true});
};

exports.createMultiMatcher = function () {
	return patrun(function (pattern, fn) {
		var api = Object.create(null);
		var keyLength = Object.keys(pattern).length;
		var items = this.find(pattern) || [];
		items.push(fn);

		api.find = function (pat) {
			if (Object.keys(pat).length > keyLength) {
				return null;
			}
			return items.length > 0 ? items : null;
		};

		api.remove = function () {
			items.pop();
			return items.length === 0;
		};

		return api;
	});
};

function PatternMatcher() {
	this.index = Object.create(null);
}

exports.PatternMatcher = PatternMatcher;

PatternMatcher.prototype.add = function (objectPattern, object) {
	var stringPattern = this.patternToString(objectPattern);
	var list = this.index[stringPattern];
	if (!list) {
		list = this.index[stringPattern] = [];
	}
	list.push(object);
};

PatternMatcher.prototype.find = function (objectPattern) {
	var stringPattern = this.patternToString(objectPattern);
	var index = this.index;

	return Object.keys(index).reduce(function (matches, pattern) {
		if (stringPattern.indexOf(pattern)) {
			matches = matches.concat(index[pattern]);
		}
		return matches;
	}, []);
};

PatternMatcher.prototype.exists = function (objectPattern) {
	var stringPattern = this.patternToString(objectPattern);
	return Boolean(this.index[stringPattern]);
};

PatternMatcher.prototype.remove = function (objectPattern, object) {
	var stringPattern = this.patternToString(objectPattern);
	var matches;
	var i;

	if (typeof object === 'undefined' && this.index.hasOwnProperty(stringPattern)) {
		delete this.index[stringPattern];
		return true;
	}

	matches = this.find(objectPattern);
	i = matches.indexOf(object);
	if (i >= 0) {
		matches.splice(i, 1);
		return true;
	}

	return false;
};

PatternMatcher.prototype.patternToString = function (objectPattern) {
	var self = this;
	if (objectPattern && typeof objectPattern === 'object') {
		return Object.keys(objectPattern).sort().map(function (key) {
			return key + ':' + self.objectToString(objectPattern[key]);
		}).join();
	}
	return this.objectToString(objectPattern);
};

PatternMatcher.prototype.objectToString = function (object) {
	if (typeof object === 'string') {
		return object;
	}
	if (typeof object === 'boolean' || (typeof object === 'number' && !isNaN(object))) {
		return object.toString();
	}
	if (object && (typeof object === 'object' || typeof object === 'function')) {
		return Object.prototype.call(object);
	}
	if (object === null || typeof object === 'undefined' || isNaN(object)) {
		return 'null';
	}
	return Object.prototype.toString.call(object);
};

PatternMatcher.create = function () {
	return new PatternMatcher();
};
<|endoftext|>


<commit_before>
/**
 * Module dependencies.
 */

var Emitter = require('events').EventEmitter;
var parser = require('socket.io-parser');

/**
 * Module exports.
 */

module.exports = Adapter;

/**
 * Memory adapter constructor.
 *
 * @param {Namespace} nsp
 * @api public
 */

function Adapter(nsp){
  this.nsp = nsp;
  this.rooms = {};
  this.sids = {};
  this.encoder = new parser.Encoder();
}

/**
 * Inherits from `EventEmitter`.
 */

Adapter.prototype.__proto__ = Emitter.prototype;

/**
 * Adds a socket to a room.
 *
 * @param {String} socket id
 * @param {String} room name
 * @param {Function} callback
 * @api public
 */

Adapter.prototype.add = function(id, room, fn){
  this.sids[id] = this.sids[id] || {};
  this.sids[id][room] = true;
  this.rooms[room] = this.rooms[room] || Room();
  this.rooms[room].add(id);
  if (fn) process.nextTick(fn.bind(null, null));
};

/**
 * Removes a socket from a room.
 *
 * @param {String} socket id
 * @param {String} room name
 * @param {Function} callback
 * @api public
 */

Adapter.prototype.del = function(id, room, fn){
  this.sids[id] = this.sids[id] || {};
  delete this.sids[id][room];
  if (this.rooms.hasOwnProperty(room)) {
    this.rooms[room].del(id);
    if (this.rooms[room].length === 0) delete this.rooms[room];
  }

  if (fn) process.nextTick(fn.bind(null, null));
};

/**
 * Removes a socket from all rooms it's joined.
 *
 * @param {String} socket id
 * @param {Function} callback
 * @api public
 */

Adapter.prototype.delAll = function(id, fn){
  var rooms = this.sids[id];
  if (rooms) {
    for (var room in rooms) {
      if (this.rooms.hasOwnProperty(room)) {
        this.rooms[room].del(id);
        if (this.rooms[room].length === 0) delete this.rooms[room];
      }
    }
  }
  delete this.sids[id];

  if (fn) process.nextTick(fn.bind(null, null));
};

/**
 * Broadcasts a packet.
 *
 * Options:
 *  - `flags` {Object} flags for this packet
 *  - `except` {Array} sids that should be excluded
 *  - `rooms` {Array} list of rooms to broadcast to
 *
 * @param {Object} packet object
 * @api public
 */

Adapter.prototype.broadcast = function(packet, opts){
  var rooms = opts.rooms || [];
  var except = opts.except || [];
  var flags = opts.flags || {};
  var packetOpts = {
    preEncoded: true,
    volatile: flags.volatile,
    compress: flags.compress
  };
  var ids = {};
  var self = this;
  var socket;

  packet.nsp = this.nsp.name;
  this.encoder.encode(packet, function(encodedPackets) {
    if (rooms.length) {
      for (var i = 0; i < rooms.length; i++) {
        var room = self.rooms[rooms[i]];
        if (!room) continue;
        var sockets = room.sockets;
        for (var id in sockets) {
          if (sockets.hasOwnProperty(id)) {
            if (ids[id] || ~except.indexOf(id)) continue;
            socket = self.nsp.connected[id];
            if (socket) {
              socket.packet(encodedPackets, packetOpts);
              ids[id] = true;
            }
          }
        }
      }
    } else {
      for (var id in self.sids) {
        if (self.sids.hasOwnProperty(id)) {
          if (~except.indexOf(id)) continue;
          socket = self.nsp.connected[id];
          if (socket) socket.packet(encodedPackets, packetOpts);
        }
      }
    }
  });
};

/**
 * Gets a list of clients by sid.
 *
 * @param {Array} explicit set of rooms to check.
 * @param {Function} callback
 * @api public
 */

Adapter.prototype.clients = function(rooms, fn){
  if ('function' == typeof rooms){
    fn = rooms;
    rooms = null;
  }

  rooms = rooms || [];

  var ids = {};
  var self = this;
  var sids = [];
  var socket;

  if (rooms.length) {
    for (var i = 0; i < rooms.length; i++) {
      var room = self.rooms[rooms[i]];
      if (!room) continue;
      var sockets = room.sockets;
      for (var id in sockets) {
        if (sockets.hasOwnProperty(id)) {
          if (ids[id]) continue;
          socket = self.nsp.connected[id];
          if (socket) {
            sids.push(id);
            ids[id] = true;
          }
        }
      }
    }
  } else {
    for (var id in self.sids) {
      if (self.sids.hasOwnProperty(id)) {
        socket = self.nsp.connected[id];
        if (socket) sids.push(id);
      }
    }
  }

  if (fn) process.nextTick(fn.bind(null, null, sids));
};

/**
 * Gets the list of rooms a given client has joined.
 *
 * @param {String} socket id
 * @param {Function} callback
 * @api public
 */
Adapter.prototype.clientRooms = function(id, fn){
  var rooms = this.sids[id];
  if (fn) process.nextTick(fn.bind(null, null, rooms ? Object.keys(rooms) : null));
};

/**
* Room constructor.
*
* @api private
*/

function Room(){
  if (!(this instanceof Room)) return new Room();
  this.sockets = {};
  this.length = 0;
}

/**
 * Adds a socket to a room.
 *
 * @param {String} socket id
 * @api private
 */

Room.prototype.add = function(id){
  if (!this.sockets.hasOwnProperty(id)) {
    this.sockets[id] = true;
    this.length++;
  }
};

/**
 * Removes a socket from a room.
 *
 * @param {String} socket id
 * @api private
 */

Room.prototype.del = function(id){
  if (this.sockets.hasOwnProperty(id)) {
    delete this.sockets[id];
    this.length--;
  }
};
<commit_msg>[refactor] Remove useless self var (#45)<commit_after>
/**
 * Module dependencies.
 */

var Emitter = require('events').EventEmitter;
var parser = require('socket.io-parser');

/**
 * Module exports.
 */

module.exports = Adapter;

/**
 * Memory adapter constructor.
 *
 * @param {Namespace} nsp
 * @api public
 */

function Adapter(nsp){
  this.nsp = nsp;
  this.rooms = {};
  this.sids = {};
  this.encoder = new parser.Encoder();
}

/**
 * Inherits from `EventEmitter`.
 */

Adapter.prototype.__proto__ = Emitter.prototype;

/**
 * Adds a socket to a room.
 *
 * @param {String} socket id
 * @param {String} room name
 * @param {Function} callback
 * @api public
 */

Adapter.prototype.add = function(id, room, fn){
  this.sids[id] = this.sids[id] || {};
  this.sids[id][room] = true;
  this.rooms[room] = this.rooms[room] || Room();
  this.rooms[room].add(id);
  if (fn) process.nextTick(fn.bind(null, null));
};

/**
 * Removes a socket from a room.
 *
 * @param {String} socket id
 * @param {String} room name
 * @param {Function} callback
 * @api public
 */

Adapter.prototype.del = function(id, room, fn){
  this.sids[id] = this.sids[id] || {};
  delete this.sids[id][room];
  if (this.rooms.hasOwnProperty(room)) {
    this.rooms[room].del(id);
    if (this.rooms[room].length === 0) delete this.rooms[room];
  }

  if (fn) process.nextTick(fn.bind(null, null));
};

/**
 * Removes a socket from all rooms it's joined.
 *
 * @param {String} socket id
 * @param {Function} callback
 * @api public
 */

Adapter.prototype.delAll = function(id, fn){
  var rooms = this.sids[id];
  if (rooms) {
    for (var room in rooms) {
      if (this.rooms.hasOwnProperty(room)) {
        this.rooms[room].del(id);
        if (this.rooms[room].length === 0) delete this.rooms[room];
      }
    }
  }
  delete this.sids[id];

  if (fn) process.nextTick(fn.bind(null, null));
};

/**
 * Broadcasts a packet.
 *
 * Options:
 *  - `flags` {Object} flags for this packet
 *  - `except` {Array} sids that should be excluded
 *  - `rooms` {Array} list of rooms to broadcast to
 *
 * @param {Object} packet object
 * @api public
 */

Adapter.prototype.broadcast = function(packet, opts){
  var rooms = opts.rooms || [];
  var except = opts.except || [];
  var flags = opts.flags || {};
  var packetOpts = {
    preEncoded: true,
    volatile: flags.volatile,
    compress: flags.compress
  };
  var ids = {};
  var self = this;
  var socket;

  packet.nsp = this.nsp.name;
  this.encoder.encode(packet, function(encodedPackets) {
    if (rooms.length) {
      for (var i = 0; i < rooms.length; i++) {
        var room = self.rooms[rooms[i]];
        if (!room) continue;
        var sockets = room.sockets;
        for (var id in sockets) {
          if (sockets.hasOwnProperty(id)) {
            if (ids[id] || ~except.indexOf(id)) continue;
            socket = self.nsp.connected[id];
            if (socket) {
              socket.packet(encodedPackets, packetOpts);
              ids[id] = true;
            }
          }
        }
      }
    } else {
      for (var id in self.sids) {
        if (self.sids.hasOwnProperty(id)) {
          if (~except.indexOf(id)) continue;
          socket = self.nsp.connected[id];
          if (socket) socket.packet(encodedPackets, packetOpts);
        }
      }
    }
  });
};

/**
 * Gets a list of clients by sid.
 *
 * @param {Array} explicit set of rooms to check.
 * @param {Function} callback
 * @api public
 */

Adapter.prototype.clients = function(rooms, fn){
  if ('function' == typeof rooms){
    fn = rooms;
    rooms = null;
  }

  rooms = rooms || [];

  var ids = {};
  var sids = [];
  var socket;

  if (rooms.length) {
    for (var i = 0; i < rooms.length; i++) {
      var room = this.rooms[rooms[i]];
      if (!room) continue;
      var sockets = room.sockets;
      for (var id in sockets) {
        if (sockets.hasOwnProperty(id)) {
          if (ids[id]) continue;
          socket = this.nsp.connected[id];
          if (socket) {
            sids.push(id);
            ids[id] = true;
          }
        }
      }
    }
  } else {
    for (var id in this.sids) {
      if (this.sids.hasOwnProperty(id)) {
        socket = this.nsp.connected[id];
        if (socket) sids.push(id);
      }
    }
  }

  if (fn) process.nextTick(fn.bind(null, null, sids));
};

/**
 * Gets the list of rooms a given client has joined.
 *
 * @param {String} socket id
 * @param {Function} callback
 * @api public
 */
Adapter.prototype.clientRooms = function(id, fn){
  var rooms = this.sids[id];
  if (fn) process.nextTick(fn.bind(null, null, rooms ? Object.keys(rooms) : null));
};

/**
* Room constructor.
*
* @api private
*/

function Room(){
  if (!(this instanceof Room)) return new Room();
  this.sockets = {};
  this.length = 0;
}

/**
 * Adds a socket to a room.
 *
 * @param {String} socket id
 * @api private
 */

Room.prototype.add = function(id){
  if (!this.sockets.hasOwnProperty(id)) {
    this.sockets[id] = true;
    this.length++;
  }
};

/**
 * Removes a socket from a room.
 *
 * @param {String} socket id
 * @api private
 */

Room.prototype.del = function(id){
  if (this.sockets.hasOwnProperty(id)) {
    delete this.sockets[id];
    this.length--;
  }
};
<|endoftext|>


<commit_before>'use strict';

var color = require('color')
  , hex = require('text-hex');

/**
 * Generate a color for a given name. But be reasonably smart about it by
 * understanding name spaces and coloring each namespace a bit lighter so they
 * still have the same base color as the root.
 *
 * @param {String} name The namespace
 * @returns {String} color
 * @api private
 */
module.exports = function colorspace(namespace, delimiter) {
  var split = namespace.split(delimiter || ':');
  var base = hex(split[0]);

  if (!split.length) return base;

  for (var i = 0, l = split.length - 1; i < l; i++) {
    base = color(base)
    .mix(color(hex(split[i + 1])))
    .saturate(1)
    .hex();
  }

  return base;
};
<commit_msg>JSDoc touchup<commit_after>'use strict';

var color = require('color')
  , hex = require('text-hex');

/**
 * Generate a color for a given name. But be reasonably smart about it by
 * understanding name spaces and coloring each namespace a bit lighter so they
 * still have the same base color as the root.
 *
 * @param {string} namespace The namespace
 * @param {string} [delimiter] The delimiter
 * @returns {string} color
 */
module.exports = function colorspace(namespace, delimiter) {
  var split = namespace.split(delimiter || ':');
  var base = hex(split[0]);

  if (!split.length) return base;

  for (var i = 0, l = split.length - 1; i < l; i++) {
    base = color(base)
    .mix(color(hex(split[i + 1])))
    .saturate(1)
    .hex();
  }

  return base;
};
<|endoftext|>


<commit_before>var request = require('request');
var config = require("./config.json");
request
    .post(
    {
        url: 'http://mws.amazonservices.co.uk/Orders/2013-09-01',
        form: {
            'Action' : 'GetServiceStatus',
            'SellerId' : 'A2JUH45EK8JPA4',
            'SignatureVersion' : '2',
            'Timestamp' : Date.now(),
            'Version' : '2013-09-01',
            'Signature' : 'j4EGXEQ%2Bm5C99K9E6FG4HjDT8AxgNK77uhbvoZRx%2B8o%3D',
            'SignatureMethod' : 'HmacSHA256',
            'AWSAccessKeyId' : config.AWSAccessKeyID
        }
    }, function (err, httpResponse, body) {
        /* ... */
        console.log(err);
        console.log(httpResponse);
        console.log(body);
    });<commit_msg>first working request<commit_after>var request = require('request');
var config = require("./config.json");
request
    .post(
    {
        url: 'https://mws.amazonservices.com/Orders/2013-09-01',
        form: {
            'Action' : 'GetServiceStatus',
            'SellerId' : config.SellerID,
            'SignatureVersion' : '2',
            'Timestamp' :'2015-08-25T19:56:52.538Z',
            'Version' : '2013-09-01',
            'Signature' : 'j4EGXEQ%2Bm5C99K9E6FG4HjDT8AxgNK77uhbvoZRx%2B8o%3D',
            'SignatureMethod' : 'HmacSHA256',
            'AWSAccessKeyId' : config.AWSAccessKeyID
        }
    }, function (err, httpResponse, body) {
        /* ... */
        console.log(err);
        console.log(httpResponse);
        console.log(body);
    });<|endoftext|>