<commit_before>/*
 * Copyright 2016, Lorenzo Mangani (lorenzo.mangani@gmail.com)
 * Copyright 2015, Rao Chenlin (rao.chenlin@gmail.com)
 *
 * This file is part of Sentinl (http://github.com/sirensolutions/sentinl)
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *  http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

import _ from 'lodash';

export default function (kibana) {
  return new kibana.Plugin({
    require: ['kibana', 'elasticsearch'],

    uiExports: {
      spyModes: ['plugins/sentinl/button/alarm_button'],
      // chromeNavControls: ['plugins/sentinl/button/alarm_button'],
      app: {
        title: 'Sentinl',
        description: 'Kibana Alert App for Elasticsearch',
        main: 'plugins/sentinl/app',
        icon: 'plugins/sentinl/sentinl.svg',
	injectVars: function (server, options) {
                               var config = server.config();
                               return {
                                   kbnIndex: config.get('kibana.index'),
                                   esShardTimeout: config.get('elasticsearch.shardTimeout'),
                                   esApiVersion: config.get('elasticsearch.apiVersion')
                               };
        }
      }
    },
    config: function (Joi) {
      return Joi.object({
        enabled: Joi.boolean().default(true),
      }).default();
    },

    init: require('./init.js')

  });
};
<commit_msg>Fixed paths<commit_after>/*
 * Copyright 2016, Lorenzo Mangani (lorenzo.mangani@gmail.com)
 * Copyright 2015, Rao Chenlin (rao.chenlin@gmail.com)
 *
 * This file is part of Sentinl (http://github.com/sirensolutions/sentinl)
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *  http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

export default function (kibana) {
  return new kibana.Plugin({
    require: ['kibana', 'elasticsearch'],

    uiExports: {
      spyModes: ['plugins/sentinl/button/alarm_button'],
      // chromeNavControls: ['plugins/sentinl/button/alarm_button'],
      app: {
        title: 'Sentinl',
        description: 'Kibana Alert App for Elasticsearch',
        main: 'plugins/sentinl/app',
        icon: 'plugins/sentinl/sentinl.svg',
	injectVars: function (server, options) {
                               var config = server.config();
                               return {
                                   kbnIndex: config.get('kibana.index'),
                                   esShardTimeout: config.get('elasticsearch.shardTimeout'),
                                   esApiVersion: config.get('elasticsearch.apiVersion')
                               };
        }
      }
    },
    config: function (Joi) {
      return Joi.object({
        enabled: Joi.boolean().default(true),
      }).default();
    },

    init: require('./init.js')

  });
};
<|endoftext|>


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

app.set('port', (process.env.PORT || 5000));

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

// views is directory for all template files
app.set('views', __dirname + '/views');
app.set('view engine', 'ejs');

app.get('/', function(request, response) {
  response.render('public/index.html');
});

app.get('/.well-known/acme-challenge/:content', function(req, res) {
  res.send('zLWrnqdgRWJHVlDvtGz9mg24uMI5YgPDFLU2cgq7lq4.aSlo6fodsx3IxhSZiebSQCHJp8DIZyYfqxjLubxwee4')
})

app.listen(app.get('port'), function() {
  console.log('Node app is running on port', app.get('port'));
});
<commit_msg>index.js - manual certbot test<commit_after>var express = require('express');
var app = express();

app.set('port', (process.env.PORT || 5000));

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

// views is directory for all template files
app.set('views', __dirname + '/views');
app.set('view engine', 'ejs');

app.get('/', function(request, response) {
  response.render('public/index.html');
});

app.get('/.well-known/acme-challenge/ZTUQWDgI1HHPdaE3_THeuGpzdAblbK6OKcHvpTYM2lo', function(req, res) {
  res.send('ZTUQWDgI1HHPdaE3_THeuGpzdAblbK6OKcHvpTYM2lo.aSlo6fodsx3IxhSZiebSQCHJp8DIZyYfqxjLubxwee4')
})

app.listen(app.get('port'), function() {
  console.log('Node app is running on port', app.get('port'));
});
<|endoftext|>


<commit_before>#!/usr/bin/env node

//require(__dirname+'/runners')(__dirname);

/*
Read config
Read local parts
From config read/install common parts
Execute runners
Require routers
*/<commit_msg>added read config<commit_after>#!/usr/bin/env node
const fs = require('fs');
let config = {};
if (fs.existsSync(process.cwd()+'/config.json')) {
	config = JSON.parse(fs.readFileSync(process.cwd()+'/config.json'));
	fs.mkdirSync(process.cwd()+'/client', { recursive: true });
	fs.mkdirSync(process.cwd()+'/server', { recursive: true });
}
if (fs.existsSync(process.cwd()+'/server.json')) {
	let serverConfig = fs.readFileSync(process.cwd()+'/server.json');
	for(let each in serverConfig){
		config[each] = serverConfig[each];
	}
}
console.log(config);
process.exit(1);
/*
Read local parts
From config read/install common parts
Execute runners
Require routers
*/
//require(__dirname+'/runners')(__dirname);<|endoftext|>


<commit_before>"use strict";
var net = require("net");
var parse = require("url-parse-lax");
var TIMEOUT = 5000;

function endSocket(socket) {
  socket.removeAllListeners("data").removeAllListeners("error").end();
}

module.exports = function(dest, seq, opts, cb) {
  var socket = new net.Socket(), interacting, saved = "";
  if (typeof opts === "function") cb = opts;
  opts = opts || {};

  socket.setTimeout(opts.timeout || TIMEOUT);
  socket.once("connect", socket.setNoDelay.bind(socket));

  dest = parse(dest);
  socket.connect(dest.port, dest.hostname);

  socket.on("error", function(err) {
    if (interacting) interacting = false;
    endSocket(socket);
    cb(err);
  });
  socket.on("end", function() {
    if (interacting) {
      process.stdin.removeAllListeners("data");
      if (opts.exit) process.exit(0);
    }
  });
  socket.on("data", function next(chunk) {
    if (interacting) return process.stdout.write(chunk);

    var i;
    seq.some(function(entry, index) {
      i = entry.done ? undefined : index;
      return !entry.done;
    });

    if (!seq[i] || seq[i].done) {
      endSocket(socket);
      return cb();
    }

    if (!seq[i].timeout) {
      seq[i].timeout = setTimeout(function() {
        endSocket(socket);
        cb(new Error("Expect sequence timeout: " + seq[i].expect));
      }, opts.timeout || TIMEOUT);
    }

    saved += chunk;

    var matched;
    if (seq[i].expect instanceof RegExp) {
      matched = seq[i].expect.test(saved);
    } else if (typeof seq[i].expect === "string") {
      matched = saved.indexOf(seq[i].expect) !== -1;
    } else {
      endSocket(socket);
      cb(new Error("Expected a String or RegExp:" + seq[i].expect));
    }

    if (matched) {
      clearTimeout(seq[i].timeout);
      seq[i].done = true;

      if (seq[i].out) {
        var lines = [];
        saved.split(/\r?\n/).forEach(function(line) {
          if (line) lines.push(line);
        });
        lines = lines.length >= 3 ? lines.slice(1, lines.length - 1) : lines;
        seq[i].out(lines.join("\n"));
      }

      if (seq[i].send) {
        socket.write(seq[i].send);
      }

      if (seq[i].interact) {
        process.stdin.setRawMode(true);
        interacting = true;
        process.stdin.on("data", function(c) {
          if (!socket.writable) return;
          if (c.toString("hex") === "7f") c = Buffer("08", "hex"); // Convert DEL to BKSP
          socket.write(c);
        });
        socket.write("\r");
      }
      saved = "";
    }
  });
};
<commit_msg>clean up socket on timeout - #6<commit_after>"use strict";
var net = require("net");
var parse = require("url-parse-lax");
var TIMEOUT = 5000;

function endSocket(socket) {
  socket.removeAllListeners("data").removeAllListeners("error").end();
}

module.exports = function(dest, seq, opts, cb) {
  var socket = new net.Socket(), interacting, saved = "";
  if (typeof opts === "function") cb = opts;
  opts = opts || {};

  socket.setTimeout(opts.timeout || TIMEOUT);
  socket.once("timeout", socket.destroy);
  socket.once("connect", socket.setNoDelay.bind(socket));

  dest = parse(dest);
  socket.connect(dest.port, dest.hostname);

  socket.on("error", function(err) {
    if (interacting) interacting = false;
    endSocket(socket);
    cb(err);
  });
  socket.on("end", function() {
    if (interacting) {
      process.stdin.removeAllListeners("data");
      if (opts.exit) process.exit(0);
    }
  });
  socket.on("data", function next(chunk) {
    if (interacting) return process.stdout.write(chunk);

    var i;
    seq.some(function(entry, index) {
      i = entry.done ? undefined : index;
      return !entry.done;
    });

    if (!seq[i] || seq[i].done) {
      endSocket(socket);
      return cb();
    }

    if (!seq[i].timeout) {
      seq[i].timeout = setTimeout(function() {
        endSocket(socket);
        cb(new Error("Expect sequence timeout: " + seq[i].expect));
      }, opts.timeout || TIMEOUT);
    }

    saved += chunk;

    var matched;
    if (seq[i].expect instanceof RegExp) {
      matched = seq[i].expect.test(saved);
    } else if (typeof seq[i].expect === "string") {
      matched = saved.indexOf(seq[i].expect) !== -1;
    } else {
      endSocket(socket);
      cb(new Error("Expected a String or RegExp:" + seq[i].expect));
    }

    if (matched) {
      clearTimeout(seq[i].timeout);
      seq[i].done = true;

      if (seq[i].out) {
        var lines = [];
        saved.split(/\r?\n/).forEach(function(line) {
          if (line) lines.push(line);
        });
        lines = lines.length >= 3 ? lines.slice(1, lines.length - 1) : lines;
        seq[i].out(lines.join("\n"));
      }

      if (seq[i].send) {
        socket.write(seq[i].send);
      }

      if (seq[i].interact) {
        process.stdin.setRawMode(true);
        interacting = true;
        process.stdin.on("data", function(c) {
          if (!socket.writable) return;
          if (c.toString("hex") === "7f") c = Buffer("08", "hex"); // Convert DEL to BKSP
          socket.write(c);
        });
        socket.write("\r");
      }
      saved = "";
    }
  });
};
<|endoftext|>


<commit_before>function decimalToBinary(num){
    var remainders = [];
    var remainder;
    var qotient;
    qotient = num;
    while(qotient>0)
    {
        remainder = qotient%2;
        qotient = Math.floor(qotient/2);
        remainders.push(remainder);
    }
    remainders = remainders.reverse();
    remainders = remainders.join('');
    return remainders;
}
function binaryToDecimal(num){
    var binArr;
    var bitSize;
    var nums = [];
    var bit = [];
    var temp;
    var decimal;
    binArr = num.toString();
    binArr = binArr.split('');
    bitSize = binArr.length-1;

    while(bitSize>=0)
    {
        temp = Math.pow(2,bitSize);
        bit.push(temp);
        bitSize--;
    }
    temp = 0;
    for(var i = 0;i<bit.length;i++)
    {
        temp = binArr[i]*bit[i];
        nums.push(temp);
    }
    decimal = 0;
    for(var j = 0;j<nums.length;j++)
    {
        temp=Number(nums[j]);
        decimal = decimal + temp;
    }
    return decimal;
}

