<commit_before>'use strict';

var AsyncLock = function (opts) {
	opts = opts || {};

	this.Promise = opts.Promise || Promise;

	// format: {key : [fn, fn]}
	// queues[key] = null indicates no job running for key
	this.queues = Object.create(null);

	// lock is reentrant for same domain
	this.domainReentrant = opts.domainReentrant || false;
	if (this.domainReentrant) {
		if (typeof process === 'undefined' || typeof process.domain === 'undefined') {
			throw new Error(
				'Domain-reentrant locks require `process.domain` to exist. Please flip `opts.domainReentrant = false`, '
				+ 'use a NodeJS version that still implements Domain, or install a browser polyfill.');
		}
		// domain of current running func {key : fn}
		this.domains = Object.create(null);
	}

	this.timeout = opts.timeout || AsyncLock.DEFAULT_TIMEOUT;
	if (opts.maxPending === Infinity || (Number.isInteger(opts.maxPending) && opts.maxPending >= 0)) {
		this.maxPending = opts.maxPending;
	} else {
		this.maxPending = AsyncLock.DEFAULT_MAX_PENDING;
	}
};

AsyncLock.DEFAULT_TIMEOUT = 0; //Never
AsyncLock.DEFAULT_MAX_PENDING = 1000;

/**
 * Acquire Locks
 *
 * @param {String|Array} key 	resource key or keys to lock
 * @param {function} fn 	async function
 * @param {function} cb 	callback function, otherwise will return a promise
 * @param {Object} opts 	options
 */
AsyncLock.prototype.acquire = function (key, fn, cb, opts) {
	if (Array.isArray(key)) {
		return this._acquireBatch(key, fn, cb, opts);
	}

	if (typeof (fn) !== 'function') {
		throw new Error('You must pass a function to execute');
	}

	// faux-deferred promise using new Promise() (as Promise.defer is deprecated)
	var deferredResolve = null;
	var deferredReject = null;
	var deferred = null;

	if (typeof (cb) !== 'function') {
		opts = cb;
		cb = null;

		// will return a promise
		deferred = new this.Promise(function(resolve, reject) {
			deferredResolve = resolve;
			deferredReject = reject;
		});
	}

	opts = opts || {};

	var resolved = false;
	var timer = null;
	var self = this;

	var done = function (locked, err, ret) {
		if (locked) {
			if (self.queues[key].length === 0) {
				delete self.queues[key];
			}
			if (self.domainReentrant) {
				delete self.domains[key];
			}
		}

		if (!resolved) {
			if (!deferred) {
				if (typeof (cb) === 'function') {
					cb(err, ret);
				}
			}
			else {
				//promise mode
				if (err) {
					deferredReject(err);
				}
				else {
					deferredResolve(ret);
				}
			}
			resolved = true;
		}

		if (locked) {
			//run next func
			if (!!self.queues[key] && self.queues[key].length > 0) {
				self.queues[key].shift()();
			}
		}
	};

	var exec = function (locked) {
		if (resolved) { // may due to timed out
			return done(locked);
		}

		if (timer) {
			clearTimeout(timer);
			timer = null;
		}

		if (self.domainReentrant && locked) {
			self.domains[key] = process.domain;
		}

		// Callback mode
		if (fn.length === 1) {
			var called = false;
			fn(function (err, ret) {
				if (!called) {
					called = true;
					done(locked, err, ret);
				}
			});
		}
		else {
			// Promise mode
			self._promiseTry(function () {
				return fn();
			})
			.then(function(ret){
				done(locked, undefined, ret);
			}, function(error){
				done(locked, error);
			});
		}
	};
	if (self.domainReentrant && !!process.domain) {
		exec = process.domain.bind(exec);
	}

	if (!self.queues[key]) {
		self.queues[key] = [];
		exec(true);
	}
	else if (self.domainReentrant && !!process.domain && process.domain === self.domains[key]) {
		// If code is in the same domain of current running task, run it directly
		// Since lock is re-enterable
		exec(false);
	}
	else if (self.queues[key].length >= self.maxPending) {
		done(false, new Error('Too much pending tasks'));
	}
	else {
		var taskFn = function () {
			exec(true);
		};
		if (opts.skipQueue) {
			self.queues[key].unshift(taskFn);
		} else {
			self.queues[key].push(taskFn);
		}

		var timeout = opts.timeout || self.timeout;
		if (timeout) {
			timer = setTimeout(function () {
				timer = null;
				done(false, new Error('async-lock timed out'));
			}, timeout);
		}
	}

	if (deferred) {
		return deferred;
	}
};

/*
 * Below is how this function works:
 *
 * Equivalent code:
 * self.acquire(key1, function(cb){
 *     self.acquire(key2, function(cb){
 *         self.acquire(key3, fn, cb);
 *     }, cb);
 * }, cb);
 *
 * Equivalent code:
 * var fn3 = getFn(key3, fn);
 * var fn2 = getFn(key2, fn3);
 * var fn1 = getFn(key1, fn2);
 * fn1(cb);
 */
AsyncLock.prototype._acquireBatch = function (keys, fn, cb, opts) {
	if (typeof (cb) !== 'function') {
		opts = cb;
		cb = null;
	}

	var self = this;
	var getFn = function (key, fn) {
		return function (cb) {
			self.acquire(key, fn, cb, opts);
		};
	};

	var fnx = fn;
	keys.reverse().forEach(function (key) {
		fnx = getFn(key, fnx);
	});

	if (typeof (cb) === 'function') {
		fnx(cb);
	}
	else {
		return new this.Promise(function (resolve, reject) {
			// check for promise mode in case keys is empty array
			if (fnx.length === 1) {
				fnx(function (err, ret) {
					if (err) {
						reject(err);
					}
					else {
						resolve(ret);
					}
				});
			} else {
				resolve(fnx());
			}
		});
	}
};

/*
 *	Whether there is any running or pending asyncFunc
 *
 *	@param {String} key
 */
AsyncLock.prototype.isBusy = function (key) {
	if (!key) {
		return Object.keys(this.queues).length > 0;
	}
	else {
		return !!this.queues[key];
	}
};

/**
 * Promise.try() implementation to become independent of Q-specific methods
 */
AsyncLock.prototype._promiseTry = function(fn) {
	try {
		return this.Promise.resolve(fn());
	} catch (e) {
		return this.Promise.reject(e);
	}
};

module.exports = AsyncLock;
<commit_msg>fix jshint error<commit_after>'use strict';

var AsyncLock = function (opts) {
	opts = opts || {};

	this.Promise = opts.Promise || Promise;

	// format: {key : [fn, fn]}
	// queues[key] = null indicates no job running for key
	this.queues = Object.create(null);

	// lock is reentrant for same domain
	this.domainReentrant = opts.domainReentrant || false;
	if (this.domainReentrant) {
		if (typeof process === 'undefined' || typeof process.domain === 'undefined') {
			throw new Error(
				'Domain-reentrant locks require `process.domain` to exist. Please flip `opts.domainReentrant = false`, ' +
				'use a NodeJS version that still implements Domain, or install a browser polyfill.');
		}
		// domain of current running func {key : fn}
		this.domains = Object.create(null);
	}

	this.timeout = opts.timeout || AsyncLock.DEFAULT_TIMEOUT;
	if (opts.maxPending === Infinity || (Number.isInteger(opts.maxPending) && opts.maxPending >= 0)) {
		this.maxPending = opts.maxPending;
	} else {
		this.maxPending = AsyncLock.DEFAULT_MAX_PENDING;
	}
};

AsyncLock.DEFAULT_TIMEOUT = 0; //Never
AsyncLock.DEFAULT_MAX_PENDING = 1000;

/**
 * Acquire Locks
 *
 * @param {String|Array} key 	resource key or keys to lock
 * @param {function} fn 	async function
 * @param {function} cb 	callback function, otherwise will return a promise
 * @param {Object} opts 	options
 */
AsyncLock.prototype.acquire = function (key, fn, cb, opts) {
	if (Array.isArray(key)) {
		return this._acquireBatch(key, fn, cb, opts);
	}

	if (typeof (fn) !== 'function') {
		throw new Error('You must pass a function to execute');
	}

	// faux-deferred promise using new Promise() (as Promise.defer is deprecated)
	var deferredResolve = null;
	var deferredReject = null;
	var deferred = null;

	if (typeof (cb) !== 'function') {
		opts = cb;
		cb = null;

		// will return a promise
		deferred = new this.Promise(function(resolve, reject) {
			deferredResolve = resolve;
			deferredReject = reject;
		});
	}

	opts = opts || {};

	var resolved = false;
	var timer = null;
	var self = this;

	var done = function (locked, err, ret) {
		if (locked) {
			if (self.queues[key].length === 0) {
				delete self.queues[key];
			}
			if (self.domainReentrant) {
				delete self.domains[key];
			}
		}

		if (!resolved) {
			if (!deferred) {
				if (typeof (cb) === 'function') {
					cb(err, ret);
				}
			}
			else {
				//promise mode
				if (err) {
					deferredReject(err);
				}
				else {
					deferredResolve(ret);
				}
			}
			resolved = true;
		}

		if (locked) {
			//run next func
			if (!!self.queues[key] && self.queues[key].length > 0) {
				self.queues[key].shift()();
			}
		}
	};

	var exec = function (locked) {
		if (resolved) { // may due to timed out
			return done(locked);
		}

		if (timer) {
			clearTimeout(timer);
			timer = null;
		}

		if (self.domainReentrant && locked) {
			self.domains[key] = process.domain;
		}

		// Callback mode
		if (fn.length === 1) {
			var called = false;
			fn(function (err, ret) {
				if (!called) {
					called = true;
					done(locked, err, ret);
				}
			});
		}
		else {
			// Promise mode
			self._promiseTry(function () {
				return fn();
			})
			.then(function(ret){
				done(locked, undefined, ret);
			}, function(error){
				done(locked, error);
			});
		}
	};
	if (self.domainReentrant && !!process.domain) {
		exec = process.domain.bind(exec);
	}

	if (!self.queues[key]) {
		self.queues[key] = [];
		exec(true);
	}
	else if (self.domainReentrant && !!process.domain && process.domain === self.domains[key]) {
		// If code is in the same domain of current running task, run it directly
		// Since lock is re-enterable
		exec(false);
	}
	else if (self.queues[key].length >= self.maxPending) {
		done(false, new Error('Too much pending tasks'));
	}
	else {
		var taskFn = function () {
			exec(true);
		};
		if (opts.skipQueue) {
			self.queues[key].unshift(taskFn);
		} else {
			self.queues[key].push(taskFn);
		}

		var timeout = opts.timeout || self.timeout;
		if (timeout) {
			timer = setTimeout(function () {
				timer = null;
				done(false, new Error('async-lock timed out'));
			}, timeout);
		}
	}

	if (deferred) {
		return deferred;
	}
};

/*
 * Below is how this function works:
 *
 * Equivalent code:
 * self.acquire(key1, function(cb){
 *     self.acquire(key2, function(cb){
 *         self.acquire(key3, fn, cb);
 *     }, cb);
 * }, cb);
 *
 * Equivalent code:
 * var fn3 = getFn(key3, fn);
 * var fn2 = getFn(key2, fn3);
 * var fn1 = getFn(key1, fn2);
 * fn1(cb);
 */
AsyncLock.prototype._acquireBatch = function (keys, fn, cb, opts) {
	if (typeof (cb) !== 'function') {
		opts = cb;
		cb = null;
	}

	var self = this;
	var getFn = function (key, fn) {
		return function (cb) {
			self.acquire(key, fn, cb, opts);
		};
	};

	var fnx = fn;
	keys.reverse().forEach(function (key) {
		fnx = getFn(key, fnx);
	});

	if (typeof (cb) === 'function') {
		fnx(cb);
	}
	else {
		return new this.Promise(function (resolve, reject) {
			// check for promise mode in case keys is empty array
			if (fnx.length === 1) {
				fnx(function (err, ret) {
					if (err) {
						reject(err);
					}
					else {
						resolve(ret);
					}
				});
			} else {
				resolve(fnx());
			}
		});
	}
};

/*
 *	Whether there is any running or pending asyncFunc
 *
 *	@param {String} key
 */
AsyncLock.prototype.isBusy = function (key) {
	if (!key) {
		return Object.keys(this.queues).length > 0;
	}
	else {
		return !!this.queues[key];
	}
};

/**
 * Promise.try() implementation to become independent of Q-specific methods
 */
AsyncLock.prototype._promiseTry = function(fn) {
	try {
		return this.Promise.resolve(fn());
	} catch (e) {
		return this.Promise.reject(e);
	}
};

module.exports = AsyncLock;
<|endoftext|>


