<commit_before>/*
 * Copyright 2009-2011 Mozilla Foundation and contributors
 * Licensed under the New BSD license. See LICENSE.txt or:
 * http://opensource.org/licenses/BSD-3-Clause
 */

define(function(require, exports, module) {

var util = require('gcli/util');
var canon = require('gcli/canon');
var domtemplate = require("gcli/ui/domtemplate");

var examiner = require("test/examiner");

var testCss = require("text!test/ui/test.css");
var testHtml = require('text!test/ui/test.html');

var template;

/**
 * Registration and de-registration.
 */
exports.startup = function() {
  canon.addCommand(testCommandSpec);
};

exports.shutdown = function() {
  canon.removeCommand(testCommandSpec);
};

/**
 * The 'test' command
 */
var testCommandSpec = {
  name: 'test',
  description: 'Runs the GCLI Unit Tests',
  params: [],
  exec: function(env, context) {
    if (!template) {
      util.importCss(testCss, context.document, 'gcli-test');
      template = util.toDom(context.document, testHtml);
    }

    var promise = context.createPromise();
    var options = { window: window };

    examiner.runAsync(options, function() {
      var newNode = template.cloneNode(true);
      domtemplate.template(newNode, examiner.toRemote(), {
        allowEval: true,
        stack: 'test.html'
      });
      promise.resolve(newNode);
    });
    return promise;
  }
};

});
<commit_msg>Bug 732780 (view): Update 'test' command - Move to view - Add 'hidden' option to prevent messing up output<commit_after>/*
 * Copyright 2009-2011 Mozilla Foundation and contributors
 * Licensed under the New BSD license. See LICENSE.txt or:
 * http://opensource.org/licenses/BSD-3-Clause
 */

define(function(require, exports, module) {

var util = require('gcli/util');
var canon = require('gcli/canon');
var domtemplate = require("gcli/ui/domtemplate");

var examiner = require("test/examiner");

var testCss = require("text!test/ui/test.css");
var testHtml = require('text!test/ui/test.html');

var template;

/**
 * Registration and de-registration.
 */
exports.startup = function() {
  canon.addCommand(testCommandSpec);
};

exports.shutdown = function() {
  canon.removeCommand(testCommandSpec);
};

/**
 * The 'test' command
 */
var testCommandSpec = {
  name: 'test',
  description: 'Runs the GCLI Unit Tests',
  params: [],
  exec: function(env, context) {
    var promise = context.createPromise();

    var testOptions = {
      window: window,
      hideExec: true
    };

    examiner.runAsync(testOptions, function() {
      promise.resolve(context.createView({
        html: testHtml,
        css: testCss,
        cssId: 'gcli-test',
        data: examiner.toRemote(),
        options: { allowEval: true, stack: 'test.html' }
      }));
    });

    return promise;
  }
};

});
<|endoftext|>


<commit_before>import _ from 'lodash';
import opn from 'opn';
var bs = require('browser-sync').create('insales server');

export function startBrowser (url, options) {
  if (options && options.start || options.launch) {
    const _option = _.omit(options, ['start', 'launch']);
    opn(url, options)
  }
}

export function startBrowserSync (_url, options, paths) {
  const _options = _.omit(options.tools.browserSync, ['start', 'uploadRestart']);
  const url = _url.replace('https', 'http');
  const _optionDefault = {
    proxy: url,
    serveStatic: [options.theme.root],
    https: false
  };
  const optionsInit = _.merge(_optionDefault, _options)
  bs.init(optionsInit);
}
<commit_msg>Добавлен reloadDebounce для BrowserSync<commit_after>import _ from 'lodash';
import opn from 'opn';
var bs = require('browser-sync').create('insales server');

export function startBrowser (url, options) {
  if (options && options.start || options.launch) {
    const _option = _.omit(options, ['start', 'launch']);
    opn(url, options)
  }
}

export function startBrowserSync (_url, options, paths) {
  const _options = _.omit(options.tools.browserSync, ['start', 'uploadRestart']);
  const url = _url.replace('https', 'http');
  const _optionDefault = {
    proxy: url,
    serveStatic: [options.theme.root],
    reloadDebounce: 3000,
    https: false
  };
  const optionsInit = _.merge(_optionDefault, _options)
  bs.init(optionsInit);
}
<|endoftext|>


<commit_before>/* @flow */

import React from 'react'
import ReactDOM from 'react-dom'
import { CompositeDisposable, Emitter } from 'atom'
import type { Disposable, Point, TextEditor } from 'atom'

import Delegate from './delegate'
import MessageElement from './message'
import { $range } from '../helpers'
import type { LinterMessage } from '../types'

class TooltipElement {
  marker: Object
  element: HTMLElement
  emitter: Emitter
  messages: Array<LinterMessage>
  subscriptions: CompositeDisposable

  constructor(messages: Array<LinterMessage>, position: Point, textEditor: TextEditor) {
    this.emitter = new Emitter()
    this.element = document.createElement('div')
    this.messages = messages
    this.subscriptions = new CompositeDisposable()

    this.subscriptions.add(this.emitter)
    this.marker = textEditor.markBufferRange([position, position])
    this.marker.onDidDestroy(() => this.emitter.emit('did-destroy'))

    const delegate = new Delegate()
    this.element.id = 'linter-tooltip'
    textEditor.decorateMarker(this.marker, {
      type: 'overlay',
      item: this.element,
    })
    this.subscriptions.add(delegate)

    const children = []
    messages.forEach(message => {
      if (message.version === 2) {
        children.push(<MessageElement key={message.key} delegate={delegate} message={message} />)
      }
    })
    ReactDOM.render(<linter-messages>{children}</linter-messages>, this.element)
  }
  isValid(position: Point, messages: Set<LinterMessage>): boolean {
    const range = $range(this.messages[0])
    return !!(this.messages.length === 1 && messages.has(this.messages[0]) && range && range.containsPoint(position))
  }
  onDidDestroy(callback: () => any): Disposable {
    this.emitter.on('did-destroy', callback)
  }
  dispose() {
    this.emitter.emit('did-destroy')
    this.subscriptions.dispose()
  }
}

module.exports = TooltipElement
<commit_msg>isValid early exit<commit_after>/* @flow */

import React from 'react'
import ReactDOM from 'react-dom'
import { CompositeDisposable, Emitter } from 'atom'
import type { Disposable, Point, TextEditor } from 'atom'

import Delegate from './delegate'
import MessageElement from './message'
import { $range } from '../helpers'
import type { LinterMessage } from '../types'

class TooltipElement {
  marker: Object
  element: HTMLElement
  emitter: Emitter
  messages: Array<LinterMessage>
  subscriptions: CompositeDisposable

  constructor(messages: Array<LinterMessage>, position: Point, textEditor: TextEditor) {
    this.emitter = new Emitter()
    this.element = document.createElement('div')
    this.messages = messages
    this.subscriptions = new CompositeDisposable()

    this.subscriptions.add(this.emitter)
    this.marker = textEditor.markBufferRange([position, position])
    this.marker.onDidDestroy(() => this.emitter.emit('did-destroy'))

    const delegate = new Delegate()
    this.element.id = 'linter-tooltip'
    textEditor.decorateMarker(this.marker, {
      type: 'overlay',
      item: this.element,
    })
    this.subscriptions.add(delegate)

    const children = []
    messages.forEach(message => {
      if (message.version === 2) {
        children.push(<MessageElement key={message.key} delegate={delegate} message={message} />)
      }
    })
    ReactDOM.render(<linter-messages>{children}</linter-messages>, this.element)
  }
  isValid(position: Point, messages: Set<LinterMessage>): boolean {
    if (this.messages.length !== 1 || !messages.has(this.messages[0])) {
      return false
    }
    const range = $range(this.messages[0])
    return Boolean(range && range.containsPoint(position))
  }
  onDidDestroy(callback: () => any): Disposable {
    this.emitter.on('did-destroy', callback)
  }
  dispose() {
    this.emitter.emit('did-destroy')
    this.subscriptions.dispose()
  }
}

module.exports = TooltipElement
<|endoftext|>


<commit_before>
/**
  * Our first transition is actually the removal of globals and
  * introducing the setup routine.
  * Thus the body of this transition is just an empty function, but displays
  * as all transitions an explanation to the user.
  */
module.exports = {

  transition: function () {

  },

  message: function () {
    console.log('Congratulations!\n\n' +
      'You just migrated from protocol 0 to 1!\n' +
      'What does that mean for you?\n' +
      'Quite simple, from 0 to 1 we introduced the setup function and we' +
      'deprecated some globals, like async or dbm. What this transition does is' +
      ' grabbing your migrations, replacing the async and dbm definitions and ' +
      'inserting the setup body if not present.\n' +
      'It might be possible, that you still run into errors, for example if ' +
      'you already have had a setup body, it wont be replaced and you might ' +
      'be missing the default routine of the setup, which provides for example ' +
      'the dataTypes to your migration.\n\n' +
      'What do I need to do now?\n' +
      'Try to rexecute all of your migrations and watch if you run into any ' +
      'Errors, if you encounter any, you need to manually fix those ' +
      'problems. But don\'t worry, this protocol transitions happen very ' +
      'rarely!\n'
    );
  }
};
<commit_msg>fix(lgtm): fix errors<commit_after>/**
 * Our first transition is actually the removal of globals and
 * introducing the setup routine.
 * Thus the body of this transition is just an empty function, but displays
 * as all transitions an explanation to the user.
 */
module.exports = {
  transition: function () {},

  message: function () {
    console.log(
      'Congratulations!\n\n' +
        'You just migrated from protocol 0 to 1!\n' +
        'What does that mean for you?\n' +
        'Quite simple, from 0 to 1 we introduced the setup function and we ' +
        'deprecated some globals, like async or dbm. What this transition does is' +
        ' grabbing your migrations, replacing the async and dbm definitions and ' +
        'inserting the setup body if not present.\n' +
        'It might be possible, that you still run into errors, for example if ' +
        'you already have had a setup body, it wont be replaced and you might ' +
        'be missing the default routine of the setup, which provides for example ' +
        'the dataTypes to your migration.\n\n' +
        'What do I need to do now?\n' +
        'Try to rexecute all of your migrations and watch if you run into any ' +
        'Errors, if you encounter any, you need to manually fix those ' +
        "problems. But don't worry, this protocol transitions happen very " +
        'rarely!\n'
    );
  }
};
<|endoftext|>


<commit_before>var util          = require("util");
var buffer        = require("../buffer");
var BaseTransport = require("./transport");

function Transport(stream, options) {
	options = options || {};

	BaseTransport.call(this, stream, options);

	var transactionId = (typeof options.transactionId != "undefined" ? options.transactionId : 1);
	var protocol      = (typeof options.protocol != "undefined" ? options.protocol : 0);
	var transport     = this;

	this.transactionId = transactionId - 1;
	this.protocol      = protocol;
	this.callbacks     = {};
	this.buffer        = null;

	this.stream.on("end", function () {
		transport.emit("close");
	});
}
util.inherits(Transport, BaseTransport);