function decimalToHexadecimal(num){
    var remainders = [];
    var remainder;
    var qotient;
    qotient = num;
    while(qotient>0)
    {
        remainder = qotient%16;
        switch(remainder)
        {
            case 10:
                remainder = "A";
                break;
            case 11:
                remainder = "B";
                break;
            case 12:
                remainder = "C";
                break;
            case 13:
                remainder = "D";
                break;
            case 14:
                remainder = "E";
                break;
            case 15:
                remainder = "F";
                break;
        }
        qotient = Math.floor(qotient/16);
        remainders.push(remainder);
    }
    remainders = remainders.reverse();
    remainders = remainders.join('');
    return remainders;
}

function binaryToHexadecimal(num){
    var decimal = binaryToDecimal(num);
    return decimalToHexadecimal(decimal);
}
function hexadecimalToDecimal(num){
    var hexaArr = [];
    var deciArr = [];
    var decimal;
    num = num.split('');
    var hexSize;
    var temp;
    for(var i = 0;i<num.length;i++)
        {
            switch(num[i])
            {
                case 'A':
                    num[i] = 10;
                    break;
                case 'B':
                    num[i] = 11;
                    break;
                case 'C':
                    num[i] = 12;
                    break;
                case 'D':
                    num[i] = 13;
                    break;
                case 'E':
                    num[i] = 14;
                    break;
                case 'F':
                    num[i] = 15;
                    break;
            }
        }
        for(var j=0;j<num.length;j++)
            {
                num[j] = Number(num[j])
            }
        hexSize = num.length - 1;

        while(hexSize>=0)
            {
                temp = Math.pow(16,hexSize);
                hexaArr.push(temp);
                hexSize--;
            }
            temp = 0;
        for(var k = 0;k<hexaArr.length;k++)
            {
                temp = num[k]*hexaArr[k];
                deciArr.push(temp);
            }
            decimal = 0;
            temp = 0;
        for(var l = 0;l<deciArr.length;l++)
            {
                temp=Number(deciArr[l]);
                decimal = decimal + temp;
            }
    return decimal;
}
function hexadecimalToBinary(num){
    var decimalEquivalent = hexadecimalToDecimal(num);
    return decimalToBinary(decimalEquivalent);
}

console.log(hexadecimalToBinary('123'));
<commit_msg>added the last function left now left with developing the UI<commit_after>function decimalToBinary(num){
    var remainders = [];
    var remainder;
    var qotient;
    qotient = num;
    while(qotient>0)
    {
        remainder = qotient%2;
        qotient = Math.floor(qotient/2);
        remainders.push(remainder);
    }
    remainders = remainders.reverse();
    remainders = remainders.join('');
    return remainders;
}
function binaryToDecimal(num){
    var binArr;
    var bitSize;
    var nums = [];
    var bit = [];
    var temp;
    var decimal;
    binArr = num.toString();
    binArr = binArr.split('');
    bitSize = binArr.length-1;

    while(bitSize>=0)
    {
        temp = Math.pow(2,bitSize);
        bit.push(temp);
        bitSize--;
    }
    temp = 0;
    for(var i = 0;i<bit.length;i++)
    {
        temp = binArr[i]*bit[i];
        nums.push(temp);
    }
    decimal = 0;
    for(var j = 0;j<nums.length;j++)
    {
        temp=Number(nums[j]);
        decimal = decimal + temp;
    }
    return decimal;
}

function decimalToHexadecimal(num){
    var remainders = [];
    var remainder;
    var qotient;
    qotient = num;
    while(qotient>0)
    {
        remainder = qotient%16;
        switch(remainder)
        {
            case 10:
                remainder = "A";
                break;
            case 11:
                remainder = "B";
                break;
            case 12:
                remainder = "C";
                break;
            case 13:
                remainder = "D";
                break;
            case 14:
                remainder = "E";
                break;
            case 15:
                remainder = "F";
                break;
        }
        qotient = Math.floor(qotient/16);
        remainders.push(remainder);
    }
    remainders = remainders.reverse();
    remainders = remainders.join('');
    return remainders;
}

function binaryToHexadecimal(num){
    var decimal = binaryToDecimal(num);
    return decimalToHexadecimal(decimal);
}
function hexadecimalToDecimal(num){
    var hexaArr = [];
    var deciArr = [];
    var decimal;
    num = num.split('');
    var hexSize;
    var temp;
    for(var i = 0;i<num.length;i++)
        {
            switch(num[i])
            {
                case 'A':
                    num[i] = 10;
                    break;
                case 'B':
                    num[i] = 11;
                    break;
                case 'C':
                    num[i] = 12;
                    break;
                case 'D':
                    num[i] = 13;
                    break;
                case 'E':
                    num[i] = 14;
                    break;
                case 'F':
                    num[i] = 15;
                    break;
            }
        }
        for(var j=0;j<num.length;j++)
            {
                num[j] = Number(num[j])
            }
        hexSize = num.length - 1;

        while(hexSize>=0)
            {
                temp = Math.pow(16,hexSize);
                hexaArr.push(temp);
                hexSize--;
            }
            temp = 0;
        for(var k = 0;k<hexaArr.length;k++)
            {
                temp = num[k]*hexaArr[k];
                deciArr.push(temp);
            }
            decimal = 0;
            temp = 0;
        for(var l = 0;l<deciArr.length;l++)
            {
                temp=Number(deciArr[l]);
                decimal = decimal + temp;
            }
    return decimal;
}
function hexadecimalToBinary(num){
    var decimalEquivalent = hexadecimalToDecimal(num);
    return decimalToBinary(decimalEquivalent);
}
function decimalToOctal(num){
    var remainders = [];
    var remainder;
    var qotient;
    qotient = num;
    while(qotient>0)
    {
        remainder = qotient%8;
        qotient = Math.floor(qotient/8);
        remainders.push(remainder);
    }
    remainders = remainders.reverse();
    remainders = remainders.join('');
    return remainders;
}
// maybe i should create a to decimal function that is passed the number base and number to be converted :) food for thought
function octalToDecimal(num){
    //just copied sam code as with binary to decimal just change the 8 in the while loop
    var binArr;
    var bitSize;
    var nums = [];
    var bit = [];
    var temp;
    var decimal;
    binArr = num.toString();
    binArr = binArr.split('');
    bitSize = binArr.length-1;

    while(bitSize>=0)
    {
        temp = Math.pow(8,bitSize); //<= this is the only the line i changed from the binary to decimal function
        bit.push(temp);
        bitSize--;
    }
    temp = 0;
    for(var i = 0;i<bit.length;i++)
    {
        temp = binArr[i]*bit[i];
        nums.push(temp);
    }
    decimal = 0;
    for(var j = 0;j<nums.length;j++)
    {
        temp=Number(nums[j]);
        decimal = decimal + temp;
    }
    return decimal;

}
function binaryToOctal(num){
    var decimalEquivalent = binaryToDecimal(num);
    return decimalToOctal(decimalEquivalent);
}
function octalToBinary(num){
    var decimalEquivalent = octalToDecimal(num);
    return decimalToBinary(decimalEquivalent);
}
function hexadecimalToOctal(num){
    var decimalEquivalent = hexadecimalToDecimal(num);
    return decimalToOctal(decimalEquivalent);
}
function octalToHexadecimal(num){
    var decimalEquivalent = octalToDecimal(num);
    return decimalToHexadecimal(decimalEquivalent);
}

console.log(octalToHexadecimal('63'));
<|endoftext|>


<commit_before>// List module dependancies
var express = require('express');
var session = require('express-session');
var bodyParser = require('body-parser');
var http = require('http');
var passport = require('passport');
var db = require('./models');

// Init express app
var app = express();

// Config on express-session
app.use(session({
    secret: 'keyboard cat',
    resave: false,
    saveUninitialized: true,
    cookie: {
        secure: false
    }
}))

// Init all dependencies used by the app
app.use(passport.initialize());
app.use(passport.session());
app.use(bodyParser.json());
app.use(bodyParser.urlencoded({
    extended: false
}));

// Init Databases

// test authentification
db.sequelize
    .authenticate()
    .then(function(success) {
        console.log('Connection has been established successfully.');
    })
    .catch(function(err) {
        console.log('Unable to connect to the database:', err);
    });

// sync DB
if (process.env.NODE_ENV == 'development') {
  db.sequelize.sync({
      force: true
  });
};

// Init oauth middleware
require('./oauth')(passport);

// Basic oauth routes set in orcid URI callback
app.get('/auth', passport.authenticate('oauth2'));
app.get('/auth/callback', passport.authenticate('oauth2', {
    successRedirect: '/auth/success',
    failureRedirect: '/auth/failed'
}));

// start server
var port = process.env.PORT || 3000;
server = http.createServer(app);
server.listen(port);

module.exports = server;
<commit_msg>add profile routes and manage req.user<commit_after>// List module dependancies
var express = require('express');
var session = require('express-session');
var bodyParser = require('body-parser');
var http = require('http');
var passport = require('passport');
var db = require('./models');

// Init express app
var app = express();

// Config on express-session
app.use(session({
    secret: 'keyboard cat',
    resave: false,
    saveUninitialized: true,
    cookie: {
        secure: false
    }
}))

// Init all dependencies used by the app
app.use(passport.initialize());
app.use(passport.session());
app.use(bodyParser.json());
app.use(bodyParser.urlencoded({
    extended: false
}));

// Init Databases

// test authentification
db.sequelize
    .authenticate()
    .then(function(success) {
        console.log('Connection has been established successfully.');
    })
    .catch(function(err) {
        console.log('Unable to connect to the database:', err);
    });

// sync DB
if (process.env.NODE_ENV == 'development') {
  db.sequelize.sync({
      force: true
  });
};

// Init oauth middleware
require('./oauth')(passport);

// Basic oauth routes
app.get('/auth', passport.authenticate('oauth2'));
app.get('/auth/callback', passport.authenticate('oauth2', {
    successRedirect: '/auth/profile',
    failureRedirect: '/auth/failed'
}));

app.get('/auth/profile', function(req,res){
  console.log(req.user);
  if(typeof req.user === 'undefined'){
    res.status(204).send('No user profile');
  } else {
    res.status(200).json(req.user);
  };
});

app.get('/auth/failed', function(req,res){
  res.status(403).send('Authorization denied by user');
});

app.get('/auth/logout', function(req,res){
  req.logout();
  res.redirect('/auth');
  // NOTE: Clear the app session, but not the ORCID session.
});

// start server
var port = process.env.PORT || 3000;
server = http.createServer(app);
server.listen(port);

module.exports = server;
<|endoftext|>


<commit_before>/**
 * The entry point of the npm module.
 */

var requirejs = require('requirejs');
requirejs.config({
    baseUrl: __dirname + '/' + 'js/grape'
});
module.exports = requirejs('main');<commit_msg>On node.js, grape is required in a context, so we can use requirejs in modules depending on grape correctly.<commit_after>/**
 * The entry point of the npm module.
 */

