<commit_before>var bpiscreen = require('./lib/bpiscreen')
var config = require('./lib/globals-config')
var internalIp = require('internal-ip')
var publicIp = require('public-ip')
var os = require('os')
var numeral = require('numeral')
var exec = require('child_process').exec
var isOnline = require('is-online')
var Bleacon = require('bleacon')
var PeaconDB = require('./lib/peacon-db')

var events = require("events"),
	displayEvents = new events.EventEmitter()

var actualScreenX = 0, actualScreenY = 0
var screenIntervalId

var beaconHistory = []
var beaconHistoryCount = 0

// ----------------------------------------------------------------
// GET SCREEN TEXT
// ----------------------------------------------------------------
// this array will return the text from each of screen position
var updateScreen = [
	[
		// first screen, show simple message
		function() {
			updateDisplayMsg("Aguardando\nbeacons...")
		}
	],
	[
		// this screen will show the last seen beacons
		function() {
			// TODO list last beacons
			if(beaconHistoryCount == 0)
				updateDisplayMsg("Nenhum beacon\nencontrado")
			else if(beaconHistoryCount == 1)
				updateDisplayMsg("1 beacon\nencontrado")
			else
				updateDisplayMsg(beaconHistoryCount + " beacons\nencontrados")
		}
	],
	[
		// this screen will display the RPi statistics, such as load average,
		// CPU temp, public and internal IP address
		function() {
			// TODO Improve to rewrite only the second line
			updateLoadAverage()
			screenIntervalId = setInterval(updateLoadAverage, 1000)
		},
		function() {
			// TODO Improve to rewrite only the second line
			updateSysTemp()
			screenIntervalId = setInterval(updateSysTemp, 1000)
		},
		function() {
			//displayEvents.emit('updated', "IP Privado\n" + internalIp())
			updateDisplayMsg("IP Privado\n" + internalIp())
		},
		function() {
			updateDisplayMsg("IP Publico\nCarregando...")
			publicIp(function (err, ip) {
				if(!ip)
					updateDisplayMsg("IP Publico\nnao encontrado")
				else
					updateDisplayMsg("IP Publico\n" + ip)
			})
		}
	]
]

var updateLoadAverage = function() {
	updateDisplayMsg("Load average\n" +
		numeral(os.loadavg()[0]).format('0.00') + " " +
		numeral(os.loadavg()[1]).format('0.00') + " " +
		numeral(os.loadavg()[2]).format('0.00'))
}

var updateSysTemp = function() {
	exec("cat /sys/class/thermal/thermal_zone0/temp", function (error, stdout, stderr) {
		if (error !== null) {
			console.log('exec error: ' + error)
		} else {
			// gets cpu temp and sends to callback function
			var temp = parseFloat(stdout) / 1000
			updateDisplayMsg("CPU Temp\n" + temp)
		}
	})
}

var updateDisplayMsg = function(message) {
	bpiscreen.write.lcd(message)
}
// ----------------------------------------------------------------
// END GET SCREEN TEXT
// ----------------------------------------------------------------

// ----------------------------------------------------------------
// CHANGE DISPLAY SCREEN
// ----------------------------------------------------------------
var changeScreen = function(opts) {
	opts = opts || {}
	clearInterval(screenIntervalId)

	var x = opts.screenX || false
	var y = opts.screenY || false
	var next = opts.next || false

	if(x) {
		if(next)
			actualScreenX++
		else
			actualScreenX--
	} else if(y) {
		if(next)
			actualScreenY++
		else
			actualScreenX--
	}

	if(actualScreenX < 0)
	{
		actualScreenX = updateScreen.length - 1
	}
	else if(actualScreenX >= updateScreen.length)
	{
		actualScreenX = 0
	}
	if(actualScreenY < 0)
	{
		actualScreenY = updateScreen[actualScreenX].length - 1
	}
	else if(actualScreenY >= updateScreen[actualScreenX].length)
	{
		actualScreenY = 0
	}

	bpiscreen.write.led(config.INTERFACELED1, Number(actualScreenX == 0))
	bpiscreen.write.led(config.INTERFACELED2, Number(actualScreenX == 1))
	bpiscreen.write.led(config.INTERFACELED3, Number(actualScreenX == 2))

	updateScreen[actualScreenX][actualScreenY]()
	//displayEvents.emit('screenUpdated' + actualScreenX)
}
// ----------------------------------------------------------------
// END CHANGE DISPLAY SCREEN
// ----------------------------------------------------------------

// ----------------------------------------------------------------
// BUTTON CLICK CALLBACK
// ----------------------------------------------------------------
var leftBtnClick = function(){
	//displayEvents.emit('changed')
	changeScreen({ screenX:true, next:false })
}
var middleBtnClick = function(){
	//displayEvents.emit('changed')
	changeScreen({ screenY:true, next:true })
}
var rightBtnClick = function(){
	//displayEvents.emit('changed')
	changeScreen({ screenX:true, next:true })
}
// ----------------------------------------------------------------
// END BUTTON CLICK CALLBACK
// ----------------------------------------------------------------

// ----------------------------------------------------------------
// CHECK INTERNET CONNECTIVITY (YELLOW LED)
// ----------------------------------------------------------------
var checkInternet = function(){
	isOnline(function(err, online) {
		bpiscreen.write.led(config.INTERNETLED, Number(online == true))
	})
}
// ----------------------------------------------------------------
// END CHECK INTERNET CONNECTIVITY (YELLOW LED)
// ----------------------------------------------------------------

// ----------------------------------------------------------------
// BEACON IDENTIFICATION
// ----------------------------------------------------------------

// save all beacons on range for a limited time
var beaconsOnRange = [ ]

// time between beacon range in and out - in ms
var beaconTime = 3000

// find a beacon at the original array
var findBeaconLocally = function(uuid, major, minor) {
	var i = 0, len = beaconsOnRange.length
	for (; i < len; ++i) {
		if ( beaconsOnRange[i].uuid == uuid &&
			beaconsOnRange[i].major == major &&
			beaconsOnRange[i].minor == minor )
			return beaconsOnRange[i]
	}
	return null
}

// creates a new beacon item to insert on the range array
var newBeacon = function(){
	var newB = {
		"uuid": "",
		"major": "",
		"minor": "",
		"name": "",
		"initialDate": Date.now(),
		"finalDate": "",
		"funcTimeout": ""
	}
	return newB
}

// timeout callback to remove a beacon from the range array
var beaconTimeoutCallback = function(beacon) {
	beacon.finalDate = Date.now()

	var index = beaconsOnRange.indexOf(beacon)
	if (index > -1) {
		beaconsOnRange.splice(index, 1)
	}

	var beaconToSaveDB = {
		"uuid": beacon.uuid,
		"major": beacon.major,
		"minor": beacon.minor,
		"total": ( (beacon.finalDate - beacon.initialDate - beaconTime) / 1000 )
	}

	PeaconDB.saveBeaconFound(beaconToSaveDB)

	/*var beaconToSaveHistory = {
		"uuid": beacon.uuid,
		"major": beacon.major,
		"minor": beacon.minor,
		"name": beacon.name
	}

	beaconHistory.push(beaconToSaveHistory)*/

	beaconHistoryCount++

	var currentBeacon = beaconHistoryCount

	updateScreen[1].push(function(){
		if(!beacon.name)
			updateDisplayMsg(currentBeacon + " de " + beaconHistoryCount + "\nDesconhecido")
		else
			updateDisplayMsg(currentBeacon + " de " + beaconHistoryCount + "\n" + beacon.name)
	})

	// TODO - SHOW ON SCREEN

	bpiscreen.write.led(config.BEACONLED, Number(beaconsOnRange.length > 0))
}

// callback when a beacon is discovered
Bleacon.on('discover', function(bleacon) {

	console.log("Bleacon Discover")

	var findB = findBeaconLocally(bleacon.uuid, bleacon.major, bleacon.minor)

	if (!findB) {
		findB = newBeacon()
		findB.uuid = bleacon.uuid
		findB.major = bleacon.major
		findB.minor = bleacon.minor
		PeaconDB.searchSavedBeacon(bleacon, function(err, beaconFound){
			if(!beaconFound.name)
				findB.name = null
			else
				findB.name = beaconFound.name
		})
		beaconsOnRange.push(findB)
	}

	// stops the older timeout
	clearTimeout(findB.funcTimeout)

	findB.funcTimeout = setTimeout(function() {
		console.log("beaconTimeoutCallback")
		beaconTimeoutCallback(findB)
	}, beaconTime)

    /*console.log("UUID: " + bleacon.uuid + " " +
		"Major: " + bleacon.major + " " +
		"Minor: " + bleacon.minor + " " +
		"RSSI: " + bleacon.rssi + " " +
		"Power: " + bleacon.measuredPower)*/

	bpiscreen.write.led(config.BEACONLED, Number(beaconsOnRange.length > 0))
})
// ----------------------------------------------------------------
// END BEACON IDENTIFICATION
// ----------------------------------------------------------------

// ----------------------------------------------------------------
// STARTING SCRIPTS
// ----------------------------------------------------------------
var start = function() {
	bpiscreen.start()

	bpiscreen.write.led(config.POWERLED, 1)
	bpiscreen.write.led(config.INTERNETLED, 0)
	bpiscreen.write.led(config.BEACONLED, 0)

	bpiscreen.write.led(config.INTERFACELED1, 0)
	bpiscreen.write.led(config.INTERFACELED2, 0)
	bpiscreen.write.led(config.INTERFACELED3, 0)

	bpiscreen.watch.button(config.LEFTBTN, leftBtnClick)
	bpiscreen.watch.button(config.MIDDLEBTN, middleBtnClick)
	bpiscreen.watch.button(config.RIGHTBTN, rightBtnClick)

	changeScreen()
	//displayEvents.emit('changed')

	// restarting hci0
	// this is a bug from my cheap ORICO BTA adapter
	run_cmd( "sudo hciconfig hci0 down", [], function(text) {
		run_cmd( "sudo hciconfig hci0 up", [], function(text) {

		})
	})

	// check internet connectivity every minute
	checkInternet()
	setInterval(checkInternet, 60000)

	Bleacon.startScanning() // scan for any bleacons

	PeaconDB.startDB() // start all databases
}

start()
// ----------------------------------------------------------------
// END STARTING SCRIPTS
// ----------------------------------------------------------------

// run shell command
// got from http://stackoverflow.com/questions/14458508/node-js-shell-command-execution
var run_cmd = function (cmd, args, callBack) {
    var spawn = require('child_process').spawn
    var child = spawn(cmd, args)
    var resp = ""

    child.stdout.on('data', function (buffer) { resp += buffer.toString() })
    child.stdout.on('end', function() { callBack (resp) })
}<commit_msg>Fix for node error<commit_after>var bpiscreen = require('./lib/bpiscreen')
var config = require('./lib/globals-config')
var internalIp = require('internal-ip')
var publicIp = require('public-ip')
var os = require('os')
var numeral = require('numeral')
var exec = require('child_process').exec
var isOnline = require('is-online')
var Bleacon = require('bleacon')
var PeaconDB = require('./lib/peacon-db')

