<commit_before>var http = require('http');
var agent = new (http.Agent)({maxSockets: 8});
var IncomingMessage = http.IncomingMessage;
var tls = require('tls');
var CRLF = '\r\n';
var CRLF_BUF = new Buffer(CRLF);
var MAX_BYTES = 1024 * 128;

function isCRLF(buffer, start) {
	   return buffer[start] ==  CRLF_BUF[0] && buffer[start + 1] == CRLF_BUF[1];
}

function getStringHeaders(req) {
	var headers = [req.method + ' ' + req.url + ' HTTP/' + req.httpVersion];
	if (req.headers && !req.headers.Host) {
		req.headers.Host = req.headers.host;
	}
	for (var key in req.headers) {
		var line = req.headers[key];
		if (Array.isArray(line)) {
			line.forEach(function(value) {
				headers.push(key + ': ' + value);
			});
		} else {
			headers.push(key + ': ' + line);
		}
	}
	headers.push(CRLF);

	return headers.join(CRLF);
}

function resolveResponse(proxyReq, callback) {
	var proxyRes = new IncomingMessage(proxyReq);
	var index = 0;
	var buffer, ended, done, over;

	function execCallback(err) {
		if (!done) {
			callback(err, proxyRes);
			done = true;
		}
	}

	function setHeaders(proxyRes, buffer) {
		var headers = {};
		buffer = buffer.toString().split(/\r\n/g);
		var firstLine = getEntry(buffer[0]);
		if (firstLine) {
			proxyRes.httpVersion = firstLine.key.split('/')[1];
			proxyRes.statusCode = firstLine.value.split(' ')[0];
		}

		for (var i = 1, len = buffer.length; i < len; i++) {
			var entry = getEntry(buffer[i]);
			if (entry) {
				var value = headers[entry.key];
				if (value) {
					if (!Array.isArray(value)) {
						value = [value];
					}
					value.push(entry.value);
				}
				headers[entry.key] = value || entry.value;
			}
		}
		proxyRes.headers = headers;
		return proxyRes;
	}

	function getEntry(line) {
		if (!(line = line && line.trim())) {
			return;
		}

		var index = line.indexOf(':');
		return index != -1 ? {
			key: line.substring(0, index).trim().toLowerCase(),
			value: line.substring(index + 1).trim()
		} : null;
	}

   proxyReq.on('data', function(data) {
	   if (ended) {
		   proxyRes.push(data);
		   return;
	   }

	   buffer = buffer ? Buffer.concat([buffer, data]) : data;
	   while(buffer[index]) {
		   if (isCRLF(buffer, index)) {
			   ended = isCRLF(buffer, index + 2);
			   if (!over) {
				   over = buffer.length >= MAX_BYTES;
				   if (ended) {
					   index += 4;
					   setHeaders(proxyRes, buffer.slice(0, index));
					   execCallback();
					   buffer = buffer.slice(index);
					   index = 0;
				   }
			   } else if (ended) {
				   proxyRes.push(buffer.slice(index + 4));
			   }
		   }
		   index++;
	   }

   });

   proxyReq.on('end', function() {
	   !done && execCallback(new Error('Bad response'));
	   proxyRes.push(null);
   });
}

module.exports = function proxy(req, callback) {
	var headers = req.headers;
	var options = req.options;
	var done;

	function execCallback(err, proxyRes) {
		if (!done) {
			callback && callback(err, proxyRes);
			done = true;
		}
	}

	options.method = 'CONNECT';
	options.path = headers.host;
	if (options.agent == null) {
		options.agent = agent;
	}
	options.headers = {
			host : headers.host,
			'proxy-connection': 'keep-alive',
			'user-agent': headers['user-agent']
		};

	http.request(options).on('error', execCallback)
	.on('connect', function (res, socket, head) {
		socket.on('error', execCallback);
	    var proxyReq = tls.connect({
	        rejectUnauthorized: false,
	        socket: socket
	    }, function () {
	        proxyReq.write(getStringHeaders(req));
	        req.on('data', function(data) {
	        	proxyReq.write(data);
	        });
	        req.on('end', function() {
	        	proxyReq.end();
	        });
	    }).on('error', execCallback);

	 resolveResponse(proxyReq, execCallback);
	}).end();
};

<commit_msg>proxy<commit_after>var http = require('http');
var agent = new (http.Agent)({maxSockets: 8});
var IncomingMessage = http.IncomingMessage;
var tls = require('tls');
var CRLF = '\r\n';
var CRLF_BUF = new Buffer(CRLF);
var MAX_BYTES = 1024 * 128;

function isCRLF(buffer, start) {
	   return buffer[start] ==  CRLF_BUF[0] && buffer[start + 1] == CRLF_BUF[1];
}

function getStringHeaders(req) {
	var headers = [req.method + ' ' + req.url + ' HTTP/' + req.httpVersion];
	if (req.headers && !req.headers.Host) {
		req.headers.Host = req.headers.host;
	}
	for (var key in req.headers) {
		var line = req.headers[key];
		if (Array.isArray(line)) {
			line.forEach(function(value) {
				headers.push(key + ': ' + value);
			});
		} else {
			headers.push(key + ': ' + line);
		}
	}
	headers.push(CRLF);

	return headers.join(CRLF);
}

function resolveResponse(proxyReq, callback) {
	var proxyRes = new IncomingMessage(proxyReq);
	var index = 0;
	var buffer, ended, done, overflow;

	function execCallback(err) {
		if (!done) {
			callback(err, proxyRes);
			done = true;
		}
	}

	function setHeaders(proxyRes, buffer) {
		var headers = {};
		buffer = buffer.toString().split(/\r\n/g);
		var firstLine = getEntry(buffer[0]);
		if (firstLine) {
			proxyRes.httpVersion = firstLine.key.split('/')[1];
			proxyRes.statusCode = firstLine.value.split(' ')[0];
		}

		for (var i = 1, len = buffer.length; i < len; i++) {
			var entry = getEntry(buffer[i]);
			if (entry) {
				var value = headers[entry.key];
				if (value) {
					if (!Array.isArray(value)) {
						value = [value];
					}
					value.push(entry.value);
				}
				headers[entry.key] = value || entry.value;
			}
		}
		proxyRes.headers = headers;
		return proxyRes;
	}

	function getEntry(line) {
		if (!(line = line && line.trim())) {
			return;
		}

		var index = line.indexOf(':');
		return index != -1 ? {
			key: line.substring(0, index).trim().toLowerCase(),
			value: line.substring(index + 1).trim()
		} : null;
	}

   proxyReq.on('data', function(data) {
	   if (ended) {
		   proxyRes.push(data);
		   return;
	   }

	   buffer = buffer ? Buffer.concat([buffer, data]) : data;
	   while(buffer[index]) {
		   if (isCRLF(buffer, index)) {
			   ended = isCRLF(buffer, index + 2);
			   if (ended) {
				   index += 4;
				   if (!overflow) {
					   setHeaders(proxyRes, buffer.slice(0, index));
					   execCallback();
				   }
				   proxyRes.push(buffer.slice(index));
				   break;
			   }

			   if (overflow = buffer.length >= MAX_BYTES) {
				   setHeaders(proxyRes, buffer.slice(0,  index));
				   execCallback();
				   buffer = buffer.slice(index);
				   index = -1;
			   }
		   }

		   index++;
	   }

   });

   proxyReq.on('end', function() {
	   !done && execCallback(new Error('Bad response'));
	   proxyRes.push(null);
   });
}

module.exports = function proxy(req, callback) {
	var headers = req.headers;
	var options = req.options;
	var done;

	function execCallback(err, proxyRes) {
		if (!done) {
			callback && callback(err, proxyRes);
			done = true;
		}
	}

	options.method = 'CONNECT';
	options.path = headers.host;
	if (options.agent == null) {
		options.agent = agent;
	}
	options.headers = {
			host : headers.host,
			'proxy-connection': 'keep-alive',
			'user-agent': headers['user-agent']
		};

	http.request(options).on('error', execCallback)
	.on('connect', function (res, socket, head) {
		socket.on('error', execCallback);
	    var proxyReq = tls.connect({
	        rejectUnauthorized: false,
	        socket: socket
	    }, function () {
	        proxyReq.write(getStringHeaders(req));
	        req.on('data', function(data) {
	        	proxyReq.write(data);
	        });
	        req.on('end', function() {
	        	proxyReq.end();
	        });
	    }).on('error', execCallback);

	 resolveResponse(proxyReq, execCallback);
	}).end();
};

<|endoftext|>


<commit_before>/*
The MIT License (MIT)

Copyright (c) 2013-2014 CNRS

Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:

The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software.

THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
SOFTWARE.
*/

/* The API controller for queue's methods
   For instance:
   	- getnext to pick up the first element in the queue and remove it from the queue
   	- put: fill up the queue
   	- putnext: intert a list of id into the queue
*/

exports.exist = function(req, res, next) {
	Queue.findById(req.params.id_queue, function(error, queue){
		if (error) res.status(400).json(error);
		else if (!queue) res.status(400).json({message:"id_queue don't exists"});
		else next();
	});
}

// create a queue
exports.create = function (req, res) {
	if (req.body.name == undefined) res.status(400).json({message:"the name is not define"});
	if (req.body.name == "") 		res.status(400).json({message:"empty string for name is not allow"});
	var queue = new Queue({
		name: req.body.name,
		description: req.body.description,
		list: [],
	}).save(function (error, newQueue) {
		if (error) res.status(400).json({message:error});
		if (newQueue) printRes(newQueue, res);
	});
}
<commit_msg>add getAll<commit_after>/*
The MIT License (MIT)

Copyright (c) 2013-2014 CNRS

Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:

The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software.

THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
SOFTWARE.
*/

/* The API controller for queue's methods
   For instance:
   	- getnext to pick up the first element in the queue and remove it from the queue
   	- put: fill up the queue
   	- putnext: intert a list of id into the queue
*/

exports.exist = function(req, res, next) {
	Queue.findById(req.params.id_queue, function(error, queue){
		if (error) res.status(400).json(error);
		else if (!queue) res.status(400).json({message:"id_queue don't exists"});
		else next();
	});
}

// create a queue
exports.create = function (req, res) {
	if (req.body.name == undefined) res.status(400).json({message:"the name is not define"});
	if (req.body.name == "") 		res.status(400).json({message:"empty string for name is not allow"});
	var queue = new Queue({
		name: req.body.name,
		description: req.body.description,
		list: [],
	}).save(function (error, newQueue) {
		if (error) res.status(400).json({message:error});
		if (newQueue) printRes(newQueue, res);
	});
}

// retrieve all queues
exports.getAll = function (req, res) {
	Queue.find({}, 'name description list', function (error, queues) {
    	if (error) res.status(400).json({error:"error", message:error});
    	if (queues) res.status(200).json(queues);
		else res.status(200).json([]);
	});
}

<|endoftext|>