var requirejs = require('requirejs');
var requireGrape = requirejs.config({
    context: 'grape-engine',
    baseUrl: __dirname + '/' + 'js/grape'
});
module.exports = requireGrape('main');<|endoftext|>


<commit_before>/* global Promise */
var nodefs = require('node-fs');
var path = require('path');
var sass = require('node-sass');
var postcss = require('postcss');

/**
 * @constructor
 */
function Processor(plugins) {
	this.plugins = plugins;
}

/**
 * Process single
 */
Processor.prototype.process = function (options) {
	var plugins = this.plugins;
	var toName = path.basename(options.to);
	var dirName = path.dirname(options.to);

	var sassPromise = new Promise(function (resolve, reject) {
		console.log('Compiling SASS: ' + options.from);

		sass.render({
			file: options.from,
			to: options.to,
			outputStyle: 'compressed',
			precision: 10,
			sourceMap: true
		}, function (err, result) {

			if (err) {
				reject(err);
			}
			else {
				resolve(result);
			}
		});
	});

	var doPostCss = function (result) {
		console.log('Running PostCss: ' + toName);

		//Post css already implements promises.
		return postcss(plugins).process(result.css, {
			from: toName,
			to: toName,
			map: { inline: false }
		});
	};

	var writeToDisk = function (result) {
		console.log('Writing file: ' + options.to);

		nodefs.mkdirSync(dirName, '0777', true);
		nodefs.writeFile(options.to, result.css);
		nodefs.writeFile(options.to + '.map', result.map);
	};

	return sassPromise
		.then(doPostCss)
		.then(writeToDisk);
};

/**
 * Process many
 */
Processor.prototype.processMany = function (optionsArray) {
	var proms = []

	for (var i = 0; i < optionsArray.length; i++) {
		proms.push(this.process(optionsArray[i]));
	}

	return Promise.all(proms);
};

module.exports = function (plugins) {
	return new Processor(plugins);
};<commit_msg>Fixed source map line numbers..<commit_after>/* global Promise */
var nodefs = require('node-fs');
var path = require('path');
var sass = require('node-sass');
var postcss = require('postcss');

/**
 * @constructor
 */
function Processor(plugins) {
	this.plugins = plugins;
}

/**
 * Process single
 */
Processor.prototype.process = function (options) {
	var plugins = this.plugins;
	var toName = path.basename(options.to);
	var dirName = path.dirname(options.to);

	var sassPromise = new Promise(function (resolve, reject) {
		console.log('Compiling SASS: ' + options.from);

		sass.render({
			file: options.from,
			outFile: options.to,
			precision: 10,
			sourceMap: true,
			sourceMapEmbed: true
		}, function (err, result) {
			if (err) {
				reject(err);
			}
			else {
				resolve(result);
			}
		});
	});

	var doPostCss = function (result) {
		console.log('Running PostCss transforms: ' + toName);

		//Post css already implements promises.
		return postcss(plugins).process(result.css, {
			from: toName,
			to: toName,
			map: { inline: false }
		});
	};

	var writeToDisk = function (result) {
		console.log('Writing file: ' + options.to);

		nodefs.mkdirSync(dirName, '0777', true);
		nodefs.writeFile(options.to, result.css);
		nodefs.writeFile(options.to + '.map', result.map);
	};

	return sassPromise
		.then(doPostCss)
		.then(writeToDisk);
};

/**
 * Process many
 */
Processor.prototype.processMany = function (optionsArray) {
	var proms = []

	for (var i = 0; i < optionsArray.length; i++) {
		proms.push(this.process(optionsArray[i]));
	}

	return Promise.all(proms);
};

module.exports = function (plugins) {
	return new Processor(plugins);
};<|endoftext|>


<commit_before>'use-strict';

/** Dependencies */
var querystring = require('querystring');
var request = require('request');

/**
 * Client
 * @param  {String} account  Beanstalk account name
 * @param  {String} username Username
 * @param  {String} token    Access token
 * @return {Client}          Returns itself
 */
var Client = function(account, username, token) {
  this.beanstalkUrl = 'https://' + account + '.beanstalkapp.com';
  this.authHeader = "Basic " + new Buffer(username + ":" + token).toString("base64");

  return this;
};

/**
 * Client constuctor
 * @param  {String} account  Beanstalk account name
 * @param  {String} username Username
 * @param  {String} token    Access token
 * @return {Client}          Returns a new instance of the Client object
 */
module.exports.createClient = function(account, username, token) {
  return new Client(account, username, token);
};

/**
 * Wrapper function for the GET requests
 * @param  {String}   path     Path to the resource
 * @param  {Object}   params   GET parameters
 * @param  {Function} callback Gets called after request is complete
 */
Client.prototype.get = function(path, params, callback) {

  request({
      url: this.beanstalkUrl + path,
      headers: {
        'Authorization': this.authHeader,
        'Content-Type': 'application/json',
        'User-Agent': 'Node.js Beanstalk Wrapper'
      },
      qs: params
    },
    function (error, response, data) {
      callback(error, data);
    }
  );

};

/**
 * Account functions
 * See: http://api.beanstalkapp.com/account.html
 */

/**
 * Gets the Beanstalk account data
 * @param  {Function} callback Gets called after request is complete
 */
Client.prototype.getAccount = function(callback) {
  this.get('/api/account.json', null, callback);
};

/**
 * Plan functions
 * See: http://api.beanstalkapp.com/plan.html
 */

/**
 * Gets all plans
 * @param  {Function} callback Gets called after request is complete
 */
Client.prototype.getPlans = function(callback) {
  this.get('/api/plans.json', null, callback);
};

/**
 * User functions
 * See: http://api.beanstalkapp.com/user.html
 */

/**
 * Gets all users
 * @param  {Function} callback Gets called after request is complete
 */
Client.prototype.getUsers = function(callback) {
  this.get('/api/users.json', null, callback);
};

/**
 * Gets a user
 * @param  {Integer}  userId  User ID
 * @param  {Function} callback Gets called after request is complete
 */
Client.prototype.getUser = function(userId, callback) {
  this.get('/api/users/' + userId + '.json', null, callback);
};

/**
 * Gets the current user
 * @param  {Function} callback Gets called after request is complete
 */
Client.prototype.getCurrentUser = function(callback) {
  this.get('/api/users/current.json', null, callback);
};

/**
 * Public Key Resource
 * See: http://api.beanstalkapp.com/public_key.html
 */

/**
 * Find All Public Keys
 * @param  {Function} callback Gets called after request is complete
 */
Client.prototype.getPublicKeys = function(callback) {
  this.get('/api/public_keys.json', null, callback);
};

/**
 * Find All Public Keys Owned by a Specific User
 * @param  {Integer}  userId  User ID
 * @param  {Function} callback Gets called after request is complete
 */
Client.prototype.getPublicKeysByUser = function(userId, callback) {
  this.get('/api/public_keys.json', { 'user_id': userId }, callback);
};

/**
 * Find All Public Keys Owned by a Specific User
 * @param  {Integer}  keyId  Public Key ID
 * @param  {Function} callback Gets called after request is complete
 */
Client.prototype.getPublicKey = function(keyId, callback) {
  this.get('/api/public_keys/' + keyId + '.json', null, callback);
};

/**
 * FeedKey Resource
 * See: http://api.beanstalkapp.com/feed_key.html
 */

/**
 * Find FeedKey for Current User
 * @param  {Function} callback Gets called after request is complete
 */
Client.prototype.getFeedKey = function(callback) {
  this.get('/api/feed_key.json', null, callback);
};

/**
 * Repository Resource
 * See: http://api.beanstalkapp.com/repository.html
 */

/**
 * Find All Repositories
 * @param  {Object} [params] Find params (optional)
 * @param  {Function} callback Gets called after request is complete
 */
Client.prototype.getRepositories = function(params, callback) {
  if(typeof params === 'function') {
    callback = params;
    params = null;
  }
  this.get('/api/repositories.json', params, callback);
};

/**
 * Find Repository
 * @param  {Object} repository  Repository ID
 * @param  {Function} callback Gets called after request is complete
 */
Client.prototype.getRepository = function(repositoryId, callback) {
  this.get('/api/repositories/' + repositoryId + '.json', null, callback);
};

/**
 * Find Branches
 * @param  {Object} repository  Repository ID
 * @param  {Function} callback Gets called after request is complete
 */
Client.prototype.getBranches = function(repositoryId, callback) {
  this.get('/api/repositories/' + repositoryId + '/branches.json', null, callback);
};

/**
 * Find Tags
 * @param  {Object} repository  Repository ID
 * @param  {Function} callback Gets called after request is complete
 */
Client.prototype.getTags = function(repositoryId, callback) {
  this.get('/api/repositories/' + repositoryId + '/tags.json', null, callback);
};
<commit_msg>Added Repository Import Resources<commit_after>'use-strict';

/** Dependencies */
var querystring = require('querystring');
var request = require('request');

/**
 * Client
 * @param  {String} account  Beanstalk account name
 * @param  {String} username Username
 * @param  {String} token    Access token
 * @return {Client}          Returns itself
 */
var Client = function(account, username, token) {
  this.beanstalkUrl = 'https://' + account + '.beanstalkapp.com';
  this.authHeader = "Basic " + new Buffer(username + ":" + token).toString("base64");

  return this;
};

/**
 * Client constuctor
 * @param  {String} account  Beanstalk account name
 * @param  {String} username Username
 * @param  {String} token    Access token
 * @return {Client}          Returns a new instance of the Client object
 */
module.exports.createClient = function(account, username, token) {
  return new Client(account, username, token);
};

/**
 * Wrapper function for the GET requests
 * @param  {String}   path     Path to the resource
 * @param  {Object}   params   GET parameters
 * @param  {Function} callback Gets called after request is complete
 */
Client.prototype.get = function(path, params, callback) {

  request({
      url: this.beanstalkUrl + path,
      headers: {
        'Authorization': this.authHeader,
        'Content-Type': 'application/json',
        'User-Agent': 'Node.js Beanstalk Wrapper'
      },
      qs: params
    },
    function (error, response, data) {
      callback(error, data);
    }
  );

};

/**
 * Account functions
 * See: http://api.beanstalkapp.com/account.html
 */

/**
 * Gets the Beanstalk account data
 * @param  {Function} callback Gets called after request is complete
 */
Client.prototype.getAccount = function(callback) {
  this.get('/api/account.json', null, callback);
};

/**
 * Plan functions
 * See: http://api.beanstalkapp.com/plan.html
 */

/**
 * Gets all plans
 * @param  {Function} callback Gets called after request is complete
 */
Client.prototype.getPlans = function(callback) {
  this.get('/api/plans.json', null, callback);
};

/**
 * User functions
 * See: http://api.beanstalkapp.com/user.html
 */

/**
 * Gets all users
 * @param  {Function} callback Gets called after request is complete
 */
Client.prototype.getUsers = function(callback) {
  this.get('/api/users.json', null, callback);
};

/**
 * Gets a user
 * @param  {Integer}  userId  User ID
 * @param  {Function} callback Gets called after request is complete
 */