var events = require("events"),
	displayEvents = new events.EventEmitter()

var actualScreenX = 0, actualScreenY = 0
var screenIntervalId

var beaconHistory = []
var beaconHistoryCount = 0

// ----------------------------------------------------------------
// GET SCREEN TEXT
// ----------------------------------------------------------------
// this array will return the text from each of screen position
var updateScreen = [
	[
		// first screen, show simple message
		function() {
			updateDisplayMsg("Aguardando\nbeacons...")
		}
	],
	[
		// this screen will show the last seen beacons
		function() {
			// TODO list last beacons
			if(beaconHistoryCount == 0)
				updateDisplayMsg("Nenhum beacon\nencontrado")
			else if(beaconHistoryCount == 1)
				updateDisplayMsg("1 beacon\nencontrado")
			else
				updateDisplayMsg(beaconHistoryCount + " beacons\nencontrados")
		}
	],
	[
		// this screen will display the RPi statistics, such as load average,
		// CPU temp, public and internal IP address
		function() {
			// TODO Improve to rewrite only the second line
			updateLoadAverage()
			screenIntervalId = setInterval(updateLoadAverage, 1000)
		},
		function() {
			// TODO Improve to rewrite only the second line
			updateSysTemp()
			screenIntervalId = setInterval(updateSysTemp, 1000)
		},
		function() {
			//displayEvents.emit('updated', "IP Privado\n" + internalIp())
			updateDisplayMsg("IP Privado\n" + internalIp())
		},
		function() {
			updateDisplayMsg("IP Publico\nCarregando...")
			publicIp(function (err, ip) {
				if(!ip)
					updateDisplayMsg("IP Publico\nnao encontrado")
				else
					updateDisplayMsg("IP Publico\n" + ip)
			})
		}
	]
]

var updateLoadAverage = function() {
	updateDisplayMsg("Load average\n" +
		numeral(os.loadavg()[0]).format('0.00') + " " +
		numeral(os.loadavg()[1]).format('0.00') + " " +
		numeral(os.loadavg()[2]).format('0.00'))
}

var updateSysTemp = function() {
	exec("cat /sys/class/thermal/thermal_zone0/temp", function (error, stdout, stderr) {
		if (error !== null) {
			console.log('exec error: ' + error)
		} else {
			// gets cpu temp and sends to callback function
			var temp = parseFloat(stdout) / 1000
			updateDisplayMsg("CPU Temp\n" + temp)
		}
	})
}

var updateDisplayMsg = function(message) {
	bpiscreen.write.lcd(message)
}
// ----------------------------------------------------------------
// END GET SCREEN TEXT
// ----------------------------------------------------------------

// ----------------------------------------------------------------
// CHANGE DISPLAY SCREEN
// ----------------------------------------------------------------
var changeScreen = function(opts) {
	opts = opts || {}
	clearInterval(screenIntervalId)

	var x = opts.screenX || false
	var y = opts.screenY || false
	var next = opts.next || false

	if(x) {
		if(next)
			actualScreenX++
		else
			actualScreenX--
	} else if(y) {
		if(next)
			actualScreenY++
		else
			actualScreenX--
	}

	if(actualScreenX < 0)
	{
		actualScreenX = updateScreen.length - 1
	}
	else if(actualScreenX >= updateScreen.length)
	{
		actualScreenX = 0
	}
	if(actualScreenY < 0)
	{
		actualScreenY = updateScreen[actualScreenX].length - 1
	}
	else if(actualScreenY >= updateScreen[actualScreenX].length)
	{
		actualScreenY = 0
	}

	bpiscreen.write.led(config.INTERFACELED1, Number(actualScreenX == 0))
	bpiscreen.write.led(config.INTERFACELED2, Number(actualScreenX == 1))
	bpiscreen.write.led(config.INTERFACELED3, Number(actualScreenX == 2))

	updateScreen[actualScreenX][actualScreenY]()
	//displayEvents.emit('screenUpdated' + actualScreenX)
}
// ----------------------------------------------------------------
// END CHANGE DISPLAY SCREEN
// ----------------------------------------------------------------

// ----------------------------------------------------------------
// BUTTON CLICK CALLBACK
// ----------------------------------------------------------------
var leftBtnClick = function(){
	//displayEvents.emit('changed')
	changeScreen({ screenX:true, next:false })
}
var middleBtnClick = function(){
	//displayEvents.emit('changed')
	changeScreen({ screenY:true, next:true })
}
var rightBtnClick = function(){
	//displayEvents.emit('changed')
	changeScreen({ screenX:true, next:true })
}
// ----------------------------------------------------------------
// END BUTTON CLICK CALLBACK
// ----------------------------------------------------------------

// ----------------------------------------------------------------
// CHECK INTERNET CONNECTIVITY (YELLOW LED)
// ----------------------------------------------------------------
var checkInternet = function(){
	isOnline(function(err, online) {
		bpiscreen.write.led(config.INTERNETLED, Number(online == true))
	})
}
// ----------------------------------------------------------------
// END CHECK INTERNET CONNECTIVITY (YELLOW LED)
// ----------------------------------------------------------------

// ----------------------------------------------------------------
// BEACON IDENTIFICATION
// ----------------------------------------------------------------

// save all beacons on range for a limited time
var beaconsOnRange = [ ]

// time between beacon range in and out - in ms
var beaconTime = 3000

// find a beacon at the original array
var findBeaconLocally = function(uuid, major, minor) {
	var i = 0, len = beaconsOnRange.length
	for (; i < len; ++i) {
		if ( beaconsOnRange[i].uuid == uuid &&
			beaconsOnRange[i].major == major &&
			beaconsOnRange[i].minor == minor )
			return beaconsOnRange[i]
	}
	return null
}

// creates a new beacon item to insert on the range array
var newBeacon = function(){
	var newB = {
		"uuid": "",
		"major": "",
		"minor": "",
		"name": "",
		"initialDate": Date.now(),
		"finalDate": "",
		"funcTimeout": ""
	}
	return newB
}

// timeout callback to remove a beacon from the range array
var beaconTimeoutCallback = function(beacon) {
	beacon.finalDate = Date.now()

	var index = beaconsOnRange.indexOf(beacon)
	if (index > -1) {
		beaconsOnRange.splice(index, 1)
	}

	var beaconToSaveDB = {
		"uuid": beacon.uuid,
		"major": beacon.major,
		"minor": beacon.minor,
		"total": ( (beacon.finalDate - beacon.initialDate - beaconTime) / 1000 )
	}

	PeaconDB.saveBeaconFound(beaconToSaveDB)

	/*var beaconToSaveHistory = {
		"uuid": beacon.uuid,
		"major": beacon.major,
		"minor": beacon.minor,
		"name": beacon.name
	}

	beaconHistory.push(beaconToSaveHistory)*/

	beaconHistoryCount++

	var currentBeacon = beaconHistoryCount

	updateScreen[1].push(function(){
		if(!beacon.name)
			updateDisplayMsg(currentBeacon + " de " + beaconHistoryCount + "\nDesconhecido")
		else
			updateDisplayMsg(currentBeacon + " de " + beaconHistoryCount + "\n" + beacon.name)
	})

	// TODO - SHOW ON SCREEN

	bpiscreen.write.led(config.BEACONLED, Number(beaconsOnRange.length > 0))
}

// callback when a beacon is discovered
Bleacon.on('discover', function(bleacon) {

	console.log("Bleacon Discover")

	var findB = findBeaconLocally(bleacon.uuid, bleacon.major, bleacon.minor)

	if (!findB) {
		findB = newBeacon()
		findB.uuid = bleacon.uuid
		findB.major = bleacon.major
		findB.minor = bleacon.minor
		PeaconDB.searchSavedBeacon(bleacon, function(err, beaconFound){
			if(!beaconFound.name)
				findB.name = null
			else
				findB.name = beaconFound.name
		})
		beaconsOnRange.push(findB)
	}

	// stops the older timeout
	clearTimeout(findB.funcTimeout)

	findB.funcTimeout = setTimeout(function() {
		console.log("beaconTimeoutCallback")
		beaconTimeoutCallback(findB)
	}, beaconTime)

    /*console.log("UUID: " + bleacon.uuid + " " +
		"Major: " + bleacon.major + " " +
		"Minor: " + bleacon.minor + " " +
		"RSSI: " + bleacon.rssi + " " +
		"Power: " + bleacon.measuredPower)*/

	bpiscreen.write.led(config.BEACONLED, Number(beaconsOnRange.length > 0))
})
// ----------------------------------------------------------------
// END BEACON IDENTIFICATION
// ----------------------------------------------------------------

// run shell command
// got from http://stackoverflow.com/questions/14458508/node-js-shell-command-execution
var run_cmd = function (cmd, args, callBack) {
    var spawn = require('child_process').spawn
    var child = spawn(cmd, args)
    var resp = ""

    child.stdout.on('data', function (buffer) { resp += buffer.toString() })
    child.stdout.on('end', function() { callBack (resp) })
}

// ----------------------------------------------------------------
// STARTING SCRIPTS
// ----------------------------------------------------------------
var start = function() {
	bpiscreen.start()

	bpiscreen.write.led(config.POWERLED, 1)
	bpiscreen.write.led(config.INTERNETLED, 0)
	bpiscreen.write.led(config.BEACONLED, 0)

	bpiscreen.write.led(config.INTERFACELED1, 0)
	bpiscreen.write.led(config.INTERFACELED2, 0)
	bpiscreen.write.led(config.INTERFACELED3, 0)

	bpiscreen.watch.button(config.LEFTBTN, leftBtnClick)
	bpiscreen.watch.button(config.MIDDLEBTN, middleBtnClick)
	bpiscreen.watch.button(config.RIGHTBTN, rightBtnClick)

	changeScreen()
	//displayEvents.emit('changed')

	// restarting hci0
	// this is a bug from my cheap ORICO BTA adapter
	run_cmd( "sudo hciconfig hci0 down", [], function(text) {
		run_cmd( "sudo hciconfig hci0 up", [], function(text) {

		})
	})

	// check internet connectivity every minute
	checkInternet()
	setInterval(checkInternet, 60000)

	Bleacon.startScanning() // scan for any bleacons

	PeaconDB.startDB() // start all databases
}

start()
// ----------------------------------------------------------------
// END STARTING SCRIPTS
// ----------------------------------------------------------------
<|endoftext|>


<commit_before>'use strict'

const fs = require('fs')
const express = require('express')
const jimp = require('jimp')
const os = require('os')
const https = require('http')
const chalk = require('chalk')

let app = express()

app.get('/', function(req, res) {
	res.sendFile(__dirname + '/public/index.html')
})

app.get('/upload', function(req, res) {
	res.sendFile(__dirname + '/public/upload.html')
})

app.use(express.static('dist'))
app.use(express.static('public'))

app.get('*', function(req, res) {
	res.sendFile(__dirname + '/public/404.html')
})