<commit_before>// Generated by CoffeeScript 1.7.1
(function() {
  var dnode, http, onSignal, phanta, shoe, spawn, startPhantomProcess, wrap,
    __slice = [].slice;

  dnode = require('dnode');

  http = require('http');

  shoe = require('shoe');

  spawn = require('win-spawn');

  phanta = [];

  startPhantomProcess = function(binary, port, args) {
    return spawn(binary, args.concat([__dirname + '/shim.js', port]));
  };

  onSignal = function() {
    var phantom, _i, _len;
    for (_i = 0, _len = phanta.length; _i < _len; _i++) {
      phantom = phanta[_i];
      phantom.exit();
    }
    return process.exit();
  };

  process.on('exit', function() {
    var phantom, _i, _len, _results;
    _results = [];
    for (_i = 0, _len = phanta.length; _i < _len; _i++) {
      phantom = phanta[_i];
      _results.push(phantom.exit());
    }
    return _results;
  });

  process.on('SIGINT', onSignal);

  process.on('SIGTERM', onSignal);

  wrap = function(ph) {
    ph.callback = function(fn) {
      return '__phantomCallback__' + fn.toString();
    };
    ph._createPage = ph.createPage;
    return ph.createPage = function(cb) {
      return ph._createPage(function(page) {
        page._evaluate = page.evaluate;
        page.evaluate = function() {
          var args, cb, fn;
          fn = arguments[0], cb = arguments[1], args = 3 <= arguments.length ? __slice.call(arguments, 2) : [];
          return page._evaluate.apply(page, [fn.toString(), cb].concat(args));
        };
        page._onResourceRequested = page.onResourceRequested;
        page.onResourceRequested = function(fn, cb) {
          return page._onResourceRequested.apply(page, [fn.toString(), cb]);
        };
        return cb(page);
      });
    };
  };

  module.exports = {
    create: function() {
      var arg, args, cb, httpServer, options, phantom, ps, sock, _i, _len;
      args = [];
      options = {};
      for (_i = 0, _len = arguments.length; _i < _len; _i++) {
        arg = arguments[_i];
        switch (typeof arg) {
          case 'function':
            cb = arg;
            break;
          case 'string':
            args.push(arg);
            break;
          case 'object':
            options = arg;
        }
      }
      if (options.binary == null) {
        options.binary = 'phantomjs';
      }
      if (options.port == null) {
        options.port = 0;
      }
      if (options.dnodeOpts == null) {
        options.dnodeOpts = {};
      }
      ps = null;
      phantom = null;
      httpServer = http.createServer();
      httpServer.listen(options.port);
      httpServer.on('listening', function() {
        var port;
        port = httpServer.address().port;
        ps = startPhantomProcess(options.binary, port, args);
        ps.stdout.on('data', options.onStdout || function(data) {
          return console.log("phantom stdout: " + data);
        });
        ps.stderr.on('data', options.onStderr || function(data) {
          return module.exports.stderrHandler(data.toString('utf8'));
        });
        ps.on('error', function(err) {
          if ((err != null ? err.code : void 0) === 'ENOENT') {
            return console.error("phantomjs-node: You don't have 'phantomjs' installed");
          } else {
            throw err;
          }
        });
        return ps.on('exit', function(code, signal) {
          var p;
          httpServer.close();
          if (phantom) {
            if (typeof phantom.onExit === "function") {
              phantom.onExit();
            }
            phanta = (function() {
              var _j, _len1, _results;
              _results = [];
              for (_j = 0, _len1 = phanta.length; _j < _len1; _j++) {
                p = phanta[_j];
                if (p !== phantom) {
                  _results.push(p);
                }
              }
              return _results;
            })();
          }
          if (options.onExit) {
            return options.onExit(code, signal);
          } else {
            console.assert(signal == null, "signal killed phantomjs: " + signal);
            return console.assert(code === 0, "abnormal phantomjs exit code: " + code);
          }
        });
      });
      sock = shoe(function(stream) {
        var d;
        d = dnode({}, options.dnodeOpts);
        d.on('remote', function(phantom) {
          wrap(phantom);
          phantom.process = ps;
          phanta.push(phantom);
          return typeof cb === "function" ? cb(phantom) : void 0;
        });
        d.pipe(stream);
        return stream.pipe(d);
      });
      return sock.install(httpServer, '/dnode');
    },
    stderrHandler: function(message) {
      if (message.match(/(No such method.*socketSentData)|(CoreText performance note)/)) {
        return;
      }
      return console.warn("phantom stderr: " + message);
    }
  };

}).call(this);
<commit_msg>Added options *hostname* and *path* to phantom.create(switches, options, callback)<commit_after>// Generated by CoffeeScript 1.7.1
(function() {
  var dnode, http, onSignal, phanta, shoe, spawn, startPhantomProcess, wrap,
    __slice = [].slice;

  dnode = require('dnode');

  http = require('http');

  shoe = require('shoe');

  spawn = require('win-spawn');

  phanta = [];

  startPhantomProcess = function(binary, port, hostname, args) {
    return spawn(binary, args.concat([__dirname + '/shim.js', port, hostname]));
  };

  onSignal = function() {
    var phantom, _i, _len;
    for (_i = 0, _len = phanta.length; _i < _len; _i++) {
      phantom = phanta[_i];
      phantom.exit();
    }
    return process.exit();
  };

  process.on('exit', function() {
    var phantom, _i, _len, _results;
    _results = [];
    for (_i = 0, _len = phanta.length; _i < _len; _i++) {
      phantom = phanta[_i];
      _results.push(phantom.exit());
    }
    return _results;
  });

  process.on('SIGINT', onSignal);

  process.on('SIGTERM', onSignal);

  wrap = function(ph) {
    ph.callback = function(fn) {
      return '__phantomCallback__' + fn.toString();
    };
    ph._createPage = ph.createPage;
    return ph.createPage = function(cb) {
      return ph._createPage(function(page) {
        page._evaluate = page.evaluate;
        page.evaluate = function() {
          var args, cb, fn;
          fn = arguments[0], cb = arguments[1], args = 3 <= arguments.length ? __slice.call(arguments, 2) : [];
          return page._evaluate.apply(page, [fn.toString(), cb].concat(args));
        };
        page._onResourceRequested = page.onResourceRequested;
        page.onResourceRequested = function(fn, cb) {
          return page._onResourceRequested.apply(page, [fn.toString(), cb]);
        };
        return cb(page);
      });
    };
  };

  module.exports = {
    create: function() {
      var arg, args, cb, httpServer, options, phantom, ps, sock, _i, _len;
      args = [];
      options = {};
      for (_i = 0, _len = arguments.length; _i < _len; _i++) {
        arg = arguments[_i];
        switch (typeof arg) {
          case 'function':
            cb = arg;
            break;
          case 'string':
            args.push(arg);
            break;
          case 'object':
            options = arg;
        }
      }
      if(options.path == null){
        options.path = "";
      }
      if (options.binary == null) {
        options.binary = options.path+'phantomjs';
      }
      if (options.port == null) {
        options.port = 0;
      }
      if(options.hostname == null){
        options.hostname = "localhost";
      }
      if (options.dnodeOpts == null) {
        options.dnodeOpts = {};
      }
      ps = null;
      phantom = null;
      httpServer = http.createServer();
      httpServer.listen(options.port, options.hostname);
      httpServer.on('listening', function() {
        var port, hostname;
        port = httpServer.address().port;
        hostname = httpServer.address().address;
        ps = startPhantomProcess(options.binary, port, hostname, args);
        ps.stdout.on('data', options.onStdout || function(data) {
          return console.log("phantom stdout: " + data);
        });
        ps.stderr.on('data', options.onStderr || function(data) {
          return module.exports.stderrHandler(data.toString('utf8'));
        });
        ps.on('error', function(err) {
          if ((err != null ? err.code : void 0) === 'ENOENT') {
            return console.error("phantomjs-node: You don't have 'phantomjs' installed");
          } else {
            throw err;
          }
        });
        return ps.on('exit', function(code, signal) {
          var p;
          httpServer.close();
          if (phantom) {
            if (typeof phantom.onExit === "function") {
              phantom.onExit();
            }
            phanta = (function() {
              var _j, _len1, _results;
              _results = [];
              for (_j = 0, _len1 = phanta.length; _j < _len1; _j++) {
                p = phanta[_j];
                if (p !== phantom) {
                  _results.push(p);
                }
              }
              return _results;
            })();
          }
          if (options.onExit) {
            return options.onExit(code, signal);
          } else {
            console.assert(signal == null, "signal killed phantomjs: " + signal);
            return console.assert(code === 0, "abnormal phantomjs exit code: " + code);
          }
        });
      });
      sock = shoe(function(stream) {
        var d;
        d = dnode({}, options.dnodeOpts);
        d.on('remote', function(phantom) {
          wrap(phantom);
          phantom.process = ps;
          phanta.push(phantom);
          return typeof cb === "function" ? cb(phantom) : void 0;
        });
        d.pipe(stream);
        return stream.pipe(d);
      });
      return sock.install(httpServer, '/dnode');
    },
    stderrHandler: function(message) {
      if (message.match(/(No such method.*socketSentData)|(CoreText performance note)/)) {
        return;
      }
      return console.warn("phantom stderr: " + message);
    }
  };

}).call(this);
<|endoftext|>


