<commit_before>var URL = require('url');
var query = require('querystring');

/*
	Example:

	var OVERRIDES = {
		'override1': {
			// Match any JS and CSS file.
			'match': new RegExp(/\/(.*\.(js|css)$/i),
			// Optional: When matched, call the following function.
			'callback': function(res, found, data, post) {
				// @res   - HTTP response object.
				// @found - result of "match" RegExp's exec().
				// @data  - whole override definition object (including match, callback, path and any other attributes).
				// @post  - data POST-ed in this request, parsed into object, e.g., "variable=value" will be passed as "{ variable: value }".
				var filename = path.join(data['path'], found[1]);
				var stats;

				try {
					stats = fs.lstatSync(filename); // lstatSync() throws if path doesn't exist.
				}
				catch (e) {
					return;
				}

				if (stats.isFile()) {
					// path exists and is a file
					var ext = path.extname(filename).split(".")[1];
					res.writeHead(200, {'Content-Type': (ext == 'js' ? 'application/x-javascript' : 'text/css')} );

					var fileStream = fs.createReadStream(filename);
					fileStream.pipe(res);
				}
				else {
					res.writeHead(500, {'Content-Type': 'text/plain'});
					res.write('500 Internal server error\n');
					res.end();
				}
			},
			// Look for an override in the following directory.
			'path': '/www/overrides/',
			// Optional: do not pass the request through CNTLM (in case there is no callback specified).
			'omitCNTLM': true,
			// Any other data that may be used by the callback function.
			'myVariable': 'example'
		},
		'summit.meetjs.pl': {
			// Match any JS and CSS file.
			'match': 'https://summit.meetjs.pl/',
			// Optional: When matched, call the following function.
			'callback': hyperProxy.overrideWithStaticOutput,
			// Look for an override in the following directory.
			'path': '/www/overrides/index.html',
			// Optional: do not pass the request through CNTLM (in case there is no callback specified).
			'omitCNTLM': true
		},
		'override3': {
			// etc...
		}
	};

	var HYPERPROXY = {
		'http_port': 8000,
		'https_port': 8001,
		// Set pac_port to false if PAC file server should not be created.
		'pac_port': 8002,
		'verbose': true,//'debug',
		'ssl_key': './certs/ssl-key.pem',
		'ssl_cert': './certs/ssl-cert.pem',

		// Set CNTLM to `false`, if cntlm proxy is not required to connect to the world.
		cntlm: {
			// Set this to the port number that is used by cntlm already running in the background
			// or that will be tried for spawned cntlm proxy.
			// Set this to false, if cntlm should not be used at all.
			'port': false,//3130,
			// Where was cntlm installed and configured (directory should contain both cntlm executable and cntlm.ini files)?
			// Set to false, if cntlm is already running and should not be controlled by our proxy
			'path': false,//'C:\\Program Files (x86)\\Cntlm\\',
			// How many ports should be tried before giving up and exiting?
			// This is needed when port specified above is already used and path is specified, i.e.,
			// cntlm is not running yet and should be spawned.
			'hitpoints': 5,
			// Should we always try to kill any other CNTLM running, before starting ours?
			'killOnBeforeStart': true,
			// Do not change this one!
			'_PID': false
		},

		// Default proxy location is used in the PAC file output.
		// Set defaultproxy to false to not use any default proxy in the PAC file output
		// (PAC will return DIRECT connection value in that case).
		defaultproxy: false
		//defaultproxy: {
		//	'proxy': 'hyper.proxy',
		//	'port': 3128
		//}
		//defaultproxy: {
		//	'proxy': '127.0.0.1',
		//	'port': 8080
		//}
	};

	var hyperProxy = require('./lib/hyperProxy.js')(OVERRIDES, HYPERPROXY);
*/

module.exports.start = function(overrides, settings) {
	var self = this;

	self.settings = settings;
	self.overrides = overrides;
	self.cntlm = false;

	/*
		Spawn cntlm "gateway", but only if settings.cntlm.port and settings.cntlm.path were set.
	*/
	if (self.settings.cntlm && self.settings.cntlm.port && self.settings.cntlm.path) {

		process.on('cntlmReady', function(PID){
			console.log('cntlm is running as '+PID);
		});

		process.on('cntlmError', function(){
			console.log('Could not run cntlm! Exiting.');
			process.exit();
		});

		var CNTLM = require('./lib/CNTLM.js');
		self.settings.cntlm.verbose = self.settings.cntlm.verbose || self.settings.verbose;
		self.cntlm = new CNTLM(self.settings.cntlm);
	}

	/*
		Setup our JS proxy.
	*/
	self.overrider = function(req, res, req_url) {
		var target = URL.format(req_url);
		var found = null;
		var omitCNTLM = false;

		for (var name in self.overrides) {
			if (self.overrides.hasOwnProperty(name)) {
				found = null;
				if (self.overrides[name].hasOwnProperty('match')) {
					if (self.overrides[name]['match'] instanceof RegExp) {
						found = self.overrides[name]['match'].exec(target);
					}
					else if (self.overrides[name]['match'] === target) {
						found = [target];
					}
				}

				if (found && found.length > 0) {
					if (self.overrides[name].hasOwnProperty('omitCNTLM') && self.overrides[name].omitCNTLM) {
						omitCNTLM = true;
					}
					if (self.overrides[name].hasOwnProperty('callback')) {
						try {
							console.log("[" + req_url.hostname + req_url.pathname + "] - Overriding using " + name);
							var data = '';
							req.on('data', function(chunk){
								data += chunk;
							});
							req.on('end', function(){
								data = (data ? query.parse(data) : false);
								(self.overrides[name]['callback'])(res, found, self.overrides[name], data);
							});
							return true;
						}
						catch (e) {
							console.log(e);
						}
					}
					break;
				}
			}
		}

		// No override was found and called, so let's pass it over to the proxy.
		// If we should use CNTLM, override target, so our Proxy will pass request through CNTLM.
		if (!omitCNTLM && self.settings.cntlm && self.settings.cntlm.port) {
			req_url.hostname = 'localhost';
			req_url.port = self.settings.cntlm.port;
			req_url.pathname = target;
			//req_url.protocol = 'http'; // should we force HTTP?
			req_url.search = '';
		}

		return false;
	};

	self.hyperProxyProcessor = function(proxy) {
		this.override_request = function(request, req_url, response, type){
			var url = req_url;
			console.log("[" + url.hostname + url.pathname + "] - Processor override_request, url: " + URL.format(url));
			return self.overrider(request, response, req_url, type);
		};
	};

	Proxy = require('./lib/node-mitm-proxy/proxy.js');
	self.proxy = new Proxy({id: 'hyperProxy', proxy_port: self.settings.http_port, mitm_port: self.settings.https_port, verbose: self.settings.verbose, key_path: self.settings.ssl_key, cert_path: self.settings.ssl_cert}, self.hyperProxyProcessor);

	if (self.settings.pac_port) {
		self.pacServer = new require('./lib/PACServer.js')(self.overrides, self.settings.pac_port, self.settings, self.settings.defaultproxy);
	}
};

// Dependencies.
var fs = require('fs');
var path = require('path');

/*
	In projects that use separate CSS and JS files there's not much additional work needed.
	This function tries to find JS, CSS, HTM(L) or SWF file, and if one does not exists, it tries the same file name but without ".min"
	part (only for JS and CSS and if there is any) - just in case there is a full source data available.

	@res - HTTP response.
	@found - result of RegExp exec(). found[1] will be used as a file name.
	@data - matched override object with any custom data that was put there, including required 'path' to the project directory.
	@post - parsed query from the POST data, e.g., "variable=value" will be passed as "{ variable: value }". Not used.
*/
module.exports.overrideJSandCSSgeneric = function (res, found, data, post){
	var filename = path.join(data['path'], found[1]);
	var stats;

	if (!fs.existsSync(filename) && filename.match(/\.(js|css)$/i)) {
		// Try without ".min" for JS and CSS
		filename = filename.replace(/\.min/, '');
	}

	try {
		stats = fs.lstatSync(filename); // throws if path doesn't exist
	}
	catch (e) {
		res.writeHead(404, {'Content-Type': 'text/plain'});
		res.write('404 Not Found\n');
		res.end();
		return;
	}

	if (stats.isFile()) {
		// path exists, is a file
		var ext = path.extname(filename).toLowerCase();
		var mime = 'text/plain';
		if (ext === '.js') {
			mime = 'application/x-javascript';
		}
		else if (ext === '.css') {
			mime = 'text/css';
		}
		else if (ext === '.html' || ext === '.htm') {
			mime = 'text/html';
		}
		else if (ext === '.swf') {
			mime = 'application/x-shockwave-flash';
		}
		res.writeHead(200, {
			'Content-Type': mime,
			'Content-Length': stats.size
		});

		var fileStream = fs.createReadStream(filename);
		fileStream.pipe(res);
	}
	else {
		res.writeHead(500, {'Content-Type': 'text/plain'});
		res.write('500 Internal server error\n');
		res.end();
	}
};

/*
	This function simply overrides requested file with the one specified in the @data['path'] parameter.

	@res - HTTP response.
	@found - result of RegExp exec(). Not used.
	@data - matched override object with any custom data that was put there, including required 'path' to the target file.
	@post - parsed query from the POST data, e.g., "variable=value" will be passed as "{ variable: value }". Not used.
*/
module.exports.overrideWithStaticOutput = function(res, found, data, post){
	var filename = data['path'];
	var stats;

	try {
		stats = fs.lstatSync(filename); // throws if path doesn't exist
	}
	catch (e) {
		res.writeHead(404, {'Content-Type': 'text/plain'});
		res.write('404 Not Found\n');
		res.end();
		return;
	}

	if (stats.isFile()) {
		// path exists, is a file
		var ext = path.extname(filename).toLowerCase();
		var mime = 'text/plain';
		if (ext === '.js') {
			mime = 'application/x-javascript';
		}
		else if (ext === '.css') {
			mime = 'text/css';
		}
		else if (ext === '.html' || ext === '.htm') {
			mime = 'text/html';
		}
		else if (ext === '.swf') {
			mime = 'application/x-shockwave-flash';
		}
		res.writeHead(200, {
			'Content-Type': mime,
			'Content-Length': stats.size
		});

		var fileStream = fs.createReadStream(filename);
		fileStream.pipe(res);
	}
	else {
		res.writeHead(500, {'Content-Type': 'text/plain'});
		res.write('500 Internal server error\n');
		res.end();
	}
};<commit_msg>domain names on Windows in hosts file<commit_after>var URL = require('url');
var query = require('querystring');