Transport.prototype.wrap = function (pdu, options, next) {
	options = options || {};
	next    = next || null;

	var unitId        = (typeof options.unitId != "undefined" ? options.unitId : 1);
	var transactionId = (typeof options.transactionId != "undefined" ? options.transactionId : null);
	var data          = buffer.alloc(pdu.length + 7);

	if (transactionId !== null) {
		data.writeUInt16BE(transactionId, 0);
	} else {
		this.transactionId += 1;

		data.writeUInt16BE(this.transactionId, 0);
	}

	if (typeof next == "function") {
		var key = [ data.readUInt16BE(0), unitId, pdu.readUInt8(0) ].join(":");

		this.callbacks[key] = next;

		data.__callback_key = key;
	}

	data.writeUInt16BE(this.protocol, 2);
	data.writeUInt16BE(pdu.length + 1, 4);
	data.writeUInt8(unitId, 6);

	pdu.copy(data, 7);

	return data;
};

Transport.prototype.close = function (next) {
	this.closed = true;

	this.stream.end(next);
};

Transport.prototype.pending = function () {
	return (this.buffer !== null && this.buffer.length);
};

Transport.prototype.unwrap = function (data) {
	this.buffer = (this.buffer === null ? data : buffer.concat([ this.buffer, data ]));

	// not enough data to see package length
	if (this.buffer.length < 6) return false;

	var length = this.buffer.readUInt16BE(4);

	if (this.buffer.length < length + 6) return false;

	var unwrapped = {
		transactionId  : this.buffer.readUInt16BE(0),
		protocol       : this.buffer.readUInt16BE(2),
		length         : length,
		unitId         : this.buffer.readUInt8(6),
		pdu            : this.buffer.slice(7, length + 6)
	};
	unwrapped.__callback_key = [ unwrapped.transactionId, unwrapped.unitId, unwrapped.pdu.readUInt8(0) & 0x7F ].join(":");

	if (typeof this.callbacks[unwrapped.__callback_key] == "function") {
		unwrapped.callback = this.callbacks[unwrapped.__callback_key];
		delete this.callbacks[unwrapped.__callback_key];
	}

	this.buffer = (this.buffer.length > length + 6 ? this.buffer.slice(length + 6) : null);

	return unwrapped;
};

Transport.prepare = function (options) {
	return function (stream) {
		return new Transport(stream, options);
	};
};

module.exports = Transport;
<commit_msg>tcp: fixes #7<commit_after>var util          = require("util");
var buffer        = require("../buffer");
var BaseTransport = require("./transport");

function Transport(stream, options) {
	options = options || {};

	BaseTransport.call(this, stream, options);

	var transactionId = (typeof options.transactionId != "undefined" ? options.transactionId : 1);
	var protocol      = (typeof options.protocol != "undefined" ? options.protocol : 0);
	var transport     = this;

	this.transactionId = transactionId - 1;
	this.protocol      = protocol;
	this.callbacks     = {};
	this.buffer        = null;

	this.stream.on("end", function () {
		transport.emit("close");
	});
}
util.inherits(Transport, BaseTransport);

Transport.prototype.wrap = function (pdu, options, next) {
	options = options || {};
	next    = next || null;

	var unitId        = (typeof options.unitId != "undefined" ? options.unitId : 1);
	var transactionId = (typeof options.transactionId != "undefined" ? options.transactionId : null);
	var data          = buffer.alloc(pdu.length + 7);

	if (transactionId !== null) {
		data.writeUInt16BE(transactionId, 0);
	} else {
		this.transactionId += 1;

		if (this.transactionId > 65535) {
			this.transactionId = 1;
		}

		data.writeUInt16BE(this.transactionId, 0);
	}

	if (typeof next == "function") {
		var key = [ data.readUInt16BE(0), unitId, pdu.readUInt8(0) ].join(":");

		this.callbacks[key] = next;

		data.__callback_key = key;
	}

	data.writeUInt16BE(this.protocol, 2);
	data.writeUInt16BE(pdu.length + 1, 4);
	data.writeUInt8(unitId, 6);

	pdu.copy(data, 7);

	return data;
};

Transport.prototype.close = function (next) {
	this.closed = true;

	this.stream.end(next);
};

Transport.prototype.pending = function () {
	return (this.buffer !== null && this.buffer.length);
};

Transport.prototype.unwrap = function (data) {
	this.buffer = (this.buffer === null ? data : buffer.concat([ this.buffer, data ]));

	// not enough data to see package length
	if (this.buffer.length < 6) return false;

	var length = this.buffer.readUInt16BE(4);

	if (this.buffer.length < length + 6) return false;

	var unwrapped = {
		transactionId  : this.buffer.readUInt16BE(0),
		protocol       : this.buffer.readUInt16BE(2),
		length         : length,
		unitId         : this.buffer.readUInt8(6),
		pdu            : this.buffer.slice(7, length + 6)
	};
	unwrapped.__callback_key = [ unwrapped.transactionId, unwrapped.unitId, unwrapped.pdu.readUInt8(0) & 0x7F ].join(":");

	if (typeof this.callbacks[unwrapped.__callback_key] == "function") {
		unwrapped.callback = this.callbacks[unwrapped.__callback_key];
		delete this.callbacks[unwrapped.__callback_key];
	}

	this.buffer = (this.buffer.length > length + 6 ? this.buffer.slice(length + 6) : null);

	return unwrapped;
};

Transport.prepare = function (options) {
	return function (stream) {
		return new Transport(stream, options);
	};
};

module.exports = Transport;
<|endoftext|>


<commit_before>var path = require('path');
var paths = require('./paths');

// Guess proxy defined in the env
/*jshint camelcase: false*/
var proxy = process.env.HTTP_PROXY
    || process.env.http_proxy
    || null;

var httpsProxy = process.env.HTTPS_PROXY
    || process.env.https_proxy
    || proxy;
/*jshint camelcase: true*/

// Use a well known user agent (in this case, curl) when using a proxy,
// to avoid potential filtering on many corporate proxies with blank or unknown agents
var userAgent = !proxy && !httpsProxy
    ? 'node/' + process.version + ' ' + process.platform + ' ' + process.arch
    : 'curl/7.21.4 (universal-apple-darwin11.0) libcurl/7.21.4 OpenSSL/0.9.8r zlib/1.2.5';

var defaults = {
    'cwd': process.cwd(),
    'directory': 'upt_modules',
    'registry': 'https://bower.herokuapp.com',
    'shorthand-resolver': 'git://github.com/{{owner}}/{{package}}.git',
    'tmp': paths.tmp,
    'proxy': proxy,
    'https-proxy': httpsProxy,
    'timeout': 30000,
    'ca': { search: [] },
    'strict-ssl': true,
    'user-agent': userAgent,
    'color': true,
    'interactive': null,
    'storage': {
        packages: path.join(paths.cache, 'packages'),
        links: path.join(paths.data, 'links'),
        completion: path.join(paths.data, 'completion'),
        registry: path.join(paths.cache, 'registry'),
        empty: path.join(paths.data, 'empty')  // Empty dir, used in GIT_TEMPLATE_DIR among others
    }
};

module.exports = defaults;
<commit_msg>increased default timeout to 300 seconds to support heavy hook scripts<commit_after>var path = require('path');
var paths = require('./paths');

// Guess proxy defined in the env
/*jshint camelcase: false*/
var proxy = process.env.HTTP_PROXY
    || process.env.http_proxy
    || null;

var httpsProxy = process.env.HTTPS_PROXY
    || process.env.https_proxy
    || proxy;
/*jshint camelcase: true*/

// Use a well known user agent (in this case, curl) when using a proxy,
// to avoid potential filtering on many corporate proxies with blank or unknown agents
var userAgent = !proxy && !httpsProxy
    ? 'node/' + process.version + ' ' + process.platform + ' ' + process.arch
    : 'curl/7.21.4 (universal-apple-darwin11.0) libcurl/7.21.4 OpenSSL/0.9.8r zlib/1.2.5';

var defaults = {
    'cwd': process.cwd(),
    'directory': 'upt_modules',
    'registry': 'https://bower.herokuapp.com',
    'shorthand-resolver': 'git://github.com/{{owner}}/{{package}}.git',
    'tmp': paths.tmp,
    'proxy': proxy,
    'https-proxy': httpsProxy,
    'timeout': 300000,
    'ca': { search: [] },
    'strict-ssl': true,
    'user-agent': userAgent,
    'color': true,
    'interactive': null,
    'storage': {
        packages: path.join(paths.cache, 'packages'),
        links: path.join(paths.data, 'links'),
        completion: path.join(paths.data, 'completion'),
        registry: path.join(paths.cache, 'registry'),
        empty: path.join(paths.data, 'empty')  // Empty dir, used in GIT_TEMPLATE_DIR among others
    }
};

module.exports = defaults;
<|endoftext|>


<commit_before>'use strict';

var hasOwnProperty = require('./object').hasOwnProperty;

/**
 * Get a property of a plain object
 * Throws an error in case the object is not a plain object or the
 * property is not defined on the object itself
 * @param {Object} object
 * @param {string} prop
 * @return {*} Returns the property value when safe
 */
function getSafeProperty (object, prop) {
  // only allow getting properties of a plain object
  if (isPlainObject(object)) {
    // only allow getting properties defined on the object itself,
    // not inherited from it's prototype.
    if (hasOwnProperty(object, prop)) {
      return object[prop];
    }

    if (!(prop in object)) {
      // this is a not existing property on a plain object
      return undefined;
    }
  }

  if (typeof object[prop] === 'function' && isSafeMethod(object, prop)) {
    throw new Error('Cannot access method "' + prop + '" as a property');
  }

  throw new Error('No access to property "' + prop + '"');
}

/**
 * Set a property on a plain object.
 * Throws an error in case the object is not a plain object or the
 * property would override an inherited property like .constructor or .toString
 * @param {Object} object
 * @param {string} prop
 * @param {*} value
 * @return {*} Returns the value
 */
// TODO: merge this function into access.js?
function setSafeProperty (object, prop, value) {
  // only allow setting properties of a plain object
  if (isPlainObject(object)) {
    // only allow setting properties defined on the object itself,
    // not inherited from it's prototype.
    if (prop in object) {
      // property already exists
      // override when the property is defined on the object itself.
      // don't allow overriding inherited properties like .constructor or .toString
      if (hasOwnProperty(object, prop)) {
        return object[prop] = value;
      }
    }
    else {
      // this is a new property, that's just ok
      return object[prop] = value;
    }
  }

  throw new Error('No access to property "' + prop + '"');
}

/**
 * Test whether a property is safe to use for an object.
 * For example .toString and .constructor are not safe
 * @param {string} prop
 * @return {boolean} Returns true when safe
 */
function isSafeProperty (prop) {
  return !(prop in {});
}

/**
 * Validate whether a method is safe.
 * Throws an error when that's not the case.
 * @param {Object} object
 * @param {string} method
 */
// TODO: merge this function into assign.js?
function validateSafeMethod (object, method) {
  if (!isSafeMethod(object, method)) {
    throw new Error('No access to method "' + method + '"');
  }
}