<commit_before>// Wrap our implementation in an Immediately-Invoked Function Expression
;(function ( root ) {
  // Create a simple namespace
  root.com = root.com || {};
  root.com.craftcms = root.com.craftcms || {};

  // Expose our main function in namespace
  root.com.craftcms.FocalPointField = function(selector){

		var craftPositonTranslate = {
      'top-left': '0% 0%',
      'top-center': '50% 0%',
      'top-right': '100% 0%',
      'center-left': '0% 50%',
      'center-center': '50% 50%',
      'center-right': '100% 50%',
      'bottom-left': '0% 100%',
      'bottom-center': '50% 100%',
      'bottom-right': '100% 100%'
    };

		var $field = $(selector);
		var $focalpointWrapper = $field.find('.focalpointfield-wrapper');
		var $inputField = $field.find('.focalpointfield-field-data');
		var $marker = $('');
		var isDragging = false;

		function placeMarker(x, y) {
			var imageWidth = $focalpointWrapper.outerWidth();
			var imageHeight = $focalpointWrapper.outerHeight();

			$focalpointWrapper.append($marker);
			$marker.css({ top: Math.round((y/100)*imageHeight), left: Math.round((x/100)*imageWidth) });
		}

		function parseValue(val) {
			if (craftPositonTranslate[val] !== undefined) {
				val = craftPositonTranslate[val];
			}

			var arr = val.split(' ');

			if (arr.length==2) {
				var x = Number(arr[0].replace('%', ''));
				var y = Number(arr[1].replace('%', ''));
				if (x<0) { x = 0; }
				if (y<0) { y = 0; }
				if (x>100) { x = 100; }
				if (y>100) { y = 100; }

				placeMarker(x, y);
			}
		}

		function setValue(x, y) {
			$inputField.val(x + '% ' + y + '%');
			placeMarker(x, y);
		}

		function parsePosition(pageX, pageY) {
			var parentOffset = $focalpointWrapper.offset();
			var imageWidth = $focalpointWrapper.outerWidth();
			var imageHeight = $focalpointWrapper.outerHeight();
			var posX = pageX-parentOffset.left;
			var posY = pageY-parentOffset.top;

			var percentX = Math.round((posX/imageWidth)*100);
			var percentY = Math.round((posY/imageHeight)*100);

			percentX = Math.max(0, Math.min(percentX, 100));
			percentY = Math.max(0, Math.min(percentY, 100));

			setValue(percentX, percentY);
		}

		$focalpointWrapper.on('click', function (e) {
			parsePosition(e.pageX, e.pageY);
		});

		$marker.on('mousedown', function (e) {
			isDragging = true;
		});

		$marker.on('mouseup', function (e) {
			isDragging = false;
		});

		$focalpointWrapper.on('mouseleave', function (e) {
			isDragging = false;
		});

		$(window).on('mousemove', function (e) {
			if (isDragging) {
				parsePosition(e.pageX, e.pageY);
			}
		});

		if ($focalpointWrapper.length>0) {
			$focalpointWrapper.waitForImages(function () {
				if ($inputField.val() != '') {
					parseValue($inputField.val());
				}
			});
		}
  };
})(window);
<commit_msg>Reduced jagged dragging by allowing higher position precision<commit_after>// Wrap our implementation in an Immediately-Invoked Function Expression
;(function ( root ) {
  // Create a simple namespace
  root.com = root.com || {};
  root.com.craftcms = root.com.craftcms || {};

  // Expose our main function in namespace
  root.com.craftcms.FocalPointField = function(selector){

		var craftPositonTranslate = {
      'top-left': '0% 0%',
      'top-center': '50% 0%',
      'top-right': '100% 0%',
      'center-left': '0% 50%',
      'center-center': '50% 50%',
      'center-right': '100% 50%',
      'bottom-left': '0% 100%',
      'bottom-center': '50% 100%',
      'bottom-right': '100% 100%'
    };

		var $field = $(selector);
		var $focalpointWrapper = $field.find('.focalpointfield-wrapper');
		var $inputField = $field.find('.focalpointfield-field-data');
		var $marker = $('');
		var isDragging = false;

		function placeMarker(x, y) {
			var imageWidth = $focalpointWrapper.outerWidth();
			var imageHeight = $focalpointWrapper.outerHeight();

			$focalpointWrapper.append($marker);
			$marker.css({ top: Math.round((y/100)*imageHeight), left: Math.round((x/100)*imageWidth) });
		}

		function parseValue(val) {
			if (craftPositonTranslate[val] !== undefined) {
				val = craftPositonTranslate[val];
			}

			var arr = val.split(' ');

			if (arr.length==2) {
				var x = Number(arr[0].replace('%', ''));
				var y = Number(arr[1].replace('%', ''));
				if (x<0) { x = 0; }
				if (y<0) { y = 0; }
				if (x>100) { x = 100; }
				if (y>100) { y = 100; }

				placeMarker(x, y);
			}
		}

		function setValue(x, y) {
			$inputField.val(x + '% ' + y + '%');
			placeMarker(x, y);
		}

		function parsePosition(pageX, pageY) {
			var parentOffset = $focalpointWrapper.offset();
			var imageWidth = $focalpointWrapper.outerWidth();
			var imageHeight = $focalpointWrapper.outerHeight();
			var posX = pageX-parentOffset.left;
			var posY = pageY-parentOffset.top;

			var precision = Math.pow(10, 2);
			var percentX = Math.round((posX/imageWidth)*100*precision) / precision;
			var percentY = Math.round((posY/imageHeight)*100*precision) / precision;

			percentX = Math.max(0, Math.min(percentX, 100));
			percentY = Math.max(0, Math.min(percentY, 100));

			setValue(percentX, percentY);
		}

		$focalpointWrapper.on('click', function (e) {
			parsePosition(e.pageX, e.pageY);
		});

		$marker.on('mousedown', function (e) {
			isDragging = true;
		});

		$marker.on('mouseup', function (e) {
			isDragging = false;
		});

		$focalpointWrapper.on('mouseleave', function (e) {
			isDragging = false;
		});

		$(window).on('mousemove', function (e) {
			if (isDragging) {
				parsePosition(e.pageX, e.pageY);
			}
		});

		if ($focalpointWrapper.length>0) {
			$focalpointWrapper.waitForImages(function () {
				if ($inputField.val() != '') {
					parseValue($inputField.val());
				}
			});
		}
  };
})(window);
<|endoftext|>


<commit_before>// ==UserScript==
// @name           ExpandOwlyURL
// @namespace      http://d.hatena.ne.jp/send/
// @description    expand ow.ly URL
// @include        *
// @require        http://gist.github.com/3238.txt#$X
// ==/UserScript==

(function() {
  setTimeout(function() {
    $X("//a[starts-with(@href, 'http://ow.ly/')]", document).forEach(function(anchor) {
      var timer = setTimeout(function() {
        if (timer) clearTimeout(timer);
        GM_xmlhttpRequest({
          method: 'GET',
          url: anchor.getAttribute('href'),
          onload: function(xhr) {
            var dom = createDocument(xhr.responseText);
            var iframe = dom.getElementById('hootFrame');
            if (!iframe) return;
            anchor.setAttribute('href', iframe.getAttribute('src'));
          }
        });
      },0);
    });
  },0);
  // this function from AutoPagerize
  function createDocument(str) {
    if (document.documentElement.nodeName != 'HTML')
      return new DOMParser().parseFromString(str, 'application/xhtml+xml');
    var html = str.replace(/^[\s\S]*?<html(?:[ \t\r\n][^>]*)?>|<\/html[ \t\r\n]*>[\w\W]*$/ig, '');
    var doc = document.implementation.createDocument(null, 'html', null);
    var range = document.createRange();
    range.setStartAfter(document.body);
    var fragment = range.createContextualFragment(html);
    try {
      fragment = doc.adoptNode(fragment);
    } catch (e) {
      fragment = doc.importNode(fragment, true);
    }
    doc.documentElement.appendChild(fragment);
    return doc;
  }

})();
<commit_msg>0 -> 100 msec<commit_after>// ==UserScript==
// @name           ExpandOwlyURL
// @namespace      http://d.hatena.ne.jp/send/
// @description    expand ow.ly URL
// @include        *
// @require        http://gist.github.com/3238.txt#$X
// ==/UserScript==

(function() {
  setTimeout(function() {
    $X("//a[starts-with(@href, 'http://ow.ly/')]", document).forEach(function(anchor) {
      var timer = setTimeout(function() {
        if (timer) clearTimeout(timer);
        GM_xmlhttpRequest({
          method: 'GET',
          url: anchor.getAttribute('href'),
          onload: function(xhr) {
            var dom = createDocument(xhr.responseText);
            var iframe = dom.getElementById('hootFrame');
            if (!iframe) return;
            anchor.setAttribute('href', iframe.getAttribute('src'));
          }
        });
      },0);
    });
  },100);
  // this function from AutoPagerize
  function createDocument(str) {
    if (document.documentElement.nodeName != 'HTML')
      return new DOMParser().parseFromString(str, 'application/xhtml+xml');
    var html = str.replace(/^[\s\S]*?<html(?:[ \t\r\n][^>]*)?>|<\/html[ \t\r\n]*>[\w\W]*$/ig, '');
    var doc = document.implementation.createDocument(null, 'html', null);
    var range = document.createRange();
    range.setStartAfter(document.body);
    var fragment = range.createContextualFragment(html);
    try {
      fragment = doc.adoptNode(fragment);
    } catch (e) {
      fragment = doc.importNode(fragment, true);
    }
    doc.documentElement.appendChild(fragment);
    return doc;
  }

})();
<|endoftext|>


<commit_before>var module = angular.module('commafeed.controllers', []);

module.run(function($rootScope) {
	$rootScope.$on('emitMark', function(event, args) {
		// args.entry - the entry
		$rootScope.$broadcast('mark', args);
	});
});

module.controller('CategoryTreeCtrl', function($scope, $routeParams, $location,
		$route, SubscriptionService) {

	$scope.$on('$routeChangeSuccess', function() {
		$scope.selectedType = $routeParams._type;
		$scope.selectedId = $routeParams._id;
	});

	$scope.SubscriptionService = SubscriptionService;

	var unreadCount = function(category) {
		var count = 0;
		if (category.children) {
			for ( var i = 0; i < category.children.length; i++) {
				count = count + unreadCount(category.children[i]);
			}
		}
		if (category.feeds) {
			for ( var i = 0; i < category.feeds.length; i++) {
				var feed = category.feeds[i];
				count = count + feed.unread;
			}
		}
		return count;
	}

	$scope.formatCategoryName = function(category) {
		var count = unreadCount(category);
		var label = category.name;
		if (count > 0) {
			label = label + " (" + count + ")";
		}
		return label;
	}

	$scope.formatFeedName = function(feed) {
		var label = feed.name;
		if (feed.unread > 0) {
			label = label + " (" + feed.unread + ")";
		}
		return label;
	}

	$scope.feedClicked = function(id) {
		if ($scope.selectedType == 'feed' && id == $scope.selectedId) {
			$route.reload();
		} else {
			$location.path('/feeds/view/feed/' + id);
		}
	};

	$scope.categoryClicked = function(id) {
		if ($scope.selectedType == 'category' && id == $scope.selectedId) {
			$route.reload();
		} else {
			$location.path('/feeds/view/category/' + id);
		}
	};

	var mark = function(node, entry) {
		if (node.children) {
			for ( var i = 0; i < node.children.length; i++) {
				mark(node.children[i], entry);
			}
		}
		if (node.feeds) {
			for ( var i = 0; i < node.feeds.length; i++) {
				var feed = node.feeds[i];
				if (feed.id == entry.feedId) {
					var c = entry.read ? -1 : 1;
					feed.unread = feed.unread + c;
				}
			}
		}
	};

	$scope.$on('mark', function(event, args) {
		mark($scope.SubscriptionService.subscriptions, args.entry)
	});
});

module.controller('FeedListCtrl', function($scope, $routeParams, $http, $route,
		$window, EntryService, SettingsService) {

	$scope.selectedType = $routeParams._type;
	$scope.selectedId = $routeParams._id;

	$scope.name = null;
	$scope.entries = [];

	$scope.settingsService = SettingsService;
	$scope.$watch('settingsService.settings.readingMode', function(newValue,
			oldValue) {
		if (newValue && oldValue && newValue != oldValue) {
			$route.reload();
		}
	});

	$scope.limit = 10;
	$scope.busy = false;
	$scope.hasMore = true;

	$scope.loadMoreEntries = function() {
		if (!$scope.hasMore)
			return;
		if ($scope.busy)
			return;
		$scope.busy = true;

		var limit = $scope.limit;
		if ($scope.entries.length == 0) {
			$window = angular.element($window);
			limit = $window.height() / 33;
			limit = parseInt(limit) + 5;
		}
		EntryService.get({
			type : $scope.selectedType,
			id : $scope.selectedId,
			readType : $scope.settingsService.settings.readingMode,
			offset : $scope.entries.length,
			limit : limit
		}, function(data) {
			for ( var i = 0; i < data.entries.length; i++) {
				$scope.entries.push(data.entries[i]);
			}
			$scope.name = data.name;
			$scope.busy = false;
			$scope.hasMore = data.entries.length == limit
		});
	}

	$scope.mark = function(entry, read) {
		if (entry.read != read) {
			entry.read = read;
			$scope.$emit('emitMark', {
				entry : entry
			});
			EntryService.mark({
				type : 'entry',
				id : entry.id,
				read : read
			});
		}
	};

	$scope.isOpen = false;
	$scope.entryClicked = function(entry, event) {
		if (!entry.read) {
			$scope.mark(entry, true);
		}
		if (!event.ctrlKey && event.which != 2) {
			event.preventDefault();
			event.stopPropagation();
			if ($scope.current != entry) {
				$scope.isOpen = true;
			} else {
				$scope.isOpen = !$scope.isOpen;
			}
			$scope.current = entry;
		}
	}

	var openNextEntry = function(event) {
		var entry = null;
		if ($scope.current) {
			var index;
			for ( var i = 0; i < $scope.entries.length; i++) {
				if ($scope.current == $scope.entries[i]) {
					index = i;
					break;
				}
			}
			index = index + 1;
			if (index < $scope.entries.length) {
				entry = $scope.entries[index];
			}
		} else if ($scope.entries.length > 0) {
			entry = $scope.entries[0];
		}
		if (entry) {
			$scope.entryClicked(entry, event);
		}
	};

	var openPreviousEntry = function(event) {
		var entry = null;
		if ($scope.current) {
			var index;
			for ( var i = 0; i < $scope.entries.length; i++) {
				if ($scope.current == $scope.entries[i]) {
					index = i;
					break;
				}
			}
			index = index - 1;
			if (index >= 0) {
				entry = $scope.entries[index];
			}
		}
		if (entry) {
			$scope.entryClicked(entry, event);
		}
	};

	Mousetrap.bind('space', function(e) {
		openNextEntry(e);
	});
	Mousetrap.bind('j', function(e) {
		openNextEntry(e);
	});
	Mousetrap.bind('k', function(e) {
		openPreviousEntry(e);
	});
});<commit_msg>fix dom refresh<commit_after>var module = angular.module('commafeed.controllers', []);