Client.prototype.getUser = function(userId, callback) {
  this.get('/api/users/' + userId + '.json', null, callback);
};

/**
 * Gets the current user
 * @param  {Function} callback Gets called after request is complete
 */
Client.prototype.getCurrentUser = function(callback) {
  this.get('/api/users/current.json', null, callback);
};

/**
 * Public Key Resource
 * See: http://api.beanstalkapp.com/public_key.html
 */

/**
 * Find All Public Keys
 * @param  {Function} callback Gets called after request is complete
 */
Client.prototype.getPublicKeys = function(callback) {
  this.get('/api/public_keys.json', null, callback);
};

/**
 * Find All Public Keys Owned by a Specific User
 * @param  {Integer}  userId  User ID
 * @param  {Function} callback Gets called after request is complete
 */
Client.prototype.getPublicKeysByUser = function(userId, callback) {
  this.get('/api/public_keys.json', { 'user_id': userId }, callback);
};

/**
 * Find All Public Keys Owned by a Specific User
 * @param  {Integer}  keyId  Public Key ID
 * @param  {Function} callback Gets called after request is complete
 */
Client.prototype.getPublicKey = function(keyId, callback) {
  this.get('/api/public_keys/' + keyId + '.json', null, callback);
};

/**
 * FeedKey Resource
 * See: http://api.beanstalkapp.com/feed_key.html
 */

/**
 * Find FeedKey for Current User
 * @param  {Function} callback Gets called after request is complete
 */
Client.prototype.getFeedKey = function(callback) {
  this.get('/api/feed_key.json', null, callback);
};

/**
 * Repository Resource
 * See: http://api.beanstalkapp.com/repository.html
 */

/**
 * Find All Repositories
 * @param  {Object} [params] Find params (optional)
 * @param  {Function} callback Gets called after request is complete
 */
Client.prototype.getRepositories = function(params, callback) {
  if(typeof params === 'function') {
    callback = params;
    params = null;
  }
  this.get('/api/repositories.json', params, callback);
};

/**
 * Find Repository
 * @param  {Object} repository  Repository ID
 * @param  {Function} callback Gets called after request is complete
 */
Client.prototype.getRepository = function(repositoryId, callback) {
  this.get('/api/repositories/' + repositoryId + '.json', null, callback);
};

/**
 * Find Branches
 * @param  {Object} repository  Repository ID
 * @param  {Function} callback Gets called after request is complete
 */
Client.prototype.getBranches = function(repositoryId, callback) {
  this.get('/api/repositories/' + repositoryId + '/branches.json', null, callback);
};

/**
 * Find Tags
 * @param  {Object} repository  Repository ID
 * @param  {Function} callback Gets called after request is complete
 */
Client.prototype.getTags = function(repositoryId, callback) {
  this.get('/api/repositories/' + repositoryId + '/tags.json', null, callback);
};

/**
 * Repository Import Resource
 * See: http://api.beanstalkapp.com/repository_import.html
 */

/**
 * Find All Repository Imports
 * @param  {Object} [params] Find params (optional)
 * @param  {Function} callback Gets called after request is complete
 */
Client.prototype.getRepositoryImports = function(callback) {
  this.get('/api/repository_imports.json', null, callback);
};

/**
 * Find Repository Import
 * @param  {Object} repository  Repository Import ID
 * @param  {Function} callback Gets called after request is complete
 */
Client.prototype.getRepositoryImport = function(repositoryImportId, callback) {
  this.get('/api/repository_imports/' + repositoryImportId + '.json', null, callback);
};<|endoftext|>


<commit_before>'use strict';

//    # Deco 2

//    ## Dependencies

const Bursary = require('bursary');
const CallerPath = require('caller-path');
const D = require('@kunio/d');
const Fs = require('fs');
const Path = require('path');
const PrototypeTool = require('./prototype-tool');

//    ## Utility Functions
// Identity function.
const identity = (a) => a;
// Check if the given value is a class.
const isClass = (a) => {
  if (a.toString().indexOf('class') !== 0) return false;
  return true;
};
// constructors stores the initialization methods for each factory
//   function created with Deco.
// defaults stores the defaults associated with a Deco factory.
const secrets = Bursary({
  constructors: Array,
  defaults: Object
});

//    ## Factory Private Static Members
// Constructors that will be applied sequentially to newly created instances.
const concatenateConstructors = (factory, ...decorators) => {
  const constructors = secrets(factory).constructors;
  constructors.push(...decorators.map((decorator) => {
    if (Reflect.hasOwnProperty.call(decorator, 'constructor')) {
      return decorator.constructor;
    }
    if (typeof decorator === 'function' && !isClass(decorator)) {
      if (!decorator.prototype) return decorator;
      return decorator.prototype.constructor;
    }
    if (isClass(decorator)) {
      return (...parameters) => Reflect.construct(decorator, parameters);
    }
    return undefined;
  }).filter(identity));
};
// Merge any defaults of the given decorators into this factory's defaults.
const concatenateDefaults = (factory, ...decorators) => {
  D.assign(secrets(factory).defaults, ...decorators.map((decorator) => {
    const defaults = secrets(decorator).defaults;
    if (Reflect.ownKeys(defaults).length) return defaults;
    if (Reflect.hasOwnProperty.call(decorator, 'defaults')) {
      return decorator.defaults;
    }
    return undefined;
  }).filter(identity));
};
// Concatenate the flattened prototype chain of the given decorators
// to the factory prototype.
const concatenatePrototypes = (factory, ...decorators) => {
  D.assign(factory.prototype, ...decorators.map((decorator) => {
    if (typeof decorator !== 'function') return decorator;
    return PrototypeTool.flatten(decorator.prototype);
  }).filter(identity));
};
// Use assignment based inheritence to mix in members from objects, vanilla
// JavaScript constructors, and/or Deco decorators.
const concatenate = (factory, ...decorators) => {
  concatenateConstructors(factory, ...decorators);
  concatenateDefaults(factory, ...decorators);
  concatenatePrototypes(factory, ...decorators);
};
// Create and assign the constructor to the given factory prototype.
const initialize = (factory) => {
  // Public instance members
  const instance = {
    constructor: function factoryConstructor (...parameters) {
      /* eslint-disable no-invalid-this */
      const constructors = secrets(factory).constructors;

      // Apply each merged constructor function, one after the other.
      return constructors.reduce((o, ƒ) => {
        const next = ƒ.apply(o, parameters);
        if (next === undefined) return o;
        if (next === o) return o;
        D.assign(next, factory.prototype);
        return next;
      }, this);
      /* eslint-enable no-invalid-this */
    },
    defaults (...updates) {
      return D.clone(secrets(factory).defaults, ...updates);
    }
  };

  // Public static members
  /* eslint-disable no-use-before-define */
  const statics = {
    defaults (...updates) {
      return Deco(this, ...updates.map((o) => ({ defaults: o })));
    }
  };
  /* eslint-enable no-use-before-define */

  // Apply public instance members to the factory prototype.
  for (const name of Reflect.ownKeys(instance)) {
    Reflect.defineProperty(factory.prototype, name, {
      configurable: true,
      enumerable: false,
      value: instance[name],
      writable: true
    });
  }

  // Apply public static members to the factory.
  for (const name of Reflect.ownKeys(statics)) {
    Reflect.defineProperty(factory, name, {
      configurable: true,
      enumerable: false,
      value: statics[name],
      writable: true
    });
  }
};

//    ## Module Definition
//
//    A function used to create factory functions (*classes*) by mixing in any
//    number of objects and/or vanilla JavaScript classes.  Deco factories
//    themselves can be passed in as a decorator to another call to `Deco()`.

const Deco = module.exports = function Deco (...decorators) {
  // A factory function for creating new instances of the "class."
  const factory = function factory (...parameters) {
    /* eslint-disable no-invalid-this */
    const ƒ = factory.prototype.constructor;

    const create = () => Reflect.construct(ƒ, parameters, factory);

    // When called as e.g. `Factory()`.
    if (!this) return create();

    // If the factory was called from a containing object, also create
    // the object e.g. when called as `YourLibrary.Factory()`.
    for (const key of Reflect.ownKeys(this)) {
      if (this[key] === factory) return create();
    }

    // If the decorator is called directly, e.g. `Factory.call(o)`, assign the
    // prototype properties and run the object through the constructor chain
    // manually.
    D.assign(this, factory.prototype);
    return ƒ.apply(this, parameters);
    /* eslint-enable no-invalid-this */
  };

  // Set up the factory prototype, statics, and constructor,
  // then apply the given decorators.
  PrototypeTool.set(factory, Deco);
  initialize(factory);
  concatenate(factory, ...decorators.filter(identity));

  // Make the factory immutable.
  Object.freeze(factory);
  Object.freeze(factory.prototype);

  return factory;
};

// Set up Deco's prototype.  The factory will cause most created objects
// to inherit from Deco.
PrototypeTool.set(Deco, Function);

//    ## Deco Public Methods
// Allow a way for instances to store private data.
Deco.hidden = (definition) => Bursary(definition);
// Load and apply decorators from the caller's directory.
Deco.load = (...files) => {
  const directory = Path.dirname(CallerPath());
  return Deco.loadFrom(directory, ...files);
};
// Load and apply decorators from a directory.
Deco.loadFrom = (directory, ...files) =>
  Deco(...Deco.requireFrom(directory, ...files));
// Require all files in the caller's directory.
Deco.require = (...files) => {
  const directory = Path.dirname(CallerPath());
  return Deco.requireFrom(directory, ...files);
};
// Require a directory, optionally specify names/order of the files
//  to be loaded.
Deco.requireFrom = (directory, ...files) => {
  /* eslint-disable global-require */
  if (!files.length) files.push(...Fs.readdirSync(directory));
  const notIndex = files.filter((file) => {
    if (file === 'index.js') return false;
    if (file === 'index.json') return false;
    if (file === 'index.node') return false;
    return true;
  });
  return notIndex.map((file) => require(Path.resolve(directory, file)));
  /* eslint-enable global-require */
};
<commit_msg>Clean up comments.<commit_after>'use strict';

// # Deco 2

// ## Dependencies

const Bursary = require('bursary');
const CallerPath = require('caller-path');
const D = require('@kunio/d');
const Fs = require('fs');
const Path = require('path');
const PrototypeTool = require('./prototype-tool');

// ## Utility Functions
//
// Identity function.
const identity = (a) => a;
// Check if the given value is a class.
const isClass = (a) => {
  if (a.toString().indexOf('class') !== 0) return false;
  return true;
};
// constructors stores the initialization methods for each factory
//   function created with Deco.
// defaults stores the defaults associated with a Deco factory.
const secrets = Bursary({
  constructors: Array,
  defaults: Object
});