/**
 * Check whether a method is safe.
 * Throws an error when that's not the case (for example for `constructor`).
 * @param {Object} object
 * @param {string} method
 * @return {boolean} Returns true when safe, false otherwise
 */
function isSafeMethod (object, method) {
  // test for plain functions defined on the object (instead of a method)
  if (hasOwnProperty(object, method)) {
    return isPlainObject(object);
  }
  else {
    // only allow methods:
    // - defined on the prototype of this object
    // - not defined on the prototype of native Object
    //   i.e. constructor, __defineGetter__, hasOwnProperty, etc. are not allowed
    // - calling methods on a function (like bind) is not allowed
    // - A few safe native methods are allowed: toString, valueOf, toLocaleString
    return (object && typeof object !== 'function' &&
        (hasOwnProperty(object.constructor.prototype, method) ||
            hasOwnProperty(object.__proto__, method)) &&
        (!hasOwnProperty(Object.prototype, method) || hasOwnProperty(safeNativeMethods, method)));
  }
}

function isPlainObject (object) {
  return typeof object === 'object' && object && object.constructor === Object;
}

var safeNativeMethods = {
  toString: true,
  valueOf: true,
  toLocaleString: true
};

exports.getSafeProperty = getSafeProperty;
exports.setSafeProperty = setSafeProperty;
exports.isSafeProperty = isSafeProperty;
exports.validateSafeMethod = validateSafeMethod;
exports.isSafeMethod = isSafeMethod;
exports.isPlainObject = isPlainObject;
<commit_msg>Refactor isSafe checks to restore inheritance<commit_after>'use strict';

var hasOwnProperty = require('./object').hasOwnProperty;

/**
 * Get a property of a plain object
 * Throws an error in case the object is not a plain object or the
 * property is not defined on the object itself
 * @param {Object} object
 * @param {string} prop
 * @return {*} Returns the property value when safe
 */
function getSafeProperty (object, prop) {
  // only allow getting properties of a plain object
  if (isPlainObject(object)) {
    // only allow getting properties defined on the object itself,
    // not inherited from it's prototype.
    if (hasOwnProperty(object, prop)) {
      return object[prop];
    }

    if (!(prop in object)) {
      // this is a not existing property on a plain object
      return undefined;
    }
  }

  if (typeof object[prop] === 'function' && isSafeMethod(object, prop)) {
    throw new Error('Cannot access method "' + prop + '" as a property');
  }

  throw new Error('No access to property "' + prop + '"');
}

/**
 * Set a property on a plain object.
 * Throws an error in case the object is not a plain object or the
 * property would override an inherited property like .constructor or .toString
 * @param {Object} object
 * @param {string} prop
 * @param {*} value
 * @return {*} Returns the value
 */
// TODO: merge this function into access.js?
function setSafeProperty (object, prop, value) {
  // only allow setting properties of a plain object
  if (isPlainObject(object)) {
    // only allow setting properties defined on the object itself,
    // not inherited from it's prototype.
    if (prop in object) {
      // property already exists
      // override when the property is defined on the object itself.
      // don't allow overriding inherited properties like .constructor or .toString
      if (hasOwnProperty(object, prop)) {
        return object[prop] = value;
      }
    }
    else {
      // this is a new property, that's just ok
      return object[prop] = value;
    }
  }

  throw new Error('No access to property "' + prop + '"');
}

/**
 * Test whether a property is safe to use for an object.
 * For example .toString and .constructor are not safe
 * @param {string} prop
 * @return {boolean} Returns true when safe
 */
function isSafeProperty (prop) {
  if (!object || typeof object !== 'object') {
    return false;
  }
  // UNSAFE: ghosted
  // e.g length
  if (hasOwnProperty(object, prop) && (prop in object.__proto__)) {
    return false;
  }
  // SAFE: whitelisted
  // e.g length
  if (hasOwnProperty(safeNativeProperties, prop)) {
    return true;
  }
  // UNSAFE: inherited from Object prototype
  // e.g constructor
  if (hasOwnProperty(Object.prototype, prop)) {
    return false;
  }
  // UNSAFE: inherited from Function prototype
  // e.g call, apply
  if (hasOwnProperty(Function.prototype, prop)) {
    return false;
  }
  return true;
}

/**
 * Validate whether a method is safe.
 * Throws an error when that's not the case.
 * @param {Object} object
 * @param {string} method
 */
// TODO: merge this function into assign.js?
function validateSafeMethod (object, method) {
  if (!isSafeMethod(object, method)) {
    throw new Error('No access to method "' + method + '"');
  }
}

/**
 * Check whether a method is safe.
 * Throws an error when that's not the case (for example for `constructor`).
 * @param {Object} object
 * @param {string} method
 * @return {boolean} Returns true when safe, false otherwise
 */
function isSafeMethod (object, method) {
  if (!object || typeof object[method] !== 'function') {
    return false;
  }
  // UNSAFE: ghosted
  // e.g toString
  if (hasOwnProperty(object, method) && (method in object.__proto__)) {
    return false;
  }
  // SAFE: whitelisted
  // e.g toString
  if (hasOwnProperty(safeNativeMethods, method)) {
    return true;
  }
  // UNSAFE: inherited from Object prototype
  // e.g constructor
  if (hasOwnProperty(Object.prototype, method)) {
    return false;
  }
  // UNSAFE: inherited from Function prototype
  // e.g call, apply
  if (hasOwnProperty(Function.prototype, method)) {
    return false;
  }
  return true;
}

function isPlainObject (object) {
  return typeof object === 'object' && object && object.constructor === Object;
}

var safeNativeProperties = {
  length: true
};

var safeNativeMethods = {
  toString: true,
  valueOf: true,
  toLocaleString: true
};

exports.getSafeProperty = getSafeProperty;
exports.setSafeProperty = setSafeProperty;
exports.isSafeProperty = isSafeProperty;
exports.validateSafeMethod = validateSafeMethod;
exports.isSafeMethod = isSafeMethod;
exports.isPlainObject = isPlainObject;
<|endoftext|>


<commit_before>'use strict';

export function statusCodeType(statusCode) {
  let res = 'success';
  if (statusCode >= 300 && statusCode < 400) {
    res = 'redirect';
  } else if (statusCode >= 400) {
    res = 'error';
  } else if (statusCode < 100) {
    res = 'info';
  }
  return res;
}
<commit_msg>statusCodeType fix<commit_after>'use strict';

export function statusCodeType(statusCode) {
  if (statusCode < 100 || statusCode > 599) {
    throw 'invalid HTTP code';
  }
  let res = 'success';
  if (statusCode >= 300 && statusCode < 400) {
    res = 'redirect';
  } else if (statusCode >= 400) {
    res = 'error';
  } else if (statusCode < 200) {
    res = 'info';
  }
  return res;
}
<|endoftext|>


<commit_before>'use strict';

const execa = require('execa');
const log = require('npmlog');
const Bluebird = require('bluebird');
const EventEmitter = require('events').EventEmitter;

const isWin = require('./is-win')();

module.exports = class Process extends EventEmitter {
  constructor(name, options, process) {
    super();

    this.name = name;
    this.killTimeout = options.killTimeout;
    this.process = process;
    this.stdout = '';
    this.stderr = '';
    this.process.stdout.on('data', chunk => {
      this.stdout += chunk;
      this.emit('out');
    });
    this.process.stderr.on('data', chunk => {
      if (chunk.indexOf('[warn] kevent: Invalid argument') >= 0) {
        return;
      }
      this.stderr += chunk;
    });

    this.process.on('close', this.onClose.bind(this));
    this.process.on('error', this.onError.bind(this));
  }

  onKillTimeout() {
    log.warn('Process ' + this.name + ' not terminated in ' + this.killTimeout + 'ms.');
    kill(this.process, 'SIGKILL');
  }

  onClose(code) {
    if (!this.process) {
      return;
    }
    log.warn(this.name + ' closed', code);
    this.process = null;
    this.exitCode = code;
    this.emit('processExit', code, this.stdout, this.stderr);
  }

  onError(error) {
    log.warn(this.name + ' errored', error);
    this.process = null;
    this.exitCode = 1;
    this.emit('processError', error, this.stdout, this.stderr);
  }

  onStdOut(pattern, fn, timeout) {
    let self = this;
    let timeoutID;

    let listener = () => {
      if (self.patternMatches(pattern)) {
        if (timeoutID) {
          clearTimeout(timeoutID);
        }
        return fn(null, self.stdout, self.stderr);
      }
    };

    this.on('out', listener);

    if (timeout) {
      timeoutID = setTimeout(() => {
        self.removeListener('out', listener);
        return fn(new Error('Timed out without seeing "' + pattern + '"'), self.stdout, self.stderr);
      }, timeout);
    }
  }

  patternMatches(pattern) {
    if (typeof pattern === 'string') {
      return this.stdout.indexOf(pattern) !== -1;
    } else { // regex
      return !!this.stdout.match(pattern);
    }
  }

  kill(sig) {
    if (!this.process) {
      log.info('Process ' + this.name + ' already killed.');

      return Bluebird.resolve(this.exitCode);
    }

    sig = sig || 'SIGTERM';

    let self = this;

    return new Bluebird.Promise(resolve => {
      self.process.once('close', (code, sig) => {
        self.process = null;
        if (self._killTimer) {
          clearTimeout(self._killTimer);
          self._killTimer = null;
        }
        log.info('Process ' + self.name + ' terminated.', code, sig);

        resolve(code);
      });
      self.process.on('error', err => {
        log.error('Error killing process ' + self.name + '.', err);
      });
      self._killTimer = setTimeout(self.onKillTimeout.bind(self), self.killTimeout);
      kill(self.process, sig);
    });
  }
};

// Kill process and all child processes cross platform
function kill(p, sig) {
  if (isWin) {
    let command = 'taskkill.exe';
    let args = ['/t', '/pid', p.pid];
    if (sig === 'SIGKILL') {
      args.push('/f');
    }

    execa(command, args).then(result => {
      // Processes without windows can't be killed without /F, detect and force
      // kill them directly
      if (result.stderr.indexOf('can only be terminated forcefully') !== -1) {
        kill(p, 'SIGKILL');
      }
    }).catch(err => {
      log.error(err);
    });
  } else {
    p.kill(sig);
  }
}
<commit_msg>Check for self.process before calling kill<commit_after>'use strict';

const execa = require('execa');
const log = require('npmlog');
const Bluebird = require('bluebird');
const EventEmitter = require('events').EventEmitter;

const isWin = require('./is-win')();