<commit_before>;
(function(root, factory) {
  if(typeof define === "function" && define.amd) {
    define(["jquery"], factory)
  } else {
    root.DateTime = factory(root.jQuery)
  }
})(this, function($) {
  var DateTime = function(year, month, date, hours, minutes) {
    if(typeof year == 'string') this.date = new Date(year)
    else if(typeof year == 'object') this.date = year
    else if(typeof year == 'number') this.date = new Date(year, month - 1, date, hours, minutes, 0, 0)
    else this.date = new Date()
  }

  DateTime.SUNDAY = 0
  DateTime.MONDAY = 1
  DateTime.TUESDAY = 2
  DateTime.WEDNESDAY = 3
  DateTime.THURSDAY = 4
  DateTime.FRIDAY = 5
  DateTime.SATURDAY = 6

  $.each([
    'getTime',
    'getFullYear',
    'getMonth',
    'getDate',
    'getDay',
    'getHours',
    'getMinutes',
    'getSeconds',
    'getMilliseconds'
  ], function(_index, func) {
    DateTime.prototype[func] = function() { return this.date[func]() }
  })

  /**
   * Returns date from ISO date ignoring time information
   * @param isoDateTime String YYYY-MM-DDTHH-MM
   * @return {DateTime}
   */
  DateTime.fromIsoDate = function(isoDateTime) {
    var date = parseDate(isoDateTime.split('T')[0])
    return new DateTime(date.year, date.month, date.day, 0, 0)
  }

  /**
   * Returns date with time from ISO date
   * @param isoDateTime String YYYY-MM-DDTHH-MM
   * @return {DateTime}
   */
  DateTime.fromIsoDateTime = function(isoDateTime) {
    var dateAndTime = isoDateTime.split('T')
    var time = parseTime(dateAndTime.length == 2 && dateAndTime[1])
    var date = parseDate(dateAndTime[0])
    return new DateTime(date.year, date.month, date.day, time.hours, time.minutes)
  }

  function parseDate(str) {
    var dateComponents = str.split('-')
    return {
      year : +dateComponents[0],
      month: +dateComponents[1],
      day  : +dateComponents[2]
    }
  }

  function parseTime(str) {
    if(str) {
      var timeComponents = str.split(':')
      return {
        hours  : +timeComponents[0],
        minutes: +timeComponents[1],
        seconds: +timeComponents[2] || 0
      }
    } else {
      return { hours: 0, minutes: 0 }
    }
  }

  DateTime.prototype.withTime = function(h, m) {
    if(typeof h == 'string') {
      var hoursAndMinutes = h.split(':')
      h = hoursAndMinutes[0]
      m = hoursAndMinutes[1]
    }
    var dateWithTime = this.clone()
    dateWithTime.date.setHours(h)
    dateWithTime.date.setMinutes(m)
    dateWithTime.date.setSeconds(0)
    dateWithTime.date.setMilliseconds(0)
    return dateWithTime
  }

  DateTime.DAYS_IN_MONTH = [31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31]
  DateTime.SECOND = 1000
  DateTime.MINUTE = 60 * DateTime.SECOND
  DateTime.HOUR = 60 * DateTime.MINUTE
  DateTime.DAY = 24 * DateTime.HOUR
  DateTime.WEEK = 7 * DateTime.DAY

  DateTime.now = function() {
    if(typeof DateTime._now == 'undefined') {
      DateTime._now = new DateTime()
    }
    return DateTime._now
  }

  DateTime.getDaysInMonth = function(year, month) {
    if(((0 == (year % 4)) && ( (0 != (year % 100)) || (0 == (year % 400)))) && month == 1) {
      return 29
    } else {
      return DateTime.DAYS_IN_MONTH[month]
    }
  }

  DateTime.getDayInYear = function(year, month, day) {
    var days = 0
    for(var i = 0; i < month; i++) {
      days += DateTime.getDaysInMonth(year, i)
    }
    days += day
    return days
  }

  DateTime.prototype.getDaysInMonth = function() { return DateTime.getDaysInMonth(this.getFullYear(), this.getMonth()) }

  DateTime.prototype.getDayInYear = function() { return DateTime.getDayInYear(this.getFullYear(), this.getMonth(), this.getDate()) }

  DateTime.prototype.plusDays = function(days) {
    var newDateTime = this.clone()
    var hours = this.getHours()
    newDateTime.date.setTime(this.getTime() + days * DateTime.DAY)

    // Fix the DateTime offset caused by daylight saving time
    var delta = hours - newDateTime.getHours()
    if(delta != 0) {
      // Correct the delta to be between [-12, 12]
      if(delta > 12) {
        delta -= 24
      }
      if(delta < -12) {
        delta += 24
      }
      newDateTime.date.setTime(newDateTime.getTime() + (delta * DateTime.HOUR))
    }
    return newDateTime
  }

  DateTime.prototype.minusDays = function(days) {
    return this.plusDays(-days)
  }

  DateTime.prototype.compareTo = function(date) {
    if(!date) {
      return 1
    }
    var lhs = this.getTime()
    var rhs = date.getTime()
    if(lhs < rhs) {
      return -1
    } else {
      if(lhs > rhs) {
        return 1
      } else {
        return 0
      }
    }
  }

  DateTime.prototype.isToday = function() { return this.equalsOnlyDate(DateTime.now()) }

  DateTime.prototype.getWeekInYear = function(weekNumberingSystem) {
    if(weekNumberingSystem != "US" && weekNumberingSystem != "ISO") {
      throw("Week numbering system must be either US or ISO, was " + weekNumberingSystem)
    }

    var firstDay = new Date(this.getFullYear(), 0, 1).getDay()
    if(weekNumberingSystem == "US") {
      return Math.ceil((this.getDayInYear() + firstDay) / 7)
    }
    var THU = 4
    var weekday = this.getDay()
    if(weekday == 0) weekday = 7
    if(firstDay == 0) firstDay = 7
    // If Dec 29 falls on Mon, Dec 30 on Mon or Tue, Dec 31 on Mon - Wed, it's on the first week of next year
    if(this.getMonth() == 11 && this.getDate() >= 29 && (this.getDate() - weekday) > 27) {
      return 1
    }
    // If Jan 1-3 falls on Fri, Sat or Sun, it's on the last week of the previous year
    if(this.getMonth() == 0 && this.getDate() < 4 && weekday > THU) {
      return new DateTime(new Date(this.getFullYear() - 1, 11, 31)).getWeekInYear('ISO')
    }
    var week = Math.ceil((this.getDayInYear() + firstDay - 1) / 7)
    // If first days of this year are on last year's last week, the above gives one week too much
    if(firstDay > THU) week--
    return week
  }

  //TODO refactor
  DateTime.prototype.clone = function() { return new DateTime(new Date(this.getTime())) }

  DateTime.prototype.isOddMonth = function() { return this.getMonth() % 2 != 0 }

  DateTime.prototype.equalsOnlyDate = function(date) {
    if(!date) {
      return false
    }
    return this.getMonth() == date.getMonth() && this.getDate() == date.getDate() && this.getFullYear() == date.getFullYear()
  }

  DateTime.prototype.isBetweenDates = function(start, end) { return this.compareTo(start) >= 0 && this.compareTo(end) <= 0 }

  DateTime.prototype.firstDateOfMonth = function() { return new DateTime((this.getMonth() + 1) + "/1/" + this.getFullYear()) }

  DateTime.prototype.lastDateOfMonth = function() { return new DateTime((this.getMonth() + 1) + "/" + this.getDaysInMonth() + "/" + this.getFullYear()) }

  DateTime.prototype.distanceInDays = function(date) {
    var first = parseInt(this.getTime() / DateTime.DAY, 10)
    var last = parseInt(date.getTime() / DateTime.DAY, 10)
    return (last - first)
  }

  DateTime.prototype.withWeekday = function(weekday) { return this.plusDays(weekday - this.getDay()) }

  DateTime.prototype.getOnlyDate = function() { return new DateTime(new Date(this.getFullYear(), this.getMonth(), this.getDate())) }

  DateTime.prototype.isWeekend = function() { return this.getDay() == 6 || this.getDay() == 0 }

  DateTime.prototype.toString = function() { return this.date.toISOString() }

  DateTime.prototype.getFirstDateOfWeek = function(locale) {
    var firstWeekday = locale ? locale.firstWeekday : DateTime.MONDAY
    if(firstWeekday < this.getDay()) return this.plusDays(firstWeekday - this.getDay())
    else if(firstWeekday > this.getDay()) return this.plusDays(firstWeekday - this.getDay() - 7)
    else return this.clone()
  }

  DateTime.daysInMonth = [31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31]
  DateTime.y2kYear = 50
  DateTime.monthNumbers = { Jan: 0, Feb: 1, Mar: 2, Apr: 3, May: 4, Jun: 5, Jul: 6, Aug: 7, Sep: 8, Oct: 9, Nov: 10, Dec: 11 }

  return DateTime
})
<commit_msg>Add factory methods fromDate and fromDateTime<commit_after>;
(function(root, factory) {
  if(typeof define === "function" && define.amd) {
    define(["jquery"], factory)
  } else {
    root.DateTime = factory(root.jQuery)
  }
})(this, function($) {
  var DateTime = function(year, month, date, hours, minutes) {
    if(typeof year == 'string') this.date = new Date(year)
    else if(typeof year == 'object') this.date = year
    else if(typeof year == 'number') this.date = new Date(year, month - 1, date, hours, minutes, 0, 0)
    else this.date = new Date()
  }

  DateTime.SUNDAY = 0
  DateTime.MONDAY = 1
  DateTime.TUESDAY = 2
  DateTime.WEDNESDAY = 3
  DateTime.THURSDAY = 4
  DateTime.FRIDAY = 5
  DateTime.SATURDAY = 6

  $.each([
    'getTime',
    'getFullYear',
    'getMonth',
    'getDate',
    'getDay',
    'getHours',
    'getMinutes',
    'getSeconds',
    'getMilliseconds'
  ], function(_index, func) {
    DateTime.prototype[func] = function() { return this.date[func]() }
  })

  DateTime.fromDateTime = function(year, month, day, hours, minutes) {
    return new DateTime(year, month, day, hours, minutes)
  }

  DateTime.fromDate = function(year, month, day) {
    return DateTime.fromDateTime(year, month, day, 0, 0)
  }

  /**
   * Returns date from ISO date ignoring time information
   * @param isoDateTime String YYYY-MM-DDTHH-MM
   * @return {DateTime}
   */
  DateTime.fromIsoDate = function(isoDateTime) {
    var date = parseDate(isoDateTime.split('T')[0])
    return new DateTime(date.year, date.month, date.day, 0, 0)
  }

  /**
   * Returns date with time from ISO date
   * @param isoDateTime String YYYY-MM-DDTHH-MM
   * @return {DateTime}
   */
  DateTime.fromIsoDateTime = function(isoDateTime) {
    var dateAndTime = isoDateTime.split('T')
    var time = parseTime(dateAndTime.length == 2 && dateAndTime[1])
    var date = parseDate(dateAndTime[0])
    return new DateTime(date.year, date.month, date.day, time.hours, time.minutes)
  }

  function parseDate(str) {
    var dateComponents = str.split('-')
    return {
      year : +dateComponents[0],
      month: +dateComponents[1],
      day  : +dateComponents[2]
    }
  }

  function parseTime(str) {
    if(str) {
      var timeComponents = str.split(':')
      return {
        hours  : +timeComponents[0],
        minutes: +timeComponents[1],
        seconds: +timeComponents[2] || 0
      }
    } else {
      return { hours: 0, minutes: 0 }
    }
  }

  DateTime.prototype.withTime = function(h, m) {
    if(typeof h == 'string') {
      var hoursAndMinutes = h.split(':')
      h = hoursAndMinutes[0]
      m = hoursAndMinutes[1]
    }
    var dateWithTime = this.clone()
    dateWithTime.date.setHours(h)
    dateWithTime.date.setMinutes(m)
    dateWithTime.date.setSeconds(0)
    dateWithTime.date.setMilliseconds(0)
    return dateWithTime
  }

  DateTime.DAYS_IN_MONTH = [31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31]
  DateTime.SECOND = 1000
  DateTime.MINUTE = 60 * DateTime.SECOND
  DateTime.HOUR = 60 * DateTime.MINUTE
  DateTime.DAY = 24 * DateTime.HOUR
  DateTime.WEEK = 7 * DateTime.DAY

  DateTime.now = function() {
    if(typeof DateTime._now == 'undefined') {
      DateTime._now = new DateTime()
    }
    return DateTime._now
  }

  DateTime.getDaysInMonth = function(year, month) {
    if(((0 == (year % 4)) && ( (0 != (year % 100)) || (0 == (year % 400)))) && month == 1) {
      return 29
    } else {
      return DateTime.DAYS_IN_MONTH[month]
    }
  }

  DateTime.getDayInYear = function(year, month, day) {
    var days = 0
    for(var i = 0; i < month; i++) {
      days += DateTime.getDaysInMonth(year, i)
    }
    days += day
    return days
  }

  DateTime.prototype.getDaysInMonth = function() { return DateTime.getDaysInMonth(this.getFullYear(), this.getMonth()) }

  DateTime.prototype.getDayInYear = function() { return DateTime.getDayInYear(this.getFullYear(), this.getMonth(), this.getDate()) }

  DateTime.prototype.plusDays = function(days) {
    var newDateTime = this.clone()
    var hours = this.getHours()
    newDateTime.date.setTime(this.getTime() + days * DateTime.DAY)

    // Fix the DateTime offset caused by daylight saving time
    var delta = hours - newDateTime.getHours()
    if(delta != 0) {
      // Correct the delta to be between [-12, 12]
      if(delta > 12) {
        delta -= 24
      }
      if(delta < -12) {
        delta += 24
      }
      newDateTime.date.setTime(newDateTime.getTime() + (delta * DateTime.HOUR))
    }
    return newDateTime
  }

  DateTime.prototype.minusDays = function(days) {
    return this.plusDays(-days)
  }

  DateTime.prototype.compareTo = function(date) {
    if(!date) {
      return 1
    }
    var lhs = this.getTime()
    var rhs = date.getTime()
    if(lhs < rhs) {
      return -1
    } else {
      if(lhs > rhs) {
        return 1
      } else {
        return 0
      }
    }
  }

  DateTime.prototype.isToday = function() { return this.equalsOnlyDate(DateTime.now()) }

  DateTime.prototype.getWeekInYear = function(weekNumberingSystem) {
    if(weekNumberingSystem != "US" && weekNumberingSystem != "ISO") {
      throw("Week numbering system must be either US or ISO, was " + weekNumberingSystem)
    }

    var firstDay = new Date(this.getFullYear(), 0, 1).getDay()
    if(weekNumberingSystem == "US") {
      return Math.ceil((this.getDayInYear() + firstDay) / 7)
    }
    var THU = 4
    var weekday = this.getDay()
    if(weekday == 0) weekday = 7
    if(firstDay == 0) firstDay = 7
    // If Dec 29 falls on Mon, Dec 30 on Mon or Tue, Dec 31 on Mon - Wed, it's on the first week of next year
    if(this.getMonth() == 11 && this.getDate() >= 29 && (this.getDate() - weekday) > 27) {
      return 1
    }
    // If Jan 1-3 falls on Fri, Sat or Sun, it's on the last week of the previous year
    if(this.getMonth() == 0 && this.getDate() < 4 && weekday > THU) {
      return new DateTime(new Date(this.getFullYear() - 1, 11, 31)).getWeekInYear('ISO')
    }
    var week = Math.ceil((this.getDayInYear() + firstDay - 1) / 7)
    // If first days of this year are on last year's last week, the above gives one week too much
    if(firstDay > THU) week--
    return week
  }

  //TODO refactor
  DateTime.prototype.clone = function() { return new DateTime(new Date(this.getTime())) }

  DateTime.prototype.isOddMonth = function() { return this.getMonth() % 2 != 0 }

  DateTime.prototype.equalsOnlyDate = function(date) {
    if(!date) {
      return false
    }
    return this.getMonth() == date.getMonth() && this.getDate() == date.getDate() && this.getFullYear() == date.getFullYear()
  }

  DateTime.prototype.isBetweenDates = function(start, end) { return this.compareTo(start) >= 0 && this.compareTo(end) <= 0 }

  DateTime.prototype.firstDateOfMonth = function() { return new DateTime((this.getMonth() + 1) + "/1/" + this.getFullYear()) }

  DateTime.prototype.lastDateOfMonth = function() { return new DateTime((this.getMonth() + 1) + "/" + this.getDaysInMonth() + "/" + this.getFullYear()) }

  DateTime.prototype.distanceInDays = function(date) {
    var first = parseInt(this.getTime() / DateTime.DAY, 10)
    var last = parseInt(date.getTime() / DateTime.DAY, 10)
    return (last - first)
  }

  DateTime.prototype.withWeekday = function(weekday) { return this.plusDays(weekday - this.getDay()) }

  DateTime.prototype.getOnlyDate = function() { return new DateTime(new Date(this.getFullYear(), this.getMonth(), this.getDate())) }

  DateTime.prototype.isWeekend = function() { return this.getDay() == 6 || this.getDay() == 0 }

  DateTime.prototype.toString = function() { return this.date.toISOString() }

  DateTime.prototype.getFirstDateOfWeek = function(locale) {
    var firstWeekday = locale ? locale.firstWeekday : DateTime.MONDAY
    if(firstWeekday < this.getDay()) return this.plusDays(firstWeekday - this.getDay())
    else if(firstWeekday > this.getDay()) return this.plusDays(firstWeekday - this.getDay() - 7)
    else return this.clone()
  }

  DateTime.daysInMonth = [31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31]
  DateTime.y2kYear = 50
  DateTime.monthNumbers = { Jan: 0, Feb: 1, Mar: 2, Apr: 3, May: 4, Jun: 5, Jul: 6, Aug: 7, Sep: 8, Oct: 9, Nov: 10, Dec: 11 }

  return DateTime
})
<|endoftext|>