// ## Factory Private Static Members
//
// Constructors that will be applied sequentially to newly
// created instances.
const concatenateConstructors = (factory, ...decorators) => {
  const constructors = secrets(factory).constructors;
  constructors.push(...decorators.map((decorator) => {
    if (Reflect.hasOwnProperty.call(decorator, 'constructor')) {
      return decorator.constructor;
    }
    if (typeof decorator === 'function' && !isClass(decorator)) {
      if (!decorator.prototype) return decorator;
      return decorator.prototype.constructor;
    }
    if (isClass(decorator)) {
      return (...parameters) => Reflect.construct(decorator, parameters);
    }
    return undefined;
  }).filter(identity));
};
// Merge any defaults of the given decorators into this factory's defaults.
const concatenateDefaults = (factory, ...decorators) => {
  D.assign(secrets(factory).defaults, ...decorators.map((decorator) => {
    const defaults = secrets(decorator).defaults;
    if (Reflect.ownKeys(defaults).length) return defaults;
    if (Reflect.hasOwnProperty.call(decorator, 'defaults')) {
      return decorator.defaults;
    }
    return undefined;
  }).filter(identity));
};
// Concatenate the flattened prototype chain of the given decorators
// to the factory prototype.
const concatenatePrototypes = (factory, ...decorators) => {
  D.assign(factory.prototype, ...decorators.map((decorator) => {
    if (typeof decorator !== 'function') return decorator;
    return PrototypeTool.flatten(decorator.prototype);
  }).filter(identity));
};
// Use assignment based inheritence to mix in members from objects, vanilla
// JavaScript constructors, and/or Deco decorators.
const concatenate = (factory, ...decorators) => {
  concatenateConstructors(factory, ...decorators);
  concatenateDefaults(factory, ...decorators);
  concatenatePrototypes(factory, ...decorators);
};
// Create and assign the constructor to the given factory prototype.
const initialize = (factory) => {
  // ### Public instance members
  const instance = {
    constructor: function factoryConstructor (...parameters) {
      /* eslint-disable no-invalid-this */
      const constructors = secrets(factory).constructors;

      // Apply each merged constructor function, one after the other.
      return constructors.reduce((o, ƒ) => {
        const next = ƒ.apply(o, parameters);
        if (next === undefined) return o;
        if (next === o) return o;
        D.assign(next, factory.prototype);
        return next;
      }, this);
      /* eslint-enable no-invalid-this */
    },
    defaults (...updates) {
      return D.clone(secrets(factory).defaults, ...updates);
    }
  };

  // ### Public static members
  /* eslint-disable no-use-before-define */
  const statics = {
    defaults (...updates) {
      return Deco(this, ...updates.map((o) => ({ defaults: o })));
    }
  };
  /* eslint-enable no-use-before-define */

  // Apply public instance members to the factory prototype.
  for (const name of Reflect.ownKeys(instance)) {
    Reflect.defineProperty(factory.prototype, name, {
      configurable: true,
      enumerable: false,
      value: instance[name],
      writable: true
    });
  }

  // Apply public static members to the factory.
  for (const name of Reflect.ownKeys(statics)) {
    Reflect.defineProperty(factory, name, {
      configurable: true,
      enumerable: false,
      value: statics[name],
      writable: true
    });
  }
};

// ## Module Definition
//
// A function used to create factory functions (*classes*) by mixing in any
// number of objects and/or vanilla JavaScript classes.  Deco factories
// themselves can be passed in as a decorator to another call to `Deco()`.

const Deco = module.exports = function Deco (...decorators) {
  // A factory function for creating new instances of the "class."
  const factory = function factory (...parameters) {
    /* eslint-disable no-invalid-this */
    const ƒ = factory.prototype.constructor;

    const create = () => Reflect.construct(ƒ, parameters, factory);

    // When called as e.g. `Factory()`.
    if (!this) return create();

    // If the factory was called from a containing object, also create
    // the object e.g. when called as `YourLibrary.Factory()`.
    for (const key of Reflect.ownKeys(this)) {
      if (this[key] === factory) return create();
    }

    // If the decorator is called directly, e.g. `Factory.call(o)`, assign the
    // prototype properties and run the object through the constructor chain
    // manually.
    D.assign(this, factory.prototype);
    return ƒ.apply(this, parameters);
    /* eslint-enable no-invalid-this */
  };

  // Set up the factory prototype, statics, and constructor,
  // then apply the given decorators.
  PrototypeTool.set(factory, Deco);
  initialize(factory);
  concatenate(factory, ...decorators.filter(identity));

  // Make the factory immutable.
  Object.freeze(factory);
  Object.freeze(factory.prototype);

  return factory;
};

// Set up Deco's prototype.  The factory will cause most created objects
// to inherit from Deco.
PrototypeTool.set(Deco, Function);

// ## Deco Public Methods
// Allow a way for instances to store private data.
Deco.hidden = (definition) => Bursary(definition);
// Load and apply decorators from the caller's directory.
Deco.load = (...files) => {
  const directory = Path.dirname(CallerPath());
  return Deco.loadFrom(directory, ...files);
};
// Load and apply decorators from a directory.
Deco.loadFrom = (directory, ...files) =>
  Deco(...Deco.requireFrom(directory, ...files));
// Require all files in the caller's directory.
Deco.require = (...files) => {
  const directory = Path.dirname(CallerPath());
  return Deco.requireFrom(directory, ...files);
};
// Require a directory, optionally specify names/order of the files
// to be loaded.
Deco.requireFrom = (directory, ...files) => {
  /* eslint-disable global-require */
  if (!files.length) files.push(...Fs.readdirSync(directory));
  const notIndex = files.filter((file) => {
    if (file === 'index.js') return false;
    if (file === 'index.json') return false;
    if (file === 'index.node') return false;
    return true;
  });
  return notIndex.map((file) => require(Path.resolve(directory, file)));
  /* eslint-enable global-require */
};
<|endoftext|>


<commit_before>/*eslint no-console: "off"*/

const mqttWildcard = require("mqtt-wildcard")
const _ = require("lodash")
const AWS = require("aws-sdk")
const request = require("request-promise-native")
const uuid = require("uuid/v4")

const {AWS_ACCESS_KEY, AWS_SECRET_ACCESS_KEY, AWS_IOT_ENDPOINT_HOST, AWS_REGION, CHRIS_TELEGRAM_ID, HANNAH_TELEGRAM_ID, GROUP_TELEGRAM_ID} = process.env

const AWSMqtt = require("aws-mqtt-client").default

const awsMqttClient = new AWSMqtt({
  accessKeyId: AWS_ACCESS_KEY,
  secretAccessKey: AWS_SECRET_ACCESS_KEY,
  endpointAddress: AWS_IOT_ENDPOINT_HOST,
  region: AWS_REGION,
  logger: console
})

const iotdata = new AWS.IotData({
  endpoint: AWS_IOT_ENDPOINT_HOST,
  accessKeyId: AWS_ACCESS_KEY,
  secretAccessKey: AWS_SECRET_ACCESS_KEY,
  region: AWS_REGION,
  logger: console

})

const s3 = new AWS.S3({
  accessKeyId: AWS_ACCESS_KEY,
  secretAccessKey: AWS_SECRET_ACCESS_KEY,
  region: AWS_REGION,
})

const awsTopics = [
  "domoticz/out",
  "owntracks/+/+/event",
  "$aws/things/alarm_status/shadow/update/documents",
  `notify/out/${CHRIS_TELEGRAM_ID}`,
  `notify/out/${HANNAH_TELEGRAM_ID}`
]

awsMqttClient.on("connect", () => awsMqttClient.subscribe(awsTopics,
  {qos: 1},
  (err, granted) => console.log("aws", err, granted)
))

const get_alarm_state = () => iotdata.getThingShadow({thingName: "alarm_status"}).promise()
  .then(thing => JSON.parse(thing.payload).state.reported.state)

const get_alarm_ready_status = () => iotdata.getThingShadow({thingName: "alarm_status"}).promise()
  .then(thing => JSON.parse(thing.payload).state.reported.ready_status)

const set_alarm_state = state => iotdata.updateThingShadow({
  thingName: "alarm_status",
  payload: JSON.stringify({state: {desired: {state: state}}})
}, (err, data) => console.log(err, data))

awsMqttClient.on("message", function (topic, message) {
  message = message_parser(message)

  if (mqttWildcard(topic, "owntracks/+/+/event") !== null) {
    const t = mqttWildcard(topic, "owntracks/+/+/event")
    const device_map = {cnsiphone: "Chris", hnsiphone: "Hannah"}
    const announce_map = {cnsiphone: "Daddy", hnsiphone: "Mummy"}
    // say_helper("garage", `${announce_map[t[1]]} is home`)
    if (message._type === "transition" && message.desc === "Home" && device_map[t[1]]) {
      if (message.event === "enter") {
        say_helper("kitchen", `${announce_map[t[1]]} is home`)
        get_alarm_state()
          .then(state => {
            if (state === "Disarm") {
              notify_helper(TL_MAP[device_map[t[1]].toLowerCase()], "You just got home, alarm is DISARMED")
              domoticz_helper(3, "Off")
            }
            else {
              notify_helper(TL_MAP[device_map[t[1]].toLowerCase()], `You just got home, alarm is ${state}, attempting to disarm`)
              set_alarm_state("disarm")
            }
          })
      }
      if (message.event === "leave") {
        say_helper("kitchen", `${device_map[t[1]]} just left`)
        say_helper("garage", `${device_map[t[1]]} just left`)
        get_alarm_state()
          .then(state => {
            if (state === "Disarm")
              notify_helper(TL_MAP[device_map[t[1]].toLowerCase()], `You just without setting the alarm`)
          })
      }
    }
  }

  if (topic === "$aws/things/alarm_status/shadow/update/documents") {
    // alarm state has changed
    if (message.previous.state.reported.state !== message.current.state.reported.state) {
      console.log(`Alarm state changed to ${message.current.state.reported.state}, it was ${message.previous.state.reported.state}`)
      notify_helper(GROUP_TELEGRAM_ID, `Alarm state changed to ${message.current.state.reported.state}, it was ${message.previous.state.reported.state}`)

      if (message.current.state.reported.state === "Disarm") {
        say_helper("kitchen", `Alarm is now disarmed`)
        domoticz_helper(3, "Off")
        domoticz_helper(51, "On")
      }
    }
  }

  //zwave log
  if (topic === "zwave/log")
    notify_helper(CHRIS_TELEGRAM_ID, `zwave ${message.homeid} ${JSON.stringify(message.log)}`)

  // react to chatbot commands
  if ((t = mqttWildcard(topic, "notify/out/+")) && t !== null) {
    // send acknowledgement back to user
    // notify_helper(t[0].toString(), "ACK", null, true)

    message = message.toLowerCase()
    console.log(`Telegram user ${t[0]} just sent:"${message}"`)

    if (message === messages.unlock_door.toLowerCase())
      iotdata.updateThingShadow({
        thingName: "zwave_d5264b94_26",
        payload: JSON.stringify({state: {desired: {user: {Locked: 0}}}})
      }, (err, data) => console.log(err, data))

    if (message === messages.doorbell_off.toLowerCase())
      domoticz_helper(195, "Off")

    if (message === messages.doorbell_on.toLowerCase())
      domoticz_helper(195, "On")

    if (message === messages.arm_alarm_home.toLowerCase()) {
      reply_with_alarm_status(t[0].toString())
      set_alarm_state("arm_home")
    }

    if (message === messages.arm_alarm_away.toLowerCase()) {
      reply_with_alarm_status(t[0].toString())
      set_alarm_state("arm_away")
    }

    if (message === messages.disarm_alarm.toLowerCase())
      set_alarm_state("disarm")

    if (message.startsWith("say")) {
      let split_message = /say\s(\w+)(.*)/gi.exec(message)
      say_helper(split_message[1], split_message[2])
    }

    if (message === messages.start.toLowerCase())
      notify_helper(t[0], `You can do these things`, messages)

    if (message === messages.cam_driveway.toLowerCase())
      send_camera_to("camera_external_driveway", t[0])

    if (message === messages.cam_garden.toLowerCase())
      send_camera_to("camera_external_garden", t[0])

    if (message === messages.get_alarm_status.toLowerCase())
      get_alarm_state()
        .then(state => notify_helper(t[0], state))

    // zwave
    if (message === messages.zwave.toLowerCase())
      notify_helper(t[0], `You can do these zwave things`, zwave_messages)

    if (message === zwave_messages.zwave_secureadd.toLowerCase())
      zwave_helper("zwave_f2e55e6c", {secureAddNode: random_number()})

    if (message === zwave_messages.zwave_add.toLowerCase())
      zwave_helper("zwave_f2e55e6c", {addNode: random_number()})

    if (message === zwave_messages.zwave_cancel.toLowerCase())
      zwave_helper("zwave_f2e55e6c", {cancelControllerCommand: random_number()})

    if (message === zwave_messages.zwave_remove.toLowerCase())
      zwave_helper("zwave_f2e55e6c", {removeNode: random_number()})

    if (message === zwave_messages.zwave_heal.toLowerCase())
      zwave_helper("zwave_f2e55e6c", {healNetwork: random_number()})

    if (message === zwave_messages.zwave_reset.toLowerCase())
      zwave_helper("zwave_f2e55e6c", {softReset: random_number()})

    if (message === zwave_messages.zwave_follow.toLowerCase()) {
      awsMqttClient.subscribe("zwave/log")
      setTimeout(awsMqttClient.unsubscribe, 5 * 60 * 1000, "zwave/log")
    }
  }

  // someone at the door
  if (topic === "domoticz/out" && message.stype === "Switch" && message.idx === 155 && message.nvalue === 1) {
    console.log("door bell!")
    get_alarm_state()
      .then(state => {
        if (state !== "Away") {
          _.times(4, () => domoticz_helper(79, "Toggle"))
          say_helper("kitchen", "Someone at the door")
          say_helper("garage", "Someone at the door")
        }
      })

    notify_helper(GROUP_TELEGRAM_ID, `Someone at the door`, [messages.unlock_door])

    send_camera_to("camera_external_driveway", GROUP_TELEGRAM_ID)

  }

  // zwave low battery alert
  if (topic === "domoticz/out" && message.Battery && message.Battery < 15)
    notify_helper(CHRIS_TELEGRAM_ID, `zwave device ${message.idx} ${message.name} is low on battery`)

})