module.run(function($rootScope) {
	$rootScope.$on('emitMark', function(event, args) {
		// args.entry - the entry
		$rootScope.$broadcast('mark', args);
	});
});

module.controller('CategoryTreeCtrl', function($scope, $routeParams, $location,
		$route, SubscriptionService) {

	$scope.$on('$routeChangeSuccess', function() {
		$scope.selectedType = $routeParams._type;
		$scope.selectedId = $routeParams._id;
	});

	$scope.SubscriptionService = SubscriptionService;

	var unreadCount = function(category) {
		var count = 0;
		if (category.children) {
			for ( var i = 0; i < category.children.length; i++) {
				count = count + unreadCount(category.children[i]);
			}
		}
		if (category.feeds) {
			for ( var i = 0; i < category.feeds.length; i++) {
				var feed = category.feeds[i];
				count = count + feed.unread;
			}
		}
		return count;
	}

	$scope.formatCategoryName = function(category) {
		var count = unreadCount(category);
		var label = category.name;
		if (count > 0) {
			label = label + " (" + count + ")";
		}
		return label;
	}

	$scope.formatFeedName = function(feed) {
		var label = feed.name;
		if (feed.unread > 0) {
			label = label + " (" + feed.unread + ")";
		}
		return label;
	}

	$scope.feedClicked = function(id) {
		if ($scope.selectedType == 'feed' && id == $scope.selectedId) {
			$route.reload();
		} else {
			$location.path('/feeds/view/feed/' + id);
		}
	};

	$scope.categoryClicked = function(id) {
		if ($scope.selectedType == 'category' && id == $scope.selectedId) {
			$route.reload();
		} else {
			$location.path('/feeds/view/category/' + id);
		}
	};

	var mark = function(node, entry) {
		if (node.children) {
			for ( var i = 0; i < node.children.length; i++) {
				mark(node.children[i], entry);
			}
		}
		if (node.feeds) {
			for ( var i = 0; i < node.feeds.length; i++) {
				var feed = node.feeds[i];
				if (feed.id == entry.feedId) {
					var c = entry.read ? -1 : 1;
					feed.unread = feed.unread + c;
				}
			}
		}
	};

	$scope.$on('mark', function(event, args) {
		mark($scope.SubscriptionService.subscriptions, args.entry)
	});
});

module.controller('FeedListCtrl', function($scope, $routeParams, $http, $route,
		$window, EntryService, SettingsService) {

	$scope.selectedType = $routeParams._type;
	$scope.selectedId = $routeParams._id;

	$scope.name = null;
	$scope.entries = [];

	$scope.settingsService = SettingsService;
	$scope.$watch('settingsService.settings.readingMode', function(newValue,
			oldValue) {
		if (newValue && oldValue && newValue != oldValue) {
			$route.reload();
		}
	});

	$scope.limit = 10;
	$scope.busy = false;
	$scope.hasMore = true;

	$scope.loadMoreEntries = function() {
		if (!$scope.hasMore)
			return;
		if ($scope.busy)
			return;
		$scope.busy = true;

		var limit = $scope.limit;
		if ($scope.entries.length == 0) {
			$window = angular.element($window);
			limit = $window.height() / 33;
			limit = parseInt(limit) + 5;
		}
		EntryService.get({
			type : $scope.selectedType,
			id : $scope.selectedId,
			readType : $scope.settingsService.settings.readingMode,
			offset : $scope.entries.length,
			limit : limit
		}, function(data) {
			for ( var i = 0; i < data.entries.length; i++) {
				$scope.entries.push(data.entries[i]);
			}
			$scope.name = data.name;
			$scope.busy = false;
			$scope.hasMore = data.entries.length == limit
		});
	}

	$scope.mark = function(entry, read) {
		if (entry.read != read) {
			entry.read = read;
			$scope.$emit('emitMark', {
				entry : entry
			});
			EntryService.mark({
				type : 'entry',
				id : entry.id,
				read : read
			});
		}
	};

	$scope.isOpen = false;
	$scope.entryClicked = function(entry, event) {
		$scope.mark(entry, true);
		if (!event.ctrlKey && event.which != 2) {
			if ($scope.current != entry) {
				$scope.isOpen = true;
			} else {
				$scope.isOpen = !$scope.isOpen;
			}
			$scope.current = entry;
			event.preventDefault();
			event.stopPropagation();
		}
	}

	var openNextEntry = function(event) {
		var entry = null;
		if ($scope.current) {
			var index;
			for ( var i = 0; i < $scope.entries.length; i++) {
				if ($scope.current == $scope.entries[i]) {
					index = i;
					break;
				}
			}
			index = index + 1;
			if (index < $scope.entries.length) {
				entry = $scope.entries[index];
			}
		} else if ($scope.entries.length > 0) {
			entry = $scope.entries[0];
		}
		if (entry) {
			$scope.entryClicked(entry, event);
		}
	};

	var openPreviousEntry = function(event) {
		var entry = null;
		if ($scope.current) {
			var index;
			for ( var i = 0; i < $scope.entries.length; i++) {
				if ($scope.current == $scope.entries[i]) {
					index = i;
					break;
				}
			}
			index = index - 1;
			if (index >= 0) {
				entry = $scope.entries[index];
			}
		}
		if (entry) {
			$scope.entryClicked(entry, event);
		}
	};

	Mousetrap.bind('space', function(e) {
		$scope.$apply(function() {
			openNextEntry(e);
		})
	});
	Mousetrap.bind('j', function(e) {
		$scope.$apply(function() {
			openNextEntry(e);
		})
	});
	Mousetrap.bind('k', function(e) {
		$scope.$apply(function() {
			openPreviousEntry(e);
		})
	});
});<|endoftext|>


<commit_before>import {app, autoUpdater, ipcMain} from 'electron';
import isDev from 'electron-is-dev';
import ms from 'ms';
import {log} from '../common/logger';
import reporter from '../common/reporter';

const FEED_URL = `https://kap-updates.now.sh/update/osx/${app.getVersion()}`;

function createInterval() {
  return setInterval(() => {
    autoUpdater.checkForUpdates();
  }, ms('30m'));
}

let manualCheckTimeout;

function init(window) {
  if (isDev) {
    return;
  }

  autoUpdater.setFeedURL(FEED_URL);

  setTimeout(() => {
    log('checking');
    autoUpdater.checkForUpdates();
  }, ms('5s')); // At this point the app is fully started and ready for everything

  let intervalId = createInterval();

  autoUpdater.on('update-available', () => {
    clearTimeout(manualCheckTimeout);
    clearInterval(intervalId);
    intervalId = undefined;
    log('update available, starting download');
  });

  autoUpdater.on('update-downloaded', () => {
    log('update downloaded, will notify the user');
    window.webContents.send('update-downloaded');
  });

  ipcMain.on('install-update', () => {
    autoUpdater.quitAndInstall();
  });

  autoUpdater.on('error', err => {
    if (intervalId === undefined) { // If the error occurred during the download
      intervalId = createInterval();
    }

    log('Error fetching updates', err);
    reporter.report(err);
  });
}

// The `callback` will be called if no update is available at the moment
function checkForUpdates(callback) {
  manualCheckTimeout = setTimeout(() => {
    callback();
  }, ms('10s'));
}

exports.init = init;
exports.checkForUpdates = checkForUpdates;
<commit_msg>Add beta update functionality<commit_after>import {app, autoUpdater, ipcMain} from 'electron';
import isDev from 'electron-is-dev';
import ms from 'ms';
import {log} from '../common/logger';
import reporter from '../common/reporter';

const URL_APP_NAME = app.getName() === 'Kap Beta' ? 'kap-beta' : 'kap';
const FEED_URL = `https://${URL_APP_NAME}-updates.now.sh/update/macos/${app.getVersion()}`;

function createInterval() {
  return setInterval(() => {
    autoUpdater.checkForUpdates();
  }, ms('30m'));
}

let manualCheckTimeout;

function init(window) {
  if (isDev) {
    return;
  }

  autoUpdater.setFeedURL(FEED_URL);

  setTimeout(() => {
    log('checking');
    autoUpdater.checkForUpdates();
  }, ms('5s')); // At this point the app is fully started and ready for everything

  let intervalId = createInterval();

  autoUpdater.on('update-available', () => {
    clearTimeout(manualCheckTimeout);
    clearInterval(intervalId);
    intervalId = undefined;
    log('update available, starting download');
  });

  autoUpdater.on('update-downloaded', () => {
    log('update downloaded, will notify the user');
    window.webContents.send('update-downloaded');
  });

  ipcMain.on('install-update', () => {
    autoUpdater.quitAndInstall();
  });

  autoUpdater.on('error', err => {
    if (intervalId === undefined) { // If the error occurred during the download
      intervalId = createInterval();
    }

    log('Error fetching updates', err);
    reporter.report(err);
  });
}

// The `callback` will be called if no update is available at the moment
function checkForUpdates(callback) {
  manualCheckTimeout = setTimeout(() => {
    callback();
  }, ms('10s'));
}

exports.init = init;
exports.checkForUpdates = checkForUpdates;
<|endoftext|>


<commit_before>#! /usr/bin/env node
"use strict";
// this is expected to run in nodejs
/* global require */
/* jshint esnext:true */

const express = require('express')
  , http = require('http')
  , socketio = require('socket.io')
  , path = require('path')
  , messages_pb = require('protocolbuffers/messages_pb')
  , { IOOperations } = require('./util/IOOperations')
  , { CacheClient }  = require('./util/CacheClient')
  , { ReportsClient } = require('./util/ReportsClient')
  , ROOT_PATH = __dirname.split(path.sep).slice(0, -1).join(path.sep)
  ;

/**
 * Using a class here, so state variables are managed not on module level
 * Initialization starts the server.
 *
 * NOTE: this is in a state of rewrite to better separate the concerns
 * of providing resources and connection to the outside word versus the
 * actual business logic implementation.
 * The sub-apps and this are rather tightly coupled.
 */