<commit_before>var _ = require('lodash');
var defaultValidations = require('./defaultValidations');
var Model = require('racer/lib/Model');

module.exports = Validator;

/**
 * Creates a validator object and initiates it
 * @param {Model} model - A scoped model to the location on where to put the validator's data
 * @param {Model|string|Object} [origin|defaultObject] - Either a scoped model to the location where the original data is stored. Or, a path (as string) to the location where to find the original data. If not passed, the fields parameter is mandatory. Can also be passed in as a defaultObject. If passed in as default objet, the fields parameter is also mandatory.
 * @param {Collection.<string, Object>} [fields] - A collection of fields to use. If not passed, the origin parameter is mandatory. The key for each object is the field name, and the value is the field object (specified below).
   * @param {*} [fields.<fieldName>.default] - A default value for this specific field.
   * @param {Object[]} [fields.<fieldName>.validations] - A list of validations to apply.
     * @param {String|Function|RegEx} [fields.<fieldName>.validations.<index>.rule] - The rule to use when validating this rule. Either, this can be a string matching the name of a default rule (specified in default checks or passed in as an option), OR a function which will get run with the value to be validated as input, which should return true|false reflecting the validity, OR a RegEx, which will get run similar to if you pass in a function.
     * @param {String} [fields.<fieldName>.validations.<index>.message] - The error message to show if validation fails
 * @param {Object} [options] - An options object
   * @param {Collection.<string, Function|RegEx>} [options.rules] - A collection of default rules to add to this instance. Each key is the name of the rule. The value is the rule, either a function or regular expression similar to field specific functions/regular expressions passed in the fields parameter
 * @returns {Validator} - Instance of Validator
 */
function Validator(model, origin, fields, options) {
  // Parse out arguments

  var args = Array.prototype.slice.call(arguments);

  if(!args.length) throw new Error('You must specify a model!');
  if(args.length == 1) throw new Error('You must either specify an origin or a fields object');

  this.model = args.shift();
  var arg = args.shift();

  // Origin cases
  if(arg instanceof Model) {
    this.origin = arg;

    arg = args.shift();
  } else if(typeof arg === 'string') {
    this.origin = this.model.scope(arg);

    arg = args.shift();
  }

  // If only a collection was passed, assume we want to add to a new doc
  if(this.origin) {
    var segments = this.origin._splitPath();

    if(segments.length === 1) {
      // Generate a new id
      this.origin = this.origin.at(model.id());
    }
  }

  if(arg) {
    // Case where we've passed in a default object
    if(!Array.isArray(arg) && typeof args[0] !== 'undefined') {
      var defaultObject = arg;

      arg = args.shift();
    }

    // Fields argument
    if(Array.isArray(arg)) {
      // Support passing in an array of fields
      this.fields = _.zipObject(arg, _.fill(Array(arg.length), {}));
    } else {
      this.fields = arg;
    }

    if(defaultObject) {
      _.each(defaultObject, function (val, key) {
        if(!this.fields[key]) this.fields[key] = {};

        this.fields[key]['default'] = val;
      }, this);
    }
  }

  this.options = _.assign({
    rules: {},
    messages: {}
  }, args.shift());

  // Setup
  this._setup();
}

// TODO: Add proper docs for external facing methods, such as this one
Validator.prototype.getValues = function () {
  var values = {};
  _.each(this.model.get(), function (field, fieldName) {
    values[fieldName] = field.value;
  });
  return values;
};

// TODO: Add proper docs for external facing methods, such as this one
Validator.prototype.validate = function (fieldname) {
  return this._validate(fieldname);
};

// TODO: Add proper docs for external facing methods, such as this one
Validator.prototype.validateAll = function() {
  var valid = true;

  _.each(this.model.get(), function (field, fieldName) {
    var fieldIsValid = this._validate(fieldName);

    if(valid) valid = fieldIsValid;
  }, this);

  return valid;
};

// TODO: Add proper docs for external facing methods, such as this one
Validator.prototype.setInvalid = function (fieldName, message) {
  this._setValidity(fieldName, false);
  this.model.push(fieldName + '.messages', message || defaultValidations['default'].message);
};

/*
 * @public
 * Reset values to origin.
 */
Validator.prototype.reset = function () {
  this._setup();
};

/*
 * @public
 * Commit values to model. Call after client- and serverside validation.
 *
 * @param {Boolean} force - Whether to force commit despite validation not passing
 */
Validator.prototype.commit = function (force) {
  if(!this.origin) return;

  if(!force && !this.validateAll()) return;

  var values = {};

  _.each(this.model.get(), function (field, fieldName) {
    if(fieldName !== 'id' && field && field.hasOwnProperty('value')) values[fieldName] = field.value;
  }, this);

  if(this.origin.get('id')) {
    this.origin.setEach(values);
  } else {
    // REVIEW: If we haven fetched/subscribed to a doc which we have the id for (i.e. we try to add a doc which already exists in DB), we get random errors that we don't handle (but doesn't seem to really affect anything)
    this.origin.add(values);
  }
};

Validator.prototype._setup = function () {
  var self = this;

  if (this.fields) {
    _.each(this.fields, function (field, fieldName) {
      self._addFieldProperties(fieldName, field);
    });
  }

  if(this.origin) {
    _.each(this.origin.get(), function (value, fieldName) {
      self.model.set(fieldName + '.value', value);
    }, this);
  }
};

Validator.prototype._addFieldProperties = function (fieldName, field) {
  var self = this;
  var data = {value: null};

  if(field) {
    data = {value: field.default};

    if(field.validations) {
      _.assign(data, {
        validations: this._assignValidations(field.validations),
        isValid: false,
        isInvalid: false,
        validate: function () {
          self._validate(fieldName);
        }
      });
    }
  }

  this.model.setEach(fieldName, data);
};

Validator.prototype._validate = function (fieldName) {
  this.model.del(fieldName + '.messages');

  var field = this.model.get(fieldName);
  if(!field || !field.hasOwnProperty('validations')) return true;

  var valid = true;
  for (var i = 0; i < field.validations.length; i++) {
    var validation = field.validations[i];

    if (!this._check(field, validation.rule)) {
      valid = false;

      this.model.push(fieldName + '.messages', validation.message);
    }
  }

  this._setValidity(fieldName, valid);

  return valid;
};

Validator.prototype._assignValidations = function (validations) {
  for (var i = 0; i < validations.length; i++) {
    var validation = validations[i];

    if (!validation.message) validation.message = this._getMessage(validation.rule);

    if (typeof validation.rule === 'string') validation.rule = this._getRule(validation.rule);

    if (typeof validation.rule !== 'function' && !_.isRegExp(validation.rule)) throw new Error('This rule is not (or does not point to) a RegEx or a function.');
  }

  return validations;
};

Validator.prototype._getRule = function (ruleName) {
  if(this.options.rules[ruleName]) return this.options.rules[ruleName];

  if(defaultValidations.hasOwnProperty(ruleName)) return defaultValidations[ruleName].rule;

  throw new Error('Rule: "' + ruleName + '" is not available. You need to add it as an option.');
};

Validator.prototype._getMessage = function (ruleName) {
  return this.options.messages[ruleName] || ((defaultValidations.hasOwnProperty(ruleName)) ? defaultValidations[ruleName].message : defaultValidations['default'].message);
};

Validator.prototype._check = function (field, rule) {
  if(_.isRegExp(rule)) return rule.test(field.value);

  if(typeof rule === 'function') return rule(field.value);
};

Validator.prototype._setValidity = function (fieldName, validity) {
  this.model.setEach(fieldName, { isValid: validity, isInvalid: !validity });
  this._setState();
};

Validator.prototype._setState = function() {
  this.model.set('hasInvalidFields', !!_.result(_.find(this.model.get(), {'isInvalid': true}), 'isInvalid'));
};
<commit_msg>Don't use deprecated lodash syntax<commit_after>var _ = require('lodash');
var defaultValidations = require('./defaultValidations');
var Model = require('racer/lib/Model');