// ssl for opensprites.org *only*
if(os.hostname() == 'opensprites.org') {
	serve.createServer({
		key: fs.readFileSync('/home/admin/conf/web/ssl.opensprites.org.key'),
		cert: fs.readFileSync('/home/admin/conf/web/ssl.opensprites.org.crt')
	}, app).listen(3000, function() {
		console.log('[	 ] ' + chalk.blue('Listening ' + chalk.underline('(ssl mode enabled!) ') + '...'))
	})
} else {
	app.listen(function() {
		console.log('[	 ] ' + chalk.blue('Listening...'))
	})
}
<commit_msg>// fix<commit_after>'use strict'

const fs = require('fs')
const express = require('express')
const jimp = require('jimp')
const os = require('os')
const https = require('https')
const chalk = require('chalk')

let app = express()

app.get('/', function(req, res) {
	res.sendFile(__dirname + '/public/index.html')
})

app.get('/upload', function(req, res) {
	res.sendFile(__dirname + '/public/upload.html')
})

app.use(express.static('dist'))
app.use(express.static('public'))

app.get('*', function(req, res) {
	res.sendFile(__dirname + '/public/404.html')
})

// ssl for opensprites.org *only*
if(os.hostname() == 'opensprites.org') {
	https.createServer({
		key: fs.readFileSync('/home/admin/conf/web/ssl.opensprites.org.key'),
		cert: fs.readFileSync('/home/admin/conf/web/ssl.opensprites.org.crt')
	}, app).listen(3000, function() {
		console.log('[	 ] ' + chalk.blue('Listening ' + chalk.underline('(ssl mode enabled!) ') + '...'))
	})
} else {
	app.listen(function() {
		console.log('[	 ] ' + chalk.blue('Listening...'))
	})
}
<|endoftext|>


<commit_before>var fs = require('fs');
var path = require('path');
var RSVP = require('rsvp');
var writeFile = RSVP.denodeify(fs.writeFile);
var readFile = RSVP.denodeify(fs.readFile);
var Styledown = require('styledown');
var Plugin = require('broccoli-plugin');
var walkSync = require('walk-sync');
var merge = require('lodash.merge');
var debug = require('debug')('broccoli-styledown');

var FS_OPTIONS = { encoding: 'utf8' };
var EXTENSIONS = '(less|css|sass|scss|styl)';
var WHITELIST_REGEXP = new RegExp('\.' + EXTENSIONS + '$');
var MD_REGEXP = new RegExp('\.md$');

function getPath(srcPath, fileName) {
  return path.join(srcPath, fileName);
}

StyledownCompiler.prototype = Object.create(Plugin.prototype);
StyledownCompiler.prototype.constructor = StyledownCompiler;

function StyledownCompiler(inputNodes, options) {
  options = options || {};

  Plugin.call(this, inputNodes, options);

  this.options = options;
  this.configMd = options.configMd || 'config.md';
  this.destFile = options.destFile || 'index.html';
  this.styledown = options.styledown || {};

  debug('inputNodes', inputNodes);
  debug('destFile', this.destFile);
  debug('config', this.configMd);
}

StyledownCompiler.name = 'StyledownCompiler';

StyledownCompiler.prototype.build = function() {
  debug('build');
  debug('inputPaths', this.inputPaths);
  debug('outputPath', this.outputPath);
  debug('cachePath', this.cachePath);

  var styledownOpts = this.styledown || {};
  var destFile = this.destFile;
  var outputPath = this.outputPath;

  var srcDataPromises = this.inputPaths.map(function(inputPath) {
    return this.getSourceFileData(inputPath);
  }, this);

  return RSVP.all(srcDataPromises).then(function(srcDataArrays) {
    // Combine file data arrays from all inputPaths
    var srcData = srcDataArrays.reduce(function(result, srcDataArray) {
      return result.concat(srcDataArray);
    }, []);

    var html = Styledown.parse(srcData, styledownOpts);

    return writeFile(path.join(outputPath, destFile), html, FS_OPTIONS);
  })
  .catch(function(err) {
    debug(err);
  });
};

/**
 * Get all data for files in srcPath.
 *
 * @param {String} srcPath Path to read for files
 * @return {Promise} Array of all files [{ name: 'fileName', data: String }]
 */
StyledownCompiler.prototype.getSourceFileData = function(srcPath) {
  var configMd = this.configMd;
  debug('srcPath', srcPath);

  var filePaths = walkSync(srcPath).filter(function(fileName) {
    if (fileName.match(WHITELIST_REGEXP)) {
      return true;
    }

    return false;
  });

  var filePathsMd = walkSync(srcPath).filter(function(fileName) {
    if (fileName !== configMd && fileName.match(MD_REGEXP)) {
      return true;
    }

    return false;
  });

  // For some reason, Styledown chokes if the md files comes before any
  // of the CSS files
  filePaths = filePaths.concat(filePathsMd);

  // If available, add configMd at the end of the list
  if (configMd) {
    filePaths = filePaths.concat(configMd);
  }

  debug('filePaths', filePaths);

  var readPromises = filePaths.map(function(filePath) {
    return readFile(getPath(srcPath, filePath), FS_OPTIONS)
      .then(function(data) {
        return { name: filePath, data: data };
      });
  });

  return RSVP.all(readPromises)
    .catch(function(err) {
      console.log('Error reading source file data');
      console.error(err);
    });
};

module.exports = StyledownCompiler;
<commit_msg>Add file exists check for config MD file<commit_after>var fs = require('fs');
var path = require('path');
var RSVP = require('rsvp');
var writeFile = RSVP.denodeify(fs.writeFile);
var readFile = RSVP.denodeify(fs.readFile);
var Styledown = require('styledown');
var Plugin = require('broccoli-plugin');
var walkSync = require('walk-sync');
var merge = require('lodash.merge');
var debug = require('debug')('broccoli-styledown');

var FS_OPTIONS = { encoding: 'utf8' };
var EXTENSIONS = '(less|css|sass|scss|styl)';
var WHITELIST_REGEXP = new RegExp('\.' + EXTENSIONS + '$');
var MD_REGEXP = new RegExp('\.md$');

function getPath(srcPath, fileName) {
  return path.join(srcPath, fileName);
}

function checkFileExists(path) {
  try {
    if (!fs.statSync(path).isFile()) {
      debug('Path is not a file');
      return false;
    }
  } catch(err) {
    debug('File not found', path);
    return false;
  }

  return true;
}

StyledownCompiler.prototype = Object.create(Plugin.prototype);
StyledownCompiler.prototype.constructor = StyledownCompiler;

function StyledownCompiler(inputNodes, options) {
  options = options || {};

  Plugin.call(this, inputNodes, options);

  this.options = options;
  this.configMd = options.configMd || 'config.md';
  this.destFile = options.destFile || 'index.html';
  this.styledown = options.styledown || {};

  debug('inputNodes', inputNodes);
  debug('destFile', this.destFile);
  debug('config', this.configMd);
}

StyledownCompiler.name = 'StyledownCompiler';

StyledownCompiler.prototype.build = function() {
  debug('build');
  debug('inputPaths', this.inputPaths);
  debug('outputPath', this.outputPath);
  debug('cachePath', this.cachePath);

  var styledownOpts = this.styledown || {};
  var destFile = this.destFile;
  var outputPath = this.outputPath;

  var srcDataPromises = this.inputPaths.map(function(inputPath) {
    return this.getSourceFileData(inputPath);
  }, this);

  return RSVP.all(srcDataPromises).then(function(srcDataArrays) {
    // Combine file data arrays from all inputPaths
    var srcData = srcDataArrays.reduce(function(result, srcDataArray) {
      return result.concat(srcDataArray);
    }, []);

    var html = Styledown.parse(srcData, styledownOpts);

    return writeFile(path.join(outputPath, destFile), html, FS_OPTIONS);
  })
  .catch(function(err) {
    debug(err);
  });
};

/**
 * Get all data for files in srcPath.
 *
 * @param {String} srcPath Path to read for files
 * @return {Promise} Array of all files [{ name: 'fileName', data: String }]
 */
StyledownCompiler.prototype.getSourceFileData = function(srcPath) {
  var configMd = this.configMd;
  debug('srcPath', srcPath);

  var filePaths = walkSync(srcPath).filter(function(fileName) {
    if (fileName.match(WHITELIST_REGEXP)) {
      return true;
    }

    return false;
  });

  debug('filter markdown files');
  var filePathsMd = walkSync(srcPath).filter(function(fileName) {
    if (fileName !== configMd && fileName.match(MD_REGEXP)) {
      debug('detected markdown', fileName);
      return true;
    }

    return false;
  });

  // For some reason, Styledown chokes if the md files comes before any
  // of the CSS files
  filePaths = filePaths.concat(filePathsMd);

  // If available, add configMd at the end of the list
  if (configMd) {
    var configPath = getPath(srcPath, configMd);
    var configExists = checkFileExists(configPath);

    if (configExists) {
      debug('Config file found', configPath);
      filePaths = filePaths.concat(configMd);
    }
  }

  debug('filePaths', filePaths);

  var readPromises = filePaths.map(function(filePath) {
    return readFile(getPath(srcPath, filePath), FS_OPTIONS)
      .then(function(data) {
        return { name: filePath, data: data };
      });
  });

  return RSVP.all(readPromises)
    .catch(function(err) {
      console.log('Error reading source file data');
      console.error(err);
      throw(err);
    });
};

module.exports = StyledownCompiler;
<|endoftext|>


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

var parser = require('./lib/parser').parser;
parser.yy = require('./lib/nodes');

fs.readFile('./examples/simple.jav', 'UTF8', function(err, data) {
  if ( err == null ) {
    var result = parser.parse(data);
    console.log(result.formatJSON({}));
    //console.log(JSON.stringify(result));
  }
});<commit_msg>Update index.js playground.<commit_after>var javelin = require('./lib/javelin');

var locals = {
  test: {
    foo: 'bar',
    bar: 'baz'
  }
};

var compile = javelin.compile('./examples/simple.jav', 'json');
console.log(compile(locals, true));<|endoftext|>


<commit_before>/* eslint-env node */

let childProcess = require('child_process');
let Slack = require('node-slack');
let Promise = require('bluebird');
let mapReduce = require('./mapreduce');

Promise.promisifyAll(childProcess);

let expireCount = process.env.EXPIRE_TICK || 4;
let ticks = process.env.TICK_RATE || 15000;
let blacklistReason = ['ContainerCreating'];

function getPods(){
	let child = childProcess.spawn('kubectl', ['--namespace', process.env.NAMESPACE || 'default', 'get', 'pod', '-o', 'json']);
	let buffer = '';
	child.stdout.on('data', (txt) => buffer += txt);
	return new Promise((resolve, reject) => {
		child.stdout.on('end', () => {
			resolve(JSON.parse(buffer));
		});
	});
}

function toContainers(item, emit){
	if(!item.status.containerStatuses){
		return;
	}
	for(let container of item.status.containerStatuses){
		container.pod = item;
		emit(container);
	}
}

let floodStore = {};

function expireStore(){
	for(let item of Object.keys(floodStore)){
		floodStore[item]--;
		if(floodStore[item] <= 0){
			delete floodStore[item];
		}
	}
}