function _BaseServer(logging, portNum, amqpSetup, dbSetup, cacheSetup
                                , reportsSetup) {
    //jshint validthis:true
    this._log = logging;
    this._portNum = portNum;
    this._app = express();
    this._httpServer = http.createServer(this._app);
    this._sio = socketio(this._httpServer);

    var serveStandardClient = this.fbIndex.bind(this);
    Object.defineProperty(this, 'serveStandardClient', {
        value: serveStandardClient
    });

    // dependency injection resources
    //         name: [builder, initFunctionName]
    this._DIResourceBuilders = new Map([
        ['server', [()=>this, null]]
      , ['log', [()=>this._log, null]]
      , ['io', [
                ()=>new IOOperations(this._log, dbSetup, amqpSetup)
              , 'init'
            ]
        ]
      , ['cache', [
                ()=>new CacheClient(
                                this._log
                              , cacheSetup.host, cacheSetup.port
                              , messages_pb, 'fontbakery.dashboard')
              , 'waitForReady'
            ]
        ]
      , ['reports', [()=>new ReportsClient(
                                this._log, reportsSetup.host
                              , reportsSetup.port)
              , 'waitForReady'
            ]
        ]
    ]);
    this._DIResourcesCache = new Map();
    this._DIResourcesCache.set('*app:/', this._app); // root express app
    var promises;
    [this._services, promises] = this._initServices();

    // Start serving when the database and rabbitmq queue is ready
    Promise.all(promises)
    .then(this._listen.bind(this))
    .catch(function(err) {
        this._log.error('Can\'t initialize server.', err);
        process.exit(1);
    }.bind(this));

    this._sio.on('connection', this._onSocketConnect.bind(this));
}

var _p = _BaseServer.prototype;

_p._serviceDefinitions = [];

_p._getServiceDependency = function(appLocation, name) {
    var promise = null;
    let key = name === '*app'
                        ? [name, appLocation].join(':')
                        : name
                        ;
    if(!this._DIResourcesCache.has(key)) {
        if(name === '*app') {
            // a special case
            // name is e.g. : *app:/dispatcher
            let subApp = express();
            this._app.get(appLocation, subApp); // register with root app
            this._DIResourcesCache.set(key, subApp);
        }
        else if (this._DIResourceBuilders.has(key)) {
            let [builder, initFunc] = this._DIResourceBuilders.get(key)
              , resource = builder.call(this)
              ;
            // initFinc is e.g. 'waitForReady' for gRPC clients
            if(initFunc)
                promise = resource[initFunc]();
            this._DIResourcesCache.set(key, resource);
        }
        else
            throw new Error('Don\'t know how to get resource named "'+name+'".');
    }
    return [this._DIResourcesCache.get(key), promise];
};

_p._initService = function(appLocation, Constructor, dependencies) {
    var service
      , promises = []
      , args = []
      ;
    for(let name of dependencies) {
        let [dependency, promise] = this._getServiceDependency(appLocation, name);
        args.push(dependency);
        if(promise)
            promises.push(promise);
    }
    service = new Constructor(...args);
    return [service, promises];
};

_p._initServices = function() {
    var services = []
      , promises = []
      ;
    for(let definition of this._serviceDefinitions) {
        let [service, promises_] = this._initService(...definition);
        services.push(service);
        promises.push(...promises_);
    }
    return [services, promises];
};

_p._listen = function() {
    this._httpServer.listen(this._portNum);
    this._log.info('Listening to port', this._portNum);
};

_p.registerSocketListener = function(eventName, eventHandler, disconnectHandler){
    this._socketListeners.push(eventName, eventHandler, disconnectHandler);
};

/**
 * GET
 *
 * CLIENT
 *  : say hello
 *  : initiate the d'n'd interface to post fonts
 *        on success
 *        change url to docid url
 *        init socketio connection for docid (with answer from post)
 */
_p.fbIndex = function(req, res, next) {
    // jshint unused:vars
    return res.sendFile('browser/html/client.html',
                                                    {root: ROOT_PATH});
};

/**
 * socketio connect
  SERVER
    : on connect
        test if docid exists
        create rethinkdb change feed for docid
        store change feed and connection together
    : on disconnect
        (implicitly: close socket)
        close changefeed
    : on error???
        close changefeed
        close socket
 *
 * wrap in:
 *
 * this._sio.on('connection', this._onSocketConnect.bind(this));
 *
 */
_p._socketOnSubscribe = function(socket, eventName, handler, data) {
    this._log.info('_onSocketConnect: socket', socket.id ,'subscription '
                                        + 'requested for', eventName, data);
    if(typeof data.id !== 'string')
        // this is actually required (historically)
        // ??? why can't we fix this with an error?
        // and at the position where data.id is actually needed/evaluated?
        data.id = '';
    handler.call(this, socket, data);
};

_p._socketOnDisconnect = function(socket, eventName, handler, reason) {
    this._log.debug('socket:', socket.id
                        , 'disconnecting from:', eventName
                        , 'reason:', reason);
    handler.call(this, socket);
};

_p._subscribeToSocketEvent = function(socket, eventName
                                    , eventHandler, disconnectHandler) {
    socket.on(eventName, data=>this._socketOnSubscribe(
                socket, eventName, eventHandler, data));
    if(disconnectHandler)
        socket.on('disconnecting',reason=>this._socketOnDisconnect(
                socket, eventName, disconnectHandler, reason));
};

_p._onSocketConnect = function(socket) {
    // wait for docid request ...
    // extracting [HEAD, ...TAIL] from the values of this._socketListeners
    for(let [eventName, ...handlers] of this._socketListeners)
        this._subscribeToSocketEvent(socket, eventName, ...handlers);
};

exports._BaseServer = _BaseServer;
<commit_msg>[backport][javascript/_BaseServer] Add RootService, renaming and cleaning up.<commit_after>#! /usr/bin/env node
"use strict";
// this is expected to run in nodejs
/* global require */
/* jshint esnext:true */

const express = require('express')
  , http = require('http')
  , socketio = require('socket.io')
  , path = require('path')
  , messages_pb = require('protocolbuffers/messages_pb')
  , { IOOperations } = require('./util/IOOperations')
  , { CacheClient }  = require('./util/CacheClient')
  , { ReportsClient } = require('./util/ReportsClient')
  , ROOT_PATH = __dirname.split(path.sep).slice(0, -1).join(path.sep)
  ;

/**
 * Using a class here, so state variables are managed not on module level
 * Initialization starts the server.
 *
 * NOTE: this is in a state of rewrite to better separate the concerns
 * of providing resources and connection to the outside word versus the
 * actual business logic implementation.
 * The sub-apps and this are rather tightly coupled.
 */
function _BaseServer(logging, portNum, setup) {
    //jshint validthis:true
    this._log = logging;
    this._portNum = portNum;
    this._app = express();
    this._httpServer = http.createServer(this._app);
    this._sio = socketio(this._httpServer);
    this._socketListeners = [];

    var serveStandardClient = this.fbIndex.bind(this);
    Object.defineProperty(this, 'serveStandardClient', {
        value: serveStandardClient
    });

    // dependency injection resources
    //         name: [builder, initFunctionName]
    this._DIResourceBuilders = new Map([
        ['server', [()=>this, null]]
      , ['log', [()=>this._log, null]]
      , ['io', [
                ()=>new IOOperations(this._log, setup.db, setup.amqp)
              , 'init'
            ]
        ]
      , ['cache', [
                ()=>new CacheClient(
                                this._log
                              , setup.cache.host, setup.cache.port
                              , messages_pb, 'fontbakery.dashboard')
              , 'waitForReady'
            ]
        ]
      , ['reports', [()=>new ReportsClient(
                                this._log, setup.reports.host
                              , setup.reports.port)
              , 'waitForReady'
            ]
        ]
      // TODO
      //, ['dispatcher', [
      //          ()=>new DispatcherClient(
      //                          this._log
      //                        , setup.dispatcher.host
      //                        , setup.dispatcher.port)
      //        , 'waitForReady'
      //      ]
      //  ]
    ]);
    this._resources = new Map();
    this._resources.set('*app:/', this._app); // root express app
    var promises;
    [this._services, promises] = this._initServices();

    // Start serving when the database and rabbitmq queue is ready
    Promise.all(promises)
    .then(this._listen.bind(this))
    .catch(function(err) {
        this._log.error('Can\'t initialize server.', err);
        process.exit(1);
    }.bind(this));

    this._sio.on('connection', this._onSocketConnect.bind(this));
}

var _p = _BaseServer.prototype;

_p._serviceDefinitions = [];

_p._getServiceDependency = function(appLocation, name) {
    var promise = null;
    let key = name === '*app'
                        ? [name, appLocation].join(':')
                        : name
                        ;
    if(!this._resources.has(key)) {
        if(name === '*app') {
            // a special case
            // name is e.g. : *app:/dispatcher
            let subApp = express();
            this._app.use(appLocation, subApp); // register with root app
            this._resources.set(key, subApp);
        }
        else if (this._DIResourceBuilders.has(key)) {
            let [builder, initFunc] = this._DIResourceBuilders.get(key)
              , resource = builder.call(this)
              ;
            // initFinc is e.g. 'waitForReady' for gRPC clients
            if(initFunc)
                promise = resource[initFunc]();
            this._resources.set(key, resource);
        }
        else
            throw new Error('Don\'t know how to acquire resource named "'+name+'".');
    }
    return [this._resources.get(key), promise];
};

_p._initService = function(appLocation, Constructor, dependencies) {
    this._log.info('Initializing service', Constructor.name, 'at', appLocation);
    var service
      , promises = []
      , args = []
      ;
    for(let name of dependencies) {
        let [dependency, promise] = this._getServiceDependency(appLocation, name);
        args.push(dependency);
        if(promise)
            promises.push(promise);
    }
    service = new Constructor(...args);
    return [service, promises];
};

_p._initServices = function() {
    var services = []
      , promises = []
      ;
    for(let definition of this._serviceDefinitions) {
        let [service, promises_] = this._initService(...definition);
        services.push(service);
        promises.push(...promises_);
    }
    return [services, promises];
};

_p._listen = function() {
    this._httpServer.listen(this._portNum);
    this._log.info('Listening to port', this._portNum);
};

_p.registerSocketListener = function(eventName, eventHandler, disconnectHandler){
    this._socketListeners.push(eventName, eventHandler, disconnectHandler);
};

/**
 * GET
 *
 * CLIENT
 *  : say hello
 *  : initiate the d'n'd interface to post fonts
 *        on success
 *        change url to docid url
 *        init socketio connection for docid (with answer from post)
 */
_p.fbIndex = function(req, res, next) {
    // jshint unused:vars
    return res.sendFile('browser/html/client.html',
                                                    {root: ROOT_PATH});
};

/**
 * socketio connect
  SERVER
    : on connect
        test if docid exists
        create rethinkdb change feed for docid
        store change feed and connection together
    : on disconnect
        (implicitly: close socket)
        close changefeed
    : on error???
        close changefeed
        close socket
 *
 * wrap in:
 *
 * this._sio.on('connection', this._onSocketConnect.bind(this));
 *
 */
_p._socketOnSubscribe = function(socket, eventName, handler, data) {
    this._log.info('_onSocketConnect: socket', socket.id ,'subscription '
                                        + 'requested for', eventName, data);
    if(typeof data.id !== 'string')
        // this is actually required (historically)
        // ??? why can't we fix this with an error?
        // and at the position where data.id is actually needed/evaluated?
        data.id = '';
    handler.call(this, socket, data);
};

_p._socketOnDisconnect = function(socket, eventName, handler, reason) {
    this._log.debug('socket:', socket.id
                        , 'disconnecting from:', eventName
                        , 'reason:', reason);
    handler.call(this, socket);
};