module.exports = Validator;

/**
 * Creates a validator object and initiates it
 * @param {Model} model - A scoped model to the location on where to put the validator's data
 * @param {Model|string|Object} [origin|defaultObject] - Either a scoped model to the location where the original data is stored. Or, a path (as string) to the location where to find the original data. If not passed, the fields parameter is mandatory. Can also be passed in as a defaultObject. If passed in as default objet, the fields parameter is also mandatory.
 * @param {Collection.<string, Object>} [fields] - A collection of fields to use. If not passed, the origin parameter is mandatory. The key for each object is the field name, and the value is the field object (specified below).
   * @param {*} [fields.<fieldName>.default] - A default value for this specific field.
   * @param {Object[]} [fields.<fieldName>.validations] - A list of validations to apply.
     * @param {String|Function|RegEx} [fields.<fieldName>.validations.<index>.rule] - The rule to use when validating this rule. Either, this can be a string matching the name of a default rule (specified in default checks or passed in as an option), OR a function which will get run with the value to be validated as input, which should return true|false reflecting the validity, OR a RegEx, which will get run similar to if you pass in a function.
     * @param {String} [fields.<fieldName>.validations.<index>.message] - The error message to show if validation fails
 * @param {Object} [options] - An options object
   * @param {Collection.<string, Function|RegEx>} [options.rules] - A collection of default rules to add to this instance. Each key is the name of the rule. The value is the rule, either a function or regular expression similar to field specific functions/regular expressions passed in the fields parameter
 * @returns {Validator} - Instance of Validator
 */
function Validator(model, origin, fields, options) {
  // Parse out arguments
  var self = this;
  var args = Array.prototype.slice.call(arguments);

  if(!args.length) throw new Error('You must specify a model!');
  if(args.length == 1) throw new Error('You must either specify an origin or a fields object');

  this.model = args.shift();
  var arg = args.shift();

  // Origin cases
  if(arg instanceof Model) {
    this.origin = arg;

    arg = args.shift();
  } else if(typeof arg === 'string') {
    this.origin = this.model.scope(arg);

    arg = args.shift();
  }

  // If only a collection was passed, assume we want to add to a new doc
  if(this.origin) {
    var segments = this.origin._splitPath();

    if(segments.length === 1) {
      // Generate a new id
      this.origin = this.origin.at(model.id());
    }
  }

  if(arg) {
    // Case where we've passed in a default object
    if(!Array.isArray(arg) && typeof args[0] !== 'undefined') {
      var defaultObject = arg;

      arg = args.shift();
    }

    // Fields argument
    if(Array.isArray(arg)) {
      // Support passing in an array of fields
      this.fields = _.zipObject(arg, _.fill(Array(arg.length), {}));
    } else {
      this.fields = arg;
    }

    if(defaultObject) {
      _.each(defaultObject, function (val, key) {
        if(!self.fields[key]) self.fields[key] = {};

        self.fields[key]['default'] = val;
      });
    }
  }

  this.options = _.assign({
    rules: {},
    messages: {}
  }, args.shift());

  // Setup
  this._setup();
}

// TODO: Add proper docs for external facing methods, such as this one
Validator.prototype.getValues = function () {
  var values = {};
  _.each(this.model.get(), function (field, fieldName) {
    values[fieldName] = field.value;
  });
  return values;
};

// TODO: Add proper docs for external facing methods, such as this one
Validator.prototype.validate = function (fieldname) {
  return this._validate(fieldname);
};

// TODO: Add proper docs for external facing methods, such as this one
Validator.prototype.validateAll = function() {
  var valid = true;
  var self = this;

  _.each(this.model.get(), function (field, fieldName) {
    var fieldIsValid = self._validate(fieldName);

    if(valid) valid = fieldIsValid;
  });

  return valid;
};

// TODO: Add proper docs for external facing methods, such as this one
Validator.prototype.setInvalid = function (fieldName, message) {
  this._setValidity(fieldName, false);
  this.model.push(fieldName + '.messages', message || defaultValidations['default'].message);
};

/*
 * @public
 * Reset values to origin.
 */
Validator.prototype.reset = function () {
  this._setup();
};

/*
 * @public
 * Commit values to model. Call after client- and serverside validation.
 *
 * @param {Boolean} force - Whether to force commit despite validation not passing
 */
Validator.prototype.commit = function (force) {
  if(!this.origin) return;

  if(!force && !this.validateAll()) return;

  var values = {};

  _.each(this.model.get(), function (field, fieldName) {
    if(fieldName !== 'id' && field && field.hasOwnProperty('value')) values[fieldName] = field.value;
  });

  if(this.origin.get('id')) {
    this.origin.setEach(values);
  } else {
    // REVIEW: If we haven fetched/subscribed to a doc which we have the id for (i.e. we try to add a doc which already exists in DB), we get random errors that we don't handle (but doesn't seem to really affect anything)
    this.origin.add(values);
  }
};

Validator.prototype._setup = function () {
  var self = this;

  if (this.fields) {
    _.each(this.fields, function (field, fieldName) {
      self._addFieldProperties(fieldName, field);
    });
  }

  if(this.origin) {
    _.each(this.origin.get(), function (value, fieldName) {
      self.model.set(fieldName + '.value', value);
    });
  }
};

Validator.prototype._addFieldProperties = function (fieldName, field) {
  var self = this;
  var data = {value: null};

  if(field) {
    data = {value: field.default};

    if(field.validations) {
      _.assign(data, {
        validations: this._assignValidations(field.validations),
        isValid: false,
        isInvalid: false,
        validate: function () {
          self._validate(fieldName);
        }
      });
    }
  }

  this.model.setEach(fieldName, data);
};

Validator.prototype._validate = function (fieldName) {
  this.model.del(fieldName + '.messages');

  var field = this.model.get(fieldName);
  if(!field || !field.hasOwnProperty('validations')) return true;

  var valid = true;
  for (var i = 0; i < field.validations.length; i++) {
    var validation = field.validations[i];

    if (!this._check(field, validation.rule)) {
      valid = false;

      this.model.push(fieldName + '.messages', validation.message);
    }
  }

  this._setValidity(fieldName, valid);

  return valid;
};

Validator.prototype._assignValidations = function (validations) {
  for (var i = 0; i < validations.length; i++) {
    var validation = validations[i];

    if (!validation.message) validation.message = this._getMessage(validation.rule);

    if (typeof validation.rule === 'string') validation.rule = this._getRule(validation.rule);

    if (typeof validation.rule !== 'function' && !_.isRegExp(validation.rule)) throw new Error('This rule is not (or does not point to) a RegEx or a function.');
  }

  return validations;
};

Validator.prototype._getRule = function (ruleName) {
  if(this.options.rules[ruleName]) return this.options.rules[ruleName];

  if(defaultValidations.hasOwnProperty(ruleName)) return defaultValidations[ruleName].rule;

  throw new Error('Rule: "' + ruleName + '" is not available. You need to add it as an option.');
};

Validator.prototype._getMessage = function (ruleName) {
  return this.options.messages[ruleName] || ((defaultValidations.hasOwnProperty(ruleName)) ? defaultValidations[ruleName].message : defaultValidations['default'].message);
};

Validator.prototype._check = function (field, rule) {
  if(_.isRegExp(rule)) return rule.test(field.value);

  if(typeof rule === 'function') return rule(field.value);
};

Validator.prototype._setValidity = function (fieldName, validity) {
  this.model.setEach(fieldName, { isValid: validity, isInvalid: !validity });
  this._setState();
};

Validator.prototype._setState = function() {
  this.model.set('hasInvalidFields', !!_.result(_.find(this.model.get(), {'isInvalid': true}), 'isInvalid'));
};
<|endoftext|>


<commit_before>"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
var querystring_1 = require("querystring");
var loader = function (source, sourceMap) {
    if (this.version && Number(this.version) >= 2) {
        try {
            this.cacheable && this.cacheable();
            this.callback(null, "module.exports = " + generateCode(source, querystring_1.parse(this.resourceQuery)), sourceMap);
        }
        catch (err) {
            this.emitError(err.message);
            this.callback(err);
        }
    }
    else {
        var message = 'support webpack 2 later';
        this.emitError(message);
        this.callback(new Error(message));
    }
};
function generateCode(source, query) {
    var _a;
    var code = '';
    var value = typeof source === 'string'
        ? JSON.parse(source)
        : Buffer.isBuffer(source)
            ? JSON.parse(source.toString())
            : null;
    if (value === null) {
        throw new Error('invalid source!');
    }
    if (query.locale && typeof query.locale === 'string') {
        value = Object.assign({}, (_a = {}, _a[query.locale] = value, _a));
    }
    value = JSON.stringify(value)
        .replace(/\u2028/g, '\\u2028')
        .replace(/\u2029/g, '\\u2029')
        .replace(/\\/g, '\\\\');
    code += "function (Component) {\n  Component.options.__i18n = Component.options.__i18n || []\n  Component.options.__i18n.push('" + value.replace(/\u0027/g, '\\u0027') + "')\n  delete Component.options._Ctor\n}\n";
    return code;
}
exports.default = loader;
<commit_msg>:bug: bug: fix dist file<commit_after>"use strict";
var __importDefault = (this && this.__importDefault) || function (mod) {
    return (mod && mod.__esModule) ? mod : { "default": mod };
};
Object.defineProperty(exports, "__esModule", { value: true });
var querystring_1 = require("querystring");
var json5_1 = __importDefault(require("json5"));
var js_yaml_1 = __importDefault(require("js-yaml"));
var loader = function (source, sourceMap) {
    if (this.version && Number(this.version) >= 2) {
        try {
            this.cacheable && this.cacheable();
            this.callback(null, "module.exports = " + generateCode(source, querystring_1.parse(this.resourceQuery)), sourceMap);
        }
        catch (err) {
            this.emitError(err.message);
            this.callback(err);
        }
    }
    else {
        var message = 'support webpack 2 later';
        this.emitError(message);
        this.callback(new Error(message));
    }
};
function generateCode(source, query) {
    var _a;
    var data = convert(source, query.lang);
    var value = JSON.parse(data);
    if (query.locale && typeof query.locale === 'string') {
        value = Object.assign({}, (_a = {}, _a[query.locale] = value, _a));
    }
    value = JSON.stringify(value)
        .replace(/\u2028/g, '\\u2028')
        .replace(/\u2029/g, '\\u2029')
        .replace(/\\/g, '\\\\');
    var code = '';
    code += "function (Component) {\n  Component.options.__i18n = Component.options.__i18n || []\n  Component.options.__i18n.push('" + value.replace(/\u0027/g, '\\u0027') + "')\n  delete Component.options._Ctor\n}\n";
    return code;
}
function convert(source, lang) {
    var value = Buffer.isBuffer(source) ? source.toString() : source;
    switch (lang) {
        case 'yaml':
        case 'yml':
            var data = js_yaml_1.default.safeLoad(value);
            return JSON.stringify(data, undefined, '\t');
        case 'json5':
            return JSON.stringify(json5_1.default.parse(value));
        default:
            return value;
    }
}
exports.default = loader;
<|endoftext|>


<commit_before>var gulp = require('gulp'),
    uglify = require('gulp-uglify'),
    eslint = require('gulp-eslint'),
    istanbul = require('gulp-istanbul'),
    rename = require('gulp-rename'),
    sourcemaps = require('gulp-sourcemaps'),
    mocha = require('gulp-mocha'),
    gzip = require('gulp-gzip'),
    umd = require('gulp-umd');

gulp.task('lint', function () {
    return gulp.src('./multivents.js')
        .pipe(eslint())
        .pipe(eslint.format())
        .pipe(eslint.failAfterError());
});

gulp.task('pre-test', [ 'build' ], function () {
    return gulp.src('../dist/multivents.umd.js')
        .pipe(istanbul())
        .pipe(istanbul.hookRequire());
});

gulp.task('test', [ 'pre-test' ], function () {
    return gulp.src('./tests/*.js')
        .pipe(mocha({ reporter: 'progress' }))
        .pipe(istanbul.writeReports({ reporters: [ 'text', 'html' ] }));
});

gulp.task('umd', function () {
    return gulp.src('./multivents.js')
        .pipe(rename('multivents.umd.js'))
        .pipe(umd({
            exports: function (file) {
                return 'Channel';
            },
            templateName: 'returnExports',
            namespace: function () {
                return 'Channel';
            }
        }))
        .pipe(gulp.dest('./dist'));
});

gulp.task('build', [ 'umd' ], function () {
    return gulp.src('./dist/multivents.umd.js')
        .pipe(rename('multivents.umd.min.js'))
        .pipe(sourcemaps.init())
            .pipe(uglify())
        .pipe(sourcemaps.write('./', {includeContent:false}))
        .pipe(gulp.dest('./dist/'));
});