module.exports = class Process extends EventEmitter {
  constructor(name, options, process) {
    super();

    this.name = name;
    this.killTimeout = options.killTimeout;
    this.process = process;
    this.stdout = '';
    this.stderr = '';
    this.process.stdout.on('data', chunk => {
      this.stdout += chunk;
      this.emit('out');
    });
    this.process.stderr.on('data', chunk => {
      if (chunk.indexOf('[warn] kevent: Invalid argument') >= 0) {
        return;
      }
      this.stderr += chunk;
    });

    this.process.on('close', this.onClose.bind(this));
    this.process.on('error', this.onError.bind(this));
  }

  onKillTimeout() {
    log.warn('Process ' + this.name + ' not terminated in ' + this.killTimeout + 'ms.');
    kill(this.process, 'SIGKILL');
  }

  onClose(code) {
    if (!this.process) {
      return;
    }
    log.warn(this.name + ' closed', code);
    this.process = null;
    this.exitCode = code;
    this.emit('processExit', code, this.stdout, this.stderr);
  }

  onError(error) {
    log.warn(this.name + ' errored', error);
    this.process = null;
    this.exitCode = 1;
    this.emit('processError', error, this.stdout, this.stderr);
  }

  onStdOut(pattern, fn, timeout) {
    let self = this;
    let timeoutID;

    let listener = () => {
      if (self.patternMatches(pattern)) {
        if (timeoutID) {
          clearTimeout(timeoutID);
        }
        return fn(null, self.stdout, self.stderr);
      }
    };

    this.on('out', listener);

    if (timeout) {
      timeoutID = setTimeout(() => {
        self.removeListener('out', listener);
        return fn(new Error('Timed out without seeing "' + pattern + '"'), self.stdout, self.stderr);
      }, timeout);
    }
  }

  patternMatches(pattern) {
    if (typeof pattern === 'string') {
      return this.stdout.indexOf(pattern) !== -1;
    } else { // regex
      return !!this.stdout.match(pattern);
    }
  }

  kill(sig) {
    if (!this.process) {
      log.info('Process ' + this.name + ' already killed.');

      return Bluebird.resolve(this.exitCode);
    }

    sig = sig || 'SIGTERM';

    let self = this;

    return new Bluebird.Promise(resolve => {
      self.process.once('close', (code, sig) => {
        self.process = null;
        if (self._killTimer) {
          clearTimeout(self._killTimer);
          self._killTimer = null;
        }
        log.info('Process ' + self.name + ' terminated.', code, sig);

        resolve(code);
      });
      self.process.on('error', err => {
        log.error('Error killing process ' + self.name + '.', err);
      });
      self._killTimer = setTimeout(self.onKillTimeout.bind(self), self.killTimeout);

      // Check for self.process to make sure the process is still available.
      // Otherwise don't do anything.
      // See https://github.com/testem/testem/pull/1335 for more information.
      if (self.process) {
        kill(self.process, sig);
      } else {
        log.info('Process ' + this.name + ' already killed.');
      }
    });
  }
};

// Kill process and all child processes cross platform
function kill(p, sig) {
  if (isWin) {
    let command = 'taskkill.exe';
    let args = ['/t', '/pid', p.pid];
    if (sig === 'SIGKILL') {
      args.push('/f');
    }

    execa(command, args).then(result => {
      // Processes without windows can't be killed without /F, detect and force
      // kill them directly
      if (result.stderr.indexOf('can only be terminated forcefully') !== -1) {
        kill(p, 'SIGKILL');
      }
    }).catch(err => {
      log.error(err);
    });
  } else {
    p.kill(sig);
  }
}
<|endoftext|>


<commit_before>'use strict';

var fileTool  = require('../utils/file-tool');
var Promise   = require('../ext/promise');
var extend    = require('extend');
var chalk     = require('chalk');
var async     = require('async');
var path      = require('path');
var mime      = require('mime');
var fs        = require('fs');
var execSync  = require('sync-exec');

mime.default_type = 'text/plain';

/**
 *  Sets the correct bucket for the s3 instance
 *   incase the wrong or no region was provided
 *
 *  @method updateBucketLocation
 *  @param {Object} s3 an S3 instance
 *  @param {String} loc The region of the bucket
 */
function updateBucketLocation(s3, loc) {
  var location = s3.config.region;
  if (location !== loc.LocationConstraint) {
    s3.config.region = loc.LocationConstraint;
  }
}

/**
 *
 *
 *  @method validateBucket
 *  @param {Object} s3 an S3 instance
 *  @param {Object} ui
 */
module.exports.validateBucket = function(s3, ui) {
  var getBucketLocation = Promise.denodeify(s3.getBucketLocation.bind(s3));

  ui.pleasantProgress.start(chalk.green('Verifying bucket'), chalk.green('.'));

  return getBucketLocation().then(function(locData) {
      ui.pleasantProgress.stop();
      ui.writeLine(chalk.green('Bucket found: ') + s3.config.params.Bucket);
      updateBucketLocation(s3, locData);
      return locData;

    }, function(err) {
      ui.writeLine(chalk.red('Error locating bucket: ') + s3.config.params.Bucket);
      throw err;
    });
}

/**
 *
 *
 *  @method uploadDirectory
 *  @param {Object} s3 an S3 instance
 *  @param {Object} ui
 *  @param {String} dir The directory to upload to s3
 *  @param {Options} options The options hash of cl
 */
module.exports.uploadDirectory = function(s3, ui, dir, options) {
    var prependPath = s3.config.prependPath || '';
    var bucketPath, params, filePath;

  var queue = async.queue(function(file, callback) {

    filePath = path.join(prependPath, file.name);

    params = buildFileParameters(file.fullPath, {
      Key: filePath,
      ContentLength: file.size
    });

    module.exports.uploadFile(s3, ui, file.fullPath, params).then(function(data) {
      callback();
    }, function(err) {
      callback(err);
    });

  }, 2);

  return new Promise(function(resolve, reject) {
    bucketPath = prependPath ? s3.config.params.Bucket + '/' + prependPath : s3.config.params.Bucket;

    ui.pleasantProgress.start(chalk.green('Uploading files to ') + bucketPath, chalk.green('.'));

    queue.drain = function() {
      ui.pleasantProgress.stop();
      return resolve();
    }

    fileTool.readDirectory(dir)
      .then(function(files) {

        files.forEach(function(file) {
          queue.push({
            fullPath: file.fullPath,
            name: file.path,
            size: file.stat.size
          }, function(err) {
            if (err) {
              throw err
            };
          });
        });

      }, function(err) {
        return reject(err);
      })
      .catch(function(err) {
        return reject(err);
      });
    });
}

/**
 *
 *
 *  @method uploadFile
 *  @param {Object} s3 an S3 instance
 *  @param {Object} ui
 *  @param {String} fullPath The full path of the file to upload
 *  @params {Object} params Parameters containing file details
 */
module.exports.uploadFile = function(s3, ui, fullPath, params) {
  var params = params || {};
  var putObject = Promise.denodeify(s3.putObject.bind(s3));
  var fileStream = fs.createReadStream(fullPath);
  var fileName = path.basename(fullPath);

  params.Body = fileStream;
  params.Key = params.Key ? params.Key : fileName;

  return putObject(params).then(function(data) {
    ui.writeLine(chalk.green('Upload complete: ') + fullPath);
    return data;
  }, function(err) {
    ui.writeLine(chalk.red('Upload error: ') + fullPath);
    return Promise.reject(err);
  });
}

/**
 *
 *
 *  @method buildFileParameters
 *  @param {String} filePath file path to be created in s3 bucket
 *  @param {String} fullPath path of file on your hard drive
 *  @param {Object} options
 *  @return {Object} details on a file.
 */
function buildFileParameters(fullPath, options) {
  options = options || {};
  var mimeType = mime.lookup(fullPath);
  var isGzip = !execSync('gzip -t "'+fullPath+'" 2> /dev/null').status;
  var params = {
    ACL: 'public-read',
    CacheControl: "max-age=31536000, public",
    ContentType: mimeType
  };
  if (isGzip) {
    params.ContentEncoding = 'gzip';
  }
  return extend(params, options);
}
<commit_msg>Changed s3-tool.js to write index.html last and have no cache on that file<commit_after>'use strict';

var fileTool  = require('../utils/file-tool');
var Promise   = require('../ext/promise');
var extend    = require('extend');
var chalk     = require('chalk');
var async     = require('async');
var path      = require('path');
var mime      = require('mime');
var fs        = require('fs');
var execSync  = require('sync-exec');

mime.default_type = 'text/plain';

/**
 *  Sets the correct bucket for the s3 instance
 *   incase the wrong or no region was provided
 *
 *  @method updateBucketLocation
 *  @param {Object} s3 an S3 instance
 *  @param {String} loc The region of the bucket
 */
function updateBucketLocation(s3, loc) {
  var location = s3.config.region;
  if (location !== loc.LocationConstraint) {
    s3.config.region = loc.LocationConstraint;
  }
}

/**
 *
 *
 *  @method validateBucket
 *  @param {Object} s3 an S3 instance
 *  @param {Object} ui
 */
module.exports.validateBucket = function(s3, ui) {
  var getBucketLocation = Promise.denodeify(s3.getBucketLocation.bind(s3));

  ui.pleasantProgress.start(chalk.green('Verifying bucket'), chalk.green('.'));

  return getBucketLocation().then(function(locData) {
      ui.pleasantProgress.stop();
      ui.writeLine(chalk.green('Bucket found: ') + s3.config.params.Bucket);
      updateBucketLocation(s3, locData);
      return locData;

    }, function(err) {
      ui.writeLine(chalk.red('Error locating bucket: ') + s3.config.params.Bucket);
      throw err;
    });
}

/**
 *
 *
 *  @method uploadDirectory
 *  @param {Object} s3 an S3 instance
 *  @param {Object} ui
 *  @param {String} dir The directory to upload to s3
 *  @param {Options} options The options hash of cl
 */
module.exports.uploadDirectory = function(s3, ui, dir, options) {
    var prependPath = s3.config.prependPath || '';
    var bucketPath, params, filePath;

  var queue = async.queue(function(file, callback) {

    filePath = path.join(prependPath, file.name);

    params = buildFileParameters(file.fullPath, {
      Key: filePath,
      ContentLength: file.size
    });

    module.exports.uploadFile(s3, ui, file.fullPath, params).then(function(data) {
      callback();
    }, function(err) {
      callback(err);
    });

  }, 2);

  return new Promise(function(resolve, reject) {
    bucketPath = prependPath ? s3.config.params.Bucket + '/' + prependPath : s3.config.params.Bucket;

    ui.pleasantProgress.start(chalk.green('Uploading files to ') + bucketPath, chalk.green('.'));

    queue.drain = function() {
      ui.pleasantProgress.stop();
      return resolve();
    }

    fileTool.readDirectory(dir)
      .then(function(files) {

        files.forEach(function(file) {
          if ( file.fullPath.indexOf("index.html", file.fullPath.length - "index.html".length) === -1 ) {
            ui.writeLine(chalk.green('Added ' + file.fullPath + ' to queue'));
            queue.push({
              fullPath: file.fullPath,
              name: file.path,
              size: file.stat.size
            }, function(err) {
              if (err) {
                throw err
              };
            });
          }
        });

		files.forEach(function(file) {
          if ( file.fullPath.indexOf("index.html", file.fullPath.length - "index.html".length) !== -1 ) {
            ui.writeLine(chalk.green('Added ' + file.fullPath + ' to queue'));
            queue.push({
              fullPath: file.fullPath,
              name: file.path,
              size: file.stat.size
            }, function(err) {
              if (err) {
                throw err
              };
            });
          }
        });

      }, function(err) {
        return reject(err);
      })
      .catch(function(err) {
        return reject(err);
      });
    });
}