_p._subscribeToSocketEvent = function(socket, eventName
                                    , eventHandler, disconnectHandler) {
    socket.on(eventName, data=>this._socketOnSubscribe(
                socket, eventName, eventHandler, data));
    if(disconnectHandler)
        socket.on('disconnecting',reason=>this._socketOnDisconnect(
                socket, eventName, disconnectHandler, reason));
};

_p._onSocketConnect = function(socket) {
    // wait for docid request ...
    // extracting [HEAD, ...TAIL] from the values of this._socketListeners
    for(let [eventName, ...handlers] of this._socketListeners)
        this._subscribeToSocketEvent(socket, eventName, ...handlers);
};

function RootService(server, app, logging) {
    this._server = server;
    this._app = app;
    this._log = logging;
    // the client decides what to serve here as default
    this._app.get('/', this._server.serveStandardClient);
    this._app.use('/browser', express.static('browser'));
}

exports._BaseServer = _BaseServer;
exports.RootService = RootService;
<|endoftext|>


<commit_before>var http = require('http');
var agent = new (http.Agent)({maxSockets: 8});
var IncomingMessage = http.IncomingMessage;
var tls = require('tls');
var CRLF = '\r\n';
var CRLF_BUF = new Buffer(CRLF);
var MAX_BYTES = 1024 * 128;

function isCRLF(buffer, start) {
	   return buffer[start] ==  CRLF_BUF[0] && buffer[start + 1] == CRLF_BUF[1];
}

function getStringHeaders(req) {
	var headers = [req.method + ' ' + req.url + ' HTTP/' + req.httpVersion];
	if (req.headers && !req.headers.Host) {
		req.headers.Host = req.headers.host;
	}
	for (var key in req.headers) {
		var line = req.headers[key];
		if (Array.isArray(line)) {
			line.forEach(function(value) {
				headers.push(key + ': ' + value);
			});
		} else {
			headers.push(key + ': ' + line);
		}
	}
	headers.push(CRLF);

	return headers.join(CRLF);
}

function resolveResponse(proxyReq, callback) {
	var proxyRes = new IncomingMessage(proxyReq);
	var index = 0;
	var buffer, ended, done, over;

	function execCallback(err) {
		if (!done) {
			callback(err, proxyRes);
			done = true;
		}
	}

	function setHeaders(proxyRes, buffer) {
		var headers = {};
		buffer = buffer.toString().split(/\r\n/g);
		var firstLine = getEntry(buffer[0]);
		if (firstLine) {
			proxyRes.httpVersion = firstLine.key.split('/')[1];
			proxyRes.statusCode = firstLine.value.split(' ')[0];
		}

		for (var i = 1, len = buffer.length; i < len; i++) {
			var entry = getEntry(buffer[i]);
			if (entry) {
				var value = headers[entry.key];
				if (value) {
					if (!Array.isArray(value)) {
						value = [value];
					}
					value.push(entry.value);
				} else {
					headers[entry.key] = entry.value;
				}
			}
		}
		proxyRes.headers = headers;
		return proxyRes;
	}

	function getEntry(line) {
		if (!(line = line && line.trim())) {
			return;
		}

		var index = line.indexOf(' ');
		return index != -1 ? {
			key: line.substring(0, index),
			value: line.substring(index + 1)
		} : null;
	}

   proxyReq.on('data', function(data) {
	   if (ended) {
		   proxyRes.push(data);
		   return;
	   }

	   buffer = buffer ? Buffer.concat([buffer, data]) : data;
	   while(buffer[index]) {
		   if (isCRLF(buffer, index)) {
			   ended = isCRLF(buffer, index + 2);
			   if (!over) {
				   over = buffer.length >= MAX_BYTES;
				   if (ended) {
					   index += 4;
					   setHeaders(proxyRes, buffer.slice(0, index));
					   execCallback();
					   buffer = buffer.slice(index);
					   index = 0;
				   }
			   } else if (ended) {
				   proxyRes.push(buffer.slice(index + 4));
			   }
		   }
		   index++;
	   }

   });

   proxyReq.on('end', function() {
	   execCallback(new Error('Bad response'));
	   proxyRes.push(null);
   });
}

module.exports = function proxy(req, callback) {
	var headers = req.headers;
	var options = req.options;
	var done;

	function execCallback(err, proxyRes) {
		if (!done) {
			callback && callback(err, proxyRes);
			done = true;
		}
	}

	options.method = 'CONNECT';
	options.path = headers.host;
	if (options.agent == null) {
		options.agent = agent;
	}
	options.headers = {
			host : headers.host,
			'proxy-connection': 'keep-alive',
			'user-agent': headers['user-agent']
		};

	http.request(options).on('error', execCallback)
	.on('connect', function (res, socket, head) {
		socket.on('error', execCallback);
	    var proxyReq = tls.connect({
	        rejectUnauthorized: false,
	        socket: socket
	    }, function () {
	        proxyReq.write(getStringHeaders(req));
	        req.on('data', function(data) {
	        	proxyReq.write(data);
	        });
	        req.on('end', function() {
	        	proxyReq.end();
	        });
	    }).on('error', execCallback);

	 resolveResponse(proxyReq, execCallback);
	}).end();
};

<commit_msg>https proxy<commit_after>var http = require('http');
var agent = new (http.Agent)({maxSockets: 8});
var IncomingMessage = http.IncomingMessage;
var tls = require('tls');
var CRLF = '\r\n';
var CRLF_BUF = new Buffer(CRLF);
var MAX_BYTES = 1024 * 128;

function isCRLF(buffer, start) {
	   return buffer[start] ==  CRLF_BUF[0] && buffer[start + 1] == CRLF_BUF[1];
}

function getStringHeaders(req) {
	var headers = [req.method + ' ' + req.url + ' HTTP/' + req.httpVersion];
	if (req.headers && !req.headers.Host) {
		req.headers.Host = req.headers.host;
	}
	for (var key in req.headers) {
		var line = req.headers[key];
		if (Array.isArray(line)) {
			line.forEach(function(value) {
				headers.push(key + ': ' + value);
			});
		} else {
			headers.push(key + ': ' + line);
		}
	}
	headers.push(CRLF);

	return headers.join(CRLF);
}

function resolveResponse(proxyReq, callback) {
	var proxyRes = new IncomingMessage(proxyReq);
	var index = 0;
	var buffer, ended, done, over;

	function execCallback(err) {
		if (!done) {
			callback(err, proxyRes);
			done = true;
		}
	}

	function setHeaders(proxyRes, buffer) {
		var headers = {};
		buffer = buffer.toString().split(/\r\n/g);
		var firstLine = getEntry(buffer[0]);
		if (firstLine) {
			proxyRes.httpVersion = firstLine.key.split('/')[1];
			proxyRes.statusCode = firstLine.value.split(' ')[0];
		}

		for (var i = 1, len = buffer.length; i < len; i++) {
			var entry = getEntry(buffer[i]);
			if (entry) {
				var value = headers[entry.key];
				if (value) {
					if (!Array.isArray(value)) {
						value = [value];
					}
					value.push(entry.value);
				} else {
					headers[entry.key] = entry.value;
				}
			}
		}
		proxyRes.headers = headers;
		return proxyRes;
	}

	function getEntry(line) {
		if (!(line = line && line.trim())) {
			return;
		}

		var index = line.indexOf(':');
		return index != -1 ? {
			key: line.substring(0, index).trim().toLowerCase(),
			value: line.substring(index + 1).trim()
		} : null;
	}

   proxyReq.on('data', function(data) {
	   if (ended) {
		   proxyRes.push(data);
		   return;
	   }

	   buffer = buffer ? Buffer.concat([buffer, data]) : data;
	   while(buffer[index]) {
		   if (isCRLF(buffer, index)) {
			   ended = isCRLF(buffer, index + 2);
			   if (!over) {
				   over = buffer.length >= MAX_BYTES;
				   if (ended) {
					   index += 4;
					   setHeaders(proxyRes, buffer.slice(0, index));
					   execCallback();
					   buffer = buffer.slice(index);
					   index = 0;
				   }
			   } else if (ended) {
				   proxyRes.push(buffer.slice(index + 4));
			   }
		   }
		   index++;
	   }

   });

   proxyReq.on('end', function() {
	   execCallback(new Error('Bad response'));
	   proxyRes.push(null);
   });
}

module.exports = function proxy(req, callback) {
	var headers = req.headers;
	var options = req.options;
	var done;

	function execCallback(err, proxyRes) {
		if (!done) {
			callback && callback(err, proxyRes);
			done = true;
		}
	}

	options.method = 'CONNECT';
	options.path = headers.host;
	if (options.agent == null) {
		options.agent = agent;
	}
	options.headers = {
			host : headers.host,
			'proxy-connection': 'keep-alive',
			'user-agent': headers['user-agent']
		};

	http.request(options).on('error', execCallback)
	.on('connect', function (res, socket, head) {
		socket.on('error', execCallback);
	    var proxyReq = tls.connect({
	        rejectUnauthorized: false,
	        socket: socket
	    }, function () {
	        proxyReq.write(getStringHeaders(req));
	        req.on('data', function(data) {
	        	proxyReq.write(data);
	        });
	        req.on('end', function() {
	        	proxyReq.end();
	        });
	    }).on('error', execCallback);

	 resolveResponse(proxyReq, execCallback);
	}).end();
};

<|endoftext|>


<commit_before>'use strict';

// A copy of npm/lib/utils/read-installed.js
// that is hacked to not cache everything :)

// Walk through the file-system "database" of installed
// packages, and create a data object related to the
// installed versions of each package.

/*
This will traverse through all node_modules folders,
resolving the dependencies object to the object corresponding to
the package that meets that dep, or just the version/range if
unmet.

Assuming that you had this folder structure:

/path/to
+-- package.json { name = "root" }
`-- node_modules
    +-- foo {bar, baz, asdf}
    | +-- node_modules
    |   +-- bar { baz }
    |   `-- baz
    `-- asdf

where "foo" depends on bar, baz, and asdf, bar depends on baz,
and bar and baz are bundled with foo, whereas "asdf" is at
the higher level (sibling to foo), you'd get this object structure:

{ <package.json data>
, path: "/path/to"
, parent: null
, dependencies:
  { foo :
    { version: "1.2.3"
    , path: "/path/to/node_modules/foo"
    , parent: <Circular: root>
    , dependencies:
      { bar:
        { parent: <Circular: foo>
        , path: "/path/to/node_modules/foo/node_modules/bar"
        , version: "2.3.4"
        , dependencies: { baz: <Circular: foo.dependencies.baz> }
        }
      , baz: { ... }
      , asdf: <Circular: asdf>
      }
    }
  , asdf: { ... }
  }
}

Unmet deps are left as strings.
Extraneous deps are marked with extraneous:true
deps that don't meet a requirement are marked with invalid:true

to READ(packagefolder, parentobj, name, reqver)
obj = read package.json
installed = ./node_modules/*
if parentobj is null, and no package.json
  obj = {dependencies:{<installed>:"*"}}
deps = Object.keys(obj.dependencies)
obj.path = packagefolder
obj.parent = parentobj
if name, && obj.name !== name, obj.invalid = true
if reqver, && obj.version !satisfies reqver, obj.invalid = true
if !reqver && parentobj, obj.extraneous = true
for each folder in installed
  obj.dependencies[folder] = READ(packagefolder+node_modules+folder,
                                  obj, folder, obj.dependencies[folder])
# walk tree to find unmet deps
for each dep in obj.dependencies not in installed
  r = obj.parent
  while r
    if r.dependencies[dep]
      if r.dependencies[dep].verion !satisfies obj.dependencies[dep]
        WARN
        r.dependencies[dep].invalid = true
      obj.dependencies[dep] = r.dependencies[dep]
      r = null
    else r = r.parent
return obj

TODO:
1. Find unmet deps in parent directories, searching as node does up
as far as the left-most node_modules folder.
2. Ignore anything in node_modules that isn't a package folder.

*/