gulp.task('compress', [ 'build' ], function () {
    return gulp.src('./dist/multivents.umd.min.js')
        .pipe(gzip())
        .pipe(gulp.dest('./dist/'));
});

gulp.task('default', [ 'lint', 'test', 'build', 'compress' ]);
<commit_msg>Fixed test-coverage not being computed correctly<commit_after>var gulp = require('gulp'),
    uglify = require('gulp-uglify'),
    eslint = require('gulp-eslint'),
    istanbul = require('gulp-istanbul'),
    rename = require('gulp-rename'),
    sourcemaps = require('gulp-sourcemaps'),
    mocha = require('gulp-mocha'),
    gzip = require('gulp-gzip'),
    umd = require('gulp-umd');

gulp.task('lint', function () {
    return gulp.src('./multivents.js')
        .pipe(eslint())
        .pipe(eslint.format())
        .pipe(eslint.failAfterError());
});

gulp.task('pre-test', [ 'build' ], function () {
    return gulp.src('./dist/multivents.umd.js')
        .pipe(istanbul())
        .pipe(istanbul.hookRequire());
});

gulp.task('test', [ 'pre-test' ], function () {
    return gulp.src('./tests/*.js')
        .pipe(mocha({ reporter: 'progress' }))
        .pipe(istanbul.writeReports({ reporters: [ 'text', 'html' ] }));
});

gulp.task('umd', function () {
    return gulp.src('./multivents.js')
        .pipe(rename('multivents.umd.js'))
        .pipe(umd({
            exports: function (file) {
                return 'Channel';
            },
            templateName: 'returnExports',
            namespace: function () {
                return 'Channel';
            }
        }))
        .pipe(gulp.dest('./dist'));
});

gulp.task('build', [ 'umd' ], function () {
    return gulp.src('./dist/multivents.umd.js')
        .pipe(rename('multivents.umd.min.js'))
        .pipe(sourcemaps.init())
            .pipe(uglify())
        .pipe(sourcemaps.write('./', {includeContent:false}))
        .pipe(gulp.dest('./dist/'));
});

gulp.task('compress', [ 'build' ], function () {
    return gulp.src('./dist/multivents.umd.min.js')
        .pipe(gzip())
        .pipe(gulp.dest('./dist/'));
});

gulp.task('default', [ 'lint', 'test', 'build', 'compress' ]);
<|endoftext|>


<commit_before>var Watchy = require('./watchy')
var Elastomer = require('./elastomer')
var HTMLElastomer = require('./htmlelastomer')
var MapWay = require('./mapway')
var HTMLElement = window.HTMLElement

module.exports = elastomer

function elastomer (name, init) {
  init = init || {}

  if (init.prototype) {
    return document.registerElement(name, init)
  } else {
    var base = init.extends ? Object.getPrototypeOf(document.createElement(init.extends)) : HTMLElement.prototype
    var proto = Object.create(base)

    // Decorate with polymer handler methods on web component's standard methods
    proto.createdCallback = function () {
      this.elastomer = new Elastomer(this, init)
      this.elastomer.createdCallback()
    }

    proto.attributeChangedCallback = function () {
      this.elastomer.attributeChangedCallback.apply(this.elastomer, arguments)
    }

    proto.attachedCallback = function () {
      this.elastomer.attachedCallback.apply(this.elastomer, arguments)
    }

    proto.detachedCallback = function () {
      this.elastomer.detachedCallback.apply(this.elastomer, arguments)
    }

    // Linking method defined in the init object
    // this is only an easy way to define them. But they can be
    // defined on the element prototype returned too
    if (init.created) proto.created = init.created
    if (init.preLink) proto.preLink = init.preLink
    if (init.link) proto.link = init.link
    if (init.unlink) proto.unlink = init.unlink

    // Extend prototype with elastomer public api
    // This can be disabled to prevent exposition of those methods on the
    // element prototype

    // NOTICE : populateProto === false could become the default in v1
    if (init.populateProto !== false) {
      var publicMethods = [
        'isAttached',
        'getScope',
        'setScope',
        'watch',
        'watchAttribute',
        'mapAttribute',
        'mapAttributes',
        'watchProperty',
        'mapProperty',
        'mapProperties',
        'addClosable',
        'removeClosable',
        'closeAll'
      ]

      publicMethods.forEach(function (method) {
        proto[method] = function () {
          return this.elastomer[method].apply(this.elastomer, arguments)
        }
      })
    }

    return document.registerElement(name, {
      prototype: proto,
      extends: init.extends
    })

  }
}

elastomer.Elastomer = Elastomer
elastomer.HTMLElastomer = HTMLElastomer
elastomer.Watchy = Watchy
elastomer.MapWay = MapWay
<commit_msg>feat: Expose registered element localName<commit_after>var Watchy = require('./watchy')
var Elastomer = require('./elastomer')
var HTMLElastomer = require('./htmlelastomer')
var MapWay = require('./mapway')
var HTMLElement = window.HTMLElement

module.exports = elastomer

function elastomer (name, init) {
  var registeredElement
  init = init || {}

  if (init.prototype) {
     registeredElement = document.registerElement(name, init)
  } else {
    var base = init.extends ? Object.getPrototypeOf(document.createElement(init.extends)) : HTMLElement.prototype
    var proto = Object.create(base)

    // Decorate with polymer handler methods on web component's standard methods
    proto.createdCallback = function () {
      this.elastomer = new Elastomer(this, init)
      this.elastomer.createdCallback()
    }

    proto.attributeChangedCallback = function () {
      this.elastomer.attributeChangedCallback.apply(this.elastomer, arguments)
    }

    proto.attachedCallback = function () {
      this.elastomer.attachedCallback.apply(this.elastomer, arguments)
    }

    proto.detachedCallback = function () {
      this.elastomer.detachedCallback.apply(this.elastomer, arguments)
    }

    // Linking method defined in the init object
    // this is only an easy way to define them. But they can be
    // defined on the element prototype returned too
    if (init.created) proto.created = init.created
    if (init.preLink) proto.preLink = init.preLink
    if (init.link) proto.link = init.link
    if (init.unlink) proto.unlink = init.unlink

    // Extend prototype with elastomer public api
    // This can be disabled to prevent exposition of those methods on the
    // element prototype

    // NOTICE : populateProto === false could become the default in v1
    if (init.populateProto !== false) {
      var publicMethods = [
        'isAttached',
        'getScope',
        'setScope',
        'watch',
        'watchAttribute',
        'mapAttribute',
        'mapAttributes',
        'watchProperty',
        'mapProperty',
        'mapProperties',
        'addClosable',
        'removeClosable',
        'closeAll'
      ]

      publicMethods.forEach(function (method) {
        proto[method] = function () {
          return this.elastomer[method].apply(this.elastomer, arguments)
        }
      })
      registeredElement = document.registerElement(name, {
        prototype: proto,
        extends: init.extends
      })
    }
    registeredElement.localName = name
    return registeredElement
  }
}

elastomer.Elastomer = Elastomer
elastomer.HTMLElastomer = HTMLElastomer
elastomer.Watchy = Watchy
elastomer.MapWay = MapWay
<|endoftext|>


<commit_before>var fs   = require('fs'),
burrito  = require('burrito'),
outcome  = require('outcome'),
uglify = require('uglify-js'),
parser   = uglify.parser;

/**
 * finds an expression based on the filter given
 */

function traverse(ast, filter, filtered) {
	if(!filtered) filtered = [];

	for(var i = ast.length; i--;) {

		var node = ast[i];
		if(!(node instanceof Array)) continue;

		if(filter(node)) {
			filtered.push(node);
		}

		traverse(node, filter, filtered);
	}

	return filtered;
}

/**
 */

function cloneArray(target) {
	return JSON.parse(JSON.stringify(target));
}

/**
 */

function parse(content) {
	return parser.parse(content);
}

/**
 */

function stringify(ast, b) {
	return uglify.uglify.gen_code(ast, { beautify : b });
}

/**
 * wraps the target JS around a shit-ton of try catch blocks. Oh god why >.>...
 */

function wrapFunctionsWithShitLoadsOfTryCatchBlocks(content, ops) {

	//preprend the error handler if the option is set for it.
	if(ops.addHandler)
	content = "var catchall = catchall || { \
		error: function() {} \
	}" + content;

	var ast = parse(content);

	//first need to find ALL the functions in the given script
	var fns = traverse(ast, function(x) {
		return x[0] == 'defun' || x[0] == 'function';
	}),

	//next we need to parse a try-catch block. this wraps around the function body
	tryCatchAst = traverse(parse('try { } catch(e){ catchall.error(e); }'), function(x) {
		return x[0] == 'try';
	}).pop();

	//finally - need to loop through all the functions and wrap the
	//bodies in try/catch blocks
	for(var i = fns.length; i--;) {
		var fn = fns[i],
		tryCatchAstClone = cloneArray(tryCatchAst);

		//set the body to the try catch tpl
		tryCatchAstClone[1] = fn[3];

		//set fn body to the try-catch block
		fn[3] = [tryCatchAstClone];

	}

	return ast;

}

/**
 * generates from content
 */

exports.generate = function(content, ops, callback) {

	if(typeof ops == 'function') {

		callback = ops;
		ops = undefined;

	}

	try {

		//grap the new ast
		var ast = wrapFunctionsWithShitLoadsOfTryCatchBlocks(content, ops);

		//error not thrown at this point - good, now we can return the result.
		callback(null, stringify(ast, true));

	} catch(e) {

		//uglify-js didn't like the input
		return callback(e);

	}

}
<commit_msg>cleanup<commit_after>var fs   = require('fs'),
burrito  = require('burrito'),
outcome  = require('outcome'),
uglify = require('uglify-js'),
parser   = uglify.parser;

/**
 * finds an expression based on the filter given
 */

function traverse(ast, filter, filtered) {
	if(!filtered) filtered = [];

	for(var i = ast.length; i--;) {

		var node = ast[i];
		if(!(node instanceof Array)) continue;

		if(filter(node)) {
			filtered.push(node);
		}

		traverse(node, filter, filtered);
	}

	return filtered;
}

/**
 */

function cloneArray(target) {
	return JSON.parse(JSON.stringify(target));
}

/**
 */

function parse(content) {
	return parser.parse(content);
}

/**
 */

function stringify(ast, b) {
	return uglify.uglify.gen_code(ast, { beautify : b });
}

/**
 * wraps the target JS around a shit-ton of try catch blocks. Oh god why >.>...
 */

function wrapWithShitLoadsOfTryCatchBlocks(content, ops) {

	//preprend the error handler if the option is set for it.
	if(ops.addHandler)
	content = "var catchall = catchall || { \
		error: function() {} \
	}" + content;

	var ast = parse(content);

	//first need to find ALL the functions in the given script
	var fns = traverse(ast, function(x) {
		return x[0] == 'defun' || x[0] == 'function';
	}),

	//next we need to parse a try-catch block. this wraps around the function body
	tryCatchAst = traverse(parse('try { } catch(e){ catchall.error(e); }'), function(x) {
		return x[0] == 'try';
	}).pop();

	//finally - need to loop through all the functions and wrap the
	//bodies in try/catch blocks
	for(var i = fns.length; i--;) {
		var fn = fns[i],
		tryCatchAstClone = cloneArray(tryCatchAst);

		//set the body to the try catch tpl
		tryCatchAstClone[1] = fn[3];

		//set fn body to the try-catch block
		fn[3] = [tryCatchAstClone];

	}

	return ast;

}

/**
 * generates from content
 */

exports.generate = function(content, ops, callback) {

	if(typeof ops == 'function') {

		callback = ops;
		ops = undefined;

	}

	try {

		//grap the new ast
		var ast = wrapWithShitLoadsOfTryCatchBlocks(content, ops);

		//error not thrown at this point - good, now we can return the result.
		callback(null, stringify(ast, true));

	} catch(e) {

		//uglify-js didn't like the input
		return callback(e);

	}

}
<|endoftext|>


<commit_before>'use strict';

// Load modules

const Processor = require('./fileload');

// Declare internals

const internals = {};

exports.Processor = Processor;
<commit_msg>Updates index.js to setup interface<commit_after>/*
'use strict';

// Load modules

//const Processor = require('./fileload');

// Declare internals

//const internals = {};

//exports.Processor = Processor;

const parse5 = require('parse5');
const utils = require('parse5-utils');

var parser = new parse5.Parser();
var parser2 = new parse5.Parser(parse5.TreeAdapters.htmlparser2);
var html = '<!DOCTYPE html><title>Parse5 is fucking awesome!</title>
42

testing paragraph

Go Home

Go Forward

';

//Then feed it with an HTML document
var document = parser.parse(html);
var document2 = parser2.parse(html);

//Now let's parse HTML-snippet
var fragment = parser.parseFragment('<title>Parse5 is fucking awesome!</title>
42
');

console.log(document2);

// console.log(fragment);
*/