function floodFilter(item){
	let result = true;
	let key = `${item.name} ${item.pod.metadata.name}`;
	if(floodStore[key]){
		result = false;
	}
	floodStore[key] = expireCount;
	return result;
}

function main(){
	if(!process.env.SLACK_URL){
		console.error('SLACK_URL is not set');
		process.exit(1);
	}
	let slack = new Slack(process.env.SLACK_URL);

	getPods().then((pods) => {
		return mapReduce(pods.items, toContainers);
	}).then((items) => {
		return items.filter((item) => {
			return item.state.waiting;
		});
	}).then((items) => {
		return items.filter((item) => {
			return !blacklistReason.includes(item.state.waiting.reason);
		});
	}).then((items) => {
		expireStore();
		return items.filter(floodFilter);
	}).then((items) => {
		if(items.length === 0){
			return;
		}
		let attachments = [];
		for(let item of items){
			let logUrl = '';
			if(process.env.LOGGING_URL){
				logUrl = process.env.LOGGING_URL
					.replace(/%CONTAINER%/g, encodeURIComponent(item.name))
					.replace(/%POD%/g, encodeURIComponent(item.pod.metadata.name))
					.replace(/%STATUS%/g, encodeURIComponent(item.state.waiting.reason));
				logUrl = `(<${logUrl}|View logs>)`;
			}

			attachments.push({
				fallback: `Container ${item.name} of pod ${item.pod.metadata.name} entered status ${item.state.waiting.reason} (${item.state.waiting.message})`,
				color: 'danger',
				footer: item.state.waiting.message,
				title: item.pod.metadata.name,
				text: `*${item.name}* entered status *${item.state.waiting.reason}* ${logUrl}`,
				mrkdwn_in: ['text'],
			});
		}
		slack.send({
			text: 'The following container(s) entered waiting status',
			attachments: attachments,
		}).then(() => {
			console.log(`Sent ${attachments.length} status to slack`);
		}, (e) => {
			console.error(e);
		});
	});
}

main();
setInterval(main, ticks);
<commit_msg>Added --all-namespaces argument<commit_after>/* eslint-env node */

let childProcess = require('child_process');
let Slack = require('node-slack');
let Promise = require('bluebird');
let mapReduce = require('./mapreduce');

Promise.promisifyAll(childProcess);

let expireCount = process.env.EXPIRE_TICK || 4;
let ticks = process.env.TICK_RATE || 15000;
let blacklistReason = ['ContainerCreating'];

function getPods(){
	let child;
	if (process.argv['--all-namespaces']) {
		child = childProcess.spawn('kubectl', ['--all-namespaces', 'get', 'pod', '-o', 'json']);
	} else {
		child = childProcess.spawn('kubectl', ['--namespace', process.env.NAMESPACE || 'default', 'get', 'pod', '-o', 'json']);
	}
	let buffer = '';
	child.stdout.on('data', (txt) => buffer += txt);
	return new Promise((resolve, reject) => {
		child.stdout.on('end', () => {
			resolve(JSON.parse(buffer));
		});
	});
}

function toContainers(item, emit){
	if(!item.status.containerStatuses){
		return;
	}
	for(let container of item.status.containerStatuses){
		container.pod = item;
		emit(container);
	}
}

let floodStore = {};

function expireStore(){
	for(let item of Object.keys(floodStore)){
		floodStore[item]--;
		if(floodStore[item] <= 0){
			delete floodStore[item];
		}
	}
}

function floodFilter(item){
	let result = true;
	let key = `${item.name} ${item.pod.metadata.name}`;
	if(floodStore[key]){
		result = false;
	}
	floodStore[key] = expireCount;
	return result;
}

function main(){
	console.log("Running main");
	if(!process.env.SLACK_URL){
		console.error('SLACK_URL is not set');
		process.exit(1);
	}
	let slack = new Slack(process.env.SLACK_URL);

	getPods().then((pods) => {
		return mapReduce(pods.items, toContainers);
	}).then((items) => {
		return items.filter((item) => {
			return item.state.waiting;
		});
	}).then((items) => {
		return items.filter((item) => {
			return !blacklistReason.includes(item.state.waiting.reason);
		});
	}).then((items) => {
		expireStore();
		return items.filter(floodFilter);
	}).then((items) => {
		if(items.length === 0){
			return;
		}
		let attachments = [];
		for(let item of items){
			let logUrl = '';
			if(process.env.LOGGING_URL){
				logUrl = process.env.LOGGING_URL
					.replace(/%CONTAINER%/g, encodeURIComponent(item.name))
					.replace(/%POD%/g, encodeURIComponent(item.pod.metadata.name))
					.replace(/%STATUS%/g, encodeURIComponent(item.state.waiting.reason));
				logUrl = `(<${logUrl}|View logs>)`;
			}

			attachments.push({
				fallback: `Container ${item.name} of pod ${item.pod.metadata.name} entered status ${item.state.waiting.reason} (${item.state.waiting.message})`,
				color: 'danger',
				footer: item.state.waiting.message,
				title: item.pod.metadata.name,
				text: `*${item.name}* entered status *${item.state.waiting.reason}* ${logUrl}`,
				mrkdwn_in: ['text'],
			});
		}
		slack.send({
			text: 'The following container(s) entered waiting status',
			attachments: attachments,
		}).then(() => {
			console.log(`Sent ${attachments.length} status to slack`);
		}, (e) => {
			console.error(e);
		});
	});
}

main();
setInterval(main, ticks);
<|endoftext|>


<commit_before>// Disable onload popups
user_pref("dom.disable_open_during_load", true);

// Disable usless security warnings
user_pref("security.warn_entering_secure", false);
user_pref("security.warn_entering_secure.show_once", true);
user_pref("security.warn_leaving_secure", false);
user_pref("security.warn_leaving_secure.show_once", false);
user_pref("security.warn_submit_insecure", false);
user_pref("security.warn_submit_insecure.show_once", false);
user_pref("security.warn_viewing_mixed", true);
user_pref("security.warn_viewing_mixed.show_once", false);
user_pref("security.warn_entering_weak", true);
user_pref("security.warn_entering_weak.show_once", false);

// Set some style properties to not follow our dark gtk theme
user_pref("ui.-moz-field", "#FFFFFF");
user_pref("ui.-moz-fieldtext", "#000000");
user_pref("ui.buttonface", "#D3D3DD");
user_pref("ui.buttontext", "#000000");

// Define our font size in points (to adapt to resolution)
user_pref("font.size.unit", "pt");

user_pref("font.size.variable.ar", 12);
user_pref("font.size.fixed.ar", 10);

user_pref("font.size.variable.el", 12);
user_pref("font.size.fixed.el", 10);

user_pref("font.size.variable.he", 12);
user_pref("font.size.fixed.he", 10);

user_pref("font.size.variable.ja", 12);
user_pref("font.size.fixed.ja", 12);

user_pref("font.size.variable.ko", 12);
user_pref("font.size.fixed.ko", 12);

user_pref("font.size.variable.th", 12);
user_pref("font.size.fixed.th", 10);

user_pref("font.size.variable.tr", 12);
user_pref("font.size.fixed.tr", 10);

user_pref("font.size.variable.x-baltic", 12);
user_pref("font.size.fixed.x-baltic", 10);

user_pref("font.size.variable.x-central-euro", 12);
user_pref("font.size.fixed.x-central-euro", 10);

user_pref("font.size.variable.x-cyrillic", 12);
user_pref("font.size.fixed.x-cyrillic", 10);

user_pref("font.size.variable.x-devanagari", 12);
user_pref("font.size.fixed.x-devanagari", 10);

user_pref("font.size.variable.x-tamil", 12);
user_pref("font.size.fixed.x-tamil", 10);

user_pref("font.size.variable.x-armn", 12);
user_pref("font.size.fixed.x-armn", 10);

user_pref("font.size.variable.x-beng", 12);
user_pref("font.size.fixed.x-beng", 10);

user_pref("font.size.variable.x-cans", 12);
user_pref("font.size.fixed.x-cans", 10);

user_pref("font.size.variable.x-ethi", 12);
user_pref("font.size.fixed.x-ethi", 10);

user_pref("font.size.variable.x-geor", 12);
user_pref("font.size.fixed.x-geor", 10);

user_pref("font.size.variable.x-gujr", 12);
user_pref("font.size.fixed.x-gujr", 10);

user_pref("font.size.variable.x-guru", 12);
user_pref("font.size.fixed.x-guru", 10);

user_pref("font.size.variable.x-khmr", 12);
user_pref("font.size.fixed.x-khmr", 10);

user_pref("font.size.variable.x-mlym", 12);
user_pref("font.size.fixed.x-mlym", 10);

user_pref("font.size.variable.x-unicode", 12);
user_pref("font.size.fixed.x-unicode", 10);

user_pref("font.size.variable.x-western", 12);
user_pref("font.size.fixed.x-western", 10);

user_pref("font.size.variable.zh-CN", 12);
user_pref("font.size.fixed.zh-CN", 12);

user_pref("font.size.variable.zh-TW", 12);
user_pref("font.size.fixed.zh-TW", 12);

user_pref("font.size.variable.zh-HK", 12);
user_pref("font.size.fixed.zh-HK", 12);

// Enable error pages (xulrunner is missing this pref)
pref("browser.xul.error_pages.enabled", true);

<commit_msg>Add families for arabic fonts<commit_after>// Disable onload popups
user_pref("dom.disable_open_during_load", true);

// Disable usless security warnings
user_pref("security.warn_entering_secure", false);
user_pref("security.warn_entering_secure.show_once", true);
user_pref("security.warn_leaving_secure", false);
user_pref("security.warn_leaving_secure.show_once", false);
user_pref("security.warn_submit_insecure", false);
user_pref("security.warn_submit_insecure.show_once", false);
user_pref("security.warn_viewing_mixed", true);
user_pref("security.warn_viewing_mixed.show_once", false);
user_pref("security.warn_entering_weak", true);
user_pref("security.warn_entering_weak.show_once", false);

// Set some style properties to not follow our dark gtk theme
user_pref("ui.-moz-field", "#FFFFFF");
user_pref("ui.-moz-fieldtext", "#000000");
user_pref("ui.buttonface", "#D3D3DD");
user_pref("ui.buttontext", "#000000");

// Define our font size in points (to adapt to resolution)
user_pref("font.size.unit", "pt");

user_pref("font.size.variable.ar", 12);
user_pref("font.size.fixed.ar", 10);

user_pref("font.size.variable.el", 12);
user_pref("font.size.fixed.el", 10);

user_pref("font.size.variable.he", 12);
user_pref("font.size.fixed.he", 10);

user_pref("font.size.variable.ja", 12);
user_pref("font.size.fixed.ja", 12);

user_pref("font.size.variable.ko", 12);
user_pref("font.size.fixed.ko", 12);

user_pref("font.size.variable.th", 12);
user_pref("font.size.fixed.th", 10);

user_pref("font.size.variable.tr", 12);
user_pref("font.size.fixed.tr", 10);

user_pref("font.size.variable.x-baltic", 12);
user_pref("font.size.fixed.x-baltic", 10);