const npm = require('npm/lib/npm.js');
const fs = require('graceful-fs');
const path = require('path');
const asyncMap = require('slide').asyncMap;
const semver = require('semver');
const log = require('log4js').getLogger('pluginfw');

let fuSeen = [];
let riSeen = [];
let rpSeen = {};

const readJson = (file, callback) => {
  fs.readFile(file, (er, buf) => {
    if (er) {
      callback(er);
      return;
    }
    try {
      callback(null, JSON.parse(buf.toString()));
    } catch (er) {
      callback(er);
    }
  });
};

const readInstalled = (folder, cb) => {
  /* This is where we clear the cache, these three lines are all the
   * new code there is */
  fuSeen = [];
  rpSeen = {};
  riSeen = [];

  const d = npm.config.get('depth');
  readInstalled_(folder, null, null, null, 0, d, (er, obj) => {
    if (er) return cb(er);
    // now obj has all the installed things, where they're installed
    // figure out the inheritance links, now that the object is built.
    resolveInheritance(obj);
    cb(null, obj);
  });
};

module.exports = readInstalled;

const readInstalled_ = (folder, parent, name, reqver, depth, maxDepth, cb) => {
  let installed,
    obj,
    real,
    link;

  fs.readdir(path.resolve(folder, 'node_modules'), (er, i) => {
    // error indicates that nothing is installed here
    if (er) i = [];
    installed = i.filter((f) => f.charAt(0) !== '.');
    next();
  });

  readJson(path.resolve(folder, 'package.json'), (er, data) => {
    obj = copy(data);

    if (!parent) {
      obj = obj || true;
      er = null;
    }
    return next(er);
  });

  fs.lstat(folder, (er, st) => {
    if (er) {
      if (!parent) real = true;
      return next(er);
    }
    fs.realpath(folder, (er, rp) => {
      real = rp;
      if (st.isSymbolicLink()) link = rp;
      next(er);
    });
  });

  let errState = null;
  let called = false;
  function next(er) {
    if (errState) return;
    if (er) {
      errState = er;
      return cb(null, []);
    }
    if (!installed || !obj || !real || called) return;
    called = true;
    if (rpSeen[real]) return cb(null, rpSeen[real]);
    if (obj === true) {
      obj = {dependencies: {}, path: folder};
      installed.forEach((i) => { obj.dependencies[i] = '*'; });
    }
    if (name && obj.name !== name) obj.invalid = true;
    obj.realName = name || obj.name;
    obj.dependencies = obj.dependencies || {};

    // "foo":"http://blah" is always presumed valid
    if (reqver &&
        semver.validRange(reqver) &&
        !semver.satisfies(obj.version, reqver)) {
      obj.invalid = true;
    }

    if (parent &&
        !(name in parent.dependencies) &&
        !(name in (parent.devDependencies || {}))) {
      obj.extraneous = true;
    }
    obj.path = obj.path || folder;
    obj.realPath = real;
    obj.link = link;
    if (parent && !obj.link) obj.parent = parent;
    rpSeen[real] = obj;
    obj.depth = depth;
    if (depth >= maxDepth) return cb(null, obj);
    asyncMap(installed, (pkg, cb) => {
      let rv = obj.dependencies[pkg];
      if (!rv && obj.devDependencies) rv = obj.devDependencies[pkg];
      readInstalled_(path.resolve(folder, `node_modules/${pkg}`)
          , obj, pkg, obj.dependencies[pkg], depth + 1, maxDepth
          , cb);
    }, (er, installedData) => {
      if (er) return cb(er);
      installedData.forEach((dep) => {
        obj.dependencies[dep.realName] = dep;
      });

      // any strings here are unmet things.  however, if it's
      // optional, then that's fine, so just delete it.
      if (obj.optionalDependencies) {
        Object.keys(obj.optionalDependencies).forEach((dep) => {
          if (typeof obj.dependencies[dep] === 'string') {
            delete obj.dependencies[dep];
          }
        });
      }
      return cb(null, obj);
    });
  }
};

// starting from a root object, call findUnmet on each layer of children
const resolveInheritance = (obj) => {
  if (typeof obj !== 'object') return;
  if (riSeen.indexOf(obj) !== -1) return;
  riSeen.push(obj);
  if (typeof obj.dependencies !== 'object') {
    obj.dependencies = {};
  }
  Object.keys(obj.dependencies).forEach((dep) => {
    findUnmet(obj.dependencies[dep]);
  });
  Object.keys(obj.dependencies).forEach((dep) => {
    resolveInheritance(obj.dependencies[dep]);
  });
};

// find unmet deps by walking up the tree object.
// No I/O
const findUnmet = (obj) => {
  if (typeof obj !== 'object') return;
  if (fuSeen.indexOf(obj) !== -1) return;
  fuSeen.push(obj);
  const deps = obj.dependencies = obj.dependencies || {};
  Object.keys(deps)
      .filter((d) => typeof deps[d] === 'string')
      .forEach((d) => {
        let r = obj.parent;
        let found = null;
        while (r && !found && typeof deps[d] === 'string') {
        // if r is a valid choice, then use that.
          found = r.dependencies[d];
          if (!found && r.realName === d) found = r;

          if (!found) {
            r = r.link ? null : r.parent;
            continue;
          }
          if (typeof deps[d] === 'string' &&
            !semver.satisfies(found.version, deps[d])) {
          // the bad thing will happen
            log.warn(`${obj.path} requires ${d}@'${deps[d]
            }' but will load\n${
              found.path},\nwhich is version ${found.version}`
            , 'unmet dependency');
            found.invalid = true;
          }
          deps[d] = found;
        }
      });
  return obj;
};

const copy = (obj) => {
  if (!obj || typeof obj !== 'object') return obj;
  if (Array.isArray(obj)) return obj.map(copy);

  const o = {};
  for (const [i, v] of Object.entries(obj)) o[i] = copy(v);
  return o;
};

if (module === require.main) {
  const util = require('util');
  console.error('testing');

  let called = 0;
  npm.load({}, (err) => {
    if (err != null) throw err;
    readInstalled(process.cwd(), (er, map) => {
      console.error(called++);
      if (er) return console.error(er.stack || er.message);
      cleanup(map);
      console.error(util.inspect(map, true, 10, true));
    });
  });

  const seen = [];
  function cleanup(map) {
    if (seen.indexOf(map) !== -1) return;
    seen.push(map);
    for (const i of Object.keys(map)) {
      switch (i) {
        case '_id':
        case 'path':
        case 'extraneous': case 'invalid':
        case 'dependencies': case 'name':
          continue;
        default: delete map[i];
      }
    }
    for (const dep of Object.values(map.dependencies || {})) {
      if (typeof dep === 'object') {
        cleanup(dep);
      }
    }
    return map;
  }
}
<commit_msg>lint: Move functions up to fix more lint errors<commit_after>'use strict';

// A copy of npm/lib/utils/read-installed.js
// that is hacked to not cache everything :)

// Walk through the file-system "database" of installed
// packages, and create a data object related to the
// installed versions of each package.

/*
This will traverse through all node_modules folders,
resolving the dependencies object to the object corresponding to
the package that meets that dep, or just the version/range if
unmet.

Assuming that you had this folder structure:

/path/to
+-- package.json { name = "root" }
`-- node_modules
    +-- foo {bar, baz, asdf}
    | +-- node_modules
    |   +-- bar { baz }
    |   `-- baz
    `-- asdf

where "foo" depends on bar, baz, and asdf, bar depends on baz,
and bar and baz are bundled with foo, whereas "asdf" is at
the higher level (sibling to foo), you'd get this object structure:

{ <package.json data>
, path: "/path/to"
, parent: null
, dependencies:
  { foo :
    { version: "1.2.3"
    , path: "/path/to/node_modules/foo"
    , parent: <Circular: root>
    , dependencies:
      { bar:
        { parent: <Circular: foo>
        , path: "/path/to/node_modules/foo/node_modules/bar"
        , version: "2.3.4"
        , dependencies: { baz: <Circular: foo.dependencies.baz> }
        }
      , baz: { ... }
      , asdf: <Circular: asdf>
      }
    }
  , asdf: { ... }
  }
}

Unmet deps are left as strings.
Extraneous deps are marked with extraneous:true
deps that don't meet a requirement are marked with invalid:true

to READ(packagefolder, parentobj, name, reqver)
obj = read package.json
installed = ./node_modules/*
if parentobj is null, and no package.json
  obj = {dependencies:{<installed>:"*"}}
deps = Object.keys(obj.dependencies)
obj.path = packagefolder
obj.parent = parentobj
if name, && obj.name !== name, obj.invalid = true
if reqver, && obj.version !satisfies reqver, obj.invalid = true
if !reqver && parentobj, obj.extraneous = true
for each folder in installed
  obj.dependencies[folder] = READ(packagefolder+node_modules+folder,
                                  obj, folder, obj.dependencies[folder])
# walk tree to find unmet deps
for each dep in obj.dependencies not in installed
  r = obj.parent
  while r
    if r.dependencies[dep]
      if r.dependencies[dep].verion !satisfies obj.dependencies[dep]
        WARN
        r.dependencies[dep].invalid = true
      obj.dependencies[dep] = r.dependencies[dep]
      r = null
    else r = r.parent
return obj

TODO:
1. Find unmet deps in parent directories, searching as node does up
as far as the left-most node_modules folder.
2. Ignore anything in node_modules that isn't a package folder.

*/

const npm = require('npm/lib/npm.js');
const fs = require('graceful-fs');
const path = require('path');
const asyncMap = require('slide').asyncMap;
const semver = require('semver');
const log = require('log4js').getLogger('pluginfw');

let fuSeen = [];
let riSeen = [];
let rpSeen = {};

const readJson = (file, callback) => {
  fs.readFile(file, (er, buf) => {
    if (er) {
      callback(er);
      return;
    }
    try {
      callback(null, JSON.parse(buf.toString()));
    } catch (er) {
      callback(er);
    }
  });
};

const readInstalled = (folder, cb) => {
  /* This is where we clear the cache, these three lines are all the
   * new code there is */
  fuSeen = [];
  rpSeen = {};
  riSeen = [];

  const d = npm.config.get('depth');
  readInstalled_(folder, null, null, null, 0, d, (er, obj) => {
    if (er) return cb(er);
    // now obj has all the installed things, where they're installed
    // figure out the inheritance links, now that the object is built.
    resolveInheritance(obj);
    cb(null, obj);
  });
};

module.exports = readInstalled;