'use strict';

// Load Modules
var Parser = require('./parser');

// Template
exports.template = function template(html, options, reporter) {
	var parser = new Parser(options, reporter);

	return parser.parse(html);
};<|endoftext|>


<commit_before>const gulp = require("gulp"),
  uglify = require("gulp-uglify"),
  cleanCss = require("gulp-clean-css"),
  ts = require("gulp-typescript"),
  rename = require("gulp-rename"),
  sass = require("gulp-sass"),
  browserSync = require("browser-sync"),
  reload = browserSync.reload;

const srcTypescriptFolder = "./src/tsc",
  srcTypescriptConfig = srcTypescriptFolder + "/tsconfig.json",
  srcTypescriptConfigES6 = srcTypescriptFolder + "/tsconfig.es6.json",
  srcTypescript = srcTypescriptFolder + "/**/*.ts",
  srcJsFolder = "./src/js",
  srcJsLocales = srcJsFolder + "/locales/*.js",
  srcSassFolder = "./src/scss",
  srcSass = srcSassFolder + "/**/*.scss",
  srcSassMain = srcSassFolder + "/main.scss",
  distFolder = "./dist",
  distLocalesFolder = distFolder + "/locales",
  demoFolder = "./demo",
  demoJs = demoFolder + "/js",
  demoJsLocales = demoJs + "/locales",
  demoCss = demoFolder + "/css",
  taskBrowserSync = "browserSync",
  taskCompileTypescript = "ts",
  taskCompileTypescriptES6 = "ts_es6",
  taskCopyLocales = "copy_locales",
  taskCompileSass = "sass",
  taskWatcher = "watch";

// Browser-sync task
gulp.task(taskBrowserSync, () => {
  browserSync({
    server: {
      baseDir: demoFolder
    }
  });
});

// Typescript task
gulp.task(taskCompileTypescript, done => {
  const tsProject = ts.createProject(srcTypescriptConfig);
  const tsResult = gulp.src(srcTypescript).pipe(tsProject());

  done();
  return [
    tsResult.js
      .pipe(gulp.dest(demoJs))
      .pipe(gulp.dest(distFolder))
      .pipe(
        uglify({
          preserveComments: "false"
        })
      )
      .pipe(
        rename({
          suffix: ".min"
        })
      )
      .pipe(gulp.dest(distFolder))
      .pipe(
        reload({
          stream: true
        })
      )
  ];
});

// Typescript ES6 compilation task
gulp.task(taskCompileTypescriptES6, done => {
  const tsProject = ts.createProject(srcTypescriptConfigES6);
  const tsResult = gulp.src(srcTypescript).pipe(tsProject());

  done();
  return [
    tsResult.js.pipe(gulp.dest(distFolder)).pipe(
      reload({
        stream: true
      })
    )
  ];
});

// Copy locales task
gulp.task(taskCopyLocales, done => {
  done();
  return gulp
    .src(srcJsLocales)
    .pipe(gulp.dest(demoJsLocales))
    .pipe(gulp.dest(distLocalesFolder));
});

// Sass task
gulp.task(taskCompileSass, done => {
  done();
  return gulp
    .src(srcSassMain)
    .pipe(sass())
    .pipe(rename("jquery.brickyeditor.css"))
    .pipe(gulp.dest(demoCss))
    .pipe(gulp.dest(distFolder))
    .pipe(cleanCss())
    .pipe(
      rename({
        suffix: ".min"
      })
    )
    .pipe(gulp.dest(distFolder))
    .pipe(
      reload({
        stream: true
      })
    );
});

// Changes tracking task
gulp.task(taskWatcher, () => {
  gulp.watch(srcTypescript, gulp.series(taskCompileTypescript));
  gulp.watch(srcSass, gulp.series(taskCompileSass));
});

gulp.task(
  "default",
  gulp.series([
    taskCompileTypescript,
    taskCompileTypescriptES6,
    taskCopyLocales,
    taskCompileSass,
    taskWatcher,
    taskBrowserSync
  ]),
  done => {
    done();
  }
);

gulp.task(
  "build",
  gulp.series([
    taskCompileTypescript,
    taskCompileTypescriptES6,
    taskCopyLocales,
    taskCompileSass
  ]),
  done => {
    done();
  }
);
<commit_msg>gulp browserWatch task fixed<commit_after>const gulp = require("gulp"),
  uglify = require("gulp-uglify"),
  cleanCss = require("gulp-clean-css"),
  ts = require("gulp-typescript"),
  rename = require("gulp-rename"),
  sass = require("gulp-sass"),
  browserSync = require("browser-sync"),
  reload = browserSync.reload;

const srcTypescriptFolder = "./src/tsc",
  srcTypescriptConfig = srcTypescriptFolder + "/tsconfig.json",
  srcTypescriptConfigES6 = srcTypescriptFolder + "/tsconfig.es6.json",
  srcTypescript = srcTypescriptFolder + "/**/*.ts",
  srcJsFolder = "./src/js",
  srcJsLocales = srcJsFolder + "/locales/*.js",
  srcSassFolder = "./src/scss",
  srcSass = srcSassFolder + "/**/*.scss",
  srcSassMain = srcSassFolder + "/main.scss",
  distFolder = "./dist",
  distLocalesFolder = distFolder + "/locales",
  demoFolder = "./demo",
  demoJs = demoFolder + "/js",
  demoJsLocales = demoJs + "/locales",
  demoCss = demoFolder + "/css",
  taskBrowserSync = "browserSync",
  taskCompileTypescript = "ts",
  taskCompileTypescriptES6 = "ts_es6",
  taskCopyLocales = "copy_locales",
  taskCompileSass = "sass",
  taskWatcher = "watch";

// Browser-sync task
gulp.task(taskBrowserSync, done => {
  browserSync({
    server: {
      baseDir: demoFolder
    },
    https: true,
    port: 3000
  });

  browserSync.watch(demoFolder).on("change", browserSync.reload);

  done();
});

// Typescript task
gulp.task(taskCompileTypescript, done => {
  const tsProject = ts.createProject(srcTypescriptConfig);
  const tsResult = gulp.src(srcTypescript).pipe(tsProject());

  done();
  return [
    tsResult.js
      .pipe(gulp.dest(demoJs))
      .pipe(gulp.dest(distFolder))
      .pipe(
        uglify({
          preserveComments: "false"
        })
      )
      .pipe(
        rename({
          suffix: ".min"
        })
      )
      .pipe(gulp.dest(distFolder))
      .pipe(
        reload({
          stream: true
        })
      )
  ];
});

// Typescript ES6 compilation task
gulp.task(taskCompileTypescriptES6, done => {
  const tsProject = ts.createProject(srcTypescriptConfigES6);
  const tsResult = gulp.src(srcTypescript).pipe(tsProject());

  done();
  return [
    tsResult.js.pipe(gulp.dest(distFolder)).pipe(
      reload({
        stream: true
      })
    )
  ];
});

// Copy locales task
gulp.task(taskCopyLocales, done => {
  done();
  return gulp
    .src(srcJsLocales)
    .pipe(gulp.dest(demoJsLocales))
    .pipe(gulp.dest(distLocalesFolder));
});

// Sass task
gulp.task(taskCompileSass, done => {
  done();
  return gulp
    .src(srcSassMain)
    .pipe(sass())
    .pipe(rename("jquery.brickyeditor.css"))
    .pipe(gulp.dest(demoCss))
    .pipe(gulp.dest(distFolder))
    .pipe(cleanCss())
    .pipe(
      rename({
        suffix: ".min"
      })
    )
    .pipe(gulp.dest(distFolder))
    .pipe(
      reload({
        stream: true
      })
    );
});

// Changes tracking task
gulp.task(taskWatcher, () => {
  gulp.watch(srcTypescript, gulp.series(taskCompileTypescript));
  gulp.watch(srcSass, gulp.series(taskCompileSass));
});

gulp.task(
  "default",
  gulp.series([
    taskCompileTypescript,
    taskCompileTypescriptES6,
    taskCopyLocales,
    taskCompileSass,
    taskBrowserSync,
    taskWatcher
  ]),
  done => {
    done();
  }
);

gulp.task(
  "build",
  gulp.series([
    taskCompileTypescript,
    taskCompileTypescriptES6,
    taskCopyLocales,
    taskCompileSass
  ]),
  done => {
    done();
  }
);
<|endoftext|>


<commit_before>#! /usr/bin/env node
"use strict";

var BrowserSync   = require("./browser-sync");
var pjson         = require("../package.json");
var defaultConfig = require("./default-config");
var utils         = require("./utils");
var cli           = require("./cli");
var init          = cli.init;
var info          = cli.info;
var options       = cli.options;

var args          = require("optimist").argv;
var argv          = process.argv;

var _             = require("lodash");

var browserSync = new BrowserSync();

/**
 * @param {Array|Null} files
 * @param {Object} config
 * @param {Function} [cb]
 */
function start(files, config, cb) {
    return browserSync.init(files || [], config, pjson.version, cb);
}
module.exports.start = start;

/**
 * Handle Command-line usage
 */
if (require.main === module) {
    init.parse(pjson.version, args, argv, function (err, data) {
        if (err) {
            utils.fail(err, {}, true);
        }
        if (data.config) {
            start(data.files, data.config);
        }
        if (data.configFile) {
            info.makeConfig(argv);
        }
    });
}

/**
 * Handle External usage.
 * @param {Array} [userFiles]
 * @param {Object} [userConfig]
 * @param {Function} [cb]
 * @returns {exports.EventEmitter}
 */
module.exports.init = function (userFiles, userConfig, cb) {
    var config = _.merge(defaultConfig, userConfig, function (a, b) {
        return _.isArray(a) ? a.concat(b) : undefined;
    });
    var files  = options._mergeFilesOption(userFiles, config.exclude);
    config = init.mergeOptions(defaultConfig, config, init.allowedOptions);
    return exports.start(files, config, cb);
};

/**
 * @param {String} name
 * @param {Function} func
 * @param {Function} [cb]
 */
module.exports.use = function (name, func, cb) {
    browserSync.registerPlugin(name, func, cb);
};
<commit_msg>Don't include duplicate values twice<commit_after>#! /usr/bin/env node
"use strict";

var BrowserSync   = require("./browser-sync");
var pjson         = require("../package.json");
var defaultConfig = require("./default-config");
var utils         = require("./utils");
var cli           = require("./cli");
var init          = cli.init;
var info          = cli.info;
var options       = cli.options;

var args          = require("optimist").argv;
var argv          = process.argv;

var _             = require("lodash");

var browserSync = new BrowserSync();

/**
 * @param {Array|Null} files
 * @param {Object} config
 * @param {Function} [cb]
 */
function start(files, config, cb) {
    return browserSync.init(files || [], config, pjson.version, cb);
}
module.exports.start = start;

/**
 * Handle Command-line usage
 */
if (require.main === module) {
    init.parse(pjson.version, args, argv, function (err, data) {
        if (err) {
            utils.fail(err, {}, true);
        }
        if (data.config) {
            start(data.files, data.config);
        }
        if (data.configFile) {
            info.makeConfig(argv);
        }
    });
}

/**
 * Handle External usage.
 * @param {Array} [userFiles]
 * @param {Object} [userConfig]
 * @param {Function} [cb]
 * @returns {exports.EventEmitter}
 */
module.exports.init = function (userFiles, userConfig, cb) {
    var config = _.merge(defaultConfig, userConfig, function (a, b) {
        return _.isArray(a) ? _.union(a, b) : undefined;
    });
    var files  = options._mergeFilesOption(userFiles, config.exclude);
    config = init.mergeOptions(defaultConfig, config, init.allowedOptions);
    return exports.start(files, config, cb);
};

/**
 * @param {String} name
 * @param {Function} func
 * @param {Function} [cb]
 */
module.exports.use = function (name, func, cb) {
    browserSync.registerPlugin(name, func, cb);
};
<|endoftext|>


<commit_before>var requireL = require("root-require")("./src/require-local.js");
var console_log = requireL("logging").logger("console");

var _ = require('underscore-node');
var serverIpAddress = "";

// @TODO move to monkeypatch-array module
Array.prototype.flatten = function() {return _.flatten(this)};

var os = require('os');
var exec = require('child_process').exec;
var bus = require("hermes-bus");
var MAX_STDOUT_BUFFER = {maxBuffer: 500 * 1024};