/**
 *
 *
 *  @method uploadFile
 *  @param {Object} s3 an S3 instance
 *  @param {Object} ui
 *  @param {String} fullPath The full path of the file to upload
 *  @params {Object} params Parameters containing file details
 */
module.exports.uploadFile = function(s3, ui, fullPath, params) {
  var params = params || {};
  var putObject = Promise.denodeify(s3.putObject.bind(s3));
  var fileStream = fs.createReadStream(fullPath);
  var fileName = path.basename(fullPath);

  params.Body = fileStream;
  params.Key = params.Key ? params.Key : fileName;
  if (fileName == 'index.html' ) {
    params.CacheControl = "no-cache, must-revalidate";
    ui.writeLine(chalk.green('No Cache for index set'));
  }

  return putObject(params).then(function(data) {
    ui.writeLine(chalk.green('Upload complete: ') + fullPath);
    return data;
  }, function(err) {
    ui.writeLine(chalk.red('Upload error: ') + fullPath);
    return Promise.reject(err);
  });
}

/**
 *
 *
 *  @method buildFileParameters
 *  @param {String} filePath file path to be created in s3 bucket
 *  @param {String} fullPath path of file on your hard drive
 *  @param {Object} options
 *  @return {Object} details on a file.
 */
function buildFileParameters(fullPath, options) {
  options = options || {};
  var mimeType = mime.lookup(fullPath);
  var isGzip = !execSync('gzip -t "'+fullPath+'" 2> /dev/null').status;
  var params = {
    ACL: 'public-read',
    CacheControl: "max-age=31536000, public",
    ContentType: mimeType
  };
  if (isGzip) {
    params.ContentEncoding = 'gzip';
  }
  return extend(params, options);
}
<|endoftext|>


<commit_before>var M = process.mono;
var fs = require('fs');
var viewCollection = "m_views";

module.exports = setup;

function setup (instance) {

    // setup view
    instance.on('view>', factoryService);

    // return view factory
    return factory;
}