user_pref("font.size.variable.x-central-euro", 12);
user_pref("font.size.fixed.x-central-euro", 10);

user_pref("font.size.variable.x-cyrillic", 12);
user_pref("font.size.fixed.x-cyrillic", 10);

user_pref("font.size.variable.x-devanagari", 12);
user_pref("font.size.fixed.x-devanagari", 10);

user_pref("font.size.variable.x-tamil", 12);
user_pref("font.size.fixed.x-tamil", 10);

user_pref("font.size.variable.x-armn", 12);
user_pref("font.size.fixed.x-armn", 10);

user_pref("font.size.variable.x-beng", 12);
user_pref("font.size.fixed.x-beng", 10);

user_pref("font.size.variable.x-cans", 12);
user_pref("font.size.fixed.x-cans", 10);

user_pref("font.size.variable.x-ethi", 12);
user_pref("font.size.fixed.x-ethi", 10);

user_pref("font.size.variable.x-geor", 12);
user_pref("font.size.fixed.x-geor", 10);

user_pref("font.size.variable.x-gujr", 12);
user_pref("font.size.fixed.x-gujr", 10);

user_pref("font.size.variable.x-guru", 12);
user_pref("font.size.fixed.x-guru", 10);

user_pref("font.size.variable.x-khmr", 12);
user_pref("font.size.fixed.x-khmr", 10);

user_pref("font.size.variable.x-mlym", 12);
user_pref("font.size.fixed.x-mlym", 10);

user_pref("font.size.variable.x-unicode", 12);
user_pref("font.size.fixed.x-unicode", 10);

user_pref("font.size.variable.x-western", 12);
user_pref("font.size.fixed.x-western", 10);

user_pref("font.size.variable.zh-CN", 12);
user_pref("font.size.fixed.zh-CN", 12);

user_pref("font.size.variable.zh-TW", 12);
user_pref("font.size.fixed.zh-TW", 12);

user_pref("font.size.variable.zh-HK", 12);
user_pref("font.size.fixed.zh-HK", 12);

// Font families for Arabic

user_pref("font.name.cursive.ar", "KacstQurn");
user_pref("font.name.fantasy.ar", "KacstDecorative");
user_pref("font.name.monospace.ar", "KacstDigital");
user_pref("font.name.sans-serif.ar", "KacstQurn");
user_pref("font.name.serif.ar", "KacstBook");

// Enable error pages (xulrunner is missing this pref)
user_pref("browser.xul.error_pages.enabled", true);
<|endoftext|>


<commit_before>'use strict';

var path = require('path'),
    util = require('util');

var browserify = require('browserify'),
    eventStream = require('event-stream'),
    glob = require('glob'),
    gUtil = require('gulp-util'),
    merge = require('merge'),
    buffer = require('vinyl-buffer'),
    source = require('vinyl-source-stream'),
    watchify = require('watchify');

var chalk = gUtil.colors,
    format = util.format,
    log = gUtil.log;

module.exports = gulpWatchifyBrowserify;

/**
 * gulp plugin for watching and bundling javascripts using watchify and browserify
 * @param  {String}    globPattern    glob pattern for entries
 * @param  {Object}    options        custom options
 * @param  {Function}  streamHandler  stream handler for using more gulp plugins and pipe to dest
 * @param  {Function}  done           callback
 * @return {undefined}
 */
function gulpWatchifyBrowserify(globPattern, options, streamHandler, done) {

  options = merge.recursive({
    watch: process.env.NODE_ENV === 'development',
    cwd: process.cwd(),
    browserify: {
      cache: {},
      packageCache: {}
    },
    watchify: {
      delay: 100,
      ignoreWatch: ['**/node_modules/**'],
      poll: true
    }
  }, options);

  /**
   * glob bundle entries using defined pattern,
   * create a bundler for each file,
   * merge output streams from bundlers,
   * callback on stream end
   */
  glob(globPattern, {cwd: options.cwd}, function(err, files) {
    if (err) return log(err);
    if (files.length <= 0) return done();
    eventStream.merge(files.map(function(file) {
      var bundler = new Bundler(file);
      return bundler.outputBundle();
    })).on('end', function() {
      if (options.watch) return;
      done();
    });
  });

  /**
   * create a browserify bundler, wrapped in a watchify watcher
   * @param  {String} file  entry file
   * @return {undefined}
   */
  function Bundler(file) {

    var bundler = this, bundle,
        watchMsg = format('Watching bundle %s...', chalk.magenta(file));

    // set entry file for this bundler
    options.browserify.entries = [path.join(options.cwd, file)];

    // initiate bundle
    bundle = watchify(browserify(options.browserify), options.watchify);

    /**
     * on update, log to console and bundle
     * @param  {Array} ev  array of event files
     * @return {undefined}
     */
    bundle.on('update', function(ev) {
      log(format('%s File %s updated. Bundling %s ...',
        chalk.yellow('☀'),
        chalk.magenta(path.relative(options.cwd, ev[0])),
        chalk.magenta(file)
      ));
      bundler.outputBundle();
    });

    /**
     * when bundling, log infos to console
     * @param  {String} msg  bundling info
     * @return {undefined}
     */
    bundle.on('log', function(msg) {
      log(format('%s Bundled %s %s',
        chalk.green('✓'),
        chalk.magenta(file),
        chalk.gray(msg)
      ));
    });

    /**
     * bundle and transform to stream
     * @return {Object} gulp stream
     */
    this.outputBundle = function() {
      return streamHandler(
        bundle.bundle()
          .on('error', function(err) {
            throw err;
          })
          .pipe(source(file))
          .pipe(buffer())
          .on('end', function() {
            if (!options.watch) {
              bundle.close();
            } else if (watchMsg) {
              log(watchMsg);
              watchMsg = false;
            }
          })
      );
    };

  }

}
<commit_msg>add 'insertGlobals: false' to browserify default options<commit_after>'use strict';

var path = require('path'),
    util = require('util');

var browserify = require('browserify'),
    eventStream = require('event-stream'),
    glob = require('glob'),
    gUtil = require('gulp-util'),
    merge = require('merge'),
    buffer = require('vinyl-buffer'),
    source = require('vinyl-source-stream'),
    watchify = require('watchify');

var chalk = gUtil.colors,
    format = util.format,
    log = gUtil.log;

module.exports = gulpWatchifyBrowserify;

/**
 * gulp plugin for watching and bundling javascripts using watchify and browserify
 * @param  {String}    globPattern    glob pattern for entries
 * @param  {Object}    options        custom options
 * @param  {Function}  streamHandler  stream handler for using more gulp plugins and pipe to dest
 * @param  {Function}  done           callback
 * @return {undefined}
 */
function gulpWatchifyBrowserify(globPattern, options, streamHandler, done) {

  options = merge.recursive({
    watch: process.env.NODE_ENV === 'development',
    cwd: process.cwd(),
    browserify: {
      insertGlobals: false,
      cache: {},
      packageCache: {}
    },
    watchify: {
      delay: 100,
      ignoreWatch: ['**/node_modules/**'],
      poll: true
    }
  }, options);

  /**
   * glob bundle entries using defined pattern,
   * create a bundler for each file,
   * merge output streams from bundlers,
   * callback on stream end
   */
  glob(globPattern, {cwd: options.cwd}, function(err, files) {
    if (err) return log(err);
    if (files.length <= 0) return done();
    eventStream.merge(files.map(function(file) {
      var bundler = new Bundler(file);
      return bundler.outputBundle();
    })).on('end', function() {
      if (options.watch) return;
      done();
    });
  });

  /**
   * create a browserify bundler, wrapped in a watchify watcher
   * @param  {String} file  entry file
   * @return {undefined}
   */
  function Bundler(file) {

    var bundler = this, bundle,
        watchMsg = format('Watching bundle %s...', chalk.magenta(file));

    // set entry file for this bundler
    options.browserify.entries = [path.join(options.cwd, file)];

    // initiate bundle
    bundle = watchify(browserify(options.browserify), options.watchify);

    /**
     * on update, log to console and bundle
     * @param  {Array} ev  array of event files
     * @return {undefined}
     */
    bundle.on('update', function(ev) {
      log(format('%s File %s updated. Bundling %s ...',
        chalk.yellow('☀'),
        chalk.magenta(path.relative(options.cwd, ev[0])),
        chalk.magenta(file)
      ));
      bundler.outputBundle();
    });

    /**
     * when bundling, log infos to console
     * @param  {String} msg  bundling info
     * @return {undefined}
     */
    bundle.on('log', function(msg) {
      log(format('%s Bundled %s %s',
        chalk.green('✓'),
        chalk.magenta(file),
        chalk.gray(msg)
      ));
    });

    /**
     * bundle and transform to stream
     * @return {Object} gulp stream
     */
    this.outputBundle = function() {
      return streamHandler(
        bundle.bundle()
          .on('error', function(err) {
            throw err;
          })
          .pipe(source(file))
          .pipe(buffer())
          .on('end', function() {
            if (!options.watch) {
              bundle.close();
            } else if (watchMsg) {
              log(watchMsg);
              watchMsg = false;
            }
          })
      );
    };

  }

}
<|endoftext|>


<commit_before>/*
* Includes
*/
var self = require('sdk/self');

var buttons = require('sdk/ui/button/action');
var preferences = require("sdk/simple-prefs").prefs;
var tabs = require("sdk/tabs");
var self = require("sdk/self");
var requests = require("./observer.js");
var style = require('sdk/stylesheet/style');
var data = require("sdk/self").data;
var { ToggleButton } = require('sdk/ui/button/toggle');
var panels = require("sdk/panel");
var shadow_preferences = require("./preferences.js"); //renamed cause of dublicated variable declaration, CHECK THIS!
var proxy = require("./data/bs_proxy.js");
var PA = require("./PA_mode.js");

/*
*  Initialize the ShadowPrefs here if needed
*/
shadow_preferences.ShadowPrefs.ShadowPref_check_exist();

if(!shadow_preferences.ShadowPrefs.SP_exist){

  // init with hardcoded default values
  shadow_preferences.ShadowPrefs.initNames();
  shadow_preferences.ShadowPrefs.initValues();

  // create ShadowPrefs (extensions.jondofox.xxxx)
  shadow_preferences.ShadowPrefs.createShadowPrefs();

  // apply all prefs here that need a restart and cant be loaded dynamically

  // restart here if needed

}
else{

  // init names of preferences we want to keep track of
  shadow_preferences.ShadowPrefs.initNames();

  // read ShadowPref values from about:config
  shadow_preferences.ShadowPrefs.readShadowPrefs();

}

/*
* Initiate Observers here
*/
PA.initTabs(PA, shadow_preferences);
//requests.httpRequestObserver.register(); <~~ this code line is gone into PA_mode.js

// Initial make a shadowcopy of preferences

//shadow_preferences.putFontBlacklist;
//shadow_preferences.jonDoFoxPreferenceService.initShadowCopy();
proxy.proxyService.initShadowProxyCopy();
/*
* Create the Toolbar Button
*/
// Removed by KKP to switch it to an toggleButton
/*var button = buttons.ActionButton({
  id: "enable-disable",
  label: "Enable/Disable Addon",
  icon: {
    "16": "./icon-16.png",
    "32": "./icon-32.png",
    //"64": "./icon-64.png"
  },
  onClick: handleClick
});*/