const random_number = () => Math.floor((Math.random() * 100000) + 1)

const send_camera_to = (camera, who) => {
  let inst_uuid = uuid()
  return iotdata.getThingShadow({thingName: camera}).promise()
    .then(thing => JSON.parse(thing.payload).state.reported.jpg)

    .then(camera_url => request({uri: camera_url, encoding: null}))
    .then(body => s3.putObject({
      Body: body,
      Key: `${inst_uuid}.jpg`,
      ContentType: "image/jpeg",
      Bucket: "me.cns.p.cams"
    }).promise())
    .then(() => s3.getSignedUrl("getObject", {Bucket: "me.cns.p.cams", Key: `${inst_uuid}.jpg`}))
    .then(signedurl => notify_helper(who, null, null, true, signedurl))
}

const reply_with_alarm_status = who => get_alarm_ready_status().then(ready_status => notify_helper(who, `Alarm is currently${ready_status ? " " : " not "}ready to arm`, null, true))

const is_alarm_device_open = device => {
  if (current_alarm_full_status && current_alarm_full_status.ready_status === true) {
    return false
  }
  return (device.troubles && device.troubles.includes("OPENED"))
}

const messages = {
  start: "/start",
  unlock_door: "Unlock the door",
  disarm_alarm: "Disarm alarm",
  arm_alarm_home: "Arm alarm home",
  arm_alarm_away: "Arm alarm away",
  get_alarm_status: "Get alarm status",
  doorbell_off: "Doorbell off",
  doorbell_on: "Doorbell on",
  cam_driveway: "Get driveway camera",
  cam_garden: "Get garden camera",
  zwave: "Z-wave management"
}

const zwave_messages = {
  start: "/start",
  zwave_secureadd: "Securely add device",
  zwave_add: "Insecurely add device",
  zwave_cancel: "Cancel controller command",
  zwave_remove: "Remove device",
  zwave_heal: "Heal network",
  zwave_reset: "Soft reset controller",
  zwave_follow: "Follow events for 5 minutes"
}

const TL_MAP = {
  chris: CHRIS_TELEGRAM_ID,
  hannah: HANNAH_TELEGRAM_ID
}

const message_parser = message => {
  try {
    return JSON.parse(message.toString())
  }
  catch (e) {
    return message.toString()
  }
}

const zwave_helper = (thing, state) => iotdata.updateThingShadow({
  thingName: thing,
  payload: JSON.stringify({state: {desired: state}})
},).promise()

const lights_helper = (light, state) => client.publish(`lifx-lights/${light}`, state)

const notify_helper = (who, message, actions = null, disableNotification = false, image = null) =>
  awsMqttClient.publish(`notify/in/${who}`, JSON.stringify({
    disableNotification: disableNotification,
    message: message,
    image: image,
    buttons: actions ? _.map(actions, action => {
      return {title: action, value: action}
    }) : null
  }))

const domoticz_helper = (idx, state) =>
  awsMqttClient.publish("domoticz/in", JSON.stringify({
    command: "switchlight",
    idx: idx,
    switchcmd: state
  }), {qos: 0})

const say_helper = (where, what) =>
  awsMqttClient.publish(`sonos/say/${where}`, JSON.stringify([what, getSayVolume()]), {qos: 0})

const getSayVolume = () => _.inRange(new Date().getHours(), 6, 18) ? 40 : 15

awsMqttClient.on("connect", () => console.log("aws connected"))
awsMqttClient.on("error", (error) => console.error("aws", error))
awsMqttClient.on("close", () => console.error("aws connection close"))
awsMqttClient.on("offline", () => console.log("aws offline"))
<commit_msg>feedback on getting subscription<commit_after>/*eslint no-console: "off"*/

const mqttWildcard = require("mqtt-wildcard")
const _ = require("lodash")
const AWS = require("aws-sdk")
const request = require("request-promise-native")
const uuid = require("uuid/v4")

const {AWS_ACCESS_KEY, AWS_SECRET_ACCESS_KEY, AWS_IOT_ENDPOINT_HOST, AWS_REGION, CHRIS_TELEGRAM_ID, HANNAH_TELEGRAM_ID, GROUP_TELEGRAM_ID} = process.env

const AWSMqtt = require("aws-mqtt-client").default

const awsMqttClient = new AWSMqtt({
  accessKeyId: AWS_ACCESS_KEY,
  secretAccessKey: AWS_SECRET_ACCESS_KEY,
  endpointAddress: AWS_IOT_ENDPOINT_HOST,
  region: AWS_REGION,
  logger: console
})

const iotdata = new AWS.IotData({
  endpoint: AWS_IOT_ENDPOINT_HOST,
  accessKeyId: AWS_ACCESS_KEY,
  secretAccessKey: AWS_SECRET_ACCESS_KEY,
  region: AWS_REGION,
  logger: console

})

const s3 = new AWS.S3({
  accessKeyId: AWS_ACCESS_KEY,
  secretAccessKey: AWS_SECRET_ACCESS_KEY,
  region: AWS_REGION,
})

const awsTopics = [
  "domoticz/out",
  "owntracks/+/+/event",
  "$aws/things/alarm_status/shadow/update/documents",
  `notify/out/${CHRIS_TELEGRAM_ID}`,
  `notify/out/${HANNAH_TELEGRAM_ID}`
]

awsMqttClient.on("connect", () => awsMqttClient.subscribe(awsTopics,
  {qos: 1},
  (err, granted) => console.log("aws", err, granted)
))

const get_alarm_state = () => iotdata.getThingShadow({thingName: "alarm_status"}).promise()
  .then(thing => JSON.parse(thing.payload).state.reported.state)

const get_alarm_ready_status = () => iotdata.getThingShadow({thingName: "alarm_status"}).promise()
  .then(thing => JSON.parse(thing.payload).state.reported.ready_status)

const set_alarm_state = state => iotdata.updateThingShadow({
  thingName: "alarm_status",
  payload: JSON.stringify({state: {desired: {state: state}}})
}, (err, data) => console.log(err, data))