var numSlaves = 1;
var dockerSlaveImageId = 'next-swarm-slave';
var dockerSlaveTimeout = 30;
var dockerSlaveOptions = "";
bus.on("registerCommandlineArguments", function (parser) {
	parser.addArgument(
		['-s', '--slaves'],
		{
			dest: 'numSlaves',
			metavar: 'NUM',
			help: 'Specify a how many slaves to start.'
		}
	);
	parser.addArgument(
		['--docker-slave-image-id'],
		{
			dest: 'dockerSlaveImageId',
			metavar: 'ID',
			help: 'The slave image id that docker uses to run a slave (default: \'next-swarm-slave\').'
		}
	);
	parser.addArgument(
		['--docker-slave-timeout'],
		{
			dest: 'dockerSlaveTimeout',
			metavar: 'SEC',
			help: 'The allowed maximum number of seconds between two consecutive heartbeats before next-swarm considers the slave lost.'
		}
	);
	parser.addArgument(
		['--docker-slave-options'],
		{
			dest: 'dockerSlaveOptions',
			metavar: 'OPTIONS',
			help: 'Additional options passed to docker when starting slaves.'
		}
	);
});

bus.on("commandlineArgumentsParsed", function (args) {
	numSlaves = args.numSlaves || numSlaves;
	dockerSlaveImageId = args.dockerSlaveImageId || dockerSlaveImageId;

	// Explicit loose equality check
	dockerSlaveTimeout = args.dockerSlaveTimeout != undefined ? args.dockerSlaveTimeout : dockerSlaveTimeout;
	dockerSlaveOptions = args.dockerSlaveOptions != undefined ? args.dockerSlaveOptions : dockerSlaveOptions;
});

with(requireL("tasks").statusTypes) {

var tasks = [];

bus.on("scheduleTasks", function(tasks2) {
	tasks = tasks2;
});

// maximum time since last heartbeat before we consider the slave lost
var getSlaveMaxTimeout = function() {
	return dockerSlaveTimeout*1000;
}

// interval at which we check if a slave was lost
var SLAVE_SANITY_CHECK_INTERVAL= 1000;
// slave looks like: {workerId: "docker container id", timeOfLastHeartBeat: 1447284644252, taskName: "name of task it was running"}
var monitoredSlaves = [];
/*
 * Every SLAVE_SANITY_CHECK_INTERVAL ms we check if slaves were lost,
 * when this happens:
 *
 * 1) restart the slave
 * 2) reschedule the job that the slave was supposed to run
 */
var isMonitoringSlaves = false;
var startMonitoringSlaves = function() {
	isMonitoringSlaves = true;
	setInterval(function() {
//		console_log("Checking slaves:", JSON.stringify(monitoredSlaves, null, 4));
		var now = Date.now();
		monitoredSlaves.forEach(function(slave) {

			if((now - slave.timeOfLastHeartBeat) > getSlaveMaxTimeout()) {
				console_log("slave " + slave.workerId + " seems lost, restarting");
				restartSlave(slave.workerId);
				var task = tasks.find((task) => task.name === slave.taskName);

				if(task && !task.completed) {
					if(task.numRecoveryRunsLeft > 0){
						task.status = SCHEDULED;
						task.workerId = "<unknown>";
						task.numRecoveryRunsLeft -= 1;
					} else {
						task.status = FAILED;
						task.completed = true;
						console_log("Task: "+ task.name +" reached max numOfRecoveryRuns!");
					}
				}
			}
		});
	}, SLAVE_SANITY_CHECK_INTERVAL);
};

bus.on("taskUpdated", function(task) {
	if(task.workerId !== "<unknown>") {
		if(task.completed) {
			unmonitorSlave(task.workerId);
		} else if(task.status === PICKED_UP) {
			if(task.numRecoveryRunsLeft == undefined) {
				task.defineProperty("numRecoveryRunsLeft", 3);
			}

			monitorSlave(task);
		}
	}
});

bus.on("heartbeatReceived", function(workerId) {
	console_log("Heartbeat received from", workerId);

	var monitoredSlave = findSlave(workerId);
	if(monitoredSlave) {
		monitoredSlave.timeOfLastHeartBeat = Date.now();
	}
});

function restartSlave(workerId) {
	console_log("Restarting slave", workerId);

	unmonitorSlave(workerId);
	var command = "docker stop --time=3 " + workerId;
	exec(command, MAX_STDOUT_BUFFER, function (error) {
		if (error) {
			console_log("FAILED to kill container", workerId, error);
		}
	});
	//For some reason this fails to start the docker container ????
	startSlave(serverIpAddress);
}

function findSlave(workerId) {
	return monitoredSlaves.find((slave) => slave.workerId === workerId);
}

function monitorSlave(taskThatSlaveIsRunning) {
	var monitoredSlave = findSlave(taskThatSlaveIsRunning.workerId);
	if(!monitoredSlave) {
		monitoredSlaves.push({
			workerId: taskThatSlaveIsRunning.workerId,
			timeOfLastHeartBeat: Date.now(),
			taskName: taskThatSlaveIsRunning.name,
		});

		if(!isMonitoringSlaves) {
			startMonitoringSlaves();
		}
	}
}

function unmonitorSlave(workerId) {
	var monitoredSlave = findSlave(workerId);
	if(monitoredSlave) {
		monitoredSlaves = _.without(monitoredSlaves, monitoredSlave);
	}
};

function startSlaves(serverAddress) {
	serverIpAddress = serverAddress;
	_.range(numSlaves).forEach(function() {
		startSlave(serverAddress);
	});
}

var SIGTERM = 137;
function startSlave(serverAddress){
	console_log("Booting-up a docker container...");
	var command = "docker run " + dockerSlaveOptions + " " + dockerSlaveImageId + " " + serverAddress;
	exec(command, MAX_STDOUT_BUFFER, function(error){
		if(error && error.code !== SIGTERM){
			console_log("Failed to boot-up a slave:", error);
			bus.triggerRequestStopApplication({value: 1});
		}
	});
}

} // with tasks.statusTypes

var localIpAddress = "127.0.0.1";

bus.on("applicationStarted", function() {
	var firstNonLocalNetworkConfig = _.values(os.networkInterfaces()).flatten().find((e) => e.address !== "127.0.0.1" && e.address !== "::1" );

	if(firstNonLocalNetworkConfig) {
		localIpAddress = firstNonLocalNetworkConfig.address;
	} else {
		console_log("Error: Unable to determine public ip address of this host!");
		console_log( "Exiting...");
		bus.triggerRequestStopApplication({value: 1});
	}
});

bus.on("connectServerStarted", function(connectServer) {
	startSlaves("http://"+localIpAddress+":"+connectServer.address().port);
});
<commit_msg>src/manage-slaves.js: Increased the stdout maxBuffer to 3MB<commit_after>var requireL = require("root-require")("./src/require-local.js");
var console_log = requireL("logging").logger("console");

var _ = require('underscore-node');
var serverIpAddress = "";

// @TODO move to monkeypatch-array module
Array.prototype.flatten = function() {return _.flatten(this)};

var os = require('os');
var exec = require('child_process').exec;
var bus = require("hermes-bus");
// 3 MB of stdout buffer (@TODO we should use a ring-buffer)
var MAX_STDOUT_BUFFER = {maxBuffer: 3000 * 1024};

var numSlaves = 1;
var dockerSlaveImageId = 'next-swarm-slave';
var dockerSlaveTimeout = 30;
var dockerSlaveOptions = "";
bus.on("registerCommandlineArguments", function (parser) {
	parser.addArgument(
		['-s', '--slaves'],
		{
			dest: 'numSlaves',
			metavar: 'NUM',
			help: 'Specify a how many slaves to start.'
		}
	);
	parser.addArgument(
		['--docker-slave-image-id'],
		{
			dest: 'dockerSlaveImageId',
			metavar: 'ID',
			help: 'The slave image id that docker uses to run a slave (default: \'next-swarm-slave\').'
		}
	);
	parser.addArgument(
		['--docker-slave-timeout'],
		{
			dest: 'dockerSlaveTimeout',
			metavar: 'SEC',
			help: 'The allowed maximum number of seconds between two consecutive heartbeats before next-swarm considers the slave lost.'
		}
	);
	parser.addArgument(
		['--docker-slave-options'],
		{
			dest: 'dockerSlaveOptions',
			metavar: 'OPTIONS',
			help: 'Additional options passed to docker when starting slaves.'
		}
	);
});

bus.on("commandlineArgumentsParsed", function (args) {
	numSlaves = args.numSlaves || numSlaves;
	dockerSlaveImageId = args.dockerSlaveImageId || dockerSlaveImageId;

	// Explicit loose equality check
	dockerSlaveTimeout = args.dockerSlaveTimeout != undefined ? args.dockerSlaveTimeout : dockerSlaveTimeout;
	dockerSlaveOptions = args.dockerSlaveOptions != undefined ? args.dockerSlaveOptions : dockerSlaveOptions;
});

with(requireL("tasks").statusTypes) {

var tasks = [];

bus.on("scheduleTasks", function(tasks2) {
	tasks = tasks2;
});

// maximum time since last heartbeat before we consider the slave lost
var getSlaveMaxTimeout = function() {
	return dockerSlaveTimeout*1000;
}

// interval at which we check if a slave was lost
var SLAVE_SANITY_CHECK_INTERVAL= 1000;
// slave looks like: {workerId: "docker container id", timeOfLastHeartBeat: 1447284644252, taskName: "name of task it was running"}
var monitoredSlaves = [];
/*
 * Every SLAVE_SANITY_CHECK_INTERVAL ms we check if slaves were lost,
 * when this happens:
 *
 * 1) restart the slave
 * 2) reschedule the job that the slave was supposed to run
 */
var isMonitoringSlaves = false;
var startMonitoringSlaves = function() {
	isMonitoringSlaves = true;
	setInterval(function() {
//		console_log("Checking slaves:", JSON.stringify(monitoredSlaves, null, 4));
		var now = Date.now();
		monitoredSlaves.forEach(function(slave) {

			if((now - slave.timeOfLastHeartBeat) > getSlaveMaxTimeout()) {
				console_log("slave " + slave.workerId + " seems lost, restarting");
				restartSlave(slave.workerId);
				var task = tasks.find((task) => task.name === slave.taskName);

				if(task && !task.completed) {
					if(task.numRecoveryRunsLeft > 0){
						task.status = SCHEDULED;
						task.workerId = "<unknown>";
						task.numRecoveryRunsLeft -= 1;
					} else {
						task.status = FAILED;
						task.completed = true;
						console_log("Task: "+ task.name +" reached max numOfRecoveryRuns!");
					}
				}
			}
		});
	}, SLAVE_SANITY_CHECK_INTERVAL);
};

bus.on("taskUpdated", function(task) {
	if(task.workerId !== "<unknown>") {
		if(task.completed) {
			unmonitorSlave(task.workerId);
		} else if(task.status === PICKED_UP) {
			if(task.numRecoveryRunsLeft == undefined) {
				task.defineProperty("numRecoveryRunsLeft", 3);
			}

			monitorSlave(task);
		}
	}
});

bus.on("heartbeatReceived", function(workerId) {
	console_log("Heartbeat received from", workerId);

	var monitoredSlave = findSlave(workerId);
	if(monitoredSlave) {
		monitoredSlave.timeOfLastHeartBeat = Date.now();
	}
});

function restartSlave(workerId) {
	console_log("Restarting slave", workerId);

	unmonitorSlave(workerId);
	var command = "docker stop --time=3 " + workerId;
	exec(command, MAX_STDOUT_BUFFER, function (error) {
		if (error) {
			console_log("FAILED to kill container", workerId, error);
		}
	});
	//For some reason this fails to start the docker container ????
	startSlave(serverIpAddress);
}

function findSlave(workerId) {
	return monitoredSlaves.find((slave) => slave.workerId === workerId);
}

function monitorSlave(taskThatSlaveIsRunning) {
	var monitoredSlave = findSlave(taskThatSlaveIsRunning.workerId);
	if(!monitoredSlave) {
		monitoredSlaves.push({
			workerId: taskThatSlaveIsRunning.workerId,
			timeOfLastHeartBeat: Date.now(),
			taskName: taskThatSlaveIsRunning.name,
		});

		if(!isMonitoringSlaves) {
			startMonitoringSlaves();
		}
	}
}

function unmonitorSlave(workerId) {
	var monitoredSlave = findSlave(workerId);
	if(monitoredSlave) {
		monitoredSlaves = _.without(monitoredSlaves, monitoredSlave);
	}
};

function startSlaves(serverAddress) {
	serverIpAddress = serverAddress;
	_.range(numSlaves).forEach(function() {
		startSlave(serverAddress);
	});
}

var SIGTERM = 137;
function startSlave(serverAddress){
	console_log("Booting-up a docker container...");
	var command = "docker run " + dockerSlaveOptions + " " + dockerSlaveImageId + " " + serverAddress;
	exec(command, MAX_STDOUT_BUFFER, function(error){
		if(error && error.code !== SIGTERM){
			console_log("Failed to boot-up a slave:", error);
			bus.triggerRequestStopApplication({value: 1});
		}
	});
}

} // with tasks.statusTypes

var localIpAddress = "127.0.0.1";