var button = ToggleButton({
  id: "togglePanelMenu",
  label: "my button",
  icon: {
    "16": "./icon-16.png",
    "32": "./icon-32.png"
    //"64": "./icon-64.png"
  },
  onChange: handleChange
});

var panelmenu = panels.Panel({
  width: 200,
  height:265,
  contentURL: self.data.url("panelmenu.html"),
  onHide: handleHide ,
  contentScriptFile :  data.url("cs_panelmenu.js"),
});

// Receive data from contentScript "options.js"
panelmenu.port.on("menuAction", function(jsonParamters) {
  console.log("panelmenu.port.on begin");
  if(jsonParamters.option) {
    console.log(jsonParamters.option)
    onExtPrefClick();
  }

  if(null != jsonParamters.JonDoFoxLite_isEnabled) {
    console.log(jsonParamters.JonDoFoxLite_isEnabled);
    require("sdk/simple-prefs").prefs.JonDoFoxLite_isEnabled =  jsonParamters.JonDoFoxLite_isEnabled;
  }

  if(null != jsonParamters.proxyChoice) {
    console.log(jsonParamters.proxyChoice);
    proxy.proxyService.setProxy(jsonParamters.proxyChoice);
  }

  console.log(jsonParamters);
  console.log("panelmenu.port.on end");
});

function handleChange(state) {
  if (state.checked) {
    panelmenu.show({
      position: button
    });
    // INIT PARAMETERS
    var panelmenuInitParameter =  "  [" +
                        "  JonDoFoxLite_isEnabled," +
                        preferences.JonDoFoxLite_isEnabled +
                        "  ]";

    panelmenu.port.emit("menuAction", panelmenuInitParameter);

  }
}

function handleHide() {
  button.state('window', {checked: false});
}

/*
* This function is run when the Toolbar Button is clicked
* it sets the JonDoFoxLite_isEnabled pref
* the return value is used for Unittests
*/
function handleClick(state){
  if(preferences.JonDoFoxLite_isEnabled){
    preferences.JonDoFoxLite_isEnabled = false;
    restoreFontBlacklist();
  }
  else if(!preferences.JonDoFoxLite_isEnabled){
    preferences.JonDoFoxLite_isEnabled = true;
    putFontBlacklist()
  }
}

/*
* Exports needed functions so they are available for others when this file is require()
*/
exports.handleClick = handleClick;

/*
* Set listerner to pref storage
*/
require("sdk/simple-prefs").on("JonDoFoxLite_isEnabled", requests.onPrefChange);

/*
* Listener button and open the tab
*/
function onExtPrefClick(){
  //optionTab.open({url: data.url("options.html")});
  tabs.open({
    url: data.url("options.html"),
    isPinned: true,
    onReady: function(tab) {
      worker = tab.attach({
        contentScriptFile: data.url("cs_options.js"),
        contentScriptOptions: {
            JonDoFoxLite_isEnabled: preferences.JonDoFoxLite_isEnabled
        }
      });

      // Send data to contentScript "options.js"
      worker.port.emit("preferences", preferences.JonDoFoxLite_isEnabled);

      // Receive data from contentScript "options.js"
      worker.port.on("preferences", function(preferences) {
        console.log("AddonScript from contentScript :" + preferences);
        // Set preferences in the storage
        console.log("XXX Preference :" + preferences);
        require("sdk/simple-prefs").prefs.JonDoFoxLite_isEnabled =  preferences;
      });
    }
  });
}
/*
* Set listener to the button
*/
require("sdk/simple-prefs").on("preferencesButton", onExtPrefClick);

// PA-Mode is now in seperate file

PA.PA.checkIfOneTabIsPrivate(shadow_preferences);
<commit_msg>small fix<commit_after>/*
* Includes
*/
var self = require('sdk/self');

var buttons = require('sdk/ui/button/action');
var preferences = require("sdk/simple-prefs").prefs;
var tabs = require("sdk/tabs");
var self = require("sdk/self");
var requests = require("./observer.js");
var style = require('sdk/stylesheet/style');
var data = require("sdk/self").data;
var { ToggleButton } = require('sdk/ui/button/toggle');
var panels = require("sdk/panel");
var shadow_preferences = require("./preferences.js"); //renamed cause of dublicated variable declaration, CHECK THIS!
var proxy = require("./data/bs_proxy.js");
var PA = require("./PA_mode.js");

/*
*  Initialize the ShadowPrefs here if needed
*/
shadow_preferences.ShadowPrefs.ShadowPref_check_exist();

if(!shadow_preferences.ShadowPrefs.SP_exist){

  // init with hardcoded default values
  shadow_preferences.ShadowPrefs.initNames();
  shadow_preferences.ShadowPrefs.initValues();

  // create ShadowPrefs (extensions.jondofox.xxxx)
  shadow_preferences.ShadowPrefs.createShadowPrefs();

  // apply all prefs here that need a restart and cant be loaded dynamically

  // restart here if needed

}
else{

  // init names of preferences we want to keep track of
  shadow_preferences.ShadowPrefs.initNames();

  // read ShadowPref values from about:config
  shadow_preferences.ShadowPrefs.readShadowPrefs();

}

/*
* Initiate Observers here
*/
PA.initTabs(PA, shadow_preferences);
//requests.httpRequestObserver.register(); <~~ this code line is gone into PA_mode.js

// Initial make a shadowcopy of preferences

//shadow_preferences.putFontBlacklist;
//shadow_preferences.jonDoFoxPreferenceService.initShadowCopy();
proxy.proxyService.initShadowProxyCopy();
/*
* Create the Toolbar Button
*/
// Removed by KKP to switch it to an toggleButton
/*var button = buttons.ActionButton({
  id: "enable-disable",
  label: "Enable/Disable Addon",
  icon: {
    "16": "./icon-16.png",
    "32": "./icon-32.png",
    //"64": "./icon-64.png"
  },
  onClick: handleClick
});*/

var button = ToggleButton({
  id: "togglePanelMenu",
  label: "my button",
  icon: {
    "16": "./icon-16.png",
    "32": "./icon-32.png"
    //"64": "./icon-64.png"
  },
  onChange: handleChange
});

var panelmenu = panels.Panel({
  width: 200,
  height:265,
  contentURL: self.data.url("panelmenu.html"),
  onHide: handleHide ,
  contentScriptFile :  data.url("cs_panelmenu.js"),
});

// Receive data from contentScript "options.js"
panelmenu.port.on("menuAction", function(jsonParamters) {
  console.log("panelmenu.port.on begin");
  if(jsonParamters.option) {
    console.log(jsonParamters.option)
    onExtPrefClick();
  }

  if(null != jsonParamters.JonDoFoxLite_isEnabled) {
    console.log(jsonParamters.JonDoFoxLite_isEnabled);
    require("sdk/simple-prefs").prefs.JonDoFoxLite_isEnabled =  jsonParamters.JonDoFoxLite_isEnabled;
  }

  if(null != jsonParamters.proxyChoice) {
    console.log(jsonParamters.proxyChoice);
    proxy.proxyService.setProxy(jsonParamters.proxyChoice);
  }

  console.log(jsonParamters);
  console.log("panelmenu.port.on end");
});

function handleChange(state) {
  if (state.checked) {
    panelmenu.show({
      position: button
    });
    // INIT PARAMETERS
    var panelmenuInitParameter =  "  [" +
                        "  JonDoFoxLite_isEnabled," +
                        preferences.JonDoFoxLite_isEnabled +
                        "  ]";

    panelmenu.port.emit("menuAction", panelmenuInitParameter);

  }
}

function handleHide() {
  button.state('window', {checked: false});
}

/*
* This function is run when the Toolbar Button is clicked
* it sets the JonDoFoxLite_isEnabled pref
* the return value is used for Unittests
*/
function handleClick(state){
  if(preferences.JonDoFoxLite_isEnabled){
    preferences.JonDoFoxLite_isEnabled = false;
    restoreFontBlacklist(); // needs an update
  }
  else if(!preferences.JonDoFoxLite_isEnabled){
    preferences.JonDoFoxLite_isEnabled = true;
    putFontBlacklist(); // needs an update
  }
}

/*
* Exports needed functions so they are available for others when this file is require()
*/
exports.handleClick = handleClick;

/*
* Set listerner to pref storage
*/
require("sdk/simple-prefs").on("JonDoFoxLite_isEnabled", requests.onPrefChange);

/*
* Listener button and open the tab
*/
function onExtPrefClick(){
  //optionTab.open({url: data.url("options.html")});
  tabs.open({
    url: data.url("options.html"),
    isPinned: true,
    onReady: function(tab) {
      worker = tab.attach({
        contentScriptFile: data.url("cs_options.js"),
        contentScriptOptions: {
            JonDoFoxLite_isEnabled: preferences.JonDoFoxLite_isEnabled
        }
      });

      // Send data to contentScript "options.js"
      worker.port.emit("preferences", preferences.JonDoFoxLite_isEnabled);

      // Receive data from contentScript "options.js"
      worker.port.on("preferences", function(preferences) {
        console.log("AddonScript from contentScript :" + preferences);
        // Set preferences in the storage
        console.log("XXX Preference :" + preferences);
        require("sdk/simple-prefs").prefs.JonDoFoxLite_isEnabled =  preferences;
      });
    }
  });
}
/*
* Set listener to the button
*/
require("sdk/simple-prefs").on("preferencesButton", onExtPrefClick);

// PA-Mode is now in seperate file

PA.PA.checkIfOneTabIsPrivate(shadow_preferences);
<|endoftext|>


<commit_before>'use strict';

var debug = false;
var stack = 'init';
var paths = [];