const readInstalled_ = (folder, parent, name, reqver, depth, maxDepth, cb) => {
  let installed,
    obj,
    real,
    link;
  let errState = null;
  let called = false;

  const next = (er) => {
    if (errState) return;
    if (er) {
      errState = er;
      return cb(null, []);
    }
    if (!installed || !obj || !real || called) return;
    called = true;
    if (rpSeen[real]) return cb(null, rpSeen[real]);
    if (obj === true) {
      obj = {dependencies: {}, path: folder};
      installed.forEach((i) => { obj.dependencies[i] = '*'; });
    }
    if (name && obj.name !== name) obj.invalid = true;
    obj.realName = name || obj.name;
    obj.dependencies = obj.dependencies || {};

    // "foo":"http://blah" is always presumed valid
    if (reqver &&
        semver.validRange(reqver) &&
        !semver.satisfies(obj.version, reqver)) {
      obj.invalid = true;
    }

    if (parent &&
        !(name in parent.dependencies) &&
        !(name in (parent.devDependencies || {}))) {
      obj.extraneous = true;
    }
    obj.path = obj.path || folder;
    obj.realPath = real;
    obj.link = link;
    if (parent && !obj.link) obj.parent = parent;
    rpSeen[real] = obj;
    obj.depth = depth;
    if (depth >= maxDepth) return cb(null, obj);
    asyncMap(installed, (pkg, cb) => {
      let rv = obj.dependencies[pkg];
      if (!rv && obj.devDependencies) rv = obj.devDependencies[pkg];
      readInstalled_(path.resolve(folder, `node_modules/${pkg}`)
          , obj, pkg, obj.dependencies[pkg], depth + 1, maxDepth
          , cb);
    }, (er, installedData) => {
      if (er) return cb(er);
      installedData.forEach((dep) => {
        obj.dependencies[dep.realName] = dep;
      });

      // any strings here are unmet things.  however, if it's
      // optional, then that's fine, so just delete it.
      if (obj.optionalDependencies) {
        Object.keys(obj.optionalDependencies).forEach((dep) => {
          if (typeof obj.dependencies[dep] === 'string') {
            delete obj.dependencies[dep];
          }
        });
      }
      return cb(null, obj);
    });
  };

  fs.readdir(path.resolve(folder, 'node_modules'), (er, i) => {
    // error indicates that nothing is installed here
    if (er) i = [];
    installed = i.filter((f) => f.charAt(0) !== '.');
    next();
  });

  readJson(path.resolve(folder, 'package.json'), (er, data) => {
    obj = copy(data);

    if (!parent) {
      obj = obj || true;
      er = null;
    }
    return next(er);
  });

  fs.lstat(folder, (er, st) => {
    if (er) {
      if (!parent) real = true;
      return next(er);
    }
    fs.realpath(folder, (er, rp) => {
      real = rp;
      if (st.isSymbolicLink()) link = rp;
      next(er);
    });
  });
};

// starting from a root object, call findUnmet on each layer of children
const resolveInheritance = (obj) => {
  if (typeof obj !== 'object') return;
  if (riSeen.indexOf(obj) !== -1) return;
  riSeen.push(obj);
  if (typeof obj.dependencies !== 'object') {
    obj.dependencies = {};
  }
  Object.keys(obj.dependencies).forEach((dep) => {
    findUnmet(obj.dependencies[dep]);
  });
  Object.keys(obj.dependencies).forEach((dep) => {
    resolveInheritance(obj.dependencies[dep]);
  });
};

// find unmet deps by walking up the tree object.
// No I/O
const findUnmet = (obj) => {
  if (typeof obj !== 'object') return;
  if (fuSeen.indexOf(obj) !== -1) return;
  fuSeen.push(obj);
  const deps = obj.dependencies = obj.dependencies || {};
  Object.keys(deps)
      .filter((d) => typeof deps[d] === 'string')
      .forEach((d) => {
        let r = obj.parent;
        let found = null;
        while (r && !found && typeof deps[d] === 'string') {
        // if r is a valid choice, then use that.
          found = r.dependencies[d];
          if (!found && r.realName === d) found = r;

          if (!found) {
            r = r.link ? null : r.parent;
            continue;
          }
          if (typeof deps[d] === 'string' &&
            !semver.satisfies(found.version, deps[d])) {
          // the bad thing will happen
            log.warn(`${obj.path} requires ${d}@'${deps[d]
            }' but will load\n${
              found.path},\nwhich is version ${found.version}`
            , 'unmet dependency');
            found.invalid = true;
          }
          deps[d] = found;
        }
      });
  return obj;
};

const copy = (obj) => {
  if (!obj || typeof obj !== 'object') return obj;
  if (Array.isArray(obj)) return obj.map(copy);

  const o = {};
  for (const [i, v] of Object.entries(obj)) o[i] = copy(v);
  return o;
};

if (module === require.main) {
  const seen = [];

  const cleanup = (map) => {
    if (seen.indexOf(map) !== -1) return;
    seen.push(map);
    for (const i of Object.keys(map)) {
      switch (i) {
        case '_id':
        case 'path':
        case 'extraneous': case 'invalid':
        case 'dependencies': case 'name':
          continue;
        default: delete map[i];
      }
    }
    for (const dep of Object.values(map.dependencies || {})) {
      if (typeof dep === 'object') {
        cleanup(dep);
      }
    }
    return map;
  };

  const util = require('util');
  console.error('testing');

  let called = 0;
  npm.load({}, (err) => {
    if (err != null) throw err;
    readInstalled(process.cwd(), (er, map) => {
      console.error(called++);
      if (er) return console.error(er.stack || er.message);
      cleanup(map);
      console.error(util.inspect(map, true, 10, true));
    });
  });
}
<|endoftext|>


<commit_before>/**
 * Licensed to the Apache Software Foundation (ASF) under one or more
 * contributor license agreements.  See the NOTICE file distributed with
 * this work for additional information regarding copyright ownership.
 * The ASF licenses this file to You under the Apache License, Version 2.0
 * (the "License"); you may not use this file except in compliance with
 * the License.  You may obtain a copy of the License at
 *
 * http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */
const path = require('path')

module.exports = {
  chainWebpack: config => {
    config
      .plugin('html')
      .tap(args => {
        args[0].title = 'Apache Jena Fuseki'
        return args
      })

    if (process.env.NODE_ENV !== 'production') {
      // devtool for test and other modes
      // https://webpack.js.org/configuration/devtool/
      if (process.env.NODE_ENV === 'test') {
        // NOTE: if you need to debug the project with WebStorm (or another IDE) and it fails, try
        //       change this value for config.devtool('eval-source-map')
        config.devtool('eval')
      } else {
        config.devtool('eval-source-map')
      }

      // coverage
      if (process.env.NODE_ENV === 'test') {
        config.module.rule('istanbul')
          .test(/\.js$/)
          .include.add(path.resolve('src')).end()
          .use('istanbul-instrumenter-loader')
          .loader('istanbul-instrumenter-loader')
          .options({ esModules: true })
          .after('cache-loader')
      }

      // resolve modules in devtool
      config.output
        .devtoolModuleFilenameTemplate('[absolute-resource-path]')
        .devtoolFallbackModuleFilenameTemplate('[absolute-resource-path]?[hash]')
    }
  },
  // see https://cli.vuejs.org/config/#devserver-proxy
  devServer: {
    proxy: {
      '/': {
        target: 'http://localhost:3030',
        ws: true,
        changeOrigin: true
      }
    }
  },
  // Change build paths to make them Maven compatible
  // see https://cli.vuejs.org/config/
  outputDir: 'target/dist',
  assetsDir: 'static'
}
<commit_msg>Fix annoying sass warning<commit_after>/**
 * Licensed to the Apache Software Foundation (ASF) under one or more
 * contributor license agreements.  See the NOTICE file distributed with
 * this work for additional information regarding copyright ownership.
 * The ASF licenses this file to You under the Apache License, Version 2.0
 * (the "License"); you may not use this file except in compliance with
 * the License.  You may obtain a copy of the License at
 *
 * http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */
const path = require('path')

module.exports = {
  chainWebpack: config => {
    config
      .plugin('html')
      .tap(args => {
        args[0].title = 'Apache Jena Fuseki'
        return args
      })

    if (process.env.NODE_ENV !== 'production') {
      // devtool for test and other modes
      // https://webpack.js.org/configuration/devtool/
      if (process.env.NODE_ENV === 'test') {
        // NOTE: if you need to debug the project with WebStorm (or another IDE) and it fails, try
        //       change this value for config.devtool('eval-source-map')
        config.devtool('eval')
      } else {
        config.devtool('eval-source-map')
      }

      // coverage
      if (process.env.NODE_ENV === 'test') {
        config.module.rule('istanbul')
          .test(/\.js$/)
          .include.add(path.resolve('src')).end()
          .use('istanbul-instrumenter-loader')
          .loader('istanbul-instrumenter-loader')
          .options({ esModules: true })
          .after('cache-loader')
      }

      // resolve modules in devtool
      config.output
        .devtoolModuleFilenameTemplate('[absolute-resource-path]')
        .devtoolFallbackModuleFilenameTemplate('[absolute-resource-path]?[hash]')
    }
  },
  // see https://cli.vuejs.org/config/#devserver-proxy
  devServer: {
    proxy: {
      '/': {
        target: 'http://localhost:3030',
        ws: true,
        changeOrigin: true
      }
    }
  },
  // Change build paths to make them Maven compatible
  // see https://cli.vuejs.org/config/
  outputDir: 'target/dist',
  assetsDir: 'static',
  css: {
    loaderOptions: {
      sass: {
        sassOptions: {
          quietDeps: [
            'node_modules/bootstrap/**/*.scss'
          ]
        }
      }
    }
  }
}
<|endoftext|>


<commit_before>/* autogenerated by the update_version script */
exports.version=1599847591;
<commit_msg>new version<commit_after>/* autogenerated by the update_version script */
exports.version=1599926172;
<|endoftext|>


<commit_before>(function () {
  var els = document.querySelectorAll('[data-role="tommy-expander"]')

  els.forEach(function (el) {
    el.classList.remove('is-hidden')
    el.addEventListener('click', onClick)
  });

  function onClick(e) {
    var target = e.currentTarget;
    var wrapper = target.parentNode;
    toggle(wrapper)
  }

  function toggle(el) {
    if (el.classList.contains('is-expanded')) {
      restore(el);
    } else {
      expand(el);
    }
  }

  function expand(el) {
    el.classList.add('is-expanded');
  }

  function restore(el) {
    el.classList.remove('is-expanded');
  }
})();
<commit_msg>Handle ESC key to discard fullscreen<commit_after>(function () {
  var els = document.querySelectorAll('[data-role="tommy-expander"]')

  els.forEach(function (el) {
    el.classList.remove('is-hidden')
    el.addEventListener('click', onClick)
  });

  function onClick(e) {
    var target = e.currentTarget;
    var wrapper = target.parentNode;
    toggle(wrapper)
  }

  function createOnKeyUp(el) {
    return function (e) {
      var keyCode = e.keyCode;

      if (keyCode === 27) {
        restore(el);
      }
    }
  }

  function toggle(el) {
    if (el.classList.contains('is-expanded')) {
      restore(el);
    } else {
      expand(el);
    }
  }

  function expand(el) {
    teardownKeyUpListener(el);
    setupKeyUpListener(el);
    el.classList.add('is-expanded');
  }

  function restore(el) {
    teardownKeyUpListener(el);
    el.classList.remove('is-expanded');
  }

  function setupKeyUpListener(el) {
    var onKeyUp = createOnKeyUp(el);
    el.onKeyUpHandler = onKeyUp;
    document.addEventListener('keyup', onKeyUp);
  }

  function teardownKeyUpListener(el) {
    var onKeyUp = el.onKeyUpHandler;

    if (onKeyUp) {
      document.removeEventListener('keyup', onKeyUp);
    }

    delete el.onKeyUpHandler
  }
})();
<|endoftext|>