bus.on("applicationStarted", function() {
	var firstNonLocalNetworkConfig = _.values(os.networkInterfaces()).flatten().find((e) => e.address !== "127.0.0.1" && e.address !== "::1" );

	if(firstNonLocalNetworkConfig) {
		localIpAddress = firstNonLocalNetworkConfig.address;
	} else {
		console_log("Error: Unable to determine public ip address of this host!");
		console_log( "Exiting...");
		bus.triggerRequestStopApplication({value: 1});
	}
});

bus.on("connectServerStarted", function(connectServer) {
	startSlaves("http://"+localIpAddress+":"+connectServer.address().port);
});
<|endoftext|>


<commit_before>( function() {
	'use strict';

	describe( 'vui', function() {

		var node, heading;

		beforeEach( function () {
			jasmine.addMatchers( d2l.jasmine.matchers );
			node = document.body.appendChild( document.createElement( 'div' ) );
			node.className = 'vui-accordion';
		} );

		afterEach( function() {
			document.body.removeChild( node );
		} );

		describe( 'accordion', function() {

			var accordion, header1, heading1, content1;

			beforeEach( function () {

				accordion = node.appendChild( document.createElement( 'div' ) );
				accordion.className = 'vui-accordion';
				accordion.setAttribute( 'data-display-mode', 'accordion' );

				header1 = accordion.appendChild( document.createElement( 'div' ) );
				header1.className = 'vui-accordion-header';
				header1.setAttribute( 'data-content-labelledby', 'heading1' );

				heading1 = header1.appendChild( document.createElement( 'h2' ) );
				heading1.id = 'heading1';
				heading1.innerHTML = 'This is heading 1.';

				content1 = accordion.appendChild( document.createElement( 'div' ) );
				content1.className = 'vui-accordion-content';

				content1.appendChild( document.createElement( 'p' ) ).innerHTML = 'This is content 1.';

			} );

			it( 'defines a "vui-accordion" selector', function() {
				expect( document ).toHaveCssSelector( '.vui-accordion' );
			} );

			it( 'initializes accordion using widget method', function() {

				$( accordion ).vui_accordion();

				expect( accordion.getAttribute( 'role' ) ).toBe( 'tablist' );

			} );

		} );

	} );

} )();<commit_msg>Remove unused variable.<commit_after>( function() {
	'use strict';

	describe( 'vui', function() {

		var node;

		beforeEach( function () {
			jasmine.addMatchers( d2l.jasmine.matchers );
			node = document.body.appendChild( document.createElement( 'div' ) );
			node.className = 'vui-accordion';
		} );

		afterEach( function() {
			document.body.removeChild( node );
		} );

		describe( 'accordion', function() {

			var accordion, header1, heading1, content1;

			beforeEach( function () {

				accordion = node.appendChild( document.createElement( 'div' ) );
				accordion.className = 'vui-accordion';
				accordion.setAttribute( 'data-display-mode', 'accordion' );

				header1 = accordion.appendChild( document.createElement( 'div' ) );
				header1.className = 'vui-accordion-header';
				header1.setAttribute( 'data-content-labelledby', 'heading1' );

				heading1 = header1.appendChild( document.createElement( 'h2' ) );
				heading1.id = 'heading1';
				heading1.innerHTML = 'This is heading 1.';

				content1 = accordion.appendChild( document.createElement( 'div' ) );
				content1.className = 'vui-accordion-content';

				content1.appendChild( document.createElement( 'p' ) ).innerHTML = 'This is content 1.';

			} );

			it( 'defines a "vui-accordion" selector', function() {
				expect( document ).toHaveCssSelector( '.vui-accordion' );
			} );

			it( 'initializes accordion using widget method', function() {

				$( accordion ).vui_accordion();

				expect( accordion.getAttribute( 'role' ) ).toBe( 'tablist' );

			} );

		} );

	} );

} )();<|endoftext|>


<commit_before>'use strict';
require('../../init');
let util = require('util');
let Client = require('../../../lib/client');
let client;
let success = false;
let game = {};
let done;

describe('Streams', function () {
    it('Stream throttle', function (testDone) {
        done = testDone;
        client = Client();
        client.rpc.on('open', clientConnectionOpen);
        client.rpc.on('error', onError);
        client.rpc.on('close', onClose);
    });
});

// ----=================[ Start helper functions ]=================----
function onError(err) {
    done(err);
}

function onClose(event) {
    if (success) {
        done();
    }
    return done(new Error(util.format("Socket closed before done", event)));
}

function getFirstResult(response) {
    expect(response.error).to.not.be.ok();
    expect(response.results.length).to.equal(1);
    let result = response.results[0];
    expect(result.error).to.not.be.ok();
    return result.value;
}

function replaceMessageHandler(fn) {
    client.rpc.emitter.removeAllListeners('message');
    client.rpc.on('message', fn);
}
// ----=================[ End helper functions ]=================----

function clientConnectionOpen() {
    let procedure = client.services.krpc.getClientId();
    client.rpc.send(procedure);
    client.rpc.on('message', getClientIdComplete);
}

function getClientIdComplete(response) {
    var id = getFirstResult(response).toString('base64');
    client.connectToStreamServer(id);
    client.stream.on('open', streamOpen);
    client.stream.on('error', onError);
    client.stream.on('close', onClose);
}

function streamOpen() {
    let procedure = client.services.spaceCenter.getActiveVessel();
    client.rpc.send(procedure);
    replaceMessageHandler(getActiveVesselComplete);
}

function getActiveVesselComplete(response) {
    game.vessel = {
        id: getFirstResult(response)
    };
    client.rpc.send(client.services.spaceCenter.vesselGetControl(game.vessel.id));
    replaceMessageHandler(getActiveVesselControlComplete);
}

function getActiveVesselControlComplete(response) {
    game.vessel.control = {
        id: getFirstResult(response)
    };
    client.rpc.send(client.services.spaceCenter.vesselGetOrbitalReferenceFrame(game.vessel.id));
    replaceMessageHandler(getOrbitalReferenceFrame);
}
function getOrbitalReferenceFrame(response) {
    game.vessel.orbitalReference = getFirstResult(response);
    client.rpc.send(client.services.spaceCenter.vesselFlight(game.vessel.id, game.vessel.orbitalReference));
    replaceMessageHandler(getVesselFlightComplete);
}

function getVesselFlightComplete(response) {
    game.vessel.flight = {
        id: getFirstResult(response)
    };
    let getThrottle = client.services.spaceCenter.controlGetThrottle(game.vessel.control.id);
    var addStreamCall = client.services.krpc.addStream(getThrottle.call);
    client.rpc.send(addStreamCall);
    replaceMessageHandler(streamAdded);
    client.stream.on('message', streamUpdate);
    function streamAdded(response) {
        var stream = getFirstResult(response);
        game.streams = game.streams || [];
        game.streams[stream.id.toString()] = getThrottle.decode;
    }
}

function streamUpdate(streamUpdate) {
    streamUpdate.results.forEach(function (update) {
        if (update.result.error) {
            console.error(update.result.error);
            return;
        }
        var parsedThrottleValue = game.streams[update.id.toString()](update.result.value);
        console.log(parsedThrottleValue);
    });
    // game.vessel.control.throttle = getFirstResult(response);
    // console.log(util.format("Updating throttle value from %s to 1", game.vessel.control.throttle));
    // replaceMessageHandler(setThrottleToFullComplete);
    // let call = client.services.spaceCenter.controlSetThrottle(game.vessel.control.id, 1);
    // client.rpc.send(call);
}

// function setThrottleToFullComplete(response) {
//     replaceMessageHandler(launched);
//     client.rpc.send(client.services.spaceCenter.controlActivateNextStage(game.vessel.control.id));
// }

// function launched(response) {
//     let vesselId = getFirstResult(response);
//     expect(vesselId).to.be.ok();
//     process.exit(0);
// }<commit_msg>Adding heading to the stream.<commit_after>'use strict';
require('../../init');
let util = require('util');
let Client = require('../../../lib/client');
let client;
let success = false;
let game = {};
let done;

describe('Streams', function () {
    it('Stream throttle', function (testDone) {
        done = testDone;
        client = Client();
        client.rpc.on('open', clientConnectionOpen);
        client.rpc.on('error', onError);
        client.rpc.on('close', onClose);
    });
});

// ----=================[ Start helper functions ]=================----
function onError(err) {
    done(err);
}

function onClose(event) {
    if (success) {
        done();
    }
    return done(new Error(util.format("Socket closed before done", event)));
}

function getFirstResult(response) {
    expect(response.error).to.not.be.ok();
    expect(response.results.length).to.equal(1);
    let result = response.results[0];
    expect(result.error).to.not.be.ok();
    return result.value;
}

function replaceMessageHandler(fn) {
    client.rpc.emitter.removeAllListeners('message');
    client.rpc.on('message', fn);
}
// ----=================[ End helper functions ]=================----

function clientConnectionOpen() {
    let procedure = client.services.krpc.getClientId();
    client.rpc.send(procedure);
    client.rpc.on('message', getClientIdComplete);
}

function getClientIdComplete(response) {
    var id = getFirstResult(response).toString('base64');
    client.connectToStreamServer(id);
    client.stream.on('open', streamOpen);
    client.stream.on('error', onError);
    client.stream.on('close', onClose);
}

function streamOpen() {
    let procedure = client.services.spaceCenter.getActiveVessel();
    client.rpc.send(procedure);
    replaceMessageHandler(getActiveVesselComplete);
}

function getActiveVesselComplete(response) {
    game.vessel = {
        id: getFirstResult(response)
    };
    client.rpc.send(client.services.spaceCenter.vesselGetControl(game.vessel.id));
    replaceMessageHandler(getActiveVesselControlComplete);
}

function getActiveVesselControlComplete(response) {
    game.vessel.control = {
        id: getFirstResult(response)
    };
    client.rpc.send(client.services.spaceCenter.vesselGetOrbitalReferenceFrame(game.vessel.id));
    replaceMessageHandler(getOrbitalReferenceFrame);
}
function getOrbitalReferenceFrame(response) {
    game.vessel.orbitalReference = getFirstResult(response);
    client.rpc.send(client.services.spaceCenter.vesselFlight(game.vessel.id, game.vessel.orbitalReference));
    replaceMessageHandler(getVesselFlightComplete);
}

function getVesselFlightComplete(response) {
    game.vessel.flight = {
        id: getFirstResult(response)
    };
    let getThrottle = client.services.spaceCenter.controlGetThrottle(game.vessel.control.id);
    var addStreamCall = client.services.krpc.addStream(getThrottle.call);
    client.rpc.send(addStreamCall);
    replaceMessageHandler(throttleStreamAdded);
    client.stream.on('message', streamUpdate);
    function throttleStreamAdded(response) {
        var stream = getFirstResult(response);
        game.streams = game.streams || [];
        game.streams[stream.id.toString()] = {
            name: "Throttle",
            decode: getThrottle.decode
        };
        let getHeading = client.services.spaceCenter.flightGetHeading(game.vessel.flight.id);
        addStreamCall = client.services.krpc.addStream(getHeading.call);
        client.rpc.send(addStreamCall);
        replaceMessageHandler(headingStreamAdded);

        function headingStreamAdded(response) {
            stream = getFirstResult(response);
            game.streams[stream.id.toString()] = {
                name: "Heading",
                decode: getHeading.decode
            };
        }
    }
}

function streamUpdate(streamUpdate) {
    streamUpdate.results.forEach(function (update) {
        if (update.result.error) {
            console.error(update.result.error);
            return;
        }
        var stream = game.streams[update.id.toString()];
        var parsedValue = stream.decode(update.result.value);
        console.log(stream.name, ' : ', parsedValue);
    });
    // game.vessel.control.throttle = getFirstResult(response);
    // console.log(util.format("Updating throttle value from %s to 1", game.vessel.control.throttle));
    // replaceMessageHandler(setThrottleToFullComplete);
    // let call = client.services.spaceCenter.controlSetThrottle(game.vessel.control.id, 1);
    // client.rpc.send(call);
}

// function setThrottleToFullComplete(response) {
//     replaceMessageHandler(launched);
//     client.rpc.send(client.services.spaceCenter.controlActivateNextStage(game.vessel.control.id));
// }

// function launched(response) {
//     let vesselId = getFirstResult(response);
//     expect(vesselId).to.be.ok();
//     process.exit(0);
// }<|endoftext|>


<commit_before>// main.js
(function() {

'use strict';

var React = require('react');
var ProductStore = require('./store/ProductStore');
var FilterableProductTable = require('./component/FilterableProductTable');

React.render(<FilterableProductTable />, document.getElementById('content'));

})();
<commit_msg>jsxhintの警告を抑えるために未使用変数を除去した<commit_after>// main.js
(function() {

'use strict';

var React = require('react');
var FilterableProductTable = require('./component/FilterableProductTable');

React.render(<FilterableProductTable />, document.getElementById('content'));

})();
<|endoftext|>