function prepareSelectors(paths, root) {
  var sPaths = [];
  for (var i = 0; i < paths.length; i++) {
    var val = '';
    var objPath = paths[i];
    var objKeys = Object.keys(objPath);
    objKeys.forEach(function(key) {
      var node = objPath[key];
      if (node !== null) {
        if (isNaN(node)) {
          val += node + '.'
        } else {
          val += '[' + node.toString() + ']' + '.';
        }
      }
    });
    var sPath = val.slice(0, -1).replace(/^root/g, root).replace(/\.\[/g, '[');
    sPaths.push(sPath)
  }
  paths = [];
  return sPaths;
}

function pushState(value) {
  var count = Object.keys(stack).length;
  stack[count] = value;
  if (debug) console.log('[INFO] PUSHed ' + value + ' : ' + JSON.stringify(stack));
}

function popState(marker) {
  var count = Object.keys(stack).length;
  if (count > 1) {
    var last_element = count - 1;
    var pop_elem = stack[last_element];
    delete stack[last_element];
    if (debug) console.log('[INFO] POPed ' + pop_elem + ' from ' + marker + ': ' + JSON.stringify(stack));
  }
}

function savePath(stack) {
  if ((paths.indexOf(stack) === -1) || paths.length === 0) {
    if (debug) console.log('[INFO] Pushing ' + JSON.stringify(stack) + ' in Paths');
    paths[paths.length] = JSON.parse(JSON.stringify(stack));
    if (debug) console.log('[INFO] Paths: ' + JSON.stringify(paths));
  }
}

function isObjEqual(a, b) {
  var aProps = Object.getOwnPropertyNames(a);
  var bProps = Object.getOwnPropertyNames(b);
  if (aProps.length != bProps.length) {
    return false;
  }
  for (var i = 0; i < aProps.length; i++) {
    var propName = aProps[i];
    if (a[propName] !== b[propName]) {
      return false;
    }
  }
  return true;
}

function findInArray(varArray, needle) {
  if (debug) console.log('================ENTERED {findInArray}================');

  var found = false;

  if (needle instanceof Array && varArray.join() === needle.join()) {
    if (debug) console.log('[INFO] Matched Array in {findInArray} IF ' + JSON.stringify(needle) + ' in ' + JSON.stringify(stack));

    found = true;
  }

  for (var item in varArray) {
    if (debug) console.log('[INFO] Working Array\'s element ' + item);
    pushState(item);
    if (needle === varArray[item]) {
      if (debug) console.log('[INFO] Found in {findInArray} IF ' + needle + ' in ' + JSON.stringify(stack));

      found = true;
    } else if (typeof(varArray[item]) === 'object') {
      if (debug) console.log('[INFO] in {findInArray} ELSE IF ');

      if (varArray[item] instanceof Array) {
        if (findInArray(varArray[item], needle)) {
          if (debug) console.log('[INFO] found in {findInArray}:{findInArray} ELSE IF');

          found = true;
        }
      } else {
        if (findInObject(varArray[item], needle)) {
          if (debug) console.log('[INFO] found in {findInArray}:{findInObject} ELSE IF');
          found = true;
        }
      }
    } else {
      if (debug) console.log('[INFO] in {findInArray} ELSE');
      if (debug) console.log('===========LEFT {findInArray}================');
      if (searchInObject(varArray[item], needle)) {
        if (debug) console.log('[INFO] found in {findInArray} ELSE');
        found = true;
      } else {
        if (debug) console.log('================ENTERED {findInArray}================');
      }
    }

    if (found) {
      savePath(stack);
      popState('{findInArray}-found');
      found = false;
    }
  }
  popState('{findInArray}');
  if (debug) console.log('===========LEFT {findInObject}================');
  return found;
}

function findInObject(varObject, needle) {
  if (debug) console.log('================ENTERED {findInObject}================');

  var found = false;

  if (typeof(needle) === 'object' && !(needle instanceof Array) && isObjEqual(needle, varObject)) {
    if (debug) console.log('[INFO] Matched Object in {findInObject} IF ' + JSON.stringify(needle) + ' in ' + JSON.stringify(stack));

    found = true;
  }

  for (var item in varObject) {

    if (debug) console.log('[INFO] Working Object\'s element ' + item);
    pushState(item);

    if ((item === needle) || (varObject[item] === needle)) {
      if (debug) console.log('[INFO] in {findInObject} IF ');
      if (debug) console.log('[INFO] Found in {findInObject} IF ' + needle + ' in ' + JSON.stringify(stack));
      if (debug) console.log('===========LEFT {findInObject}================');
      found = true;

    } else if (typeof(varObject[item]) === 'object') {
      if (debug) console.log('[INFO] in {findInObject} ELSE IF ');

      if (varObject[item] instanceof Array) {

        if (findInArray(varObject[item], needle)) {
          if (debug) console.log('[INFO] found in {findInObject}:{findInArray} ELSE IF');

          found = true;
        }

      } else {

        if (findInObject(varObject[item], needle)) {
          if (debug) console.log('[INFO] found in {findInObject}:{findInObject} ELSE IF');

          found = true;
        }

      }
    } else {

      if (debug) console.log('[INFO] in {findInObject} ELSE');
      if (debug) console.log('===========LEFT {findInObject}================');
      if (searchInObject(varObject[item], needle)) {
        if (debug) console.log('[INFO] found in {findInObject} ELSE');

        found = true;

      } else {
        if (debug) console.log('================ENTERED {findInObject}================');
      }
    }

    if (found) {

      savePath(stack);
      popState('{findInObject}-found');
      found = false;
    }
  }

  popState('{findInObject}');
  if (debug) console.log('===========LEFT {findInObject}================');
  return found;
}

function searchInObject(haystack, needle) {
  if (debug) console.log('================ENTERED {search}================');
  if (stack === 'init') {
    stack = {
      0: 'root'
    };
  }

  var type = typeof(haystack);

  switch (type) {

    case 'object':
      if (haystack instanceof Array) {
        if (debug) console.log('===========LEFT {search} to {findInArray}================');
        var result = findInArray(haystack, needle);
      } else {
        if (debug) console.log('===========LEFT {search} to {findInObject}================');
        var result = findInObject(haystack, needle);
      }

    default:
      if (needle === haystack) {
        var result = true;
        if (debug) console.log('[search] Found: ' + JSON.stringify(stack));
        result = false;
        savePath(stack);
      }
  }
  if (result) {
    if (debug) console.log('[INFO] (search) Found ' + JSON.stringify(needle) + ' in ' + JSON.stringify(result));
    if (debug) console.log('===========LEFT {search}================');
    return true;
  }
  popState(stack, '{search}');
  if (debug) console.log('===========LEFT {search}================');
  return false;
}

// Duplicate definition of getParent to deal with scoping issues
function getParentNode(selector) {
  if (selector.endsWith(']')) {
    return selector.substring(0, selector.lastIndexOf('['));
  } else {
    return selector.substring(0, selector.lastIndexOf('.'));
  }
}

function getSibling(selector, json, direction) {
  //replace the original object's literal name with "json"
  var strOriginalContext = selector.substring(0, selector.indexOf('.'));
  selector = selector.replace(strOriginalContext, "json");
  if (!selector || !json || !direction) return undefined;
  var found = false;
  var nextSiblingValue = null;
  if (selector === undefined) return undefined;
  if (selector.endsWith(']')) {
    var bookmark = parseInt(selector.split('[').pop(-1).split(']')[0]);
  } else {
    var bookmark = selector.split('.').slice(-1)[0];
  }
  if (debug) console.log('selector: ' + selector);
  if (debug) console.log('bookmark: ' + bookmark);
  var parentSelector = getParentNode(selector);

  if (debug) console.log('parent before eval: ' + parentSelector);
  var parentObject = eval(parentSelector);
  var that = this;
  if (debug) console.log('parent after eval: ' + JSON.stringify(parentObject));
  var keys = Object.keys(parentObject);
  if (debug) console.log('keys: ' + JSON.stringify(keys));
  if (debug) console.log('direction: ' + direction);
  switch (direction) {
    case 'previous':
      if (!isNaN(bookmark)) {
        var index = bookmark - 1;
        index = index < 0 ? undefined : index;
        if(index === undefined) return undefined;
        var strNewContext = parentSelector.substring(0, parentSelector.indexOf('.'));
        parentSelector = parentSelector.replace("json", strOriginalContext);
        return parentSelector + '[' + index + ']';
      } else {
        for (var i = 0; i < keys.length; i++) {
          if (keys[i] === bookmark) {
            if (!keys[i - 1]) return undefined;
            var strNewContext = parentSelector.substring(0, parentSelector.indexOf('.'));
            parentSelector = parentSelector.replace("json", strOriginalContext);
            return parentSelector + '.' + keys[i - 1];
          }
        }
      }
    case 'next':
      if (!isNaN(bookmark)) {
        var index = bookmark + 1;
        index = index >= parentObject.length ? undefined : index
        if(index === undefined) return undefined;
        var strNewContext = parentSelector.substring(0, parentSelector.indexOf('.'));
        parentSelector = parentSelector.replace("json", strOriginalContext);
        return parentSelector + '[' + index + ']';
      } else {
        for (var i = 0; i < keys.length; i++) {
          if (keys[i] === bookmark) {
            if (!keys[i + 1]) return undefined;
            var strNewContext = parentSelector.substring(0, parentSelector.indexOf('.'));
            parentSelector = parentSelector.replace("json", strOriginalContext);
            return parentSelector + '.' + keys[i + 1];
          }
        }
      }
  }
}

function Path(path, haystack) {
  this.path = path;
  this.haystack = haystack;
}

Path.prototype.parent = function() {
  if (!this.path) return undefined;
  var selector = this.path
  if (selector.endsWith(']')) {
    selector = selector.substring(0, selector.lastIndexOf('['));
  } else {
    selector = selector.substring(0, selector.lastIndexOf('.'));
  }
  return new Path(selector, this.haystack);
};

Path.prototype.val = function() {
  if (!this.path || !this.haystack) return undefined;
  var rootObject = this.path.split('.');
  rootObject[0] = 'this.haystack';
  var value = eval(rootObject.join('.'));
  return value;
}

Path.prototype.next = function() {
  if (!this.path || !this.haystack) return undefined;
  return new Path(getSibling(this.path, this.haystack, 'next'), this.haystack);
}

Path.prototype.prev = function() {
  if (!this.path || !this.haystack) return undefined;
  return new Path(getSibling(this.path, this.haystack, 'previous'), this.haystack);
}

Path.prototype.addAfter = function() {
  if(!this.path || !this.haystack) return undefined;
  console.log(this.path);
}

var jsonq = {
  findAll: function(keyword, objHaystack, strContext, callback) {
    paths = [];
    var pathObject = [];
    searchInObject(objHaystack, keyword); // paths[] enumerated
    var allselectors = prepareSelectors(paths, strContext);
    for (var i = 0; i < allselectors.length; i++) {
      pathObject.push(new Path(allselectors[i], objHaystack));
    }
    if (callback) {
      callback(pathObject);
    } else {
      return pathObject;
    }
  },

  findAndReplaceAll: function(data, find, replace, callback) {
    paths = [];
    var json = typeof data === 'string' ? JSON.parse(data) : typeof data === 'object' ? data : {};
    searchInObject(json, find);
    var selectors = prepareSelectors(paths, 'json');
    selectors.forEach(function(selector) {
      eval(selector + '=\'' + replace + '\'');
    });
    if (callback) {
      callback(json);
    } else {
      return json;
    }
  }
}

module.exports = {
  init: function(options) {
    options = {} || options;
    debug = options && options.debug || false;
    return jsonq;
  }
}<commit_msg>rename attribute name<commit_after>'use strict';

var debug = false;
var stack = 'init';
var paths = [];

function prepareSelectors(paths, root) {
  var sPaths = [];
  for (var i = 0; i < paths.length; i++) {
    var val = '';
    var objPath = paths[i];
    var objKeys = Object.keys(objPath);
    objKeys.forEach(function(key) {
      var node = objPath[key];
      if (node !== null) {
        if (isNaN(node)) {
          val += node + '.'
        } else {
          val += '[' + node.toString() + ']' + '.';
        }
      }
    });
    var sPath = val.slice(0, -1).replace(/^root/g, root).replace(/\.\[/g, '[');
    sPaths.push(sPath)
  }
  paths = [];
  return sPaths;
}

function pushState(value) {
  var count = Object.keys(stack).length;
  stack[count] = value;
  if (debug) console.log('[INFO] PUSHed ' + value + ' : ' + JSON.stringify(stack));
}

function popState(marker) {
  var count = Object.keys(stack).length;
  if (count > 1) {
    var last_element = count - 1;
    var pop_elem = stack[last_element];
    delete stack[last_element];
    if (debug) console.log('[INFO] POPed ' + pop_elem + ' from ' + marker + ': ' + JSON.stringify(stack));
  }
}

function savePath(stack) {
  if ((paths.indexOf(stack) === -1) || paths.length === 0) {
    if (debug) console.log('[INFO] Pushing ' + JSON.stringify(stack) + ' in Paths');
    paths[paths.length] = JSON.parse(JSON.stringify(stack));
    if (debug) console.log('[INFO] Paths: ' + JSON.stringify(paths));
  }
}

function isObjEqual(a, b) {
  var aProps = Object.getOwnPropertyNames(a);
  var bProps = Object.getOwnPropertyNames(b);
  if (aProps.length != bProps.length) {
    return false;
  }
  for (var i = 0; i < aProps.length; i++) {
    var propName = aProps[i];
    if (a[propName] !== b[propName]) {
      return false;
    }
  }
  return true;
}

function findInArray(varArray, needle) {
  if (debug) console.log('================ENTERED {findInArray}================');

  var found = false;

  if (needle instanceof Array && varArray.join() === needle.join()) {
    if (debug) console.log('[INFO] Matched Array in {findInArray} IF ' + JSON.stringify(needle) + ' in ' + JSON.stringify(stack));

    found = true;
  }

  for (var item in varArray) {
    if (debug) console.log('[INFO] Working Array\'s element ' + item);
    pushState(item);
    if (needle === varArray[item]) {
      if (debug) console.log('[INFO] Found in {findInArray} IF ' + needle + ' in ' + JSON.stringify(stack));

      found = true;
    } else if (typeof(varArray[item]) === 'object') {
      if (debug) console.log('[INFO] in {findInArray} ELSE IF ');

      if (varArray[item] instanceof Array) {
        if (findInArray(varArray[item], needle)) {
          if (debug) console.log('[INFO] found in {findInArray}:{findInArray} ELSE IF');

          found = true;
        }
      } else {
        if (findInObject(varArray[item], needle)) {
          if (debug) console.log('[INFO] found in {findInArray}:{findInObject} ELSE IF');
          found = true;
        }
      }
    } else {
      if (debug) console.log('[INFO] in {findInArray} ELSE');
      if (debug) console.log('===========LEFT {findInArray}================');
      if (searchInObject(varArray[item], needle)) {
        if (debug) console.log('[INFO] found in {findInArray} ELSE');
        found = true;
      } else {
        if (debug) console.log('================ENTERED {findInArray}================');
      }
    }

    if (found) {
      savePath(stack);
      popState('{findInArray}-found');
      found = false;
    }
  }
  popState('{findInArray}');
  if (debug) console.log('===========LEFT {findInObject}================');
  return found;
}

function findInObject(varObject, needle) {
  if (debug) console.log('================ENTERED {findInObject}================');

  var found = false;

  if (typeof(needle) === 'object' && !(needle instanceof Array) && isObjEqual(needle, varObject)) {
    if (debug) console.log('[INFO] Matched Object in {findInObject} IF ' + JSON.stringify(needle) + ' in ' + JSON.stringify(stack));

    found = true;
  }

  for (var item in varObject) {

    if (debug) console.log('[INFO] Working Object\'s element ' + item);
    pushState(item);

    if ((item === needle) || (varObject[item] === needle)) {
      if (debug) console.log('[INFO] in {findInObject} IF ');
      if (debug) console.log('[INFO] Found in {findInObject} IF ' + needle + ' in ' + JSON.stringify(stack));
      if (debug) console.log('===========LEFT {findInObject}================');
      found = true;

    } else if (typeof(varObject[item]) === 'object') {
      if (debug) console.log('[INFO] in {findInObject} ELSE IF ');

      if (varObject[item] instanceof Array) {

        if (findInArray(varObject[item], needle)) {
          if (debug) console.log('[INFO] found in {findInObject}:{findInArray} ELSE IF');

          found = true;
        }

      } else {

        if (findInObject(varObject[item], needle)) {
          if (debug) console.log('[INFO] found in {findInObject}:{findInObject} ELSE IF');

          found = true;
        }

      }
    } else {

      if (debug) console.log('[INFO] in {findInObject} ELSE');
      if (debug) console.log('===========LEFT {findInObject}================');
      if (searchInObject(varObject[item], needle)) {
        if (debug) console.log('[INFO] found in {findInObject} ELSE');

        found = true;

      } else {
        if (debug) console.log('================ENTERED {findInObject}================');
      }
    }

    if (found) {

      savePath(stack);
      popState('{findInObject}-found');
      found = false;
    }
  }

  popState('{findInObject}');
  if (debug) console.log('===========LEFT {findInObject}================');
  return found;
}

function searchInObject(haystack, needle) {
  if (debug) console.log('================ENTERED {search}================');
  if (stack === 'init') {
    stack = {
      0: 'root'
    };
  }

  var type = typeof(haystack);

  switch (type) {

    case 'object':
      if (haystack instanceof Array) {
        if (debug) console.log('===========LEFT {search} to {findInArray}================');
        var result = findInArray(haystack, needle);
      } else {
        if (debug) console.log('===========LEFT {search} to {findInObject}================');
        var result = findInObject(haystack, needle);
      }

    default:
      if (needle === haystack) {
        var result = true;
        if (debug) console.log('[search] Found: ' + JSON.stringify(stack));
        result = false;
        savePath(stack);
      }
  }
  if (result) {
    if (debug) console.log('[INFO] (search) Found ' + JSON.stringify(needle) + ' in ' + JSON.stringify(result));
    if (debug) console.log('===========LEFT {search}================');
    return true;
  }
  popState(stack, '{search}');
  if (debug) console.log('===========LEFT {search}================');
  return false;
}

// Duplicate definition of getParent to deal with scoping issues
function getParentNode(selector) {
  if (selector.endsWith(']')) {
    return selector.substring(0, selector.lastIndexOf('['));
  } else {
    return selector.substring(0, selector.lastIndexOf('.'));
  }
}

function getSibling(selector, json, direction) {
  //replace the original object's literal name with "json"
  var strOriginalContext = selector.substring(0, selector.indexOf('.'));
  selector = selector.replace(strOriginalContext, "json");
  if (!selector || !json || !direction) return undefined;
  var found = false;
  var nextSiblingValue = null;
  if (selector === undefined) return undefined;
  if (selector.endsWith(']')) {
    var bookmark = parseInt(selector.split('[').pop(-1).split(']')[0]);
  } else {
    var bookmark = selector.split('.').slice(-1)[0];
  }
  if (debug) console.log('selector: ' + selector);
  if (debug) console.log('bookmark: ' + bookmark);
  var parentSelector = getParentNode(selector);

  if (debug) console.log('parent before eval: ' + parentSelector);
  var parentObject = eval(parentSelector);
  var that = this;
  if (debug) console.log('parent after eval: ' + JSON.stringify(parentObject));
  var keys = Object.keys(parentObject);
  if (debug) console.log('keys: ' + JSON.stringify(keys));
  if (debug) console.log('direction: ' + direction);
  switch (direction) {
    case 'previous':
      if (!isNaN(bookmark)) {
        var index = bookmark - 1;
        index = index < 0 ? undefined : index;
        if(index === undefined) return undefined;
        var strNewContext = parentSelector.substring(0, parentSelector.indexOf('.'));
        parentSelector = parentSelector.replace("json", strOriginalContext);
        return parentSelector + '[' + index + ']';
      } else {
        for (var i = 0; i < keys.length; i++) {
          if (keys[i] === bookmark) {
            if (!keys[i - 1]) return undefined;
            var strNewContext = parentSelector.substring(0, parentSelector.indexOf('.'));
            parentSelector = parentSelector.replace("json", strOriginalContext);
            return parentSelector + '.' + keys[i - 1];
          }
        }
      }
    case 'next':
      if (!isNaN(bookmark)) {
        var index = bookmark + 1;
        index = index >= parentObject.length ? undefined : index
        if(index === undefined) return undefined;
        var strNewContext = parentSelector.substring(0, parentSelector.indexOf('.'));
        parentSelector = parentSelector.replace("json", strOriginalContext);
        return parentSelector + '[' + index + ']';
      } else {
        for (var i = 0; i < keys.length; i++) {
          if (keys[i] === bookmark) {
            if (!keys[i + 1]) return undefined;
            var strNewContext = parentSelector.substring(0, parentSelector.indexOf('.'));
            parentSelector = parentSelector.replace("json", strOriginalContext);
            return parentSelector + '.' + keys[i + 1];
          }
        }
      }
  }
}

function Path(path, haystack) {
  this.path = path;
  this.obj = haystack;
}

Path.prototype.parent = function() {
  if (!this.path) return undefined;
  var selector = this.path
  if (selector.endsWith(']')) {
    selector = selector.substring(0, selector.lastIndexOf('['));
  } else {
    selector = selector.substring(0, selector.lastIndexOf('.'));
  }
  return new Path(selector, this.obj);
};

Path.prototype.val = function() {
  if (!this.path || !this.obj) return undefined;
  var rootObject = this.path.split('.');
  rootObject[0] = 'this.obj';
  var value = eval(rootObject.join('.'));
  return value;
}

Path.prototype.next = function() {
  if (!this.path || !this.obj) return undefined;
  return new Path(getSibling(this.path, this.obj, 'next'), this.obj);
}

Path.prototype.prev = function() {
  if (!this.path || !this.obj) return undefined;
  return new Path(getSibling(this.path, this.obj, 'previous'), this.obj);
}

Path.prototype.addAfter = function() {
  if(!this.path || !this.obj) return undefined;
  console.log(this.path);
}

var jsonq = {
  findAll: function(keyword, objHaystack, strContext, callback) {
    paths = [];
    var pathObject = [];
    searchInObject(objHaystack, keyword); // paths[] enumerated
    var allselectors = prepareSelectors(paths, strContext);
    for (var i = 0; i < allselectors.length; i++) {
      pathObject.push(new Path(allselectors[i], objHaystack));
    }
    if (callback) {
      callback(pathObject);
    } else {
      return pathObject;
    }
  },

  findAndReplaceAll: function(data, find, replace, callback) {
    paths = [];
    var json = typeof data === 'string' ? JSON.parse(data) : typeof data === 'object' ? data : {};
    searchInObject(json, find);
    var selectors = prepareSelectors(paths, 'json');
    selectors.forEach(function(selector) {
      eval(selector + '=\'' + replace + '\'');
    });
    if (callback) {
      callback(json);
    } else {
      return json;
    }
  }
}

module.exports = {
  init: function(options) {
    options = {} || options;
    debug = options && options.debug || false;
    return jsonq;
  }
}<|endoftext|>