awsMqttClient.on("message", function (topic, message) {
  message = message_parser(message)

  if (mqttWildcard(topic, "owntracks/+/+/event") !== null) {
    const t = mqttWildcard(topic, "owntracks/+/+/event")
    const device_map = {cnsiphone: "Chris", hnsiphone: "Hannah"}
    const announce_map = {cnsiphone: "Daddy", hnsiphone: "Mummy"}
    // say_helper("garage", `${announce_map[t[1]]} is home`)
    if (message._type === "transition" && message.desc === "Home" && device_map[t[1]]) {
      if (message.event === "enter") {
        say_helper("kitchen", `${announce_map[t[1]]} is home`)
        get_alarm_state()
          .then(state => {
            if (state === "Disarm") {
              notify_helper(TL_MAP[device_map[t[1]].toLowerCase()], "You just got home, alarm is DISARMED")
              domoticz_helper(3, "Off")
            }
            else {
              notify_helper(TL_MAP[device_map[t[1]].toLowerCase()], `You just got home, alarm is ${state}, attempting to disarm`)
              set_alarm_state("disarm")
            }
          })
      }
      if (message.event === "leave") {
        say_helper("kitchen", `${device_map[t[1]]} just left`)
        say_helper("garage", `${device_map[t[1]]} just left`)
        get_alarm_state()
          .then(state => {
            if (state === "Disarm")
              notify_helper(TL_MAP[device_map[t[1]].toLowerCase()], `You just without setting the alarm`)
          })
      }
    }
  }

  if (topic === "$aws/things/alarm_status/shadow/update/documents") {
    // alarm state has changed
    if (message.previous.state.reported.state !== message.current.state.reported.state) {
      console.log(`Alarm state changed to ${message.current.state.reported.state}, it was ${message.previous.state.reported.state}`)
      notify_helper(GROUP_TELEGRAM_ID, `Alarm state changed to ${message.current.state.reported.state}, it was ${message.previous.state.reported.state}`)

      if (message.current.state.reported.state === "Disarm") {
        say_helper("kitchen", `Alarm is now disarmed`)
        domoticz_helper(3, "Off")
        domoticz_helper(51, "On")
      }
    }
  }

  //zwave log
  if (topic === "zwave/log")
    notify_helper(CHRIS_TELEGRAM_ID, `zwave ${message.homeid} ${JSON.stringify(message.log)}`)

  // react to chatbot commands
  if ((t = mqttWildcard(topic, "notify/out/+")) && t !== null) {
    // send acknowledgement back to user
    // notify_helper(t[0].toString(), "ACK", null, true)

    message = message.toLowerCase()
    console.log(`Telegram user ${t[0]} just sent:"${message}"`)

    if (message === messages.unlock_door.toLowerCase())
      iotdata.updateThingShadow({
        thingName: "zwave_d5264b94_26",
        payload: JSON.stringify({state: {desired: {user: {Locked: 0}}}})
      }, (err, data) => console.log(err, data))

    if (message === messages.doorbell_off.toLowerCase())
      domoticz_helper(195, "Off")

    if (message === messages.doorbell_on.toLowerCase())
      domoticz_helper(195, "On")

    if (message === messages.arm_alarm_home.toLowerCase()) {
      reply_with_alarm_status(t[0].toString())
      set_alarm_state("arm_home")
    }

    if (message === messages.arm_alarm_away.toLowerCase()) {
      reply_with_alarm_status(t[0].toString())
      set_alarm_state("arm_away")
    }

    if (message === messages.disarm_alarm.toLowerCase())
      set_alarm_state("disarm")

    if (message.startsWith("say")) {
      let split_message = /say\s(\w+)(.*)/gi.exec(message)
      say_helper(split_message[1], split_message[2])
    }

    if (message === messages.start.toLowerCase())
      notify_helper(t[0], `You can do these things`, messages)

    if (message === messages.cam_driveway.toLowerCase())
      send_camera_to("camera_external_driveway", t[0])

    if (message === messages.cam_garden.toLowerCase())
      send_camera_to("camera_external_garden", t[0])

    if (message === messages.get_alarm_status.toLowerCase())
      get_alarm_state()
        .then(state => notify_helper(t[0], state))

    // zwave
    if (message === messages.zwave.toLowerCase())
      notify_helper(t[0], `You can do these zwave things`, zwave_messages)

    if (message === zwave_messages.zwave_secureadd.toLowerCase())
      zwave_helper("zwave_f2e55e6c", {secureAddNode: random_number()})

    if (message === zwave_messages.zwave_add.toLowerCase())
      zwave_helper("zwave_f2e55e6c", {addNode: random_number()})

    if (message === zwave_messages.zwave_cancel.toLowerCase())
      zwave_helper("zwave_f2e55e6c", {cancelControllerCommand: random_number()})

    if (message === zwave_messages.zwave_remove.toLowerCase())
      zwave_helper("zwave_f2e55e6c", {removeNode: random_number()})

    if (message === zwave_messages.zwave_heal.toLowerCase())
      zwave_helper("zwave_f2e55e6c", {healNetwork: random_number()})

    if (message === zwave_messages.zwave_reset.toLowerCase())
      zwave_helper("zwave_f2e55e6c", {softReset: random_number()})

    if (message === zwave_messages.zwave_follow.toLowerCase()) {
      awsMqttClient.subscribe("zwave/log", {qos: 1},
        (err, granted) => console.log("aws", err, granted)
      )
      setTimeout(awsMqttClient.unsubscribe, 5 * 60 * 1000, "zwave/log")
    }
  }

  // someone at the door
  if (topic === "domoticz/out" && message.stype === "Switch" && message.idx === 155 && message.nvalue === 1) {
    console.log("door bell!")
    get_alarm_state()
      .then(state => {
        if (state !== "Away") {
          _.times(4, () => domoticz_helper(79, "Toggle"))
          say_helper("kitchen", "Someone at the door")
          say_helper("garage", "Someone at the door")
        }
      })

    notify_helper(GROUP_TELEGRAM_ID, `Someone at the door`, [messages.unlock_door])

    send_camera_to("camera_external_driveway", GROUP_TELEGRAM_ID)

  }

  // zwave low battery alert
  if (topic === "domoticz/out" && message.Battery && message.Battery < 15)
    notify_helper(CHRIS_TELEGRAM_ID, `zwave device ${message.idx} ${message.name} is low on battery`)

})

const random_number = () => Math.floor((Math.random() * 100000) + 1)

const send_camera_to = (camera, who) => {
  let inst_uuid = uuid()
  return iotdata.getThingShadow({thingName: camera}).promise()
    .then(thing => JSON.parse(thing.payload).state.reported.jpg)

    .then(camera_url => request({uri: camera_url, encoding: null}))
    .then(body => s3.putObject({
      Body: body,
      Key: `${inst_uuid}.jpg`,
      ContentType: "image/jpeg",
      Bucket: "me.cns.p.cams"
    }).promise())
    .then(() => s3.getSignedUrl("getObject", {Bucket: "me.cns.p.cams", Key: `${inst_uuid}.jpg`}))
    .then(signedurl => notify_helper(who, null, null, true, signedurl))
}

const reply_with_alarm_status = who => get_alarm_ready_status().then(ready_status => notify_helper(who, `Alarm is currently${ready_status ? " " : " not "}ready to arm`, null, true))

const is_alarm_device_open = device => {
  if (current_alarm_full_status && current_alarm_full_status.ready_status === true) {
    return false
  }
  return (device.troubles && device.troubles.includes("OPENED"))
}

const messages = {
  start: "/start",
  unlock_door: "Unlock the door",
  disarm_alarm: "Disarm alarm",
  arm_alarm_home: "Arm alarm home",
  arm_alarm_away: "Arm alarm away",
  get_alarm_status: "Get alarm status",
  doorbell_off: "Doorbell off",
  doorbell_on: "Doorbell on",
  cam_driveway: "Get driveway camera",
  cam_garden: "Get garden camera",
  zwave: "Z-wave management"
}

const zwave_messages = {
  start: "/start",
  zwave_secureadd: "Securely add device",
  zwave_add: "Insecurely add device",
  zwave_cancel: "Cancel controller command",
  zwave_remove: "Remove device",
  zwave_heal: "Heal network",
  zwave_reset: "Soft reset controller",
  zwave_follow: "Follow events for 5 minutes"
}

const TL_MAP = {
  chris: CHRIS_TELEGRAM_ID,
  hannah: HANNAH_TELEGRAM_ID
}

const message_parser = message => {
  try {
    return JSON.parse(message.toString())
  }
  catch (e) {
    return message.toString()
  }
}

const zwave_helper = (thing, state) => iotdata.updateThingShadow({
  thingName: thing,
  payload: JSON.stringify({state: {desired: state}})
},).promise()

const lights_helper = (light, state) => client.publish(`lifx-lights/${light}`, state)

const notify_helper = (who, message, actions = null, disableNotification = false, image = null) =>
  awsMqttClient.publish(`notify/in/${who}`, JSON.stringify({
    disableNotification: disableNotification,
    message: message,
    image: image,
    buttons: actions ? _.map(actions, action => {
      return {title: action, value: action}
    }) : null
  }))

const domoticz_helper = (idx, state) =>
  awsMqttClient.publish("domoticz/in", JSON.stringify({
    command: "switchlight",
    idx: idx,
    switchcmd: state
  }), {qos: 0})

const say_helper = (where, what) =>
  awsMqttClient.publish(`sonos/say/${where}`, JSON.stringify([what, getSayVolume()]), {qos: 0})

const getSayVolume = () => _.inRange(new Date().getHours(), 6, 18) ? 40 : 15

awsMqttClient.on("connect", () => console.log("aws connected"))
awsMqttClient.on("error", (error) => console.error("aws", error))
awsMqttClient.on("close", () => console.error("aws connection close"))
awsMqttClient.on("offline", () => console.log("aws offline"))
<|endoftext|>


<commit_before>var http = require('http');

http.createServer(function (req, res) {
  console.log(req);

  res.statusCode = 200;
  res.end('OK');
}).listen(process.env.PORT);
<commit_msg>OK - let's try this again<commit_after>var http = require('http')
var createHandler = require('github-webhook-handler')
var handler = createHandler({ path: '/webhook', secret: 'myhashsecret' })

http.createServer(function (req, res) {
  handler(req, res, function (err) {
    res.statusCode = 404
    res.end('no such location')
  })
}).listen(process.env.PORT)

handler.on('error', function (err) {
  console.error('Error:', err.message)
})

handler.on('push', function (event) {
  console.log('Received a push event for %s to %s',
    event.payload.repository.name,
    event.payload.ref)
})

handler.on('issues', function (event) {
  console.log('Received an issue event for %s action=%s: #%d %s',
    event.payload.repository.name,
    event.payload.action,
    event.payload.issue.number,
    event.payload.issue.title)
})
<|endoftext|>


<commit_before>var
    node_static = require('node-static'),
    work_dir = process.env.WORKDIR || '/var/www',
    file_server = new node_static.Server(work_dir),
    port = process.env.PORT || 3000;

require('http').createServer(function(request, response) {
    request.addListener('end', function() {
        file_server.serve(request, response);
    }).resume();
}).listen(port, function() {
    console.log('Running node-static server on port: ' + port);
});<commit_msg>duplicated<commit_after><|endoftext|>


<commit_before>// -- Transforms -----

import {extend} from 'vega-util';
import {transforms} from 'vega-dataflow';
import * as tx from 'vega-transforms';
import * as vtx from 'vega-view-transforms';
import * as encode from 'vega-encode';
import * as geo from 'vega-geo';
import * as force from 'vega-force';
import * as tree from 'vega-hierarchy';
import * as voronoi from 'vega-voronoi';
import * as wordcloud from 'vega-wordcloud';
import * as xf from 'vega-crossfilter';
extend(transforms, tx, vtx, encode, geo, force, tree, voronoi, wordcloud, xf);

// -- Exports -----

export {
  version
} from './package.json';

export * from 'vega-statistics';

export * from 'vega-util';

export * from 'vega-loader';

export * from 'vega-scenegraph';

export {
  Dataflow,
  EventStream,
  Parameters,
  Pulse,
  MultiPulse,
  Operator,
  Transform,
  changeset,
  ingest,
  isTuple,
  definition,
  transform,
  transforms,
  tupleid
} from 'vega-dataflow';

export {
  scale,
  scheme,
  interpolate,
  interpolateRange
} from 'vega-scale';

export {
  projection
} from 'vega-projection';

export {
  View
} from 'vega-view';

export {
  parse,
  expressionFunction,
  formatLocale,
  timeFormatLocale
} from 'vega-parser';

export {
  parse as runtime,
  context as runtimeContext
} from 'vega-runtime';
<commit_msg>Export timeInterval and utcInterval utilities.<commit_after>// -- Transforms -----

import {extend} from 'vega-util';
import {transforms} from 'vega-dataflow';
import * as tx from 'vega-transforms';
import * as vtx from 'vega-view-transforms';
import * as encode from 'vega-encode';
import * as geo from 'vega-geo';
import * as force from 'vega-force';
import * as tree from 'vega-hierarchy';
import * as voronoi from 'vega-voronoi';
import * as wordcloud from 'vega-wordcloud';
import * as xf from 'vega-crossfilter';
extend(transforms, tx, vtx, encode, geo, force, tree, voronoi, wordcloud, xf);