/*
	Example:

	var OVERRIDES = {
		'override1': {
			// Optional host, in case of handling domain name added to the Windows hosts file.
			'host': '127.0.0.1',
			// Match any JS and CSS file.
			'match': new RegExp(/\/(.*\.(js|css)$/i),
			// Optional: When matched, call the following function.
			'callback': function(res, found, data, post) {
				// @res   - HTTP response object.
				// @found - result of "match" RegExp's exec().
				// @data  - whole override definition object (including match, callback, path and any other attributes).
				// @post  - data POST-ed in this request, parsed into object, e.g., "variable=value" will be passed as "{ variable: value }".
				var filename = path.join(data['path'], found[1]);
				var stats;

				try {
					stats = fs.lstatSync(filename); // lstatSync() throws if path doesn't exist.
				}
				catch (e) {
					return;
				}

				if (stats.isFile()) {
					// path exists and is a file
					var ext = path.extname(filename).split(".")[1];
					res.writeHead(200, {'Content-Type': (ext == 'js' ? 'application/x-javascript' : 'text/css')} );

					var fileStream = fs.createReadStream(filename);
					fileStream.pipe(res);
				}
				else {
					res.writeHead(500, {'Content-Type': 'text/plain'});
					res.write('500 Internal server error\n');
					res.end();
				}
			},
			// Look for an override in the following directory.
			'path': '/www/overrides/',
			// Optional: do not pass the request through CNTLM (in case there is no callback specified).
			'omitCNTLM': true,
			// Any other data that may be used by the callback function.
			'myVariable': 'example'
		},
		'summit.meetjs.pl': {
			// Match any JS and CSS file.
			'match': 'https://summit.meetjs.pl/',
			// Optional: When matched, call the following function.
			'callback': hyperProxy.overrideWithStaticOutput,
			// Look for an override in the following directory.
			'path': '/www/overrides/index.html',
			// Optional: do not pass the request through CNTLM (in case there is no callback specified).
			'omitCNTLM': true
		},
		'override3': {
			// etc...
		}
	};

	var HYPERPROXY = {
		'http_port': 8000,
		'https_port': 8001,
		// Set pac_port to false if PAC file server should not be created.
		'pac_port': 8002,
		'verbose': true,//'debug',
		'ssl_key': './certs/ssl-key.pem',
		'ssl_cert': './certs/ssl-cert.pem',

		// Set CNTLM to `false`, if cntlm proxy is not required to connect to the world.
		cntlm: {
			// Set this to the port number that is used by cntlm already running in the background
			// or that will be tried for spawned cntlm proxy.
			// Set this to false, if cntlm should not be used at all.
			'port': false,//3130,
			// Where was cntlm installed and configured (directory should contain both cntlm executable and cntlm.ini files)?
			// Set to false, if cntlm is already running and should not be controlled by our proxy
			'path': false,//'C:\\Program Files (x86)\\Cntlm\\',
			// How many ports should be tried before giving up and exiting?
			// This is needed when port specified above is already used and path is specified, i.e.,
			// cntlm is not running yet and should be spawned.
			'hitpoints': 5,
			// Should we always try to kill any other CNTLM running, before starting ours?
			'killOnBeforeStart': true,
			// Do not change this one!
			'_PID': false
		},

		// Default proxy location is used in the PAC file output.
		// Set defaultproxy to false to not use any default proxy in the PAC file output
		// (PAC will return DIRECT connection value in that case).
		defaultproxy: false
		//defaultproxy: {
		//	'proxy': 'hyper.proxy',
		//	'port': 3128
		//}
		//defaultproxy: {
		//	'proxy': '127.0.0.1',
		//	'port': 8080
		//}
	};

	var hyperProxy = require('./lib/hyperProxy.js')(OVERRIDES, HYPERPROXY);
*/

module.exports.start = function(overrides, settings) {
	var self = this;

	self.settings = settings;
	self.overrides = overrides;
	self.cntlm = false;

	/*
		Spawn cntlm "gateway", but only if settings.cntlm.port and settings.cntlm.path were set.
	*/
	if (self.settings.cntlm && self.settings.cntlm.port && self.settings.cntlm.path) {

		process.on('cntlmReady', function(PID){
			console.log('cntlm is running as '+PID);
		});

		process.on('cntlmError', function(){
			console.log('Could not run cntlm! Exiting.');
			process.exit();
		});

		var CNTLM = require('./lib/CNTLM.js');
		self.settings.cntlm.verbose = self.settings.cntlm.verbose || self.settings.verbose;
		self.cntlm = new CNTLM(self.settings.cntlm);
	}

	/*
		Setup our JS proxy.
	*/
	self.overrider = function(req, res, req_url) {
		var target = URL.format(req_url);
		var found = null;
		var omitCNTLM = false;

		for (var name in self.overrides) {
			if (self.overrides.hasOwnProperty(name)) {
				found = null;
				if (self.overrides[name].hasOwnProperty('match')) {
					if (self.overrides[name]['match'] instanceof RegExp) {
						found = self.overrides[name]['match'].exec(target);
					}
					else if (self.overrides[name]['match'] === target) {
						found = [target];
					}
				}

				if (found && found.length > 0) {
					if (self.overrides[name].hasOwnProperty('omitCNTLM') && self.overrides[name].omitCNTLM) {
						omitCNTLM = true;
					}
					if (self.overrides[name].hasOwnProperty('host') && self.overrides[name].host) {
						req_url.hostname = self.overrides[name].host;
						delete req_url.host;
						target = URL.format(req_url);
					}
					if (self.overrides[name].hasOwnProperty('callback')) {
						try {
							console.log("[" + req_url.hostname + req_url.pathname + "] - Overriding using " + name);
							var data = '';
							req.on('data', function(chunk){
								data += chunk;
							});
							req.on('end', function(){
								data = (data ? query.parse(data) : false);
								(self.overrides[name]['callback'])(res, found, self.overrides[name], data);
							});
							return true;
						}
						catch (e) {
							console.log(e);
						}
					}
					break;
				}
			}
		}

		// No override was found and called, so let's pass it over to the proxy.
		// If we should use CNTLM, override target, so our Proxy will pass request through CNTLM.
		if (!omitCNTLM && self.settings.cntlm && self.settings.cntlm.port) {
			req_url.hostname = 'localhost';
			req_url.port = self.settings.cntlm.port;
			req_url.pathname = target;
			//req_url.protocol = 'http'; // should we force HTTP?
			req_url.search = '';
		}

		return false;
	};

	self.hyperProxyProcessor = function(proxy) {
		this.override_request = function(request, req_url, response, type){
			var url = req_url;
			console.log("[" + url.hostname + url.pathname + "] - Processor override_request, url: " + URL.format(url));
			return self.overrider(request, response, req_url, type);
		};
	};

	Proxy = require('./lib/node-mitm-proxy/proxy.js');
	self.proxy = new Proxy({id: 'hyperProxy', proxy_port: self.settings.http_port, mitm_port: self.settings.https_port, verbose: self.settings.verbose, key_path: self.settings.ssl_key, cert_path: self.settings.ssl_cert}, self.hyperProxyProcessor);

	if (self.settings.pac_port) {
		self.pacServer = new require('./lib/PACServer.js')(self.overrides, self.settings.pac_port, self.settings, self.settings.defaultproxy);
	}
};

// Dependencies.
var fs = require('fs');
var path = require('path');

/*
	In projects that use separate CSS and JS files there's not much additional work needed.
	This function tries to find JS, CSS, HTM(L) or SWF file, and if one does not exists, it tries the same file name but without ".min"
	part (only for JS and CSS and if there is any) - just in case there is a full source data available.

	@res - HTTP response.
	@found - result of RegExp exec(). found[1] will be used as a file name.
	@data - matched override object with any custom data that was put there, including required 'path' to the project directory.
	@post - parsed query from the POST data, e.g., "variable=value" will be passed as "{ variable: value }". Not used.
*/
module.exports.overrideJSandCSSgeneric = function (res, found, data, post){
	var filename = path.join(data['path'], found[1]);
	var stats;

	if (!fs.existsSync(filename) && filename.match(/\.(js|css)$/i)) {
		// Try without ".min" for JS and CSS
		filename = filename.replace(/\.min/, '');
	}

	try {
		stats = fs.lstatSync(filename); // throws if path doesn't exist
	}
	catch (e) {
		res.writeHead(404, {'Content-Type': 'text/plain'});
		res.write('404 Not Found\n');
		res.end();
		return;
	}

	if (stats.isFile()) {
		// path exists, is a file
		var ext = path.extname(filename).toLowerCase();
		var mime = 'text/plain';
		if (ext === '.js') {
			mime = 'application/x-javascript';
		}
		else if (ext === '.css') {
			mime = 'text/css';
		}
		else if (ext === '.html' || ext === '.htm') {
			mime = 'text/html';
		}
		else if (ext === '.swf') {
			mime = 'application/x-shockwave-flash';
		}
		res.writeHead(200, {
			'Content-Type': mime,
			'Content-Length': stats.size
		});

		var fileStream = fs.createReadStream(filename);
		fileStream.pipe(res);
	}
	else {
		res.writeHead(500, {'Content-Type': 'text/plain'});
		res.write('500 Internal server error\n');
		res.end();
	}
};

/*
	This function simply overrides requested file with the one specified in the @data['path'] parameter.

	@res - HTTP response.
	@found - result of RegExp exec(). Not used.
	@data - matched override object with any custom data that was put there, including required 'path' to the target file.
	@post - parsed query from the POST data, e.g., "variable=value" will be passed as "{ variable: value }". Not used.
*/
module.exports.overrideWithStaticOutput = function(res, found, data, post){
	var filename = data['path'];
	var stats;

	try {
		stats = fs.lstatSync(filename); // throws if path doesn't exist
	}
	catch (e) {
		res.writeHead(404, {'Content-Type': 'text/plain'});
		res.write('404 Not Found\n');
		res.end();
		return;
	}

	if (stats.isFile()) {
		// path exists, is a file
		var ext = path.extname(filename).toLowerCase();
		var mime = 'text/plain';
		if (ext === '.js') {
			mime = 'application/x-javascript';
		}
		else if (ext === '.css') {
			mime = 'text/css';
		}
		else if (ext === '.html' || ext === '.htm') {
			mime = 'text/html';
		}
		else if (ext === '.swf') {
			mime = 'application/x-shockwave-flash';
		}
		res.writeHead(200, {
			'Content-Type': mime,
			'Content-Length': stats.size
		});

		var fileStream = fs.createReadStream(filename);
		fileStream.pipe(res);
	}
	else {
		res.writeHead(500, {'Content-Type': 'text/plain'});
		res.write('500 Internal server error\n');
		res.end();
	}
};
<|endoftext|>


<commit_before>var express = require('express'),
    app = express(),
    http = require('http'),
    env = process.env.DYNO ? 'production' : 'development';

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

app.configure(function() {
    app.use(express.static(__dirname + '/public'));
    app.use(express.methodOverride());
    app.use(function(req, res, next) {
        res.header("Access-Control-Allow-Origin", "*");
        res.header('Access-Control-Allow-Headers', 'X-Requested-With,Content-Type,Authorization')
        res.header('Access-Control-Allow-Methods', 'GET,PUT,PATCH,POST,DELETE')
        //res.header("Access-Control-Allow-Headers", 'Authorization");
        next();
    });
    app.use(app.router);
    app.use(error);

    function error(err, req, res, next) {
        console.error(err.stack);
        res.send(500);
    }
});

app.listen(app.get('port'), function() {
    console.log("API listening on port " + app.get('port'));
});

app.get('/fiddle/:id',function(req,res){

    console.log(req.headers['user-agent']);

    // Set up the request
    http.get('http://jsfiddle.net/AdapTeach/' + req.params.id + '/', function(res) {
        res.setEncoding('utf8');
        res.on('data', function (chunk) {
        });
    });

});
<commit_msg>sending jsfiddle's html<commit_after>var express = require('express'),
    app = express(),
    http = require('http'),
    env = process.env.DYNO ? 'production' : 'development';

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

app.configure(function() {
    app.use(express.static(__dirname + '/public'));
    app.use(express.methodOverride());
    app.use(function(req, res, next) {
        res.header("Access-Control-Allow-Origin", "*");
        res.header('Access-Control-Allow-Headers', 'X-Requested-With,Content-Type,Authorization')
        res.header('Access-Control-Allow-Methods', 'GET,PUT,PATCH,POST,DELETE')
        //res.header("Access-Control-Allow-Headers", 'Authorization");
        next();
    });
    app.use(app.router);
    app.use(error);

    function error(err, req, res, next) {
        console.error(err.stack);
        res.send(500);
    }
});

app.listen(app.get('port'), function() {
    console.log("API listening on port " + app.get('port'));
});

app.get('/fiddle/:id',function(req,res){

    console.log(req.headers['user-agent']);
    var url = 'http://jsfiddle.net/AdapTeach/' + req.params.id + '/';
    if(req.headers['user-agent'].indexOf('PhantomJS') !== -1){
        url += "embedded/";
    }
    http.get(url, function(response) {
        response.setEncoding('utf8');
        response.on('data', function (chunk) {
            res.send(chunk);
        });
    });

});
<|endoftext|>


<commit_before>import { findIndex } from './array.js';

const handlers = {
	Identifier: destructureIdentifier,
	AssignmentPattern: destructureAssignmentPattern,
	ArrayPattern: destructureArrayPattern,
	ObjectPattern: destructureObjectPattern
};

export default function destructure ( code, scope, node, ref, inline, statementGenerators ) {
	handlers[ node.type ]( code, scope, node, ref, inline, statementGenerators );
}