// get html snipptets (ws)
// TODO cache
function getSnipped (path, callback) {
    var self = this;

    if (!path) {
        return callback('No path given');
    }

    var file = M.config.paths.TEMPLATE_ROOT + path.replace(/[^a-z0-9\/\.\-_]|\.\.\//gi, "");
    fs.readFile(file, {encoding: 'utf8'}, function (err, data) {

        if (err) {
            return callback('File not found');
        }

        callback(null, data);
    });
}

function factory (config, callback) {

     // create cache key
    var cacheKey = (config.project || '') + config.name;

    // check cache
    var view = M.cache.views.get(cacheKey);
    if (view) {
        return callback(null, view);
    }

    // get system store to fetch models
    M.store(M.config.store.systemStoreName, config.project, function (err, systemStore) {

        if (err) {
            return callback(err);
        }

        // get view config
        // TODO check access
        systemStore.collection(viewCollection).findOne({name: config.name}, function (err, view) {

            if (err || !view) {
                return callback(err || 'View not found');
            }

            // get here the html snipped
            getSnipped(view.client.template.html, function (err, snipped) {

                if (err) {
                    return callback(err);
                }

                // add snipped to view
                if (snipped) {
                    view.client.template.html = snipped;
                }

                // save view in cache
                M.cache.views.save(cacheKey, view);

                callback(null, view);
            });
        });
    });
}

function factoryService (err, message) {
    var self = this;

    // check message
    if (!message) {
        return self.emit('<view', 'Bad message');
    }

    // create factory config
    if (typeof message === 'string') {
        message = {name: message};
    } else {
        message = {
            name: message[0],
            project: message[1]
        };
    }

    // create model
    factory(message, function (err, view) {

        if (err) {
            return self.emit('<view', err);
        }

        // create client view
        var clientView = view.client;
        clientView.name = view.name;

        self.emit('<view', null, clientView);
    });
}
<commit_msg>adjust view config format<commit_after>var M = process.mono;
var fs = require('fs');
var viewCollection = "m_views";

module.exports = setup;

function setup (instance) {

    // setup view
    instance.on('view>', factoryService);

    // return view factory
    return factory;
}

// get html snipptets (ws)
// TODO cache
function getSnipped (path, callback) {
    var self = this;

    if (!path) {
        return callback('No path given');
    }

    var file = M.config.paths.TEMPLATE_ROOT + path.replace(/[^a-z0-9\/\.\-_]|\.\.\//gi, "");
    fs.readFile(file, {encoding: 'utf8'}, function (err, data) {

        if (err) {
            return callback('File not found');
        }

        callback(null, data);
    });
}

function factory (config, callback) {

     // create cache key
    var cacheKey = (config.project || '') + config.name;

    // check cache
    var view = M.cache.views.get(cacheKey);
    if (view) {
        return callback(null, view);
    }

    // get system store to fetch models
    M.store(M.config.store.systemStoreName, config.project, function (err, systemStore) {

        if (err) {
            return callback(err);
        }

        // get view config
        // TODO check access
        systemStore.collection(viewCollection).findOne({name: config.name}, function (err, view) {

            if (err || !view) {
                return callback(err || 'View not found');
            }

            // get here the html snipped
            getSnipped(view.client.html, function (err, snipped) {

                if (err) {
                    return callback(err);
                }

                // add snipped to view
                if (snipped) {
                    view.client.html = snipped;
                }

                // save view in cache
                M.cache.views.save(cacheKey, view);

                callback(null, view);
            });
        });
    });
}

function factoryService (err, message) {
    var self = this;

    // check message
    if (!message) {
        return self.emit('<view', 'Bad message');
    }

    // create factory config
    if (typeof message === 'string') {
        message = {name: message};
    } else {
        message = {
            name: message[0],
            project: message[1]
        };
    }

    // create model
    factory(message, function (err, view) {

        if (err) {
            return self.emit('<view', err);
        }

        // create client view
        var clientView = view.client;
        clientView.name = view.name;

        self.emit('<view', null, clientView);
    });
}
<|endoftext|>


<commit_before>var Mustache = require('mustache')
var fs = require('fs')
var _ = require('lodash')

module.exports = function(data, options){

  var chartType = options.chartType

  if (options.location == undefined){
    options.location = __dirname+'/../../templates/_charts/'
  }
  options.id = 'testing'

  options.width = options.width ? options.width = 1200

  //data should simply be a 2d array... That simple.

  forPlotting = []

  data.forEach(function(x){
    switch (x.key) {
        case 'building':
          buildings = _.collect(_.groupBy(x.dates), function(values, date){ return {date: date, value: values.length}})
          forPlotting.push({data: buildings, title: "Buildings"})
          break;
        case 'highway':
          buildings = _.collect(_.groupBy(x.dates), function(values, date){ return {date: date, value: values.length}})
          forPlotting.push({data: buildings, title: "Highways"})
          break;
        default:
          forPlotting.push(x)
      }
  })

  //console.log(forPlotting)

  options.data = JSON.stringify(forPlotting)

  //Pass an array of data

  return Mustache.render(fs.readFileSync(options.location + chartType + ".html", 'utf-8'), options)
}
<commit_msg>updating<commit_after>var Mustache = require('mustache')
var fs = require('fs')
var _ = require('lodash')

module.exports = function(data, options){

  var chartType = options.chartType

  if (options.location == undefined){
    options.location = __dirname+'/../../templates/_charts/'
  }
  options.id = 'testing'

  console.log(options.width)

  //data should simply be a 2d array... That simple.

  forPlotting = []

  data.forEach(function(x){
    switch (x.key) {
        case 'building':
          buildings = _.collect(_.groupBy(x.dates), function(values, date){ return {date: date, value: values.length}})
          forPlotting.push({data: buildings, title: "Buildings"})
          break;
        case 'highway':
          buildings = _.collect(_.groupBy(x.dates), function(values, date){ return {date: date, value: values.length}})
          forPlotting.push({data: buildings, title: "Highways"})
          break;
        default:
          forPlotting.push(x)
      }
  })

  //console.log(forPlotting)

  options.data = JSON.stringify(forPlotting)

  //Pass an array of data

  return Mustache.render(fs.readFileSync(options.location + chartType + ".html", 'utf-8'), options)
}
<|endoftext|>


<commit_before>var path = require("path");
var fs = require("fs");
var net = require("net");
var express = require("express");
var webroot = path.join(__dirname, "..", "www");
var sendJade = require("./jade").sendJade;
var Server = require("../server");
var $util = require("../utilities");
var Logger = require("../logger");
var Config = require("../config");
var db = require("../database");
var bodyParser = require("body-parser");
var cookieParser = require("cookie-parser");
var static = require("serve-static");
var morgan = require("morgan");
var session = require("../session");
var csrf = require("./csrf");

const LOG_FORMAT = ':real-address - :remote-user [:date] ":method :url HTTP/:http-version" :status :res[content-length] ":referrer" ":user-agent"';
morgan.token('real-address', function (req) { return req._ip; });

/**
 * Extracts an IP address from a request.  Uses X-Forwarded-For if the IP is localhost
 */
function ipForRequest(req) {
    var ip = req.ip;
    if (ip === "127.0.0.1" || ip === "::1") {
        var xforward = req.header("x-forwarded-for");
        if (typeof xforward !== "string") {
            xforward = [];
        } else {
            xforward = xforward.split(",");
        }

        for (var i = 0; i < xforward.length; i++) {
            if (net.isIP(xforward[i])) {
                return xforward[i];
            }
        }
        return ip;
    }
    return ip;
}

/**
 * Redirects a request to HTTPS if the server supports it
 */
function redirectHttps(req, res) {
    if (!req.secure && Config.get("https.enabled") && Config.get("https.redirect")) {
        var ssldomain = Config.get("https.full-address");
        if (ssldomain.indexOf(req.hostname) < 0) {
            return false;
        }

        res.redirect(ssldomain + req.path);
        return true;
    }
    return false;
}

/**
 * Redirects a request to HTTP if the server supports it
 */
function redirectHttp(req, res) {
    if (req.secure) {
        var domain = Config.get("http.full-address");
        res.redirect(domain + req.path);
        return true;
    }
    return false;
}

/**
 * Handles a GET request for /r/:channel - serves channel.html
 */
function handleChannel(req, res) {
    if (!$util.isValidChannelName(req.params.channel)) {
        res.status(404);
        res.send("Invalid channel name '" + req.params.channel + "'");
        return;
    }

    var sio;
    if (net.isIPv6(ipForRequest(req))) {
        sio = Config.get("io.ipv6-default");
    }

    if (!sio) {
        sio = Config.get("io.ipv4-default");
    }

    sio += "/socket.io/socket.io.js";

    sendJade(res, "channel", {
        channelName: req.params.channel,
        sioSource: sio
    });
}

/**
 * Handles a request for the index page
 */
function handleIndex(req, res) {
    var channels = Server.getServer().packChannelList(true);
    channels.sort(function (a, b) {
        if (a.usercount === b.usercount) {
            return a.uniqueName > b.uniqueName ? -1 : 1;
        }

        return b.usercount - a.usercount;
    });

    sendJade(res, "index", {
        channels: channels
    });
}

/**
 * Handles a request for the socket.io information
 */
function handleSocketConfig(req, res) {
    res.type("application/javascript");

    var sioconfig = Config.get("sioconfig");
    var iourl;
    var ip = ipForRequest(req);
    var ipv6 = false;

    if (net.isIPv6(ip)) {
        iourl = Config.get("io.ipv6-default");
        ipv6 = true;
    }

    if (!iourl) {
        iourl = Config.get("io.ipv4-default");
    }

    sioconfig += "var IO_URL='" + iourl + "';";
    sioconfig += "var IO_V6=" + ipv6 + ";";
    res.send(sioconfig);
}

function handleUserAgreement(req, res) {
    sendJade(res, "tos", {
        domain: Config.get("http.domain")
    });
}

function handleContactPage(req, res) {
    // Make a copy to prevent messing with the original
    var contacts = Config.get("contacts").map(function (c) {
        return {
            name: c.name,
            email: c.email,
            title: c.title
        };
    });

    // Rudimentary hiding of email addresses to prevent spambots
    contacts.forEach(function (c) {
        c.emkey = $util.randomSalt(16)
        var email = new Array(c.email.length);
        for (var i = 0; i < c.email.length; i++) {
          email[i] = String.fromCharCode(
            c.email.charCodeAt(i) ^ c.emkey.charCodeAt(i % c.emkey.length)
          );
        }
        c.email = escape(email.join(""));
        c.emkey = escape(c.emkey);
    });

    sendJade(res, "contact", {
        contacts: contacts
    });
}

module.exports = {
    /**
     * Initializes webserver callbacks
     */
    init: function (app) {
        app.use(function (req, res, next) {
            req._ip = ipForRequest(req);
            next();
        });
        app.use(bodyParser.urlencoded({
            extended: false,
            limit: '1kb' // No POST data should ever exceed this size under normal usage
        }));
        if (Config.get("http.cookie-secret") === "change-me") {
            Logger.errlog.log("YOU SHOULD CHANGE THE VALUE OF cookie-secret IN config.yaml");
        }
        app.use(cookieParser(Config.get("http.cookie-secret")));
        app.use(csrf.init(Config.get("http.root-domain-dotted")));
        app.use(morgan(LOG_FORMAT, {
            stream: require("fs").createWriteStream(path.join(__dirname, "..", "..",
            "http.log"), {
                flags: "a",
                encoding: "utf-8"
            })
        }));

        app.use(function (req, res, next) {
            if (req.path.match(/^\/(css|js|img|boop).*$/)) {
                return next();
            }

            if (!req.signedCookies || !req.signedCookies.auth) {
                return next();
            }

            session.verifySession(req.signedCookies.auth, function (err, account) {
                if (!err) {
                    req.user = res.user = account;
                }

                next();
            });
        });

        if (Config.get("http.gzip")) {
            app.use(require("compression")({ threshold: Config.get("http.gzip-threshold") }));
            Logger.syslog.log("Enabled gzip compression");
        }

        if (Config.get("http.minify")) {
            var cache = path.join(__dirname, "..", "..", "www", "cache")
            if (!fs.existsSync(cache)) {
                fs.mkdirSync(cache);
            }
            app.use(require("express-minify")({
                cache: cache
            }));
            Logger.syslog.log("Enabled express-minify for CSS and JS");
        }

        app.get("/r/:channel", handleChannel);
        app.get("/", handleIndex);
        app.get("/sioconfig", handleSocketConfig);
        app.get("/useragreement", handleUserAgreement);
        app.get("/contact", handleContactPage);
        require("./auth").init(app);
        require("./account").init(app);
        require("./acp").init(app);
        app.use(static(path.join(__dirname, "..", "..", "www"), {
            maxAge: Config.get("http.max-age") || Config.get("http.cache-ttl")
        }));
        app.use(function (err, req, res, next) {
            if (err) {
                if (err.message && err.message.match(/failed to decode param/i)) {
                    return res.status(400).send("Malformed path: " + req.path);
                } else if (err.message && err.message.match(/requested range not/i)) {
                    return res.status(416).end();
                } else if (err.message && err.message.match(/request entity too large/i)) {
                    return res.status(413).end();
                } else if (err.message && err.message.match(/bad request/i)) {
                    return res.status(400).end("Bad Request");
                } else if (err.message && err.message.match(/invalid csrf token/i)) {
                    res.status(403);
                    sendJade(res, 'csrferror', { path: req.path });
                    return;
                }
                Logger.errlog.log(err.stack);
                res.status(500).end();
            } else {
                next();
            }
        });
    },

    ipForRequest: ipForRequest,

    redirectHttps: redirectHttps,

    redirectHttp: redirectHttp
};
<commit_msg>Sanitized output of channel name in invalid channel<commit_after>var path = require("path");
var fs = require("fs");
var net = require("net");
var express = require("express");
var webroot = path.join(__dirname, "..", "www");
var sendJade = require("./jade").sendJade;
var Server = require("../server");
var $util = require("../utilities");
var Logger = require("../logger");
var Config = require("../config");
var db = require("../database");
var bodyParser = require("body-parser");
var cookieParser = require("cookie-parser");
var static = require("serve-static");
var morgan = require("morgan");
var session = require("../session");
var csrf = require("./csrf");
var XSS = require("../xss");

const LOG_FORMAT = ':real-address - :remote-user [:date] ":method :url HTTP/:http-version" :status :res[content-length] ":referrer" ":user-agent"';
morgan.token('real-address', function (req) { return req._ip; });

/**
 * Extracts an IP address from a request.  Uses X-Forwarded-For if the IP is localhost
 */
function ipForRequest(req) {
    var ip = req.ip;
    if (ip === "127.0.0.1" || ip === "::1") {
        var xforward = req.header("x-forwarded-for");
        if (typeof xforward !== "string") {
            xforward = [];
        } else {
            xforward = xforward.split(",");
        }

        for (var i = 0; i < xforward.length; i++) {
            if (net.isIP(xforward[i])) {
                return xforward[i];
            }
        }
        return ip;
    }
    return ip;
}

/**
 * Redirects a request to HTTPS if the server supports it
 */
function redirectHttps(req, res) {
    if (!req.secure && Config.get("https.enabled") && Config.get("https.redirect")) {
        var ssldomain = Config.get("https.full-address");
        if (ssldomain.indexOf(req.hostname) < 0) {
            return false;
        }

        res.redirect(ssldomain + req.path);
        return true;
    }
    return false;
}

/**
 * Redirects a request to HTTP if the server supports it
 */
function redirectHttp(req, res) {
    if (req.secure) {
        var domain = Config.get("http.full-address");
        res.redirect(domain + req.path);
        return true;
    }
    return false;
}

/**
 * Handles a GET request for /r/:channel - serves channel.html
 */
function handleChannel(req, res) {
    if (!$util.isValidChannelName(req.params.channel)) {
        res.status(404);
        res.send("Invalid channel name '" + XSS.sanitizeText(req.params.channel) + "'");
        return;
    }

    var sio;
    if (net.isIPv6(ipForRequest(req))) {
        sio = Config.get("io.ipv6-default");
    }

    if (!sio) {
        sio = Config.get("io.ipv4-default");
    }

    sio += "/socket.io/socket.io.js";

    sendJade(res, "channel", {
        channelName: req.params.channel,
        sioSource: sio
    });
}

/**
 * Handles a request for the index page
 */
function handleIndex(req, res) {
    var channels = Server.getServer().packChannelList(true);
    channels.sort(function (a, b) {
        if (a.usercount === b.usercount) {
            return a.uniqueName > b.uniqueName ? -1 : 1;
        }

        return b.usercount - a.usercount;
    });

    sendJade(res, "index", {
        channels: channels
    });
}

/**
 * Handles a request for the socket.io information
 */
function handleSocketConfig(req, res) {
    res.type("application/javascript");

    var sioconfig = Config.get("sioconfig");
    var iourl;
    var ip = ipForRequest(req);
    var ipv6 = false;

    if (net.isIPv6(ip)) {
        iourl = Config.get("io.ipv6-default");
        ipv6 = true;
    }

    if (!iourl) {
        iourl = Config.get("io.ipv4-default");
    }

    sioconfig += "var IO_URL='" + iourl + "';";
    sioconfig += "var IO_V6=" + ipv6 + ";";
    res.send(sioconfig);
}

function handleUserAgreement(req, res) {
    sendJade(res, "tos", {
        domain: Config.get("http.domain")
    });
}

function handleContactPage(req, res) {
    // Make a copy to prevent messing with the original
    var contacts = Config.get("contacts").map(function (c) {
        return {
            name: c.name,
            email: c.email,
            title: c.title
        };
    });

    // Rudimentary hiding of email addresses to prevent spambots
    contacts.forEach(function (c) {
        c.emkey = $util.randomSalt(16)
        var email = new Array(c.email.length);
        for (var i = 0; i < c.email.length; i++) {
          email[i] = String.fromCharCode(
            c.email.charCodeAt(i) ^ c.emkey.charCodeAt(i % c.emkey.length)
          );
        }
        c.email = escape(email.join(""));
        c.emkey = escape(c.emkey);
    });

    sendJade(res, "contact", {
        contacts: contacts
    });
}

module.exports = {
    /**
     * Initializes webserver callbacks
     */
    init: function (app) {
        app.use(function (req, res, next) {
            req._ip = ipForRequest(req);
            next();
        });
        app.use(bodyParser.urlencoded({
            extended: false,
            limit: '1kb' // No POST data should ever exceed this size under normal usage
        }));
        if (Config.get("http.cookie-secret") === "change-me") {
            Logger.errlog.log("YOU SHOULD CHANGE THE VALUE OF cookie-secret IN config.yaml");
        }
        app.use(cookieParser(Config.get("http.cookie-secret")));
        app.use(csrf.init(Config.get("http.root-domain-dotted")));
        app.use(morgan(LOG_FORMAT, {
            stream: require("fs").createWriteStream(path.join(__dirname, "..", "..",
            "http.log"), {
                flags: "a",
                encoding: "utf-8"
            })
        }));

        app.use(function (req, res, next) {
            if (req.path.match(/^\/(css|js|img|boop).*$/)) {
                return next();
            }

            if (!req.signedCookies || !req.signedCookies.auth) {
                return next();
            }

            session.verifySession(req.signedCookies.auth, function (err, account) {
                if (!err) {
                    req.user = res.user = account;
                }

                next();
            });
        });

        if (Config.get("http.gzip")) {
            app.use(require("compression")({ threshold: Config.get("http.gzip-threshold") }));
            Logger.syslog.log("Enabled gzip compression");
        }

        if (Config.get("http.minify")) {
            var cache = path.join(__dirname, "..", "..", "www", "cache")
            if (!fs.existsSync(cache)) {
                fs.mkdirSync(cache);
            }
            app.use(require("express-minify")({
                cache: cache
            }));
            Logger.syslog.log("Enabled express-minify for CSS and JS");
        }

        app.get("/r/:channel", handleChannel);
        app.get("/", handleIndex);
        app.get("/sioconfig", handleSocketConfig);
        app.get("/useragreement", handleUserAgreement);
        app.get("/contact", handleContactPage);
        require("./auth").init(app);
        require("./account").init(app);
        require("./acp").init(app);
        app.use(static(path.join(__dirname, "..", "..", "www"), {
            maxAge: Config.get("http.max-age") || Config.get("http.cache-ttl")
        }));
        app.use(function (err, req, res, next) {
            if (err) {
                if (err.message && err.message.match(/failed to decode param/i)) {
                    return res.status(400).send("Malformed path: " + req.path);
                } else if (err.message && err.message.match(/requested range not/i)) {
                    return res.status(416).end();
                } else if (err.message && err.message.match(/request entity too large/i)) {
                    return res.status(413).end();
                } else if (err.message && err.message.match(/bad request/i)) {
                    return res.status(400).end("Bad Request");
                } else if (err.message && err.message.match(/invalid csrf token/i)) {
                    res.status(403);
                    sendJade(res, 'csrferror', { path: req.path });
                    return;
                }
                Logger.errlog.log(err.stack);
                res.status(500).end();
            } else {
                next();
            }
        });
    },

    ipForRequest: ipForRequest,

    redirectHttps: redirectHttps,

    redirectHttp: redirectHttp
};
<|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.
 *
*/

/*jslint sloppy:true, plusplus:true*/
/*global require, module, console */

var cordova = require('cordova');
var commandProxy = require('cordova/windows8/commandProxy');

/**
 * Execute a cordova command.  It is up to the native side whether this action
 * is synchronous or asynchronous.  The native side can return:
 *      Synchronous: PluginResult object as a JSON string
 *      Asynchronous: Empty string ""
 * If async, the native side will cordova.callbackSuccess or cordova.callbackError,
 * depending upon the result of the action.
 *
 * @param {Function} success    The success callback
 * @param {Function} fail       The fail callback
 * @param {String} service      The name of the service to use
 * @param {String} action       Action to be run in cordova
 * @param {String[]} [args]     Zero or more arguments to pass to the method
 */
module.exports = function (success, fail, service, action, args) {

    var proxy = commandProxy.get(service, action),
        callbackId;

    if (proxy) {
        callbackId = service + cordova.callbackId++;
        // console.log("EXEC:" + service + " : " + action);
        if (typeof success === "function" || typeof fail === "function") {
            cordova.callbacks[callbackId] = {success: success, fail: fail};
        }
        try {
            proxy(success, fail, args);
        } catch (e) {
            console.log("Exception calling native with command :: " + service + " :: " + action  + " ::exception=" + e);
        }
    } else {
        return (fail && fail("Missing Command Error"));
    }
};
<commit_msg>[CB-4905] CordovaJS on Windows8 has memoryleak on exec.js<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.
 *
*/

/*jslint sloppy:true, plusplus:true*/
/*global require, module, console */

var cordova = require('cordova');
var commandProxy = require('cordova/windows8/commandProxy');

/**
 * Execute a cordova command.  It is up to the native side whether this action
 * is synchronous or asynchronous.  The native side can return:
 *      Synchronous: PluginResult object as a JSON string
 *      Asynchronous: Empty string ""
 * If async, the native side will cordova.callbackSuccess or cordova.callbackError,
 * depending upon the result of the action.
 *
 * @param {Function} success    The success callback
 * @param {Function} fail       The fail callback
 * @param {String} service      The name of the service to use
 * @param {String} action       Action to be run in cordova
 * @param {String[]} [args]     Zero or more arguments to pass to the method
 */
module.exports = function (success, fail, service, action, args) {

    var proxy = commandProxy.get(service, action),
        callbackId,
        onSuccess,
        onError;

    if (proxy) {
        callbackId = service + cordova.callbackId++;
        // console.log("EXEC:" + service + " : " + action);
        if (typeof success === "function" || typeof fail === "function") {
            cordova.callbacks[callbackId] = {success: success, fail: fail};
        }
        try {
            onSuccess = function (result) {
                cordova.callbackSuccess(callbackId,
                        {
                        status: cordova.callbackStatus.OK,
                        message: result
                    });
            };
            onError = function (err) {
                cordova.callbackError(callbackId,
                        {
                        status: cordova.callbackStatus.ERROR,
                        message: err
                    });
            };
            proxy(onSuccess, onError, args);

        } catch (e) {
            console.log("Exception calling native with command :: " + service + " :: " + action  + " ::exception=" + e);
        }
    } else {
        if (typeof fail === "function") {
            fail("Missing Command Error");
        }
    }
};
<|endoftext|>


<commit_before>/*
 * winston-redis.js: A fixed-length Redis transport for Winston
 *
 * (C) 2011, Charlie Robbins
 *
 */

var redis = require('redis'),
    winston = require('winston'),
    common = require('winston/lib/winston/common'),
    util = require('util'),
    Stream = require('stream').Stream,
    async = require('async'),
    _ = require('lodash');

var Redis = exports.Redis = function (options) {
  winston.Transport.call(this, options);

  var self = this;

  options       = options || {};

  this.name      = 'redis';

  if (options.redis instanceof redis.RedisClient) {
    this.redis = options.redis;
  } else if (options.redis instanceof Object) {
    this.redis = redis.createClient(options.redis);
  } else {
    options.host  = options.host || 'localhost';
    options.port  = options.port || 6379;
    this.redis = redis.createClient(options.port, options.host);
  }

  this.json      = options.json !== false;
  this.length    = options.length    || 200;
  this.container = options.container || 'winston';
  this.timestamp = options.timestamp || true;
  this.channel   = options.pchannel || options.channel;
  this.pattern   = options.pattern || !!options.pchannel;
  this.logstash  = options.logstash === true;
  this.metadata  = options.meta || {};

  if (options.auth) {
    this.redis.auth(options.auth);
  }

  // Suppress errors from the Redis client
  this.redis.on('error', function (err) {
    self.emit('error', err);
  });

  if (typeof this.container !== 'function') {
    var container = this.container;
    this.container = function () {
      return container;
    };
  }

  if (this.channel && typeof this.channel !== 'function') {
    var channel = this.channel;
    this.channel = function () {
      return channel;
    };
  }
};

//
// Inherit from `winston.Transport`.
//
util.inherits(Redis, winston.Transport);

//
// Expose the name of this Transport on the prototype
//
Redis.prototype.name = 'redis';

//
// Define a getter so that `winston.transports.Redis`
// is available and thus backwards compatible.
//
winston.transports.Redis = Redis;

//
// ### function log (level, msg, [meta], callback)
// #### @level {string} Level at which to log the message.
// #### @msg {string} Message to log
// #### @meta {Object} **Optional** Additional metadata to attach
// #### @callback {function} Continuation to respond to when complete.
// Core logging method exposed to Winston. Metadata is optional.
//
Redis.prototype.log = function (level, msg, meta, callback) {
  var self = this,
      container = this.container(meta),
      channel = this.channel && this.channel(meta);

  var output = common.log({
    level:       level,
    message:     msg,
    meta:        _.merge(meta, this.metadata),
    json:        this.json,
    logstash:    this.logstash,
    colorize:    this.colorize,
    prettyPrint: this.prettyPrint,
    timestamp:   this.timestamp,
    showLevel:   this.showLevel,
    stringify:   this.stringify,
    label:       this.label,
    depth:       this.depth,
    formatter:   this.formatter,
    humanReadableUnhandledException: this.humanReadableUnhandledException
  });

  async.series([
    function(cb) {
      self.redis.lpush(container, output, cb);
    },
    function(cb) {
      self.redis.ltrim(container, 0, self.length, cb);
    }
  ], function(err) {
    if (err) {
      if (callback) callback(err, false);
      return self.emit('error', err);
    }

    if (channel) {
      self.redis.publish(channel, output);
    }

    // TODO: emit 'logged' correctly,
    // keep track of pending logs.
    self.emit('logged');

    if (callback) callback(null, true);
  });
};

//
// ### function query (options, callback)
// #### @options {Object} Loggly-like query options for this instance.
// #### @callback {function} Continuation to respond to when complete.
// Query the transport. Options object is optional.
//
Redis.prototype.query = function (options, callback) {
  if (typeof options === 'function') {
    callback = options;
    options = {};
  }

  var options = this.normalizeQuery(options),
      start = options.start || 0,
      end = options.rows + start,
      container = this.container(options);

  this.redis.lrange(container, start, end - 1, function (err, results) {
    if (err) return callback(err);

    results = results.map(function (data) {
      var log, time, obj;

      try {
        log = JSON.parse(data);
      } catch (e) {
        return;
      }

      if (typeof log !== 'object' || !log) return;

      time = new Date(log.timestamp);
      if ((options.from && time < options.from)
         || (options.until && time > options.until)) {
        return;
      }

      if (options.fields) {
        obj = {};
        options.fields.forEach(function (key) {
          obj[key] = log[key];
        });
        log = obj;
      }

      return log;
    }).filter(Boolean);

    if (options.order !== 'desc') {
      results = results.reverse();
    }

    callback(null, results);
  });
};

//
// ### function stream (options)
// #### @options {Object} Stream options for this instance.
// Returns a log stream for this transport. Options object is optional.
// This will use Redis' builtin pubsub capabilities.
// http://redis.io/topics/pubsub
//
Redis.prototype.stream = function (options) {
  var self = this,
      options = options || {},
      stream = new Stream,
      container = this.container(options),
      channel = this.channel(options);

  stream.destroy = function () {
    if (this.destroyed) return;

    this.destroyed = true;

    var i = self.subscription.__channels[channel].indexOf(message);
    if (~i) self.subscription.__channels[channel].splice(i, 1);

    if (!self.subscription.__channels[channel].length) {
      self.subscription.punsubscribe(channel);
      delete self.subscription.__channels[channel];
    }

    if (!Object.keys(self.subscription.__channels).length) {
      try {
        self.subscription.end(false);
        self.subscription.stream.destroy();
      } catch (e) {
        ;
      }
      delete self.subscription;
    }
  };

  if (!this.subscription) {
    this.subscription = redis.createClient(this.redis.options);
    this.subscription.__channels = {};
    this.subscription.on('pmessage', function (pattern, channel, message) {
      var listeners = self.subscription.__channels[pattern];
      if (!listeners) return;
      listeners.forEach(function (listener) {
        listener.call(self.subscription, pattern, channel, message);
      });
    });
  }

  if (!this.subscription.__channels[channel]) {
    this.subscription.psubscribe(channel);
    this.subscription.__channels[channel] = [];
  }

  this.subscription.__channels[channel].push(message);

  function message(pattern, channel, message) {
    if (stream.destroyed) return;

    try {
      message = JSON.parse(message);
    } catch (e) {
      return stream.emit('error',
        new Error('Could not parse: "' + message + '".'));
    }

    stream.emit('log', message);
  }

  if (options.start === -1) {
    delete options.start;
  }

  if (options.start == null) {
    return stream;
  }

  this.redis.lrange(container, options.start, -1, function (err, results) {
    if (stream.destroyed) return;

    if (err) {
      return stream.emit('error', err);
    }

    results.forEach(function (log) {
      try {
        stream.emit('log', JSON.parse(log));
      } catch (e) {
        return stream.emit('error',
          new Error('Could not parse: "' + log + '".'));
      }
    });
  });

  return stream;
};

//Close Connection to redis Server
//Winston will call close function from clear/remove to attempt to cleanly exit.
Redis.prototype.close = function(){
  if (this.redis)
    this.redis.end(false);
};
<commit_msg>do not modify provided redis client<commit_after>/*
 * winston-redis.js: A fixed-length Redis transport for Winston
 *
 * (C) 2011, Charlie Robbins
 *
 */

var redis = require('redis'),
    winston = require('winston'),
    common = require('winston/lib/winston/common'),
    util = require('util'),
    Stream = require('stream').Stream,
    async = require('async'),
    _ = require('lodash');

var Redis = exports.Redis = function (options) {
  winston.Transport.call(this, options);

  var self = this;

  options       = options || {};

  this.name      = 'redis';

  if (options.redis instanceof redis.RedisClient) {
    this.redis = options.redis;
  } else if (options.redis instanceof Object) {
    this.redis = redis.createClient(options.redis);
    this.createdClient = true;
  } else {
    options.host  = options.host || 'localhost';
    options.port  = options.port || 6379;
    this.redis = redis.createClient(options.port, options.host);
    this.createdClient = true;
  }

  this.json      = options.json !== false;
  this.length    = options.length    || 200;
  this.container = options.container || 'winston';
  this.timestamp = options.timestamp || true;
  this.channel   = options.pchannel || options.channel;
  this.pattern   = options.pattern || !!options.pchannel;
  this.logstash  = options.logstash === true;
  this.metadata  = options.meta || {};

  if (options.auth) {
    this.redis.auth(options.auth);
  }

  if (this.createdClient) {
    // Suppress errors from the Redis client
    this.redis.on('error', function (err) {
      self.emit('error', err);
    });
  }

  if (typeof this.container !== 'function') {
    var container = this.container;
    this.container = function () {
      return container;
    };
  }

  if (this.channel && typeof this.channel !== 'function') {
    var channel = this.channel;
    this.channel = function () {
      return channel;
    };
  }
};

//
// Inherit from `winston.Transport`.
//
util.inherits(Redis, winston.Transport);

//
// Expose the name of this Transport on the prototype
//
Redis.prototype.name = 'redis';

//
// Define a getter so that `winston.transports.Redis`
// is available and thus backwards compatible.
//
winston.transports.Redis = Redis;

//
// ### function log (level, msg, [meta], callback)
// #### @level {string} Level at which to log the message.
// #### @msg {string} Message to log
// #### @meta {Object} **Optional** Additional metadata to attach
// #### @callback {function} Continuation to respond to when complete.
// Core logging method exposed to Winston. Metadata is optional.
//
Redis.prototype.log = function (level, msg, meta, callback) {
  var self = this,
      container = this.container(meta),
      channel = this.channel && this.channel(meta);

  var output = common.log({
    level:       level,
    message:     msg,
    meta:        _.merge(meta, this.metadata),
    json:        this.json,
    logstash:    this.logstash,
    colorize:    this.colorize,
    prettyPrint: this.prettyPrint,
    timestamp:   this.timestamp,
    showLevel:   this.showLevel,
    stringify:   this.stringify,
    label:       this.label,
    depth:       this.depth,
    formatter:   this.formatter,
    humanReadableUnhandledException: this.humanReadableUnhandledException
  });

  async.series([
    function(cb) {
      self.redis.lpush(container, output, cb);
    },
    function(cb) {
      self.redis.ltrim(container, 0, self.length, cb);
    }
  ], function(err) {
    if (err) {
      if (callback) callback(err, false);
      return self.emit('error', err);
    }

    if (channel) {
      self.redis.publish(channel, output);
    }

    // TODO: emit 'logged' correctly,
    // keep track of pending logs.
    self.emit('logged');

    if (callback) callback(null, true);
  });
};

//
// ### function query (options, callback)
// #### @options {Object} Loggly-like query options for this instance.
// #### @callback {function} Continuation to respond to when complete.
// Query the transport. Options object is optional.
//
Redis.prototype.query = function (options, callback) {
  if (typeof options === 'function') {
    callback = options;
    options = {};
  }

  var options = this.normalizeQuery(options),
      start = options.start || 0,
      end = options.rows + start,
      container = this.container(options);

  this.redis.lrange(container, start, end - 1, function (err, results) {
    if (err) return callback(err);

    results = results.map(function (data) {
      var log, time, obj;

      try {
        log = JSON.parse(data);
      } catch (e) {
        return;
      }

      if (typeof log !== 'object' || !log) return;

      time = new Date(log.timestamp);
      if ((options.from && time < options.from)
         || (options.until && time > options.until)) {
        return;
      }

      if (options.fields) {
        obj = {};
        options.fields.forEach(function (key) {
          obj[key] = log[key];
        });
        log = obj;
      }

      return log;
    }).filter(Boolean);

    if (options.order !== 'desc') {
      results = results.reverse();
    }

    callback(null, results);
  });
};

//
// ### function stream (options)
// #### @options {Object} Stream options for this instance.
// Returns a log stream for this transport. Options object is optional.
// This will use Redis' builtin pubsub capabilities.
// http://redis.io/topics/pubsub
//
Redis.prototype.stream = function (options) {
  var self = this,
      options = options || {},
      stream = new Stream,
      container = this.container(options),
      channel = this.channel(options);

  stream.destroy = function () {
    if (this.destroyed) return;

    this.destroyed = true;

    var i = self.subscription.__channels[channel].indexOf(message);
    if (~i) self.subscription.__channels[channel].splice(i, 1);

    if (!self.subscription.__channels[channel].length) {
      self.subscription.punsubscribe(channel);
      delete self.subscription.__channels[channel];
    }

    if (!Object.keys(self.subscription.__channels).length) {
      try {
        self.subscription.end(false);
        self.subscription.stream.destroy();
      } catch (e) {
        ;
      }
      delete self.subscription;
    }
  };

  if (!this.subscription) {
    this.subscription = redis.createClient(this.redis.options);
    this.subscription.__channels = {};
    this.subscription.on('pmessage', function (pattern, channel, message) {
      var listeners = self.subscription.__channels[pattern];
      if (!listeners) return;
      listeners.forEach(function (listener) {
        listener.call(self.subscription, pattern, channel, message);
      });
    });
  }

  if (!this.subscription.__channels[channel]) {
    this.subscription.psubscribe(channel);
    this.subscription.__channels[channel] = [];
  }

  this.subscription.__channels[channel].push(message);

  function message(pattern, channel, message) {
    if (stream.destroyed) return;

    try {
      message = JSON.parse(message);
    } catch (e) {
      return stream.emit('error',
        new Error('Could not parse: "' + message + '".'));
    }

    stream.emit('log', message);
  }

  if (options.start === -1) {
    delete options.start;
  }

  if (options.start == null) {
    return stream;
  }

  this.redis.lrange(container, options.start, -1, function (err, results) {
    if (stream.destroyed) return;

    if (err) {
      return stream.emit('error', err);
    }

    results.forEach(function (log) {
      try {
        stream.emit('log', JSON.parse(log));
      } catch (e) {
        return stream.emit('error',
          new Error('Could not parse: "' + log + '".'));
      }
    });
  });

  return stream;
};

//Close Connection to redis Server
//Winston will call close function from clear/remove to attempt to cleanly exit.
Redis.prototype.close = function(){
  if (this.redis && this.createdClient)
    this.redis.end(false);
};
<|endoftext|>


<commit_before>/*
 *     (C) Copyright 2012 Universidad Politécnica de Madrid
 *
 *     This file is part of Wirecloud Platform.
 *
 *     Wirecloud Platform is free software: you can redistribute it and/or
 *     modify it under the terms of the GNU Affero General Public License as
 *     published by the Free Software Foundation, either version 3 of the
 *     License, or (at your option) any later version.
 *
 *     Wirecloud is distributed in the hope that it will be useful, but WITHOUT
 *     ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
 *     FITNESS FOR A PARTICULAR PURPOSE.  See the GNU Affero General Public
 *     License for more details.
 *
 *     You should have received a copy of the GNU Affero General Public License
 *     along with Wirecloud Platform.  If not, see
 *     <http://www.gnu.org/licenses/>.
 *
 */

/*jshint forin:true, eqnull:true, noarg:true, noempty:true, eqeqeq:true, bitwise:true, undef:true, curly:true, browser:true, indent:4, maxerr:50 */
/*global gettext, StyledElements*/

(function () {

    "use strict";

    var NewWorkspaceWindowMenu = function NewWorkspaceWindowMenu () {
        var fields = {
            'name': {
                label: gettext('Name'),
                type: 'text',
                required: true
            }
        }
        Wirecloud.ui.FormWindowMenu.call(this, fields, gettext('Create Workspace'));
    };
    NewWorkspaceWindowMenu.prototype = new Wirecloud.ui.FormWindowMenu();

    NewWorkspaceWindowMenu.prototype.setFocus = function setFocus () {
        this.form.fieldInterfaces['name'].focus();
    };

    NewWorkspaceWindowMenu.prototype.executeOperation = function executeOperation (data) {
        OpManagerFactory.getInstance().addWorkspace(data.name);
    };

    Wirecloud.ui.NewWorkspaceWindowMenu = NewWorkspaceWindowMenu;
})();
<commit_msg>Fix jshint problems in NewWorkspaceWindowMenu.js<commit_after>/*
 *     (C) Copyright 2012 Universidad Politécnica de Madrid
 *
 *     This file is part of Wirecloud Platform.
 *
 *     Wirecloud Platform is free software: you can redistribute it and/or
 *     modify it under the terms of the GNU Affero General Public License as
 *     published by the Free Software Foundation, either version 3 of the
 *     License, or (at your option) any later version.
 *
 *     Wirecloud is distributed in the hope that it will be useful, but WITHOUT
 *     ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
 *     FITNESS FOR A PARTICULAR PURPOSE.  See the GNU Affero General Public
 *     License for more details.
 *
 *     You should have received a copy of the GNU Affero General Public License
 *     along with Wirecloud Platform.  If not, see
 *     <http://www.gnu.org/licenses/>.
 *
 */

/*global gettext, OpManagerFactory, Wirecloud*/

(function () {

    "use strict";

    var NewWorkspaceWindowMenu = function NewWorkspaceWindowMenu() {
        var fields = {
            'name': {
                label: gettext('Name'),
                type: 'text',
                required: true
            }
        };
        Wirecloud.ui.FormWindowMenu.call(this, fields, gettext('Create Workspace'));
    };
    NewWorkspaceWindowMenu.prototype = new Wirecloud.ui.FormWindowMenu();

    NewWorkspaceWindowMenu.prototype.setFocus = function setFocus() {
        this.form.fieldInterfaces.name.focus();
    };

    NewWorkspaceWindowMenu.prototype.executeOperation = function executeOperation(data) {
        OpManagerFactory.getInstance().addWorkspace(data.name);
    };

    Wirecloud.ui.NewWorkspaceWindowMenu = NewWorkspaceWindowMenu;
})();
<|endoftext|>