// -- Exports -----

export {
  version
} from './package.json';

export * from 'vega-statistics';

export * from 'vega-util';

export * from 'vega-loader';

export * from 'vega-scenegraph';

export {
  Dataflow,
  EventStream,
  Parameters,
  Pulse,
  MultiPulse,
  Operator,
  Transform,
  changeset,
  ingest,
  isTuple,
  definition,
  transform,
  transforms,
  tupleid
} from 'vega-dataflow';

export {
  scale,
  scheme,
  interpolate,
  interpolateRange,
  timeInterval,
  utcInterval
} from 'vega-scale';

export {
  projection
} from 'vega-projection';

export {
  View
} from 'vega-view';

export {
  parse,
  expressionFunction,
  formatLocale,
  timeFormatLocale
} from 'vega-parser';

export {
  parse as runtime,
  context as runtimeContext
} from 'vega-runtime';
<|endoftext|>


<commit_before>/* jshint node:true */

'use strict';

var through     = require('through2'),
    mkdirp      = require('mkdirp'),
    gutil       = require('gulp-util'),
    path        = require('path'),
    fs          = require('fs'),
    async       = require('async'),
    PluginError = gutil.PluginError,
    File        = gutil.File,
    isWin       = process.platform === 'win32',
    debug;

var PLUGIN_NAME = 'gulp-symlink';

/**
 * Wrapper to log when debug === true
 * it's basically a console.log
 */
var log = function() {
  if(debug === true) {
    console.log.apply(console, [].slice.call(arguments));
    return console.log;
  } else {
    return function() { };
  }

};

/**
 * Error wrapper - this is called in the through context
 * @param  {Error}   error  The error
 * @return  {Function} cb    The through callback
 */
var errored = function(error, cb) {
  this.emit('error', new PluginError(PLUGIN_NAME, error));
  //Push the file so that the stream is piped to the next task even if it has errored
  //might be discussed
  this.push(this.source);
  return cb();
};

var symlinker = function(destination, resolver, options) {

  if(typeof resolver === 'object') {
    options = resolver;
    resolver = 'relative';
  }

  options = typeof options === 'object' ? options : {};
  options.force = options.force === undefined ? false : options.force;
  options.log = options.log === undefined ? true : options.log;

  //Handling array of destinations, this test is because "instance of" isn't safe
  if( Object.prototype.toString.call( destination ) === '[object Array]' ) {
    //copy array because we'll shift values
    var destinations = destination.slice();
  }

  return through.obj(function(source, encoding, callback) {

    var self = this, symlink;

    this.source = source; //error binding

    //else if we've got an array from before take the next element as a destination path
    symlink = destinations !== undefined ? destinations.shift() : symlink;

    //if destination is a function pass the source to it
    if(symlink === undefined) {
      symlink = typeof destination === 'function' ? destination(source) : destination;
    }

    //if symlink is still undefined there is a problem!
    if (symlink === undefined) {
      return errored.call(self, 'An output destination is required.', callback);
    }

    // Convert the destination path to a new vinyl instance
    symlink = symlink instanceof File ? symlink : new File({ path: symlink });

    log('Before resolving')('Source: %s – dest: %s', source.path, symlink.path);

    symlink.directory = path.dirname(symlink.path); //this is the parent directory of the symlink

    // Resolve the path to the symlink
    if(resolver === 'relative' || options.relative === true) {
      source.resolved = path.relative(symlink.directory, source.path);
    } else {
      //resolve the absolute path from the source. It need to be from the current working directory to handle relative sources
      source.resolved =  path.resolve(source.cwd, source.path);
    }

    log('After resolving')(source.resolved + ' in ' + symlink.path);

    fs.exists(symlink.path, function(exists) {

      //No force option, we can't override!
      if(exists && !options.force) {
        return errored.call(self, 'Destination file exists ('+symlink.path+') - use force option to replace', callback);
      } else {

        async.waterfall([
          function(next){
            //remove destination if it exists already
            if(exists && options.force === true) {
              fs.unlink(symlink.path, function(err) {
                if(err) {
                  return errored.call(self, err, callback);
                }

                next();
              });
            } else {
              next();
            }
          },
          //checking if the parent directory exists
          function(next) {
            mkdirp(symlink.directory, function(err) {
              //ignoring directory err if it exists
              if(err && err.code !== 'EEXIST') {
                return errored.call(self, err, callback);
              }

              next();
            });
          }
        ], function () {
          //this is a windows check as specified in http://nodejs.org/api/fs.html#fs_fs_symlink_srcpath_dstpath_type_callback
          fs.stat(source.path, function(err, stat) {
            if(err) {
              return errored.call(self, err, callback);
            }

            source.stat = stat;

            fs.symlink(source.resolved, symlink.path, source.stat.isDirectory() ? 'dir' : 'file', function(err) {
              var success = function(){
                if (options.log) {
                  gutil.log(PLUGIN_NAME + ':' + gutil.colors.magenta(source.path), 'symlinked to', gutil.colors.magenta(symlink.path));
                }
                self.push(source);
                return callback();
              };

              if(err) {
                  if (!isWin || err.code !== 'EPERM') {
                    return errored.call(self, err, callback);
                  }

                  // Try with type "junction" on Windows
                  // Junctions behave equally to true symlinks and can be created in
                  // non elevated terminal (well, not always..)
                  fs.symlink(source.resolved, symlink.path, 'junction', function(err) {
                    if (err) {
                      return errored.call(self, err, callback);
                    }

                    return success();
                  });
              }

              return success();

            });

          });

        });

      }

    });

  });
};

var relativesymlinker = function(symlink, options) {
  return symlinker(symlink, 'relative', options);
};

var absolutesymlinker = function(symlink, options) {
  return symlinker(symlink, 'absolute', options);
};

// Expose main functionality under relative, for convenience
module.exports           = relativesymlinker;
module.exports.relative  = relativesymlinker;
module.exports.absolute  = absolutesymlinker;
module.exports.File      = File;

module.exports._setDebug = function(value) {
  debug = value;
};
<commit_msg>Full path now given for windows juntions<commit_after>/* jshint node:true */

'use strict';

var through     = require('through2'),
    mkdirp      = require('mkdirp'),
    gutil       = require('gulp-util'),
    path        = require('path'),
    fs          = require('fs'),
    async       = require('async'),
    PluginError = gutil.PluginError,
    File        = gutil.File,
    isWin       = process.platform === 'win32',
    debug;

var PLUGIN_NAME = 'gulp-symlink';

/**
 * Wrapper to log when debug === true
 * it's basically a console.log
 */
var log = function() {
  if(debug === true) {
    console.log.apply(console, [].slice.call(arguments));
    return console.log;
  } else {
    return function() { };
  }

};

/**
 * Error wrapper - this is called in the through context
 * @param  {Error}   error  The error
 * @return  {Function} cb    The through callback
 */
var errored = function(error, cb) {
  this.emit('error', new PluginError(PLUGIN_NAME, error));
  //Push the file so that the stream is piped to the next task even if it has errored
  //might be discussed
  this.push(this.source);
  return cb();
};

var symlinker = function(destination, resolver, options) {

  if(typeof resolver === 'object') {
    options = resolver;
    resolver = 'relative';
  }

  options = typeof options === 'object' ? options : {};
  options.force = options.force === undefined ? false : options.force;
  options.log = options.log === undefined ? true : options.log;

  //Handling array of destinations, this test is because "instance of" isn't safe
  if( Object.prototype.toString.call( destination ) === '[object Array]' ) {
    //copy array because we'll shift values
    var destinations = destination.slice();
  }

  return through.obj(function(source, encoding, callback) {

    var self = this, symlink;

    this.source = source; //error binding

    //else if we've got an array from before take the next element as a destination path
    symlink = destinations !== undefined ? destinations.shift() : symlink;

    //if destination is a function pass the source to it
    if(symlink === undefined) {
      symlink = typeof destination === 'function' ? destination(source) : destination;
    }

    //if symlink is still undefined there is a problem!
    if (symlink === undefined) {
      return errored.call(self, 'An output destination is required.', callback);
    }

    // Convert the destination path to a new vinyl instance
    symlink = symlink instanceof File ? symlink : new File({ path: symlink });

    log('Before resolving')('Source: %s – dest: %s', source.path, symlink.path);

    symlink.directory = path.dirname(symlink.path); //this is the parent directory of the symlink

    // Resolve the path to the symlink
    if(resolver === 'relative' || options.relative === true) {
      source.resolved = path.relative(symlink.directory, source.path);
    } else {
      //resolve the absolute path from the source. It need to be from the current working directory to handle relative sources
      source.resolved =  path.resolve(source.cwd, source.path);
    }

    log('After resolving')(source.resolved + ' in ' + symlink.path);

    fs.exists(symlink.path, function(exists) {

      //No force option, we can't override!
      if(exists && !options.force) {
        return errored.call(self, 'Destination file exists ('+symlink.path+') - use force option to replace', callback);
      } else {

        async.waterfall([
          function(next){
            //remove destination if it exists already
            if(exists && options.force === true) {
              fs.unlink(symlink.path, function(err) {
                if(err) {
                  return errored.call(self, err, callback);
                }

                next();
              });
            } else {
              next();
            }
          },
          //checking if the parent directory exists
          function(next) {
            mkdirp(symlink.directory, function(err) {
              //ignoring directory err if it exists
              if(err && err.code !== 'EEXIST') {
                return errored.call(self, err, callback);
              }

              next();
            });
          }
        ], function () {
          //this is a windows check as specified in http://nodejs.org/api/fs.html#fs_fs_symlink_srcpath_dstpath_type_callback
          fs.stat(source.path, function(err, stat) {
            if(err) {
              return errored.call(self, err, callback);
            }

            source.stat = stat;

            fs.symlink(source.resolved, symlink.path, source.stat.isDirectory() ? 'dir' : 'file', function(err) {
              var success = function(){
                if (options.log) {
                  gutil.log(PLUGIN_NAME + ':' + gutil.colors.magenta(source.path), 'symlinked to', gutil.colors.magenta(symlink.path));
                }
                self.push(source);
                return callback();
              };

              if(err) {
                  if (!isWin || err.code !== 'EPERM') {
                    return errored.call(self, err, callback);
                  }

                  // Try with type "junction" on Windows
                  // Junctions behave equally to true symlinks and can be created in
                  // non elevated terminal (well, not always..)
                  fs.symlink(source.path, symlink.path, 'junction', function(err) {
                    if (err) {
                      return errored.call(self, err, callback);
                    }

                    return success();
                  });
              }

              return success();

            });

          });

        });

      }

    });

  });
};

var relativesymlinker = function(symlink, options) {
  return symlinker(symlink, 'relative', options);
};

var absolutesymlinker = function(symlink, options) {
  return symlinker(symlink, 'absolute', options);
};

// Expose main functionality under relative, for convenience
module.exports           = relativesymlinker;
module.exports.relative  = relativesymlinker;
module.exports.absolute  = absolutesymlinker;
module.exports.File      = File;

module.exports._setDebug = function(value) {
  debug = value;
};
<|endoftext|>