function destructureIdentifier ( code, scope, node, ref, inline, statementGenerators ) {
	statementGenerators.push( ( start, prefix, suffix ) => {
		code.insertRight( node.start, inline ? prefix : `${prefix}var ` );
		code.insertLeft( node.end, ` = ${ref}${suffix}` );
		code.move( node.start, node.end, start );
	});
}

function destructureAssignmentPattern ( code, scope, node, ref, inline, statementGenerators ) {
	const isIdentifier = node.left.type === 'Identifier';
	const name = isIdentifier ? node.left.name : ref;

	if ( !inline ) {
		statementGenerators.push( ( start, prefix, suffix ) => {
			code.insertRight( node.left.end, `${prefix}if ( ${name} === void 0 ) ${name}` );
			code.move( node.left.end, node.right.end, start );
			code.insertLeft( node.right.end, suffix );
		});
	}

	if ( !isIdentifier ) {
		destructure( code, scope, node.left, ref, inline, statementGenerators );
	}
}

function destructureArrayPattern ( code, scope, node, ref, inline, statementGenerators ) {
	let c = node.start;

	node.elements.forEach( ( element, i ) => {
		if ( !element ) return;

		if ( element.type === 'RestElement' ) {
			handleProperty( code, scope, c, element.argument, `${ref}.slice(${i})`, inline, statementGenerators );
		} else {
			handleProperty( code, scope, c, element, `${ref}[${i}]`, inline, statementGenerators );
		}
		c = element.end;
	});

	code.remove( c, node.end );
}

function destructureObjectPattern ( code, scope, node, ref, inline, statementGenerators ) {
	let c = node.start;

	node.properties.forEach( prop => {
		let value = prop.computed || prop.key.type !== 'Identifier' ? `${ref}[${code.slice(prop.key.start, prop.key.end)}]` : `${ref}.${prop.key.name}`;
		handleProperty( code, scope, c, prop.value, value, inline, statementGenerators );
		c = prop.end;
	});

	code.remove( c, node.end );
}

function handleProperty ( code, scope, c, node, value, inline, statementGenerators ) {
	switch ( node.type ) {
		case 'Identifier': {
			code.remove( c, node.start );
			destructureIdentifier( code, scope, node, value, inline, statementGenerators );
			break;
		}

		case 'AssignmentPattern': {
			let name;

			const isIdentifier = node.left.type === 'Identifier';

			if ( isIdentifier ) {
				name = node.left.name;
				const declaration = scope.findDeclaration( name );
				if ( declaration ) name = declaration.name;
			} else {
				name = scope.createIdentifier( value );
			}

			statementGenerators.push( ( start, prefix, suffix ) => {
				if ( inline ) {
					code.insertRight( node.right.start, `${name} = ${value} === undefined ? ` );
					code.insertLeft( node.right.end, ` : ${value}` );
				} else {
					code.insertRight( node.right.start, `${prefix}var ${name} = ${value}; if ( ${name} === void 0 ) ${name} = ` );
					code.insertLeft( node.right.end, suffix );
				}

				code.move( node.right.start, node.right.end, start );
			});

			if ( isIdentifier ) {
				code.remove( c, node.right.start );
			} else {
				code.remove( c, node.left.start );
				code.remove( node.left.end, node.right.start );
				handleProperty( code, scope, c, node.left, name, inline, statementGenerators );
			}

			break;
		}

		case 'ObjectPattern': {
			code.remove( c, c = node.start );

			if ( node.properties.length > 1 ) {
				const ref = scope.createIdentifier( value );

				statementGenerators.push( ( start, prefix, suffix ) => {
					// this feels a tiny bit hacky, but we can't do a
					// straightforward insertLeft and keep correct order...
					code.insertRight( node.start, `${prefix}var ${ref} = ` );
					code.overwrite( node.start, c = node.start + 1, value );
					code.insertLeft( c, suffix );

					code.move( node.start, c, start );
				});

				node.properties.forEach( prop => {
					const value = prop.computed || prop.key.type !== 'Identifier' ? `${ref}[${code.slice(prop.key.start, prop.key.end)}]` : `${ref}.${prop.key.name}`;
					handleProperty( code, scope, c, prop.value, value, inline, statementGenerators );
					c = prop.end;
				});
			} else {
				const prop = node.properties[0];
				const value_suffix = prop.computed || prop.key.type !== 'Identifier' ? `[${code.slice(prop.key.start, prop.key.end)}]` : `.${prop.key.name}`;
				handleProperty( code, scope, c, prop.value, `${value}${value_suffix}`, inline, statementGenerators );
				c = prop.end;
			}

			code.remove( c, node.end );
			break;
		}

		case 'ArrayPattern': {
			code.remove( c, c = node.start );

			if ( node.elements.filter( Boolean ).length > 1 ) {
				const ref = scope.createIdentifier( value );

				statementGenerators.push( ( start, prefix, suffix ) => {
					code.insertRight( node.start, `${prefix}var ${ref} = ` );
					code.overwrite( node.start, c = node.start + 1, value );
					code.insertLeft( c, suffix );

					code.move( node.start, c, start );
				});

				node.elements.forEach( ( element, i ) => {
					if ( !element ) return;

					if ( element.type === 'RestElement' ) {
						handleProperty( code, scope, c, element.argument, `${ref}.slice(${i})`, inline, statementGenerators );
					} else {
						handleProperty( code, scope, c, element, `${ref}[${i}]`, inline, statementGenerators );
					}
					c = element.end;
				});
			} else {
				const index = findIndex( node.elements, Boolean );
				const element = node.elements[ index ];
				if ( element.type === 'RestElement' ) {
					handleProperty( code, scope, c, element.argument, `${value}.slice(${index})`, inline, statementGenerators );
				} else {
					handleProperty( code, scope, c, element, `${value}[${index}]`, inline, statementGenerators );
				}
				c = element.end;
			}

			code.remove( c, node.end );
			break;
		}

		default: {
			throw new Error( `Unexpected node type in destructuring (${node.type})` );
		}
	}
}
<commit_msg>Re-use destructureObjectPattern<commit_after>import { findIndex } from './array.js';

const handlers = {
	Identifier: destructureIdentifier,
	AssignmentPattern: destructureAssignmentPattern,
	ArrayPattern: destructureArrayPattern,
	ObjectPattern: destructureObjectPattern
};

export default function destructure ( code, scope, node, ref, inline, statementGenerators ) {
	handlers[ node.type ]( code, scope, node, ref, inline, statementGenerators );
}

function destructureIdentifier ( code, scope, node, ref, inline, statementGenerators ) {
	statementGenerators.push( ( start, prefix, suffix ) => {
		code.insertRight( node.start, inline ? prefix : `${prefix}var ` );
		code.insertLeft( node.end, ` = ${ref}${suffix}` );
		code.move( node.start, node.end, start );
	});
}

function destructureAssignmentPattern ( code, scope, node, ref, inline, statementGenerators ) {
	const isIdentifier = node.left.type === 'Identifier';
	const name = isIdentifier ? node.left.name : ref;

	if ( !inline ) {
		statementGenerators.push( ( start, prefix, suffix ) => {
			code.insertRight( node.left.end, `${prefix}if ( ${name} === void 0 ) ${name}` );
			code.move( node.left.end, node.right.end, start );
			code.insertLeft( node.right.end, suffix );
		});
	}

	if ( !isIdentifier ) {
		destructure( code, scope, node.left, ref, inline, statementGenerators );
	}
}

function destructureArrayPattern ( code, scope, node, ref, inline, statementGenerators ) {
	let c = node.start;

	node.elements.forEach( ( element, i ) => {
		if ( !element ) return;

		if ( element.type === 'RestElement' ) {
			handleProperty( code, scope, c, element.argument, `${ref}.slice(${i})`, inline, statementGenerators );
		} else {
			handleProperty( code, scope, c, element, `${ref}[${i}]`, inline, statementGenerators );
		}
		c = element.end;
	});

	code.remove( c, node.end );
}

function destructureObjectPattern ( code, scope, node, ref, inline, statementGenerators ) {
	let c = node.start;

	node.properties.forEach( prop => {
		let value = prop.computed || prop.key.type !== 'Identifier' ? `${ref}[${code.slice(prop.key.start, prop.key.end)}]` : `${ref}.${prop.key.name}`;
		handleProperty( code, scope, c, prop.value, value, inline, statementGenerators );
		c = prop.end;
	});

	code.remove( c, node.end );
}

function handleProperty ( code, scope, c, node, value, inline, statementGenerators ) {
	switch ( node.type ) {
		case 'Identifier': {
			code.remove( c, node.start );
			destructureIdentifier( code, scope, node, value, inline, statementGenerators );
			break;
		}

		case 'AssignmentPattern': {
			let name;

			const isIdentifier = node.left.type === 'Identifier';

			if ( isIdentifier ) {
				name = node.left.name;
				const declaration = scope.findDeclaration( name );
				if ( declaration ) name = declaration.name;
			} else {
				name = scope.createIdentifier( value );
			}

			statementGenerators.push( ( start, prefix, suffix ) => {
				if ( inline ) {
					code.insertRight( node.right.start, `${name} = ${value} === undefined ? ` );
					code.insertLeft( node.right.end, ` : ${value}` );
				} else {
					code.insertRight( node.right.start, `${prefix}var ${name} = ${value}; if ( ${name} === void 0 ) ${name} = ` );
					code.insertLeft( node.right.end, suffix );
				}

				code.move( node.right.start, node.right.end, start );
			});

			if ( isIdentifier ) {
				code.remove( c, node.right.start );
			} else {
				code.remove( c, node.left.start );
				code.remove( node.left.end, node.right.start );
				handleProperty( code, scope, c, node.left, name, inline, statementGenerators );
			}

			break;
		}

		case 'ObjectPattern': {
			code.remove( c, c = node.start );

			let ref = value
			if ( node.properties.length > 1 ) {
				ref = scope.createIdentifier( value );

				statementGenerators.push( ( start, prefix, suffix ) => {
					// this feels a tiny bit hacky, but we can't do a
					// straightforward insertLeft and keep correct order...
					code.insertRight( node.start, `${prefix}var ${ref} = ` );
					code.overwrite( node.start, c = node.start + 1, value );
					code.insertLeft( c, suffix );

					code.move( node.start, c, start );
				});
			}

			destructureObjectPattern( code, scope, node, ref, inline, statementGenerators )

			break;
		}

		case 'ArrayPattern': {
			code.remove( c, c = node.start );

			if ( node.elements.filter( Boolean ).length > 1 ) {
				const ref = scope.createIdentifier( value );

				statementGenerators.push( ( start, prefix, suffix ) => {
					code.insertRight( node.start, `${prefix}var ${ref} = ` );
					code.overwrite( node.start, c = node.start + 1, value );
					code.insertLeft( c, suffix );

					code.move( node.start, c, start );
				});

				node.elements.forEach( ( element, i ) => {
					if ( !element ) return;

					if ( element.type === 'RestElement' ) {
						handleProperty( code, scope, c, element.argument, `${ref}.slice(${i})`, inline, statementGenerators );
					} else {
						handleProperty( code, scope, c, element, `${ref}[${i}]`, inline, statementGenerators );
					}
					c = element.end;
				});
			} else {
				const index = findIndex( node.elements, Boolean );
				const element = node.elements[ index ];
				if ( element.type === 'RestElement' ) {
					handleProperty( code, scope, c, element.argument, `${value}.slice(${index})`, inline, statementGenerators );
				} else {
					handleProperty( code, scope, c, element, `${value}[${index}]`, inline, statementGenerators );
				}
				c = element.end;
			}

			code.remove( c, node.end );
			break;
		}

		default: {
			throw new Error( `Unexpected node type in destructuring (${node.type})` );
		}
	}
}
<|endoftext|>


<commit_before>// escape strings to show them directly in the html.
function htmlentities(str) {
  return String(str).replace(/&/g, '&').replace(/</g, '<').replace(/>/g, '>').replace(/"/g, '"');
}
$(document).ready(function() {
  // some initalizations
  $.fn.dialog = function() {
    alert("error :( "+$(this).html());
  };
  settings = {
    appname: "overpass-ide-map",
    code:{},
    server: "http://overpass-api.de/api/",
    tileServer: "http://{s}.tile.openstreetmap.org/{z}/{x}/{y}.png",
    force_simple_cors_request: true,
    //disable_poiomatic: true,
  };
  ide = {
    getQuery: function() {return settings.code["overpass"];},
    getQueryLang: function() {return ($.trim(settings.code["overpass"]).match(/^</))?"xml":"OverpassQL";},
    update_map: function() {overpass.run_query(ide.getQuery(true,false),ide.getQueryLang());},
  };
  // (very raw) compatibility check
  if (jQuery.support.cors != true ||
      false) {
    // the currently used browser is not capable of running the IDE. :(
    $('
'+
        '
The browser you are currently using, is not capable of running this Application. It has to support cross origin resource sharing (CORS).
'+
        '
Please update to a more up-to-date version of your browser or switch to a more capable browser! Recent versions of Opera, Chrome and Firefox have been tested to work.
'+
      '
').dialog({modal:true});
  }
  // check for any get-parameters
  var get = location.search.substring(1).split("&");
  for (var i=0; i<get.length; i++) {
    var kv = get[i].split("=");
    if (kv[0] == "Q") // uncompressed query set in url
      settings.code["overpass"] = decodeURIComponent(kv[1]);
  }
  // init leaflet
  ide.map = new L.Map("map");
  var tilesUrl = settings.tileServer;
  var tilesAttrib = '© OpenStreetMap contributors Data:ODbL, Map:cc-by-sa';
  var tiles = new L.TileLayer(tilesUrl,{attribution:tilesAttrib});
  ide.map.setView([0,0],1).addLayer(tiles);
  scaleControl = new L.Control.Scale({metric:true,imperial:false,});
  scaleControl.addTo(ide.map);
  // wait spinner
  $(document).on({
    ajaxStart: function() {
      $("body").addClass("loading");
    },
    ajaxStop: function() {
      $("body").removeClass("loading");
    },
  });
  ide.map.on("layeradd", function(e) {
    if (!(e.layer instanceof L.GeoJSON)) return;
    ide.map.setView([0,0],18,true);
    ide.map.fitBounds(e.layer.getBounds() );
  });
  // overpass functionality
  overpass.handlers["onEmptyMap"] = function(empty_msg, data_mode) {$('
This map intentionally left blank. ('+empty_msg+')
').appendTo("#map");};
  overpass.handlers["onAjaxError"] = function(errmsg) {alert("An error occured during the execution of the overpass query!\n" + errmsg);};
  overpass.handlers["onQueryError"] = function(errmsg) {alert("An error occured during the execution of the overpass query!\nThis is what overpass API returned:\n" + errmsg);};
  overpass.handlers["onGeoJsonReady"] = function() {ide.map.addLayer(overpass.osmLayer);};
  overpass.handlers["onPopupReady"] = function(p) {p.openOn(ide.map);};
  overpass.handlers["onDataRecieved"] = function(amount,txt, abortCB,continueCB) {continueCB();};
  // load the data
  ide.update_map();
});
<commit_msg>disabled "display of small features as POI" on map.html view (again).<commit_after>// escape strings to show them directly in the html.
function htmlentities(str) {
  return String(str).replace(/&/g, '&').replace(/</g, '<').replace(/>/g, '>').replace(/"/g, '"');
}
$(document).ready(function() {
  // some initalizations
  $.fn.dialog = function() {
    alert("error :( "+$(this).html());
  };
  settings = {
    appname: "overpass-ide-map",
    code:{},
    server: "http://overpass-api.de/api/",
    tileServer: "http://{s}.tile.openstreetmap.org/{z}/{x}/{y}.png",
    force_simple_cors_request: true,
    disable_poiomatic: true,
  };
  ide = {
    getQuery: function() {return settings.code["overpass"];},
    getQueryLang: function() {return ($.trim(settings.code["overpass"]).match(/^</))?"xml":"OverpassQL";},
    update_map: function() {overpass.run_query(ide.getQuery(true,false),ide.getQueryLang());},
  };
  // (very raw) compatibility check
  if (jQuery.support.cors != true ||
      false) {
    // the currently used browser is not capable of running the IDE. :(
    $('
'+
        '
The browser you are currently using, is not capable of running this Application. It has to support cross origin resource sharing (CORS).
'+
        '
Please update to a more up-to-date version of your browser or switch to a more capable browser! Recent versions of Opera, Chrome and Firefox have been tested to work.
'+
      '
').dialog({modal:true});
  }
  // check for any get-parameters
  var get = location.search.substring(1).split("&");
  for (var i=0; i<get.length; i++) {
    var kv = get[i].split("=");
    if (kv[0] == "Q") // uncompressed query set in url
      settings.code["overpass"] = decodeURIComponent(kv[1]);
  }
  // init leaflet
  ide.map = new L.Map("map");
  var tilesUrl = settings.tileServer;
  var tilesAttrib = '© OpenStreetMap contributors Data:ODbL, Map:cc-by-sa';
  var tiles = new L.TileLayer(tilesUrl,{attribution:tilesAttrib});
  ide.map.setView([0,0],1).addLayer(tiles);
  scaleControl = new L.Control.Scale({metric:true,imperial:false,});
  scaleControl.addTo(ide.map);
  // wait spinner
  $(document).on({
    ajaxStart: function() {
      $("body").addClass("loading");
    },
    ajaxStop: function() {
      $("body").removeClass("loading");
    },
  });
  ide.map.on("layeradd", function(e) {
    if (!(e.layer instanceof L.GeoJSON)) return;
    ide.map.setView([0,0],18,true);
    ide.map.fitBounds(e.layer.getBounds() );
  });
  // overpass functionality
  overpass.handlers["onEmptyMap"] = function(empty_msg, data_mode) {$('
This map intentionally left blank. ('+empty_msg+')
').appendTo("#map");};
  overpass.handlers["onAjaxError"] = function(errmsg) {alert("An error occured during the execution of the overpass query!\n" + errmsg);};
  overpass.handlers["onQueryError"] = function(errmsg) {alert("An error occured during the execution of the overpass query!\nThis is what overpass API returned:\n" + errmsg);};
  overpass.handlers["onGeoJsonReady"] = function() {ide.map.addLayer(overpass.osmLayer);};
  overpass.handlers["onPopupReady"] = function(p) {p.openOn(ide.map);};
  overpass.handlers["onDataRecieved"] = function(amount,txt, abortCB,continueCB) {continueCB();};
  // load the data
  ide.update_map();
});
<|endoftext|>


<commit_before>'use strict';

const fs = require('fs');
const path = require('path');
const _ = require('lodash');

const express = require('express');
const cookieParser = require('cookie-parser');
const compress = require('compression');
const bodyParser = require('body-parser');
const logger = require('morgan');
const lusca = require('lusca');
const dotenv = require('dotenv');
const session = require('express-session');
const expressValidator = require('express-validator');
const multer = require('multer');
const upload = multer({dest: path.join(__dirname, 'uploads')});

dotenv.load({path: '.env'});

const authController = require('./backend/controller/auth');
const userController = require('./backend/controller/user');
const dashboardController = require('./backend/controller/dashboard');

require('./backend/db');

const app = express();
app.set('port', process.env.SERVER_PORT || 3000);
app.use(compress(6));
app.use(logger('dev'));
app.use(bodyParser.json());
app.use(bodyParser.urlencoded({extended: true}));
app.use(expressValidator());
app.use(cookieParser());
app.use(session({
  resave: true,
  saveUninitialized: true,
  secret: process.env.SESSION_SECRET
}));
app.use(function (req, res, next) {
  if (req.path === '/api/upload') {
    next();
  } else {
    //lusca.csrf()(req, res, next);
    next();
  }
});
// app.use(lusca({
//   csp: {/* ... */},
//   xframe: 'SAMEORIGIN',
//   p3p: 'ABCDEF',
//   hsts: {maxAge: 31536000, includeSubDomains: true, preload: true},
//   xssProtection: true
// }));

app.use(express.static(path.join(__dirname, 'public'), {maxAge: 31557600000}));

app.post('/api/login', authController.postLogin);
app.post('/api/signup-local', authController.postSignupLocal);
app.post('/api/forgot-password/email', authController.postForgotPasswordEmail);
app.post('/api/forgot-password/token', authController.postForgotPasswordToken);

app.get('/api/google-auth', authController.getGoogleCode);
app.get('/api/google-auth/response', authController.getGoogleToken);
app.get('/api/google-auth/user', authController.getGoogleUser);

app.get('/api/facebook-auth', authController.getFacebookCode);
app.get('/api/facebook-auth/response', authController.getFacebookToken);
app.get('/api/facebook-auth/user', authController.getFacebookUser);

app.use('/api/*', authController.checkToken);

app.post('/api/forgot-password/new-password', authController.postForgotPasswordNewPassword);
app.post('/api/reset-password', authController.postResetPassword);
app.post('/api/verify-email', authController.postVerifyEmailToken);

app.get('/api/dashboard', dashboardController.getDashboard);

app.get('/*', function (req, res) {
  res.sendFile(path.join(__dirname, 'public', 'index.html'));
});

app.use('*', function (req, res, next) {
  let err = new Error('Not Found');
  err.status = 404;
  next(err);
});

app.use(function (err, req, res, next) {
  res.status(err.status || 500);
  fs.readFile(path.join(__dirname, 'public/error.html'), 'utf8', (errRead, data) => {
    if (errRead) {
      console.error(errRead);
    }
    let ErrorPage = _.template(data);
    let errorPage = ErrorPage({
      status: err.status || 500,
      message: err.message,
      error: err.toString()
    });
    console.log(errorPage);
    res.send(errorPage);
  });
});

app.listen(app.get('port'), function () {
  console.log(`Server listening on port ${app.get('port')} in ${app.get('env')} mode`);
});

module.exports = app;<commit_msg>error handler<commit_after>'use strict';

const fs = require('fs');
const path = require('path');
const _ = require('lodash');

const express = require('express');
const cookieParser = require('cookie-parser');
const compress = require('compression');
const bodyParser = require('body-parser');
const logger = require('morgan');
const lusca = require('lusca');
const dotenv = require('dotenv');
const session = require('express-session');
const expressValidator = require('express-validator');
const multer = require('multer');
const upload = multer({dest: path.join(__dirname, 'uploads')});

dotenv.load({path: '.env'});

const authController = require('./backend/controller/auth');
const userController = require('./backend/controller/user');
const dashboardController = require('./backend/controller/dashboard');

require('./backend/db');

const app = express();
app.set('port', process.env.SERVER_PORT || 3000);
app.use(compress(6));
app.use(logger('dev'));
app.use(bodyParser.json());
app.use(bodyParser.urlencoded({extended: true}));
app.use(expressValidator());
app.use(cookieParser());
app.use(session({
  resave: true,
  saveUninitialized: true,
  secret: process.env.SESSION_SECRET
}));
app.use(function (req, res, next) {
  if (req.path === '/api/upload') {
    next();
  } else {
    //lusca.csrf()(req, res, next);
    next();
  }
});
// app.use(lusca({
//   csp: {/* ... */},
//   xframe: 'SAMEORIGIN',
//   p3p: 'ABCDEF',
//   hsts: {maxAge: 31536000, includeSubDomains: true, preload: true},
//   xssProtection: true
// }));

app.use(express.static(path.join(__dirname, 'public'), {maxAge: 31557600000}));

app.post('/api/login', authController.postLogin);
app.post('/api/signup-local', authController.postSignupLocal);
app.post('/api/forgot-password/email', authController.postForgotPasswordEmail);
app.post('/api/forgot-password/token', authController.postForgotPasswordToken);

app.get('/api/google-auth', authController.getGoogleCode);
app.get('/api/google-auth/response', authController.getGoogleToken);
app.get('/api/google-auth/user', authController.getGoogleUser);

app.get('/api/facebook-auth', authController.getFacebookCode);
app.get('/api/facebook-auth/response', authController.getFacebookToken);
app.get('/api/facebook-auth/user', authController.getFacebookUser);

app.use('/api/*', authController.checkToken);

app.post('/api/forgot-password/new-password', authController.postForgotPasswordNewPassword);
app.post('/api/reset-password', authController.postResetPassword);
app.post('/api/verify-email', authController.postVerifyEmailToken);

app.get('/api/dashboard', dashboardController.getDashboard);

let currentError = {};
// app.get('/error', (req, res) => {
//   fs.readFile(path.join(__dirname, 'public/error.html'), 'utf8', (errRead, data) => {
//     if (errRead) {
//       console.error(errRead);
//     }
//     let ErrorPage = _.template(data);
//     let errorPage = ErrorPage({
//       status: currentError.status || 500,
//       message: currentError.message,
//       error: currentError.toString()
//     });
//     console.log(errorPage);
//     res.send(errorPage);
//   });
// });

app.get('/*', function (req, res) {
  res.sendFile(path.join(__dirname, 'public', 'index.html'));
});

app.use('*', function (req, res, next) {
  let err = new Error('Not Found');
  err.status = 404;
  next(err);
});

app.use(function (err, req, res, next) {
  res.status(err.status || 500);
  currentError = err;
  //res.redirect('/error');
  res.json(currentError);
});

app.listen(app.get('port'), function () {
  console.log(`Server listening on port ${app.get('port')} in ${app.get('env')} mode`);
});

module.exports = app;<|endoftext|>


<commit_before>import { swalClasses } from '../classes'
import { uniqueArray, warnOnce } from '../utils'

export const getContainer = () => document.body.querySelector('.' + swalClasses.container)

const elementByClass = (className) => {
  const container = getContainer()
  return container ? container.querySelector('.' + className) : null
}

export const getPopup = () => elementByClass(swalClasses.popup)

export const getIcons = () => {
  const popup = getPopup()
  return popup.querySelectorAll('.' + swalClasses.icon)
}

export const getTitle = () => elementByClass(swalClasses.title)

export const getContent = () => elementByClass(swalClasses.content)

export const getImage = () => elementByClass(swalClasses.image)

export const getProgressSteps = () => elementByClass(swalClasses.progresssteps)

export const getValidationError = () => elementByClass(swalClasses.validationerror)

export const getConfirmButton = () => elementByClass(swalClasses.confirm)

export const getCancelButton = () => elementByClass(swalClasses.cancel)

export const getButtonsWrapper = () => {
  warnOnce(`swal.getButtonsWrapper() is deprecated and will be removed in the next major release, use swal.getActions() instead`)
  return elementByClass(swalClasses.actions)
}

export const getActions = () => elementByClass(swalClasses.actions)

export const getFooter = () => elementByClass(swalClasses.footer)

export const getCloseButton = () => elementByClass(swalClasses.close)

export const getFocusableElements = () => {
  const focusableElementsWithTabindex = Array.prototype.slice.call(
    getPopup().querySelectorAll('[tabindex]:not([tabindex="-1"]):not([tabindex="0"])')
  )
  // sort according to tabindex
    .sort((a, b) => {
      a = parseInt(a.getAttribute('tabindex'))
      b = parseInt(b.getAttribute('tabindex'))
      if (a > b) {
        return 1
      } else if (a < b) {
        return -1
      }
      return 0
    })

  const otherFocusableElements = Array.prototype.slice.call(
    getPopup().querySelectorAll('button, input:not([type=hidden]), textarea, select, a, [tabindex="0"]')
  )

  return uniqueArray(focusableElementsWithTabindex.concat(otherFocusableElements))
}

export const isModal = () => {
  return !document.body.classList.contains(swalClasses['toast-shown'])
}

export const isToast = () => {
  return document.body.classList.contains(swalClasses['toast-shown'])
}

export const isLoading = () => {
  return getPopup().hasAttribute('data-loading')
}
<commit_msg>fix: improve focusableElements selector string (#1015)<commit_after>import { swalClasses } from '../classes'
import { uniqueArray, warnOnce } from '../utils'

export const getContainer = () => document.body.querySelector('.' + swalClasses.container)

const elementByClass = (className) => {
  const container = getContainer()
  return container ? container.querySelector('.' + className) : null
}

export const getPopup = () => elementByClass(swalClasses.popup)

export const getIcons = () => {
  const popup = getPopup()
  return popup.querySelectorAll('.' + swalClasses.icon)
}

export const getTitle = () => elementByClass(swalClasses.title)

export const getContent = () => elementByClass(swalClasses.content)

export const getImage = () => elementByClass(swalClasses.image)

export const getProgressSteps = () => elementByClass(swalClasses.progresssteps)

export const getValidationError = () => elementByClass(swalClasses.validationerror)

export const getConfirmButton = () => elementByClass(swalClasses.confirm)

export const getCancelButton = () => elementByClass(swalClasses.cancel)

export const getButtonsWrapper = () => {
  warnOnce(`swal.getButtonsWrapper() is deprecated and will be removed in the next major release, use swal.getActions() instead`)
  return elementByClass(swalClasses.actions)
}

export const getActions = () => elementByClass(swalClasses.actions)

export const getFooter = () => elementByClass(swalClasses.footer)

export const getCloseButton = () => elementByClass(swalClasses.close)

export const getFocusableElements = () => {
  const focusableElementsWithTabindex = Array.prototype.slice.call(
    getPopup().querySelectorAll('[tabindex]:not([tabindex="-1"]):not([tabindex="0"])')
  )
  // sort according to tabindex
    .sort((a, b) => {
      a = parseInt(a.getAttribute('tabindex'))
      b = parseInt(b.getAttribute('tabindex'))
      if (a > b) {
        return 1
      } else if (a < b) {
        return -1
      }
      return 0
    })

  // https://github.com/jkup/focusable/blob/master/index.js
  const otherFocusableElements = Array.prototype.slice.call(
    getPopup().querySelectorAll('a[href], area[href], input:not([disabled]), select:not([disabled]), textarea:not([disabled]), button:not([disabled]), iframe, object, embed, [tabindex="0"], [contenteditable], audio[controls], video[controls]')
  )

  return uniqueArray(focusableElementsWithTabindex.concat(otherFocusableElements))
}

export const isModal = () => {
  return !document.body.classList.contains(swalClasses['toast-shown'])
}

export const isToast = () => {
  return document.body.classList.contains(swalClasses['toast-shown'])
}

export const isLoading = () => {
  return getPopup().hasAttribute('data-loading')
}
<|endoftext|>


<commit_before>/*
	This file is part of cdauth’s map.

	OSM Route Manager is free software: you can redistribute it and/or modify
	it under the terms of the GNU Affero General Public License as published by
	the Free Software Foundation, either version 3 of the License, or
	(at your option) any later version.

	cdauth’s map is distributed in the hope that it will be useful,
	but WITHOUT ANY WARRANTY; without even the implied warranty of
	MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
	GNU Affero General Public License for more details.

	You should have received a copy of the GNU Affero General Public License
	along with cdauth’s map.  If not, see <http://www.gnu.org/licenses/>.

	Obtain the source code from http://gitorious.org/cdauths-map
	or git://gitorious.org/cdauths-map/map.git.
*/

var mapObject;
var layerResults;
var nameFinder;

function initMap()
{
	if(location.search.length > 1)
	{ // Move query string to location hash part
		var search_obj = decodeQueryString(location.search.substr(1));
		var hash_obj = decodeQueryString(OpenLayers.URLHashHandler.prototype.getLocationHash());
		for(var i in search_obj)
			hash_obj[i] = search_obj[i];
		location.replace(location.pathname+"#"+encodeQueryString(hash_obj));
		return;
	}

	var form_el = document.createElement("form");
	form_el.method = "get";
	form_el.action = "";
	form_el.id = "search";
	form_el.onsubmit = function(){ geoSearch(); return false; };
	var el1,el2,el3;
	el1 = document.createElement("dl");
	el2 = document.createElement("dt");
	el3 = document.createElement("label");
	el3.htmlFor = "search-input";
	el3.appendChild(document.createTextNode(OpenLayers.i18n("Search")));
	el2.appendChild(el3);
	el1.appendChild(el2);
	el2 = document.createElement("dd");
	el3 = document.createElement("input");
	el3.type = "text";
	el3.id = "search-input";
	el3.name = "search";
	el3.title = OpenLayers.i18n("Enter a search string, a URL of a GPX, KML, OSM or GML file or an OSM object like “node 123” or “trace 123”.");
	el2.appendChild(el3);
	el1.appendChild(el2);
	form_el.appendChild(el1);

	el1 = document.createElement("ul");
	el2 = document.createElement("li");
	el3 = document.createElement("input");
	el3.type = "submit";
	el3.id = "search-button";
	el3.value = OpenLayers.i18n("Search");
	el2.appendChild(el3);
	el1.appendChild(el2);
	el2 = document.createElement("li");
	el3 = document.createElement("input");
	el3.type = "button";
	el3.id = "search-button-reset";
	el3.onclick = function(){ document.getElementById("search-input").value = ""; this.form.onsubmit(); return false; };
	el3.value = OpenLayers.i18n("Clear");
	el2.appendChild(el3);
	el1.appendChild(el2);
	form_el.appendChild(el1);

	var osmcc = document.createElement("p");
	osmcc.id = "search-osm-cc";
	osmcc.innerHTML = OpenLayers.i18n("Search results from OpenStreetMap, cc-by-sa-2.0");
	form_el.appendChild(osmcc);

	form_el.onmouseover = function(){ changeOpacity(this, 1); changeOpacity(osmcc, 1); };
	form_el.onmouseout = function(){ changeOpacity(this, 0.5); changeOpacity(osmcc, 0.3); };
	form_el.onmouseout();

	domInsertAfter(form_el, document.getElementById("map"));

	OpenLayers.Popup.OPACITY = 0.7;

	mapObject = new OpenLayers.Map.cdauth("map", { cdauthTheme : null });

	var addingLayers = true;
	mapObject.setBaseLayer = function(layer) {
		if(addingLayers)
		{ // Prevent loading the default base layer if another layer will be set initially by the Permalink
			layer.setVisibility(false);
			return;
		}
		OpenLayers.Map.cdauth.prototype.setBaseLayer.apply(this, arguments);
	};

	mapObject.addAllAvailableLayers();
	mapObject.addLayer(new OpenLayers.Layer.cdauth.CoordinateGrid(null, { visibility: false, shortName: "grid" }));

	var activeTool = null;
	var cookies = document.cookie.split(/;\s*/);
	for(var i=0; i<cookies.length; i++)
	{
		var cookie = cookies[i].split("=");
		if(cookie[0] == "cdauthTool")
		{
			activeTool = decodeURIComponent(cookie[1]);
			break;
		}
	}

	var toolbar = new OpenLayers.Control.Panel();
	var moveControl = new OpenLayers.Control({ title : OpenLayers.i18n("Move map") });
	mapObject.addControl(moveControl);
	toolbar.addControls(moveControl);
	toolbar.defaultControl = moveControl;

	var osb = new OpenLayers.Layer.OpenStreetBugs(OpenLayers.i18n("OpenStreetBugs"), { visibility: false, theme: null, shortName: "OSBu" });
	mapObject.addLayer(osb);

	var osbControl = new OpenLayers.Control.OpenStreetBugs(osb);
	mapObject.addControl(osbControl);
	toolbar.addControls(osbControl);

	var layerMarkers = new OpenLayers.Layer.cdauth.Markers.LonLat(OpenLayers.i18n("Markers"), { shortName : "m", saveInPermalink : true });
	mapObject.addLayer(layerMarkers);
	var markerControl = new OpenLayers.Control.cdauth.CreateMarker(layerMarkers);
	mapObject.addControl(markerControl);
	toolbar.addControls(markerControl);

	mapObject.addControl(toolbar);
	if(activeTool)
	{
		for(var i=0; i<toolbar.controls.length; i++)
		{
			if(toolbar.controls[i].title == activeTool)
			{
				toolbar.activateControl(toolbar.controls[i]);
				break;
			}
		}
	}

	toolbar.activateControl = function(control) {
		var ret = OpenLayers.Control.Panel.prototype.activateControl.apply(this, arguments);

		document.cookie = "cdauthTool="+encodeURIComponent(control.title)+";expires="+(new Date((new Date()).getTime() + 86400000000)).toGMTString();
		return ret;
	};

	nameFinder = new OpenLayers.cdauth.NameFinder.Nominatim();
	layerResults = new OpenLayers.Layer.cdauth.Markers.GeoSearch(OpenLayers.i18n("Search results"), nameFinder, { shortName : "s", saveInPermalink : true });
	mapObject.addLayer(layerResults);

	addingLayers = false;
	var hashHandler = new OpenLayers.Control.cdauth.URLHashHandler({
		updateMapView : function() {
			var query_object = decodeQueryString(this.hashHandler.getLocationHash());
			if(typeof query_object.search != "undefined")
			{
				if(query_object.search != "%s")
				{
					document.getElementById("search-input").value = query_object.search;
					geoSearch(true, (typeof query_object.lon != "undefined" && typeof query_object.lat != "undefined"));
				}
				delete query_object.search;
			}
			else if(query_object.l && query_object.l.s && query_object.l.s.search)
				document.getElementById("search-input").value = query_object.l.s.search;
			this.map.zoomToQuery(query_object);
			this.updateLocationHash();
		}
	});
	mapObject.addControl(hashHandler);
	hashHandler.activate();
	hashHandler.updateMapView();

	mapObject.addControl(new OpenLayers.Control.cdauth.GeoLocation());

	layerResults.events.register("searchBegin", mapObject, function(){
		document.getElementById("search-input").disabled = document.getElementById("search-button").disabled = document.getElementById("search-button-reset").disabled = true;
	});
	layerResults.events.register("searchSuccess", mapObject, function(){
		document.getElementById("search-input").disabled = document.getElementById("search-button").disabled = document.getElementById("search-button-reset").disabled = false;
	});
	layerResults.events.register("searchFailure", mapObject, function(evt){
		if(!evt.dontzoom)
			alert(OpenLayers.i18n("No results."));
		document.getElementById("search-input").disabled = document.getElementById("search-button").disabled = document.getElementById("search-button-reset").disabled = false;
	});

	var els = document.getElementsByClassName("olControlPanel");
	for(var i=0; i<els.length; i++)
	{
		els[i].onmouseover = function(){ changeOpacity(this, 1); }
		els[i].onmouseout = function(){ changeOpacity(this, 0.5); }
		els[i].onmouseout();
	}
}

function geoSearch()
{
	var search = document.getElementById("search-input").value;

	var gpx = false;
	if(search.match(/^http:\/\//) && !search.match(/^http:\/\/(www\.)?osm\.org\/go\//))
	{
		var m;
		if(m = search.match(/[#?](.*)$/))
		{
			var query_string = decodeQueryString(m[1]);
			if(typeof query_string.lon == "undefined" || typeof query_string.lat == "undefined")
				gpx = true;
		}
		else
			gpx = true;
	}
	else
	{
		var m = search.match(/^(node|way|relation|trace)\s*#?\s*(\d+)$/i);
		if(m)
		{
			gpx = true;
			switch(m[1].toLowerCase())
			{
				case "node": search = "http://www.openstreetmap.org/api/0.6/node/"+m[2]; break;
				case "way": search = "http://www.openstreetmap.org/api/0.6/way/"+m[2]+"/full"; break;
				case "relation": search = "http://www.openstreetmap.org/api/0.6/relation/"+m[2]+"/full"; break;
				case "trace": search = "http://www.openstreetmap.org/trace/"+m[2]+"/data"; break;
			}
		}
	}

	if(gpx)
	{
		layerResults.geoSearch("");

		document.getElementById("search-input").disabled = document.getElementById("search-button").disabled = document.getElementById("search-button-reset").disabled = true;
		var layer = new OpenLayers.Layer.cdauth.XML(null, search, { removableInLayerSwitcher: true, saveInPermalink : true });
		mapObject.addLayer(layer);
		layer.events.register("loadend", layer, function() {
			var extent = this.getDataExtent();
			if(extent)
				mapObject.zoomToExtent(extent);
			document.getElementById("search-input").disabled = document.getElementById("search-button").disabled = document.getElementById("search-button-reset").disabled = false;
		});
	}
	else
		layerResults.geoSearch(search);
}

function changeOpacity(el, opacity, ms)
{
	if(changeOpacity.timeouts == undefined)
		changeOpacity.timeouts = { };

	var timeoutObj = null;
	for(var i in changeOpacity.timeouts)
	{
		if(changeOpacity.timeouts[i] != undefined && changeOpacity.timeouts[i].el === el)
		{
			timeoutObj = i;
			break;
		}
	}
	if(timeoutObj == null)
	{
		var i=0;
		while(changeOpacity.timeouts[i] != undefined)
			i++;
		timeoutObj = i;
		changeOpacity.timeouts[timeoutObj] = { el : el, timeout : null }
	}
	else if(changeOpacity.timeouts[timeoutObj].timeout != null)
		clearTimeout(changeOpacity.timeouts[timeoutObj].timeout);

	if(ms == undefined)
		ms = 750;
	var initTime = new Date().getTime();
	var initOpacity = 1 * (el.style.opacity == "" ? 1 : 1*el.style.opacity);
	var callback = function() {
		var period = new Date().getTime()-initTime;
		if(period > ms)
			period = ms;
		var newOpacity = initOpacity+(period/ms)*(opacity-initOpacity);
		OpenLayers.Util.modifyDOMElement(el, null, null, null, null, null, null, newOpacity);

		if(period < ms)
			changeOpacity.timeouts[timeoutObj].timeout = setTimeout(callback, 100);
		else
			changeOpacity.timeouts[timeoutObj] = undefined;
	};
	callback();
}

OpenLayers.Lang.en = OpenLayers.Util.extend(OpenLayers.Lang.en, {
	"Move map" : "Move map",
	"Search" : "Search",
	"Enter a search string, a URL of a GPX, KML, OSM or GML file or an OSM object like “node 123” or “trace 123”." : "Enter a search string, a URL of a GPX, KML, OSM or GML file or an OSM object like “node 123” or “trace 123”.",
	"Clear" : "Clear",
	"Search results from OpenStreetMap, cc-by-sa-2.0" : "Search results from OpenStreetMap, cc-by-sa-2.0",
	"OpenStreetBugs" : "OpenStreetBugs",
	"Markers" : "Markers",
	"Search results" : "Search results",
	"No results." : "No results."
});

OpenLayers.Lang.de = OpenLayers.Util.extend(OpenLayers.Lang.de, {
	"Move map" : "Karte verschieben",
	"Search" : "Suchen",
	"Enter a search string, a URL of a GPX, KML, OSM or GML file or an OSM object like “node 123” or “trace 123”." : "Ein Suchbegriff, eine URL einer GPX-, KML- OSM- oder GML-Datei oder ein OSM-Objekt wie „node 123“, „way 123“, „relation 123“ oder „trace 123“",
	"Clear" : "Löschen",
	"Search results from OpenStreetMap, cc-by-sa-2.0" : "Suchergebnisse aus OpenStreetMap, cc-by-sa-2.0",
	"OpenStreetBugs" : "OpenStreetBugs",
	"Markers" : "Marker",
	"Search results" : "Suchergebnisse",
	"No results." : "Kein Ergebnis."
});<commit_msg>Also fading popup opacity now.<commit_after>/*
	This file is part of cdauth’s map.

	OSM Route Manager is free software: you can redistribute it and/or modify
	it under the terms of the GNU Affero General Public License as published by
	the Free Software Foundation, either version 3 of the License, or
	(at your option) any later version.

	cdauth’s map is distributed in the hope that it will be useful,
	but WITHOUT ANY WARRANTY; without even the implied warranty of
	MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
	GNU Affero General Public License for more details.

	You should have received a copy of the GNU Affero General Public License
	along with cdauth’s map.  If not, see <http://www.gnu.org/licenses/>.

	Obtain the source code from http://gitorious.org/cdauths-map
	or git://gitorious.org/cdauths-map/map.git.
*/

var mapObject;
var layerResults;
var nameFinder;

function initMap()
{
	if(location.search.length > 1)
	{ // Move query string to location hash part
		var search_obj = decodeQueryString(location.search.substr(1));
		var hash_obj = decodeQueryString(OpenLayers.URLHashHandler.prototype.getLocationHash());
		for(var i in search_obj)
			hash_obj[i] = search_obj[i];
		location.replace(location.pathname+"#"+encodeQueryString(hash_obj));
		return;
	}

	var form_el = document.createElement("form");
	form_el.method = "get";
	form_el.action = "";
	form_el.id = "search";
	form_el.onsubmit = function(){ geoSearch(); return false; };
	var el1,el2,el3;
	el1 = document.createElement("dl");
	el2 = document.createElement("dt");
	el3 = document.createElement("label");
	el3.htmlFor = "search-input";
	el3.appendChild(document.createTextNode(OpenLayers.i18n("Search")));
	el2.appendChild(el3);
	el1.appendChild(el2);
	el2 = document.createElement("dd");
	el3 = document.createElement("input");
	el3.type = "text";
	el3.id = "search-input";
	el3.name = "search";
	el3.title = OpenLayers.i18n("Enter a search string, a URL of a GPX, KML, OSM or GML file or an OSM object like “node 123” or “trace 123”.");
	el2.appendChild(el3);
	el1.appendChild(el2);
	form_el.appendChild(el1);

	el1 = document.createElement("ul");
	el2 = document.createElement("li");
	el3 = document.createElement("input");
	el3.type = "submit";
	el3.id = "search-button";
	el3.value = OpenLayers.i18n("Search");
	el2.appendChild(el3);
	el1.appendChild(el2);
	el2 = document.createElement("li");
	el3 = document.createElement("input");
	el3.type = "button";
	el3.id = "search-button-reset";
	el3.onclick = function(){ document.getElementById("search-input").value = ""; this.form.onsubmit(); return false; };
	el3.value = OpenLayers.i18n("Clear");
	el2.appendChild(el3);
	el1.appendChild(el2);
	form_el.appendChild(el1);

	var osmcc = document.createElement("p");
	osmcc.id = "search-osm-cc";
	osmcc.innerHTML = OpenLayers.i18n("Search results from OpenStreetMap, cc-by-sa-2.0");
	form_el.appendChild(osmcc);

	form_el.onmouseover = function(){ changeOpacity(this, 1); changeOpacity(osmcc, 1); };
	form_el.onmouseout = function(){ changeOpacity(this, 0.5); changeOpacity(osmcc, 0.3); };
	form_el.onmouseout();

	domInsertAfter(form_el, document.getElementById("map"));

	OpenLayers.Popup.OPACITY = 0.7;

	mapObject = new OpenLayers.Map.cdauth("map", { cdauthTheme : null });

	var addingLayers = true;
	mapObject.setBaseLayer = function(layer) {
		if(addingLayers)
		{ // Prevent loading the default base layer if another layer will be set initially by the Permalink
			layer.setVisibility(false);
			return;
		}
		OpenLayers.Map.cdauth.prototype.setBaseLayer.apply(this, arguments);
	};

	mapObject.addAllAvailableLayers();
	mapObject.addLayer(new OpenLayers.Layer.cdauth.CoordinateGrid(null, { visibility: false, shortName: "grid" }));

	var activeTool = null;
	var cookies = document.cookie.split(/;\s*/);
	for(var i=0; i<cookies.length; i++)
	{
		var cookie = cookies[i].split("=");
		if(cookie[0] == "cdauthTool")
		{
			activeTool = decodeURIComponent(cookie[1]);
			break;
		}
	}

	var toolbar = new OpenLayers.Control.Panel();
	var moveControl = new OpenLayers.Control({ title : OpenLayers.i18n("Move map") });
	mapObject.addControl(moveControl);
	toolbar.addControls(moveControl);
	toolbar.defaultControl = moveControl;

	var osb = new OpenLayers.Layer.OpenStreetBugs(OpenLayers.i18n("OpenStreetBugs"), { visibility: false, theme: null, shortName: "OSBu" });
	mapObject.addLayer(osb);

	var osbControl = new OpenLayers.Control.OpenStreetBugs(osb);
	mapObject.addControl(osbControl);
	toolbar.addControls(osbControl);

	var layerMarkers = new OpenLayers.Layer.cdauth.Markers.LonLat(OpenLayers.i18n("Markers"), { shortName : "m", saveInPermalink : true });
	mapObject.addLayer(layerMarkers);
	var markerControl = new OpenLayers.Control.cdauth.CreateMarker(layerMarkers);
	mapObject.addControl(markerControl);
	toolbar.addControls(markerControl);

	mapObject.addControl(toolbar);
	if(activeTool)
	{
		for(var i=0; i<toolbar.controls.length; i++)
		{
			if(toolbar.controls[i].title == activeTool)
			{
				toolbar.activateControl(toolbar.controls[i]);
				break;
			}
		}
	}

	toolbar.activateControl = function(control) {
		var ret = OpenLayers.Control.Panel.prototype.activateControl.apply(this, arguments);

		document.cookie = "cdauthTool="+encodeURIComponent(control.title)+";expires="+(new Date((new Date()).getTime() + 86400000000)).toGMTString();
		return ret;
	};

	nameFinder = new OpenLayers.cdauth.NameFinder.Nominatim();
	layerResults = new OpenLayers.Layer.cdauth.Markers.GeoSearch(OpenLayers.i18n("Search results"), nameFinder, { shortName : "s", saveInPermalink : true });
	mapObject.addLayer(layerResults);

	addingLayers = false;
	var hashHandler = new OpenLayers.Control.cdauth.URLHashHandler({
		updateMapView : function() {
			var query_object = decodeQueryString(this.hashHandler.getLocationHash());
			if(typeof query_object.search != "undefined")
			{
				if(query_object.search != "%s")
				{
					document.getElementById("search-input").value = query_object.search;
					geoSearch(true, (typeof query_object.lon != "undefined" && typeof query_object.lat != "undefined"));
				}
				delete query_object.search;
			}
			else if(query_object.l && query_object.l.s && query_object.l.s.search)
				document.getElementById("search-input").value = query_object.l.s.search;
			this.map.zoomToQuery(query_object);
			this.updateLocationHash();
		}
	});
	mapObject.addControl(hashHandler);
	hashHandler.activate();
	hashHandler.updateMapView();

	mapObject.addControl(new OpenLayers.Control.cdauth.GeoLocation());

	layerResults.events.register("searchBegin", mapObject, function(){
		document.getElementById("search-input").disabled = document.getElementById("search-button").disabled = document.getElementById("search-button-reset").disabled = true;
	});
	layerResults.events.register("searchSuccess", mapObject, function(){
		document.getElementById("search-input").disabled = document.getElementById("search-button").disabled = document.getElementById("search-button-reset").disabled = false;
	});
	layerResults.events.register("searchFailure", mapObject, function(evt){
		if(!evt.dontzoom)
			alert(OpenLayers.i18n("No results."));
		document.getElementById("search-input").disabled = document.getElementById("search-button").disabled = document.getElementById("search-button-reset").disabled = false;
	});

	var els = document.getElementsByClassName("olControlPanel");
	for(var i=0; i<els.length; i++)
	{
		els[i].onmouseover = function(){ changeOpacity(this, 1); }
		els[i].onmouseout = function(){ changeOpacity(this, 0.5); }
		els[i].onmouseout();
	}
}

function geoSearch()
{
	var search = document.getElementById("search-input").value;

	var gpx = false;
	if(search.match(/^http:\/\//) && !search.match(/^http:\/\/(www\.)?osm\.org\/go\//))
	{
		var m;
		if(m = search.match(/[#?](.*)$/))
		{
			var query_string = decodeQueryString(m[1]);
			if(typeof query_string.lon == "undefined" || typeof query_string.lat == "undefined")
				gpx = true;
		}
		else
			gpx = true;
	}
	else
	{
		var m = search.match(/^(node|way|relation|trace)\s*#?\s*(\d+)$/i);
		if(m)
		{
			gpx = true;
			switch(m[1].toLowerCase())
			{
				case "node": search = "http://www.openstreetmap.org/api/0.6/node/"+m[2]; break;
				case "way": search = "http://www.openstreetmap.org/api/0.6/way/"+m[2]+"/full"; break;
				case "relation": search = "http://www.openstreetmap.org/api/0.6/relation/"+m[2]+"/full"; break;
				case "trace": search = "http://www.openstreetmap.org/trace/"+m[2]+"/data"; break;
			}
		}
	}

	if(gpx)
	{
		layerResults.geoSearch("");

		document.getElementById("search-input").disabled = document.getElementById("search-button").disabled = document.getElementById("search-button-reset").disabled = true;
		var layer = new OpenLayers.Layer.cdauth.XML(null, search, { removableInLayerSwitcher: true, saveInPermalink : true });
		mapObject.addLayer(layer);
		layer.events.register("loadend", layer, function() {
			var extent = this.getDataExtent();
			if(extent)
				mapObject.zoomToExtent(extent);
			document.getElementById("search-input").disabled = document.getElementById("search-button").disabled = document.getElementById("search-button-reset").disabled = false;
		});
	}
	else
		layerResults.geoSearch(search);
}

OpenLayers.Lang.en = OpenLayers.Util.extend(OpenLayers.Lang.en, {
	"Move map" : "Move map",
	"Search" : "Search",
	"Enter a search string, a URL of a GPX, KML, OSM or GML file or an OSM object like “node 123” or “trace 123”." : "Enter a search string, a URL of a GPX, KML, OSM or GML file or an OSM object like “node 123” or “trace 123”.",
	"Clear" : "Clear",
	"Search results from OpenStreetMap, cc-by-sa-2.0" : "Search results from OpenStreetMap, cc-by-sa-2.0",
	"OpenStreetBugs" : "OpenStreetBugs",
	"Markers" : "Markers",
	"Search results" : "Search results",
	"No results." : "No results."
});

OpenLayers.Lang.de = OpenLayers.Util.extend(OpenLayers.Lang.de, {
	"Move map" : "Karte verschieben",
	"Search" : "Suchen",
	"Enter a search string, a URL of a GPX, KML, OSM or GML file or an OSM object like “node 123” or “trace 123”." : "Ein Suchbegriff, eine URL einer GPX-, KML- OSM- oder GML-Datei oder ein OSM-Objekt wie „node 123“, „way 123“, „relation 123“ oder „trace 123“",
	"Clear" : "Löschen",
	"Search results from OpenStreetMap, cc-by-sa-2.0" : "Suchergebnisse aus OpenStreetMap, cc-by-sa-2.0",
	"OpenStreetBugs" : "OpenStreetBugs",
	"Markers" : "Marker",
	"Search results" : "Suchergebnisse",
	"No results." : "Kein Ergebnis."
});<|endoftext|>


<commit_before>'use strict'

const express = require('express')
const Slapp = require('slapp')
const ConvoStore = require('slapp-convo-beepboop')
const Context = require('slapp-context-beepboop')

// use `PORT` env var on Beep Boop - default to 3000 locally
var port = process.env.PORT || 3000

var slapp = Slapp({
  // Beep Boop sets the SLACK_VERIFY_TOKEN env var
  verify_token: process.env.SLACK_VERIFY_TOKEN,
  convo_store: ConvoStore(),
  context: Context()
})

var HELP_TEXT = `
I will respond to the following messages:
\`help\` - to see this message.
\`hi\` - to demonstrate a conversation that tracks state.
\`thanks\` - to demonstrate a simple response.
\`<type-any-other-text>\` - to demonstrate a random emoticon response, some of the time :wink:.
\`attachment\` - to see a Slack attachment message.
`

//*********************************************
// Setup different handlers for messages
//*********************************************

// response to the user typing "help"
slapp.message('help', ['mention', 'direct_message'], (msg) => {
  msg.say(HELP_TEXT)
})

// "Conversation" flow that tracks state - kicks off when user says hi, hello or hey
slapp
  .message('^(hi|hello|hey)$', ['direct_mention', 'direct_message'], (msg, text) => {
    msg
      .say(`${text}, how are you?`)
      // sends next event from user to this route, passing along state
      .route('how-are-you', { greeting: text })
  })
  .route('how-are-you', (msg, state) => {
    var text = (msg.body.event && msg.body.event.text) || ''

    // user may not have typed text as their next action, ask again and re-route
    if (!text) {
      return msg
        .say("Whoops, I'm still waiting to hear how you're doing.")
        .say('How are you?')
        .route('how-are-you', state)
    }

    // add their response to state
    state.status = text

    msg
      .say(`Ok then. What's your favorite color?`)
      .route('color', state)
  })
  .route('color', (msg, state) => {
    var text = (msg.body.event && msg.body.event.text) || ''

    // user may not have typed text as their next action, ask again and re-route
    if (!text) {
      return msg
        .say("I'm eagerly awaiting to hear your favorite color.")
        .route('color', state)
    }

    // add their response to state
    state.color = text

    msg
      .say('Thanks for sharing.')
      .say(`Here's what you've told me so far: \`\`\`${JSON.stringify(state)}\`\`\``)
    // At this point, since we don't route anywhere, the "conversation" is over
  })

// Can use a regex as well
slapp.message(/^(thanks|thank you)/i, ['mention', 'direct_message'], (msg) => {
  // You can provide a list of responses, and a random one will be chosen
  // You can also include slack emoji in your responses
  msg.say([
    "You're welcome :smile:",
    'You bet',
    ':+1: Of course',
    'Anytime :sun_with_face: :full_moon_with_face:'
  ])
})

// demonstrate returning an attachment...
slapp.message('attachment', ['mention', 'direct_message'], (msg) => {
  msg.say({
    text: 'Check out this amazing attachment! :confetti_ball: ',
    attachments: [{
      text: 'Slapp is a robust open source library that sits on top of the Slack APIs',
      title: 'Slapp Library - Open Source',
      image_url: 'https://storage.googleapis.com/beepboophq/_assets/bot-1.22f6fb.png',
      title_link: 'https://beepboophq.com/',
      color: '#7CD197'
    }]
  })
})

// Catch-all for any other responses not handled above
slapp.message('.*', ['direct_mention', 'direct_message'], (msg) => {
  // respond only 40% of the time
  if (Math.random() < 0.4) {
    msg.say([':wave:', ':pray:', ':raised_hands:'])
  }
})

// attach Slapp to express server
var server = slapp.attachToExpress(express())

slapp.message('goodnight', (msg) => {
  msg.say('sweet dreams :crescent_moon: ')
})
// start http server
server.listen(port, (err) => {
  if (err) {
    return console.error(err)
  }

  console.log(`Listening on port ${port}`)
})
<commit_msg>Adding button to acknowledge sync alerts<commit_after>'use strict'

const express = require('express')
const Slapp = require('slapp')
const ConvoStore = require('slapp-convo-beepboop')
const Context = require('slapp-context-beepboop')

// use `PORT` env var on Beep Boop - default to 3000 locally
var port = process.env.PORT || 3000

var slapp = Slapp({
  // Beep Boop sets the SLACK_VERIFY_TOKEN env var
  verify_token: process.env.SLACK_VERIFY_TOKEN,
  convo_store: ConvoStore(),
  context: Context()
})

var HELP_TEXT = `
I will respond to the following messages:
\`help\` - to see this message.
\`hi\` - to demonstrate a conversation that tracks state.
\`thanks\` - to demonstrate a simple response.
\`<type-any-other-text>\` - to demonstrate a random emoticon response, some of the time :wink:.
\`attachment\` - to see a Slack attachment message.
`

//*********************************************
// Setup different handlers for messages
//*********************************************

// response to the user typing "help"
slapp.message('help', ['mention', 'direct_message'], (msg) => {
  msg.say(HELP_TEXT)
})

// "Conversation" flow that tracks state - kicks off when user says hi, hello or hey
slapp
  .message('^(hi|hello|hey)$', ['direct_mention', 'direct_message'], (msg, text) => {
    msg
      .say(`${text}, how are you?`)
      // sends next event from user to this route, passing along state
      .route('how-are-you', { greeting: text })
  })
  .route('how-are-you', (msg, state) => {
    var text = (msg.body.event && msg.body.event.text) || ''

    // user may not have typed text as their next action, ask again and re-route
    if (!text) {
      return msg
        .say("Whoops, I'm still waiting to hear how you're doing.")
        .say('How are you?')
        .route('how-are-you', state)
    }

    // add their response to state
    state.status = text

    msg
      .say(`Ok then. What's your favorite color?`)
      .route('color', state)
  })
  .route('color', (msg, state) => {
    var text = (msg.body.event && msg.body.event.text) || ''

    // user may not have typed text as their next action, ask again and re-route
    if (!text) {
      return msg
        .say("I'm eagerly awaiting to hear your favorite color.")
        .route('color', state)
    }

    // add their response to state
    state.color = text

    msg
      .say('Thanks for sharing.')
      .say(`Here's what you've told me so far: \`\`\`${JSON.stringify(state)}\`\`\``)
    // At this point, since we don't route anywhere, the "conversation" is over
  })

// Can use a regex as well
slapp.message(/^(thanks|thank you)/i, ['mention', 'direct_message'], (msg) => {
  // You can provide a list of responses, and a random one will be chosen
  // You can also include slack emoji in your responses
  msg.say([
    "You're welcome :smile:",
    'You bet',
    ':+1: Of course',
    'Anytime :sun_with_face: :full_moon_with_face:'
  ])
})

// demonstrate returning an attachment...
slapp.message('attachment', ['mention', 'direct_message'], (msg) => {
  msg.say({
    text: 'Check out this amazing attachment! :confetti_ball: ',
    attachments: [{
      text: 'Slapp is a robust open source library that sits on top of the Slack APIs',
      title: 'Slapp Library - Open Source',
      image_url: 'https://storage.googleapis.com/beepboophq/_assets/bot-1.22f6fb.png',
      title_link: 'https://beepboophq.com/',
      color: '#7CD197'
    }]
  })
})

// Catch-all for any other responses not handled above
slapp.message('.*', ['direct_mention', 'direct_message'], (msg) => {
  // respond only 40% of the time
  if (Math.random() < 0.4) {
    msg.say([':wave:', ':pray:', ':raised_hands:'])
  }
})

// attach Slapp to express server
var server = slapp.attachToExpress(express())

slapp.message('*SYNC TABLE ALERT*:', (msg) => {
  msg.say('({
    "attachments": [
        {
            "text": "I have detected an out of sync issue from Slackbot, who is working on it?",
            "fallback": "You are unable to choose a game",
            "callback_id": "sync_ack",
            "color": "#3AA3E3",
            "attachment_type": "default",
            "actions": [
                {
                    "name": "acknowledge",
                    "text": "Acknowledge",
                    "type": "button",
                    "value": "acknowledge"
                }
            ]
        }
    ]
} )')
})
// start http server
server.listen(port, (err) => {
  if (err) {
    return console.error(err)
  }

  console.log(`Listening on port ${port}`)
})
<|endoftext|>


<commit_before>// @flow
import update from 'immutability-helper';
import get from 'lodash/get';

type Props = Object;

const getTarget = (name: string, value: any): Object => ({
  name,
  value: get(value, name, [])
});

const getAddAction = (position: "before" | "after"): string => {
  if (position === 'before') {
    return '$unshift';
  }
  return '$push';
}

const addDelta = (name: string, action: string): Object => ({
  [name]: {
    $apply: (item: Array<any>): Array<any> => {
      return item ? item : [];
    },
    [action]: [{}]
  }
});

const add = (position: "before" | "after", name: string, props: Props, event: SyntheticFormEvent): SyntheticFormEvent => {
  const delta: Object = addDelta(name, getAddAction(position));
  event.formData = update(props.formData, delta);
  event.formMeta = update(props.formMeta, delta);
  event.target = getTarget(name, event.formData);
  return event;
}

const changeDelta = (name: string, idx: number) => (value: any): Object => ({
  [name]: {
    [idx]: {
      $set: value
    }
  }
});

const change = (idx: number, name: string, props: Props, event: SyntheticFormEvent): SyntheticFormEvent => {
  const delta: Object = changeDelta(name, idx);
  event.formData = update(props.formData, delta(event.formData));
  event.formMeta = update(props.formMeta, delta(event.formMeta));
  event.target = getTarget(name, event.formData);
  return event;
};

const removeDelta = (name: string, idx: number): Object => ({
  [name]: {
    $splice: [[idx, 1]]
  }
});

const remove = (idx: number, name: string, props: Props, event: SyntheticFormEvent): SyntheticFormEvent => {
  const delta: Object = removeDelta(name, idx);
  event.formData = update(props.formData, delta);
  event.formMeta = update(props.formMeta, delta);
  event.target = getTarget(name, event.formData);
  return event;
};

export default {
  add,
  change,
  remove
};
<commit_msg>fix def<commit_after>// @flow
import update from 'immutability-helper';
import get from 'lodash/get';

type Props = Object;

const getTarget = (name: string, value: any): Object => ({
  name,
  value: get(value, name, [])
});

const getAddAction = (position: "before" | "after"): string => {
  if (position === 'before') {
    return '$unshift';
  }
  return '$push';
}

const addDelta = (name: string, action: string): Object => ({
  [name]: {
    $apply: (item: Array<any>): Array<any> => {
      return item ? item : [];
    },
    [action]: [{}]
  }
});

const add = (position: "before" | "after", name: string, props: Props, event: SyntheticFormEvent): SyntheticFormEvent => {
  const delta: Object = addDelta(name, getAddAction(position));
  event.formData = update(props.formData, delta);
  event.formMeta = update(props.formMeta, delta);
  event.target = getTarget(name, event.formData);
  return event;
}

const changeDelta = (name: string, idx: number) => (value: any): Object => ({
  [name]: {
    [idx]: {
      $set: value
    }
  }
});

const change = (idx: number, name: string, props: Props, event: SyntheticFormEvent): SyntheticFormEvent => {
  const delta: Function = changeDelta(name, idx);
  event.formData = update(props.formData, delta(event.formData));
  event.formMeta = update(props.formMeta, delta(event.formMeta));
  event.target = getTarget(name, event.formData);
  return event;
};

const removeDelta = (name: string, idx: number): Object => ({
  [name]: {
    $splice: [[idx, 1]]
  }
});

const remove = (idx: number, name: string, props: Props, event: SyntheticFormEvent): SyntheticFormEvent => {
  const delta: Object = removeDelta(name, idx);
  event.formData = update(props.formData, delta);
  event.formMeta = update(props.formMeta, delta);
  event.target = getTarget(name, event.formData);
  return event;
};

export default {
  add,
  change,
  remove
};
<|endoftext|>


<commit_before>
/*
Server reads stream of filtered twitter data and relays a count, avg and time
every second to its clients.
*/
'use strict';
const INDEX ="/Users/peltzr/projects/streaming/index.html";
let MAIN = "/Users/peltzr/projects/streaming/main.js";
const PORT = 3000;
const path = require('path');
const express = require("express");
const WebSocket = require('ws');
const moment = require('moment');

console.log(path.join(__dirname,'node_modules'))
const server = express()
.use('/moment',express.static(__dirname + '/node_modules/moment'))
.use('/chart',express.static(__dirname + '/node_modules/chart.js/dist'))
.use('/chart-stream',express.static(__dirname + '/node_modules/chartjs-plugin-streaming/dist'))
.use('/ws',express.static(__dirname + '/node_modules/ws/lib'))
.get('/', function(req, res) {
  res.sendFile(INDEX);
})
.get('/index.html', function(req, res) {
  res.sendFile(INDEX);
})
.get('/main.js', function(req, res) {
  res.sendFile(MAIN);
})
.listen(process.env.port || PORT , () => console.log(`Listening on ${ PORT }`));

const Twitter = require('twitter');

let twitClient = new Twitter({
  consumer_key: process.env.TWITTER_CONSUMER_KEY,
  consumer_secret: process.env.TWITTER_CONSUMER_SECRET,
  access_token_key: process.env.TWITTER_ACCESS_TOKEN_KEY,
  access_token_secret: process.env.TWITTER_ACCESS_TOKEN_SECRET
});
let trackOption = 'Trump';

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

wss.on('connection', (ws) => {
  console.log('Client connected');
  ws.on('close', () => console.log('Client disconnected'));
});

function getAvg(prevAvg, x, n)
{
  if (prevAvg === 0) return x;
  return (prevAvg*n + x)/(n+1);
}

let start = Date.now();
let next = start + 1000;
let total = 0;
let avg = 0;
let count = 0;
twitClient.stream('statuses/filter', {
  track: 'Trump'
}, function (stream) {
  stream.on('data', function (event) {
    // console.log(JSON.stringify(event))
    start = Date.now();
    count++;
    if (start > next) {
      wss.clients.forEach((client) => {
        total++;
        avg = getAvg(avg, count, total);
        // client.send(`count:${count} avg:${avg} date:${Date(start).toString()} text:` + (event && encodeURIComponent(event.text)));
        client.send(JSON.stringify({"count":count, "avg":avg, "date": moment(start).format()}));
        count = 0;

        console.log(event && event.text);
      });
      next = start + 1000;
    }
  });

  stream.on('error', function (error) {
    console.log("steam error", error);
    throw error;
  });
});
<commit_msg>get keys from config<commit_after>
/*
Server reads stream of filtered twitter data and relays a count, avg and time
every second to its clients.
*/
'use strict';
const INDEX ="/Users/peltzr/projects/streaming/index.html";
let MAIN = "/Users/peltzr/projects/streaming/main.js";
const PORT = 3000;
const path = require('path');
const express = require("express");
const WebSocket = require('ws');
const moment = require('moment');
const config = require('./config');

console.log(path.join(__dirname,'node_modules'))
const server = express()
.use('/moment',express.static(__dirname + '/node_modules/moment'))
.use('/chart',express.static(__dirname + '/node_modules/chart.js/dist'))
.use('/chart-stream',express.static(__dirname + '/node_modules/chartjs-plugin-streaming/dist'))
.use('/ws',express.static(__dirname + '/node_modules/ws/lib'))
.get('/', function(req, res) {
  res.sendFile(INDEX);
})
.get('/index.html', function(req, res) {
  res.sendFile(INDEX);
})
.get('/main.js', function(req, res) {
  res.sendFile(MAIN);
})
.listen(process.env.port || PORT , () => console.log(`Listening on ${ PORT }`));

var consumerKey = process.env.TWITTER_CONSUMER_KEY  || config.TWITTER_CONSUMER_KEY;
var consumerSecret = process.env.TWITTER_CONSUMER_SECRET || config.TWITTER_CONSUMER_SECRET;
var accessTokenKey = process.env.TWITTER_ACCESS_TOKEN_KEY || config.TWITTER_ACCESS_TOKEN_KEY;
var accessTokenSecret = process.env.TWITTER_ACCESS_TOKEN_SECRET || config.TWITTER_ACCESS_TOKEN_SECRET;

const Twitter = require('twitter');

let twitClient = new Twitter({
  consumer_key: consumerKey,
  consumer_secret: consumerSecret,
  access_token_key: accessTokenKey,
  access_token_secret: accessTokenSecret
});
let trackOption = 'Trump';

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

wss.on('connection', (ws) => {
  console.log('Client connected');
  ws.on('close', () => console.log('Client disconnected'));
});

function getAvg(prevAvg, x, n)
{
  if (prevAvg === 0) return x;
  return (prevAvg*n + x)/(n+1);
}

let start = Date.now();
let next = start + 1000;
let total = 0;
let avg = 0;
let count = 0;
twitClient.stream('statuses/filter', {
  track: 'Trump'
}, function (stream) {
  stream.on('data', function (event) {
    // console.log(JSON.stringify(event))
    start = Date.now();
    count++;
    if (start > next) {
      wss.clients.forEach((client) => {
        total++;
        avg = getAvg(avg, count, total);
        // client.send(`count:${count} avg:${avg} date:${Date(start).toString()} text:` + (event && encodeURIComponent(event.text)));
        client.send(JSON.stringify({"count":count, "avg":avg, "date": moment(start).format()}));
        count = 0;

        console.log(event && event.text);
      });
      next = start + 1000;
    }
  });

  stream.on('error', function (error) {
    console.log("steam error", error);
    throw error;
  });
});
<|endoftext|>