<commit_before>'use strict';

const preq = require('preq');
const assert = require('../../utils/assert.js');
const headers = require('../../utils/headers.js');
const server = require('../../utils/server.js');

describe('summary', function() {

    this.timeout(20000); // eslint-disable-line no-invalid-this

    before(() => { return server.start(); });

    const localUri = (title, domain = 'en.wikipedia.org') => {
        return `${server.config.uri}${domain}/v1/page/summary/${title}`;
    };

    it('should respond to GET request with expected headers, incl. CORS and CSP headers', () => {
        const uri = localUri('Foobar');
        return headers.checkHeaders(uri);
    });

    it('should respond with expected properties in payload', () => {
        const uri = localUri('Foobar/798652007');
        return preq.get({ uri })
            .then((res) => {
                assert.deepEqual(res.status, 200);
                assert.deepEqual(res.body.type, 'standard');
                assert.deepEqual(res.body.revision, 798652007);
                assert.deepEqual(res.body.titles.canonical, "Foobar");
                assert.deepEqual(res.body.titles.normalized, "Foobar");
                assert.deepEqual(res.body.titles.display, "Foobar");
                assert.ok(res.body.extract.indexOf('foobar') > -1);
                assert.ok(res.body.extract_html.indexOf('foobar') > -1);
            });
    });

    it('empty summary (not 204) should be sent for empty page', () => {
        const uri = localUri('PreviewsEmpty%2Fsandbox', 'en.wikipedia.beta.wmflabs.org');
        return preq.get({ uri })
            .then((res) => {
                assert.deepEqual(res.status, 200);
                assert.deepEqual(res.body.type, 'standard');
                assert.deepEqual(res.body.extract, '', 'should send empty plaintext extract');
                assert.deepEqual(res.body.extract_html, '', 'should send empty html extract');
            });
    });

    it('empty summary (not 204) should be sent for project main page', () => {
        const uri = localUri('Main_Page');
        return preq.get({ uri })
            .then((res) => {
                assert.deepEqual(res.status, 200);
                assert.deepEqual(res.body.type, 'standard');
                assert.deepEqual(res.body.extract, '', 'should send empty plaintext extract');
                assert.deepEqual(res.body.extract_html, '', 'should send empty html extract');
            });
    });

    it('204 should be returned for redirect page', () => {
        const uri = localUri('Barack');
        return preq.get({ uri })
            .then((res) => {
                assert.deepEqual(res.status, 204);
                assert.ok(!res.body);
            });
    });
});
<commit_msg>Hygiene: Move test request from enwiki beta to testwiki<commit_after>'use strict';

const preq = require('preq');
const assert = require('../../utils/assert.js');
const headers = require('../../utils/headers.js');
const server = require('../../utils/server.js');

describe('summary', function() {

    this.timeout(20000); // eslint-disable-line no-invalid-this

    before(() => { return server.start(); });

    const localUri = (title, domain = 'en.wikipedia.org') => {
        return `${server.config.uri}${domain}/v1/page/summary/${title}`;
    };

    it('should respond to GET request with expected headers, incl. CORS and CSP headers', () => {
        const uri = localUri('Foobar');
        return headers.checkHeaders(uri);
    });

    it('should respond with expected properties in payload', () => {
        const uri = localUri('Foobar/798652007');
        return preq.get({ uri })
            .then((res) => {
                assert.deepEqual(res.status, 200);
                assert.deepEqual(res.body.type, 'standard');
                assert.deepEqual(res.body.revision, 798652007);
                assert.deepEqual(res.body.titles.canonical, "Foobar");
                assert.deepEqual(res.body.titles.normalized, "Foobar");
                assert.deepEqual(res.body.titles.display, "Foobar");
                assert.ok(res.body.extract.indexOf('foobar') > -1);
                assert.ok(res.body.extract_html.indexOf('foobar') > -1);
            });
    });

    it('empty summary (not 204) should be sent for empty page', () => {
        const uri = localUri('Empty', 'test.wikipedia.org');
        return preq.get({ uri })
            .then((res) => {
                assert.deepEqual(res.status, 200);
                assert.deepEqual(res.body.type, 'standard');
                assert.deepEqual(res.body.extract, '', 'should send empty plaintext extract');
                assert.deepEqual(res.body.extract_html, '', 'should send empty html extract');
            });
    });

    it('empty summary (not 204) should be sent for project main page', () => {
        const uri = localUri('Main_Page');
        return preq.get({ uri })
            .then((res) => {
                assert.deepEqual(res.status, 200);
                assert.deepEqual(res.body.type, 'standard');
                assert.deepEqual(res.body.extract, '', 'should send empty plaintext extract');
                assert.deepEqual(res.body.extract_html, '', 'should send empty html extract');
            });
    });

    it('204 should be returned for redirect page', () => {
        const uri = localUri('Barack');
        return preq.get({ uri })
            .then((res) => {
                assert.deepEqual(res.status, 204);
                assert.ok(!res.body);
            });
    });
});
<|endoftext|>


<commit_before>'use strict';

var last      = require('es5-ext/lib/Array/prototype/last')
  , d         = require('es5-ext/lib/Object/descriptor')
  , forEach   = require('es5-ext/lib/Object/for-each')
  , callable  = require('es5-ext/lib/Object/valid-callable')
  , Relation  = require('./relation')
  , Item      = require('./rel-set-item')
  , serialize = require('./serialize')
  , signal    = require('./signal')

  , isArray = Array.isArray, call = Function.prototype.call
  , defineProperty = Object.defineProperty
  , defineProperties = Object.defineProperties
  , getOwnPropertyNames = Object.getOwnPropertyNames
  , getPrototypeOf = Object.getPrototypeOf, keys = Object.keys;

defineProperties(Relation.prototype, {
	_initSet_: d(function () {
		var value, key;
		defineProperty(this, '_count_', d(0));
		if (this.hasOwnProperty('_value') && (this._value != null) &&
				((typeof this._value !== 'function') || this._value._id_)) {
			value = this.ns.normalize(this._value);
			if (value == null) return;
			key = this.ns._serialize_(value);
			defineProperty(this, key, d('ce', new Item(this, key, this._value)));
			++this._count_;
		}
	}),
	count: d.gs(function () {
		var count;
		this._assertSet_();
		if (this.hasOwnProperty('_value')) return this._count_;
		count = 0;
		this.forEach(function () { ++count; });
		return count;
	}),
	_isSet_: d.gs(function () {
		return this.multiple &&
			((typeof this._value !== 'function') || this._value._id_) &&
			this.hasOwnProperty('_count_');
	}),
	_last_: d.gs(function () {
		if (!this._count_) return null;
		return this[last.call(keys(this))];
	}),
	_assertSet_: d(function () {
		if (!this._isSet_) throw new TypeError("Property is not a set");
	}),
	add: d(function (value) {
		var error = this.addValidate(value);
		if (error) throw error;
		if (!this.ns.is(value)) value = this.ns.$construct(value);
		return this.$add(value);
	}),
	$add: d(function (value) {
		var key = serialize(value), item;
		if (!this.propertyIsEnumerable(key)) {
			if (this.hasOwnProperty(key)) {
				item = this[key];
				item._value = value;
				defineProperty(this, key, d('ce', item));
			} else {
				item = new Item(this, key, value);
				defineProperty(this, key, d('ce', item));
			}
			if (this.hasOwnProperty('_value')) {
				if (this._value === null) this._onOld_(null);
				this._value = value;
			}
			++this._count_;
			this._onNew_(value);
			this.emit('add', value, item);
		} else {
			item = this[key];
		}
		signal(item, true);
		return item;
	}),
	$setItem: d(function (key) {
		if (this.hasOwnProperty(key)) return;
		defineProperty(this, key, d('c', new Item(this, key)));
	}),
	addValidate: d(function (value) {
		this._assertSet_();
		if ((value == null) || ((typeof value === 'function') && !value._id_) ||
				isArray(value)) {
			return new TypeError(value + " is not valid " + this.ns._id_);
		}
		return this._validate_(value);
	}),
	delete: d(function (value) {
		var key, isTopValue, item;
		this._assertSet_();
		if ((value == null) || ((typeof value === 'function') && !value._id_)) {
			return;
		}

		value = this.ns.normalize(value);
		if (value == null) return;
		if (!(key = this.ns._serialize_(value))) return;

		if (this.propertyIsEnumerable(key)) {
			isTopValue = this.hasOwnProperty('_value') && (this._value === value);
			if (isTopValue && this._required && (this._count_ === 1)) {
				throw new TypeError('Cannot remove the only value');
			}
			item = this[key];
			item._value = null;
			--this._count_;
			defineProperty(this, key, d('c', item));
			if (isTopValue) {
				this._value = this._last_._value;
				if (this._value === null) this._onNew_(null);
			}
			this._onOld_(value);
			this.emit('delete', value, item);
		} else if (!this.hasOwnProperty(key)) {
			item = new Item(this, key);
			defineProperty(this, key, d('c', item));
		} else {
			item = this[key];
		}
		signal(item);
	}),
	has: d(function (value) {
		var key, proto;
		this._assertSet_();
		if ((value == null) || ((typeof value === 'function') && !value._id_)) {
			return false;
		}
		value = this.ns.normalize(value);
		if (value == null) return false;

		key = this.ns._serialize_(value);
		if (key == null) return false;

		if (this.propertyIsEnumerable(key)) return true;
		if (this.hasOwnProperty(key) || this.hasOwnProperty('_value')) {
			return false;
		}
		if (this._value == null) return false;
		if (this._value === value) return true;
		proto = getPrototypeOf(this);
		while (proto) {
			if (!proto.multiple) return false;
			if (proto.hasOwnProperty('_count_')) return proto.has(value);
			if (proto.hasOwnProperty('_value')) return false;
			proto = getPrototypeOf(proto);
		}
	}),
	forEach: d(function (cb/*, thisArg*/) {
		var thisArg = arguments[1], index = -1, proto
		  , ignores, iterate, setIgnore, value;
		this._assertSet_();
		callable(cb);
		forEach(this, function (value, name) {
			call.call(cb, thisArg, value.value, value, this, ++index);
		}, this, function (a, b) {
			return this[a].order - this[b].order;
		});

		if (this.hasOwnProperty('_value')) return;
		ignores = {};
		getOwnPropertyNames(this)
			.forEach(setIgnore = function (key) { ignores[key] = true; });
		proto = getPrototypeOf(this);
		iterate = function (key) {
			if (!ignores[key]) {
				call.call(cb, thisArg, proto[key].value, null, this, ++index);
			}
		};
		while (proto) {
			if (!proto.multiple) {
				if ((proto._value == null) ||
						ignores[proto.ns._serialize_(value = proto.value)]) {
					return;
				}
				call.call(cb, thisArg, value, null, this, ++index);
				return;
			}
			if (proto.hasOwnProperty('_count_')) keys(proto).forEach(iterate, this);
			if (proto.hasOwnProperty('_value')) return;
			getOwnPropertyNames(proto).forEach(setIgnore);
			proto = getPrototypeOf(proto);
		}
	}),
	get: d(function (value) {
		var key;
		this._assertSet_();
		if ((value == null) || ((typeof value === 'function') && !value._id_)) {
			return null;
		}
		value = this.ns.normalize(value);
		if (value == null) return null;
		key = this.ns._serialize_(value);
		return this.propertyIsEnumerable(key) ? this[key] : null;
	}),
	values: d.gs(function () {
		var arr = [];
		this._assertSet_();
		this.forEach(function (item) { arr.push(item); });
		return arr;
	}),
	_clear_: d(function () {
		keys(this).forEach(function (key) {
			var item = this[key], value;
			this._onOld_(value = item._value);
			item._value = null;
			defineProperty(this, key, d('c', item));
			signal(item._order);
			signal(item);
			this.emit('delete', value, item);
		}, this);
		this._count_ = 0;
	}),
	_reset_: d(function (value) {
		var key, ns, map, signalled, item;
		if (!this.hasOwnProperty('_descriptor_')) this._setVisibility_(value);

		if (value === undefined) {
			this._clear_();
			if (this.hasOwnProperty('_value')) {
				delete this._value;
				this._onNew_(undefined);
			}
			signal(this);
			return;
		}
		if ((value === null) || ((typeof value === 'function') && !value._id_)) {
			this._clear_();
		} else if (isArray(value)) {
			if (!value.length) {
				this._clear_();
				value = null;
			} else {
				ns = this.ns;
				map = {};
				value.map(function (value, index) {
					if (!ns.is(value)) value = ns.$construct(value);
					last = map[ns._serialize_(value)] = { value: value, index: index };
				}, this);
				keys(this).forEach(function (key) {
					var item = this[key], value;
					if (!map[key]) {
						this._onOld_(value = item._value);
						item._value = null;
						defineProperty(this, key, d('c', this[key]));
						--this._count_;
						signal(item);
						signal(item._order);
						this.emit('delete', value, item);
					} else {
						signal(item, true);
						item._order.$setValue(map[key].index);
						signal(item._order, map[key].index);
						delete map[key];
					}
				}, this);
				forEach(map, function (value, key) {
					var item = this.hasOwnProperty(key) && this[key];
					if (!item) {
						defineProperty(this, key, d('ce',
							item = new Item(this, key, value.value)));
					} else {
						defineProperty(this, key, d('ce', item));
					}
					item._value = value.value;
					++this._count_;
					this._onNew_(value.value);
					item._order.$setValue(value.index);
					signal(item, true);
					signal(item._order, value.index);
					this.emit('add', value.value, item);
				}, this);
				value = last;
			}
			signalled = true;
		} else {
			key = serialize(value);
			keys(this).forEach(function (lkey) {
				var item = this[lkey], value;
				if (lkey !== key) {
					this._onOld_(value = item._value);
					item._value = null;
					defineProperty(this, lkey, d('c', item));
					signal(item);
					signal(item._order);
					this.emit('remove', value, item);
				} else {
					key = null;
				}
			}, this);
			if (key) {
				if (this.hasOwnProperty(key)) {
					item = this[key];
					item._value = value;
					defineProperty(this, key, d('ce', item));
				} else {
					item = new Item(this, key, value);
					defineProperty(this, key, d('ce', item));
				}
				this._onNew_(value);
				this.emit('add', value, item);
			} else {
				item = this[key];
			}
			this._count_ = 1;
			signal(item, true);
			signalled = true;
		}

		if (!this.hasOwnProperty('_value')) this._onOld_(undefined);
		if (!this.hasOwnProperty('_value')) {
			defineProperty(this, '_value', d('cw', value));
		} else {
			this._value = value;
		}
		if (!signalled) signal(this, value);
	})
});
<commit_msg>Do not normalize on initSet<commit_after>'use strict';

var last      = require('es5-ext/lib/Array/prototype/last')
  , d         = require('es5-ext/lib/Object/descriptor')
  , forEach   = require('es5-ext/lib/Object/for-each')
  , callable  = require('es5-ext/lib/Object/valid-callable')
  , Relation  = require('./relation')
  , Item      = require('./rel-set-item')
  , serialize = require('./serialize')
  , signal    = require('./signal')

  , isArray = Array.isArray, call = Function.prototype.call
  , defineProperty = Object.defineProperty
  , defineProperties = Object.defineProperties
  , getOwnPropertyNames = Object.getOwnPropertyNames
  , getPrototypeOf = Object.getPrototypeOf, keys = Object.keys;

defineProperties(Relation.prototype, {
	_initSet_: d(function () {
		var value, key;
		defineProperty(this, '_count_', d(0));
		if (this.hasOwnProperty('_value') && (this._value != null) &&
				((typeof this._value !== 'function') || this._value._id_)) {
			value = this._value;
			key = this.ns._serialize_(value);
			defineProperty(this, key, d('ce', new Item(this, key, this._value)));
			++this._count_;
		}
	}),
	count: d.gs(function () {
		var count;
		this._assertSet_();
		if (this.hasOwnProperty('_value')) return this._count_;
		count = 0;
		this.forEach(function () { ++count; });
		return count;
	}),
	_isSet_: d.gs(function () {
		return this.multiple &&
			((typeof this._value !== 'function') || this._value._id_) &&
			this.hasOwnProperty('_count_');
	}),
	_last_: d.gs(function () {
		if (!this._count_) return null;
		return this[last.call(keys(this))];
	}),
	_assertSet_: d(function () {
		if (!this._isSet_) throw new TypeError("Property is not a set");
	}),
	add: d(function (value) {
		var error = this.addValidate(value);
		if (error) throw error;
		if (!this.ns.is(value)) value = this.ns.$construct(value);
		return this.$add(value);
	}),
	$add: d(function (value) {
		var key = serialize(value), item;
		if (!this.propertyIsEnumerable(key)) {
			if (this.hasOwnProperty(key)) {
				item = this[key];
				item._value = value;
				defineProperty(this, key, d('ce', item));
			} else {
				item = new Item(this, key, value);
				defineProperty(this, key, d('ce', item));
			}
			if (this.hasOwnProperty('_value')) {
				if (this._value === null) this._onOld_(null);
				this._value = value;
			}
			++this._count_;
			this._onNew_(value);
			this.emit('add', value, item);
		} else {
			item = this[key];
		}
		signal(item, true);
		return item;
	}),
	$setItem: d(function (key) {
		if (this.hasOwnProperty(key)) return;
		defineProperty(this, key, d('c', new Item(this, key)));
	}),
	addValidate: d(function (value) {
		this._assertSet_();
		if ((value == null) || ((typeof value === 'function') && !value._id_) ||
				isArray(value)) {
			return new TypeError(value + " is not valid " + this.ns._id_);
		}
		return this._validate_(value);
	}),
	delete: d(function (value) {
		var key, isTopValue, item;
		this._assertSet_();
		if ((value == null) || ((typeof value === 'function') && !value._id_)) {
			return;
		}

		value = this.ns.normalize(value);
		if (value == null) return;
		if (!(key = this.ns._serialize_(value))) return;

		if (this.propertyIsEnumerable(key)) {
			isTopValue = this.hasOwnProperty('_value') && (this._value === value);
			if (isTopValue && this._required && (this._count_ === 1)) {
				throw new TypeError('Cannot remove the only value');
			}
			item = this[key];
			item._value = null;
			--this._count_;
			defineProperty(this, key, d('c', item));
			if (isTopValue) {
				this._value = this._last_._value;
				if (this._value === null) this._onNew_(null);
			}
			this._onOld_(value);
			this.emit('delete', value, item);
		} else if (!this.hasOwnProperty(key)) {
			item = new Item(this, key);
			defineProperty(this, key, d('c', item));
		} else {
			item = this[key];
		}
		signal(item);
	}),
	has: d(function (value) {
		var key, proto;
		this._assertSet_();
		if ((value == null) || ((typeof value === 'function') && !value._id_)) {
			return false;
		}
		value = this.ns.normalize(value);
		if (value == null) return false;

		key = this.ns._serialize_(value);
		if (key == null) return false;

		if (this.propertyIsEnumerable(key)) return true;
		if (this.hasOwnProperty(key) || this.hasOwnProperty('_value')) {
			return false;
		}
		if (this._value == null) return false;
		if (this._value === value) return true;
		proto = getPrototypeOf(this);
		while (proto) {
			if (!proto.multiple) return false;
			if (proto.hasOwnProperty('_count_')) return proto.has(value);
			if (proto.hasOwnProperty('_value')) return false;
			proto = getPrototypeOf(proto);
		}
	}),
	forEach: d(function (cb/*, thisArg*/) {
		var thisArg = arguments[1], index = -1, proto
		  , ignores, iterate, setIgnore, value;
		this._assertSet_();
		callable(cb);
		forEach(this, function (value, name) {
			call.call(cb, thisArg, value.value, value, this, ++index);
		}, this, function (a, b) {
			return this[a].order - this[b].order;
		});

		if (this.hasOwnProperty('_value')) return;
		ignores = {};
		getOwnPropertyNames(this)
			.forEach(setIgnore = function (key) { ignores[key] = true; });
		proto = getPrototypeOf(this);
		iterate = function (key) {
			if (!ignores[key]) {
				call.call(cb, thisArg, proto[key].value, null, this, ++index);
			}
		};
		while (proto) {
			if (!proto.multiple) {
				if ((proto._value == null) ||
						ignores[proto.ns._serialize_(value = proto.value)]) {
					return;
				}
				call.call(cb, thisArg, value, null, this, ++index);
				return;
			}
			if (proto.hasOwnProperty('_count_')) keys(proto).forEach(iterate, this);
			if (proto.hasOwnProperty('_value')) return;
			getOwnPropertyNames(proto).forEach(setIgnore);
			proto = getPrototypeOf(proto);
		}
	}),
	get: d(function (value) {
		var key;
		this._assertSet_();
		if ((value == null) || ((typeof value === 'function') && !value._id_)) {
			return null;
		}
		value = this.ns.normalize(value);
		if (value == null) return null;
		key = this.ns._serialize_(value);
		return this.propertyIsEnumerable(key) ? this[key] : null;
	}),
	values: d.gs(function () {
		var arr = [];
		this._assertSet_();
		this.forEach(function (item) { arr.push(item); });
		return arr;
	}),
	_clear_: d(function () {
		keys(this).forEach(function (key) {
			var item = this[key], value;
			this._onOld_(value = item._value);
			item._value = null;
			defineProperty(this, key, d('c', item));
			signal(item._order);
			signal(item);
			this.emit('delete', value, item);
		}, this);
		this._count_ = 0;
	}),
	_reset_: d(function (value) {
		var key, ns, map, signalled, item;
		if (!this.hasOwnProperty('_descriptor_')) this._setVisibility_(value);

		if (value === undefined) {
			this._clear_();
			if (this.hasOwnProperty('_value')) {
				delete this._value;
				this._onNew_(undefined);
			}
			signal(this);
			return;
		}
		if ((value === null) || ((typeof value === 'function') && !value._id_)) {
			this._clear_();
		} else if (isArray(value)) {
			if (!value.length) {
				this._clear_();
				value = null;
			} else {
				ns = this.ns;
				map = {};
				value.map(function (value, index) {
					if (!ns.is(value)) value = ns.$construct(value);
					last = map[ns._serialize_(value)] = { value: value, index: index };
				}, this);
				keys(this).forEach(function (key) {
					var item = this[key], value;
					if (!map[key]) {
						this._onOld_(value = item._value);
						item._value = null;
						defineProperty(this, key, d('c', this[key]));
						--this._count_;
						signal(item);
						signal(item._order);
						this.emit('delete', value, item);
					} else {
						signal(item, true);
						item._order.$setValue(map[key].index);
						signal(item._order, map[key].index);
						delete map[key];
					}
				}, this);
				forEach(map, function (value, key) {
					var item = this.hasOwnProperty(key) && this[key];
					if (!item) {
						defineProperty(this, key, d('ce',
							item = new Item(this, key, value.value)));
					} else {
						defineProperty(this, key, d('ce', item));
					}
					item._value = value.value;
					++this._count_;
					this._onNew_(value.value);
					item._order.$setValue(value.index);
					signal(item, true);
					signal(item._order, value.index);
					this.emit('add', value.value, item);
				}, this);
				value = last;
			}
			signalled = true;
		} else {
			key = serialize(value);
			keys(this).forEach(function (lkey) {
				var item = this[lkey], value;
				if (lkey !== key) {
					this._onOld_(value = item._value);
					item._value = null;
					defineProperty(this, lkey, d('c', item));
					signal(item);
					signal(item._order);
					this.emit('remove', value, item);
				} else {
					key = null;
				}
			}, this);
			if (key) {
				if (this.hasOwnProperty(key)) {
					item = this[key];
					item._value = value;
					defineProperty(this, key, d('ce', item));
				} else {
					item = new Item(this, key, value);
					defineProperty(this, key, d('ce', item));
				}
				this._onNew_(value);
				this.emit('add', value, item);
			} else {
				item = this[key];
			}
			this._count_ = 1;
			signal(item, true);
			signalled = true;
		}

		if (!this.hasOwnProperty('_value')) this._onOld_(undefined);
		if (!this.hasOwnProperty('_value')) {
			defineProperty(this, '_value', d('cw', value));
		} else {
			this._value = value;
		}
		if (!signalled) signal(this, value);
	})
});
<|endoftext|>


<commit_before>'use strict';

const tools = require('../tools.js');
const dgram = require('dgram');
const adapterName = 'kecontact';
var txSocket = null;
var rxSocket = null;
const DEFAULT_UDP_PORT = 7090;
const BROADCAST_UDP_PORT = 7092;
const DETECT_MESSAGE = "i";
const KEBA_TIMEOUT = 500;
var timeout = null;

function addInstance(ip, device, options) {
    let instance = tools.findInstance (options, adapterName, obj => obj.native.host === ip);
    if (instance) {
        options.log.info('Keba KeContact adapter already present for IP ' + ip);
    } else {
        instance = {
            _id: tools.getNextInstanceID(adapterName, options),
            common: {
                name: adapterName,
                title: 'Keba KeContact P30 (' + ip + ')'
            },
            native: {
                host: ip
            },
            comment: {
                add: ["control you Keba KeContact P30 charging station"]
            }
        };
        options.newInstances.push(instance);
        return true;
    }
    return false;
}

function detect(ip, device, options, callback) {
    options.log.info('Detecting Keba KeContact wallbox on ' + ip + '...');

    timeout = setTimeout(() => {
        timeout = null;
        cleanup(ip, callback, false);
        callback = null;
    }, KEBA_TIMEOUT);

    rxSocket = dgram.createSocket('udp4');
    rxSocket.on('error', (err) => {
        if (err.message.includes('EADDRINUSE')) {
            options.log.info('Keba adapter already running');
        } else {
            options.log.error(`Keba rxSocket error:${err.stack}`);
        }
        cleanup(ip, callback, false);
        callback = null;
    });

    rxSocket.on('listening', function () {
        var address = rxSocket.address();
        options.log.debug('Keba UDP server listening on ' + address.address + ":" + address.port);
        // send connect request
        txSocket = dgram.createSocket('udp4');
        txSocket.on('listening', function() {
            txSocket.setBroadcast(true);
            txSocket.send(DETECT_MESSAGE, 0, DETECT_MESSAGE.length, DEFAULT_UDP_PORT, ip, (err, bytes) => err && options.log.warn('Error from KeContact: ' + err));
        });
        txSocket.bind(BROADCAST_UDP_PORT);
    });

    rxSocket.on('message', (message, remote) => {
        options.log.debug('UDP datagram from ' + remote.address + ':' + remote.port + ': "' + message + '"');
        if (message == DETECT_MESSAGE) {
            options.log.debug('broadcast message received by myself ...');
            return;
        }

        if (timeout) {
            clearTimeout(timeout);
            timeout = null;
        }
        if (message.length > 0) {
            // no defined response needed regarding Keba docs
            cleanup(ip, callback, addInstance(remote.address, device, options));
            callback = null;
        } else {
            cleanup(ip, callback, false);
            callback = null;
        }

    });
    rxSocket.bind(DEFAULT_UDP_PORT);
}

function cleanup(ip, callback, callbackResult) {
    if (txSocket) {
        txSocket.close();
        txSocket = null;
    }
    if (rxSocket) {
        rxSocket.close(() => {
            if (callback) {
                callback(null, callbackResult, ip);
            }
        });
        rxSocket = null;
    }
}

exports.detect = detect;
exports.type = ['udp'];
exports.timeout = KEBA_TIMEOUT;<commit_msg>changes according to git page<commit_after>'use strict';

const tools = require('../tools.js');
const dgram = require('dgram');
const adapterName = 'kecontact';
var txSocket = null;
var rxSocket = null;
const DEFAULT_UDP_PORT = 7090;
const BROADCAST_UDP_PORT = 7092;
const DETECT_MESSAGE = new Buffer("i");
const KEBA_TIMEOUT = 500;
var timeout = null;

function addInstance(ip, device, options) {
    let instance = tools.findInstance (options, adapterName, obj => obj.native.host === ip);
    if (instance) {
        options.log.info('Keba KeContact adapter already present for IP ' + ip);
    } else {
        instance = {
            _id: tools.getNextInstanceID(adapterName, options),
            common: {
                name: adapterName,
                title: 'Keba KeContact P30 (' + ip + ')'
            },
            native: {
                host: ip
            },
            comment: {
                add: ["control you Keba KeContact P30 charging station"]
            }
        };
        options.newInstances.push(instance);
        return true;
    }
    return false;
}

function detect(ip, device, options, callback) {
    options.log.info('Detecting Keba KeContact wallbox on ' + ip + '...');

    timeout = setTimeout(() => {
        timeout = null;
        cleanup(ip, callback, false);
        callback = null;
    }, KEBA_TIMEOUT);

    rxSocket = dgram.createSocket('udp4');
    rxSocket.on('error', (err) => {
        if (err.message.includes('EADDRINUSE')) {
            options.log.info('Keba adapter already running');
        } else {
            options.log.error(`Keba rxSocket error:${err.stack}`);
        }
        cleanup(ip, callback, false);
        callback = null;
    });

    rxSocket.on('listening', function () {
        var address = rxSocket.address();
        options.log.debug('Keba UDP server listening on ' + address.address + ":" + address.port);
        // send connect request
        //txSocket = dgram.createSocket('udp4');
        //txSocket.on('listening', function() {
            rxSocket.setBroadcast(true);
            rxSocket.send(DETECT_MESSAGE, 0, DETECT_MESSAGE.length, DEFAULT_UDP_PORT, ip, (err, bytes) => err && options.log.warn('Error from KeContact: ' + err));
        //});
        //txSocket.bind(BROADCAST_UDP_PORT);
    });

    rxSocket.on('message', (message, remote) => {
        options.log.debug('UDP datagram from ' + remote.address + ':' + remote.port + ': "' + message + '"');
        if (message == DETECT_MESSAGE) {
            options.log.debug('broadcast message received by myself ...');
            return;
        }

        if (timeout) {
            clearTimeout(timeout);
            timeout = null;
        }
        if (message.length > 0) {
            // no defined response needed regarding Keba docs
            cleanup(ip, callback, addInstance(remote.address, device, options));
            callback = null;
        } else {
            cleanup(ip, callback, false);
            callback = null;
        }

    });
    rxSocket.bind(DEFAULT_UDP_PORT);
}

function cleanup(ip, callback, callbackResult) {
    if (txSocket) {
        txSocket.close();
        txSocket = null;
    }
    if (rxSocket) {
        rxSocket.close(() => {
            if (callback) {
                callback(null, callbackResult, ip);
            }
        });
        rxSocket = null;
    }
}

exports.detect = detect;
exports.type = ['udp'];
exports.timeout = KEBA_TIMEOUT;<|endoftext|>


<commit_before>/* global require, module */
'use strict';

var p = require('../preprocessors');

var cleanBaseURL = require('../utilities/clean-base-url');

var preprocessJs  = p.preprocessJs;
var preprocessCss = p.preprocessCss;
var isType        = p.isType;

var preprocessTemplates = p.preprocessTemplates;

var preprocessMinifyCss = p.preprocessMinifyCss;

var replace     = require('broccoli-replace');
var compileES6  = require('broccoli-es6-concatenator');
var validateES6 = require('broccoli-es6-import-validate');
var pickFiles   = require('broccoli-static-compiler');
var mergeTrees  = require('broccoli-merge-trees');
var jshintTrees = require('broccoli-jshint');
var concatFiles = require('broccoli-concat');

var unwatchedTree    = require('broccoli-unwatched-tree');
var uglifyJavaScript = require('broccoli-uglify-js');

var memoize    = require('lodash-node/modern/functions').memoize;
var assign     = require('lodash-node/modern/objects/assign');
var defaults   = require('lodash-node/modern/objects/defaults');
var path       = require('path');

module.exports = EmberApp;

function EmberApp(options) {
  this.env  = process.env.EMBER_ENV || 'development';
  this.name = options.name;

  var isProduction = this.env === 'production';

  this.tests = this.hinting = !isProduction;

  this.options = defaults(options, {
    wrapInEval: !isProduction,
    minifyCSS: {
      enabled: true,
      options: {}
    },
    loader: 'vendor/loader/loader.js',
    trees: {},
  });

  this.options.trees = defaults(this.options.trees, {
      app:    'app',
      styles: 'app/styles',
      tests:  'tests',
      vendor: unwatchedTree('vendor'),
    });

  this.importWhitelist     = {};
  this.legacyFilesToAppend = [];
  this.vendorStaticStyles  = [];
  this.otherAssetTrees     = [];
  this._importTrees        = [];

  this.trees = this.options.trees;

  this.populateLegacyFiles();
}

EmberApp.prototype.populateLegacyFiles = function () {

  this.import('vendor/jquery/dist/jquery.js');

  this.import({
    development: 'vendor/handlebars/handlebars.js',
    production:  'vendor/handlebars/handlebars.runtime.js'
  });

  this.import({
    development: 'vendor/ember/ember.js',
    production:  'vendor/ember/ember.prod.js'
  });

  this.import('vendor/ember-cli-shims/app-shims.js', {
    ember: ['default']
  });

  this.import('vendor/ember-resolver/dist/modules/ember-resolver.js', {
    'ember/resolver': ['default']
  });

  this.import('vendor/ember-load-initializers/ember-load-initializers.js', {
    'ember/load-initializers': ['default']
  });
};

EmberApp.prototype.index = memoize(function() {
  var files = [
    'index.html'
  ];

  var index = pickFiles(this.trees.app, {
    srcDir: '/',
    files: files,
    destDir: '/'
  });

  return injectENVJson(this.options.getEnvJSON, this.env, index, files);
});

EmberApp.prototype.testIndex = memoize(function() {
  var index = pickFiles(this.trees.tests, {
    srcDir: '/',
    files: ['index.html'],
    destDir: '/tests'
  });

  return injectENVJson(this.options.getEnvJSON, this.env, index, [
      'tests/index.html'
    ]);
});

EmberApp.prototype.publicFolder = function() {
  return 'public';
};

EmberApp.prototype._processedAppTree = memoize(function() {
  return pickFiles(this.trees.app, {
    srcDir: '/',
    destDir: this.name
  });
});

EmberApp.prototype._processedVendorTree = memoize(function() {
  var mergedVendor = mergeTrees([this.trees.vendor].concat(this._importTrees), {
    overwrite: true
  });

  return pickFiles(mergedVendor, {
    srcDir: '/',
    destDir: 'vendor/'
  });
});

EmberApp.prototype.appAndDependencies = memoize(function() {
  var app    = this._processedAppTree();
  var vendor = this._processedVendorTree();

  var appAndTemplates = preprocessTemplates(app);

  var sourceTrees = [ appAndTemplates, vendor ];

  if (this.tests) {
    var tests = pickFiles(this.trees.tests, {
      srcDir: '/',
      destDir: this.name + '/tests'
    });

    sourceTrees.push(tests);

    if (this.hinting) {
      var importWhitelist = this.importWhitelist;

      var validatedJS = validateES6(mergeTrees([app, tests]), {
        whitelist: importWhitelist
      });
      sourceTrees.push(validatedJS);

      var jshintedApp = jshintTrees(app, {
        destFile: this.name + '/tests/app-jshint-test.js'
      });
      sourceTrees.push(jshintedApp);
      var jshintedTests = jshintTrees(tests, {
        jshintrcRoot: this.name + '/tests/',
        destFile: this.name + '/tests/tests-jshint-test.js'
      });
      sourceTrees.push(jshintedTests);
    }
  }

  return mergeTrees(sourceTrees, {
      overwrite: true
    });
});

EmberApp.prototype.javascript = memoize(function() {
  var applicationJs       = preprocessJs(this.appAndDependencies(), '/', this.name);
  var legacyFilesToAppend = this.legacyFilesToAppend;

  if (this.env !== 'production') {
    this.import('vendor/ember-qunit/dist/named-amd/main.js', {
      'ember-qunit': [
        'globalize',
        'moduleFor',
        'moduleForComponent',
        'moduleForModel',
        'test',
        'setResolver'
      ]
    });

    this.import('vendor/ember-cli-shims/test-shims.js', {
      'qunit': ['default']
    });
  }

  var es6 = compileES6(applicationJs, {
    loaderFile: this.options.loader,
    ignoredModules: Object.keys(this.importWhitelist),
    inputFiles: [
      this.name + '/**/*.js'
    ],
    wrapInEval: this.options.wrapInEval,
    outputFile: '/assets/' + this.name + '.js',
    legacyFilesToAppend: legacyFilesToAppend
  });

  if (this.env === 'production') {
    return uglifyJavaScript(es6, {
      mangle: true,
      compress: true
    });
  } else {
    return es6;
  }
});

EmberApp.prototype.styles = memoize(function() {
  var vendor = this._processedVendorTree();
  var styles = pickFiles(this.trees.styles, {
    srcDir: '/',
    destDir: '/app/styles'
  });

  var stylesAndVendor = mergeTrees([vendor, styles]);

  var processedStyles = preprocessCss(stylesAndVendor, '/app/styles', '/assets');
  var vendorStyles    = concatFiles(stylesAndVendor, {
    inputFiles: this.vendorStaticStyles,
    outputFile: '/assets/vendor.css'
  });

  if (this.env === 'production' && this.options.minifyCSS.enabled === true) {
    var options = this.options.minifyCSS.options || {};
    processedStyles = preprocessMinifyCss(processedStyles, options);
    vendorStyles    = preprocessMinifyCss(vendorStyles, options);
  }

  return mergeTrees([processedStyles, vendorStyles]);
});

EmberApp.prototype.testFiles = memoize(function() {
  var qunitFiles = pickFiles(this.trees.vendor, {
      srcDir: '/qunit/qunit',
      files: [
        'qunit.css', 'qunit.js'
      ],
      destDir: '/assets/'
    });

  var testemPath = path.join(__dirname, 'testem');
  testemPath = path.dirname(testemPath);

  var testemTree = pickFiles(testemPath, {
      files: ['testem.js'],
      srcDir: '/',
      destDir: '/'
    });

  var sourceTrees = [qunitFiles, testemTree];

  return mergeTrees(sourceTrees, {
      overwrite: true
    });
});

EmberApp.prototype.otherAssets = memoize(function() {
  return mergeTrees(this.otherAssetTrees);
});

EmberApp.prototype.import = function(asset, modules) {
  var assetPath;

  if (typeof asset === 'object') {
    assetPath = asset[this.env];
  } else {
    assetPath = asset;
  }

  var directory = path.dirname(assetPath);
  var extension = path.extname(assetPath);
  var basename  = path.basename(assetPath);

  if (!extension) {
    throw new Error('You must pass a file to `EmberApp::import`. For directories specify them to the constructor under the `trees` option.');
  }

  var assetTree = pickFiles(directory, {
    srcDir: '/',
    files: [basename],
    destDir: directory.replace(/^vendor\//, '')
  });

  this._importTrees.push(assetTree);

  if (isType(assetPath, 'js')) {
    this.legacyFilesToAppend.push(assetPath);

    this.importWhitelist = assign(this.importWhitelist, modules || {});
  } else if (extension === '.css') {
    this.vendorStaticStyles.push(assetPath);
  } else {
    this.otherAssetTrees.push(assetTree);
  }
};

EmberApp.prototype.toArray = function() {
  var sourceTrees = [
    this.index(),
    this.javascript(),
    this.publicFolder(),
    this.styles(),
    this.otherAssets()
  ];

  if (this.tests) {
    sourceTrees = sourceTrees.concat(this.testIndex(), this.testFiles());
  }

  return sourceTrees;
};

EmberApp.prototype.toTree = memoize(function() {
  return mergeTrees(this.toArray(), {
    overwrite: true
  });
});

function injectENVJson(fn, env, tree, files) {
  // TODO: real templating
  var envJsonString = function(){
    return JSON.stringify(fn(env));
  };

  var baseTag = function(){
    var envJSON      = fn(env);
    var baseURL      = cleanBaseURL(envJSON.baseURL);
    var locationType = envJSON.locationType;

    if (locationType === 'hash' || locationType === 'none') {
      return '';
    }

    if (baseURL) {
      return '<base href="' + baseURL + '" />';
    } else {
      return '';
    }
  };

  return replace(tree, {
    files: files,
    patterns: [{
      match: /\{\{ENV\}\}/g,
      replacement: envJsonString
    },
    {
      match: /\{\{BASE_TAG\}\}/g,
      replacement: baseTag
    }]
  });
}
<commit_msg>Fix JS regression in `app.import`.<commit_after>/* global require, module */
'use strict';

var p = require('../preprocessors');

var cleanBaseURL = require('../utilities/clean-base-url');

var preprocessJs  = p.preprocessJs;
var preprocessCss = p.preprocessCss;
var isType        = p.isType;

var preprocessTemplates = p.preprocessTemplates;

var preprocessMinifyCss = p.preprocessMinifyCss;

var replace     = require('broccoli-replace');
var compileES6  = require('broccoli-es6-concatenator');
var validateES6 = require('broccoli-es6-import-validate');
var pickFiles   = require('broccoli-static-compiler');
var mergeTrees  = require('broccoli-merge-trees');
var jshintTrees = require('broccoli-jshint');
var concatFiles = require('broccoli-concat');

var unwatchedTree    = require('broccoli-unwatched-tree');
var uglifyJavaScript = require('broccoli-uglify-js');

var memoize    = require('lodash-node/modern/functions').memoize;
var assign     = require('lodash-node/modern/objects/assign');
var defaults   = require('lodash-node/modern/objects/defaults');
var path       = require('path');

module.exports = EmberApp;

function EmberApp(options) {
  this.env  = process.env.EMBER_ENV || 'development';
  this.name = options.name;

  var isProduction = this.env === 'production';

  this.tests = this.hinting = !isProduction;

  this.options = defaults(options, {
    wrapInEval: !isProduction,
    minifyCSS: {
      enabled: true,
      options: {}
    },
    loader: 'vendor/loader/loader.js',
    trees: {},
  });

  this.options.trees = defaults(this.options.trees, {
      app:    'app',
      styles: 'app/styles',
      tests:  'tests',
      vendor: unwatchedTree('vendor'),
    });

  this.importWhitelist     = {};
  this.legacyFilesToAppend = [];
  this.vendorStaticStyles  = [];
  this.otherAssetTrees     = [];
  this._importTrees        = [];

  this.trees = this.options.trees;

  this.populateLegacyFiles();
}

EmberApp.prototype.populateLegacyFiles = function () {

  this.import('vendor/jquery/dist/jquery.js');

  this.import({
    development: 'vendor/handlebars/handlebars.js',
    production:  'vendor/handlebars/handlebars.runtime.js'
  });

  this.import({
    development: 'vendor/ember/ember.js',
    production:  'vendor/ember/ember.prod.js'
  });

  this.import('vendor/ember-cli-shims/app-shims.js', {
    ember: ['default']
  });

  this.import('vendor/ember-resolver/dist/modules/ember-resolver.js', {
    'ember/resolver': ['default']
  });

  this.import('vendor/ember-load-initializers/ember-load-initializers.js', {
    'ember/load-initializers': ['default']
  });
};

EmberApp.prototype.index = memoize(function() {
  var files = [
    'index.html'
  ];

  var index = pickFiles(this.trees.app, {
    srcDir: '/',
    files: files,
    destDir: '/'
  });

  return injectENVJson(this.options.getEnvJSON, this.env, index, files);
});

EmberApp.prototype.testIndex = memoize(function() {
  var index = pickFiles(this.trees.tests, {
    srcDir: '/',
    files: ['index.html'],
    destDir: '/tests'
  });

  return injectENVJson(this.options.getEnvJSON, this.env, index, [
      'tests/index.html'
    ]);
});

EmberApp.prototype.publicFolder = function() {
  return 'public';
};

EmberApp.prototype._processedAppTree = memoize(function() {
  return pickFiles(this.trees.app, {
    srcDir: '/',
    destDir: this.name
  });
});

EmberApp.prototype._processedVendorTree = memoize(function() {
  var mergedVendor = mergeTrees([this.trees.vendor].concat(this._importTrees), {
    overwrite: true
  });

  return pickFiles(mergedVendor, {
    srcDir: '/',
    destDir: 'vendor/'
  });
});

EmberApp.prototype.appAndDependencies = memoize(function() {
  var app    = this._processedAppTree();
  var vendor = this._processedVendorTree();

  var appAndTemplates = preprocessTemplates(app);

  var sourceTrees = [ appAndTemplates, vendor ];

  if (this.tests) {
    var tests = pickFiles(this.trees.tests, {
      srcDir: '/',
      destDir: this.name + '/tests'
    });

    sourceTrees.push(tests);

    if (this.hinting) {
      var importWhitelist = this.importWhitelist;

      var validatedJS = validateES6(mergeTrees([app, tests]), {
        whitelist: importWhitelist
      });
      sourceTrees.push(validatedJS);

      var jshintedApp = jshintTrees(app, {
        destFile: this.name + '/tests/app-jshint-test.js'
      });
      sourceTrees.push(jshintedApp);
      var jshintedTests = jshintTrees(tests, {
        jshintrcRoot: this.name + '/tests/',
        destFile: this.name + '/tests/tests-jshint-test.js'
      });
      sourceTrees.push(jshintedTests);
    }
  }

  return mergeTrees(sourceTrees, {
      overwrite: true
    });
});

EmberApp.prototype.javascript = memoize(function() {
  var applicationJs       = preprocessJs(this.appAndDependencies(), '/', this.name);
  var legacyFilesToAppend = this.legacyFilesToAppend;

  if (this.env !== 'production') {
    this.import('vendor/ember-qunit/dist/named-amd/main.js', {
      'ember-qunit': [
        'globalize',
        'moduleFor',
        'moduleForComponent',
        'moduleForModel',
        'test',
        'setResolver'
      ]
    });

    this.import('vendor/ember-cli-shims/test-shims.js', {
      'qunit': ['default']
    });
  }

  var es6 = compileES6(applicationJs, {
    loaderFile: this.options.loader,
    ignoredModules: Object.keys(this.importWhitelist),
    inputFiles: [
      this.name + '/**/*.js'
    ],
    wrapInEval: this.options.wrapInEval,
    outputFile: '/assets/' + this.name + '.js',
    legacyFilesToAppend: legacyFilesToAppend
  });

  if (this.env === 'production') {
    return uglifyJavaScript(es6, {
      mangle: true,
      compress: true
    });
  } else {
    return es6;
  }
});

EmberApp.prototype.styles = memoize(function() {
  var vendor = this._processedVendorTree();
  var styles = pickFiles(this.trees.styles, {
    srcDir: '/',
    destDir: '/app/styles'
  });

  var stylesAndVendor = mergeTrees([vendor, styles]);

  var processedStyles = preprocessCss(stylesAndVendor, '/app/styles', '/assets');
  var vendorStyles    = concatFiles(stylesAndVendor, {
    inputFiles: this.vendorStaticStyles,
    outputFile: '/assets/vendor.css'
  });

  if (this.env === 'production' && this.options.minifyCSS.enabled === true) {
    var options = this.options.minifyCSS.options || {};
    processedStyles = preprocessMinifyCss(processedStyles, options);
    vendorStyles    = preprocessMinifyCss(vendorStyles, options);
  }

  return mergeTrees([processedStyles, vendorStyles]);
});

EmberApp.prototype.testFiles = memoize(function() {
  var qunitFiles = pickFiles(this.trees.vendor, {
      srcDir: '/qunit/qunit',
      files: [
        'qunit.css', 'qunit.js'
      ],
      destDir: '/assets/'
    });

  var testemPath = path.join(__dirname, 'testem');
  testemPath = path.dirname(testemPath);

  var testemTree = pickFiles(testemPath, {
      files: ['testem.js'],
      srcDir: '/',
      destDir: '/'
    });

  var sourceTrees = [qunitFiles, testemTree];

  return mergeTrees(sourceTrees, {
      overwrite: true
    });
});

EmberApp.prototype.otherAssets = memoize(function() {
  return mergeTrees(this.otherAssetTrees);
});

EmberApp.prototype.import = function(asset, modules) {
  var assetPath;

  if (typeof asset === 'object') {
    assetPath = asset[this.env];
  } else {
    assetPath = asset;
  }

  var directory = path.dirname(assetPath);
  var extension = path.extname(assetPath);
  var basename  = path.basename(assetPath);

  if (!extension) {
    throw new Error('You must pass a file to `EmberApp::import`. For directories specify them to the constructor under the `trees` option.');
  }

  var assetTree = pickFiles(directory, {
    srcDir: '/',
    destDir: directory.replace(/^vendor\//, '')
  });

  this._importTrees.push(assetTree);

  if (isType(assetPath, 'js')) {
    this.legacyFilesToAppend.push(assetPath);

    this.importWhitelist = assign(this.importWhitelist, modules || {});
  } else if (extension === '.css') {
    this.vendorStaticStyles.push(assetPath);
  } else {
    var otherAssetTree = pickFiles(this.trees.vendor, {
      srcDir: directory,
      files: [basename],
      destDir: directory
    });

    this.otherAssetTrees.push(otherAssetTree);
  }
};

EmberApp.prototype.toArray = function() {
  var sourceTrees = [
    this.index(),
    this.javascript(),
    this.publicFolder(),
    this.styles(),
    this.otherAssets()
  ];

  if (this.tests) {
    sourceTrees = sourceTrees.concat(this.testIndex(), this.testFiles());
  }

  return sourceTrees;
};

EmberApp.prototype.toTree = memoize(function() {
  return mergeTrees(this.toArray(), {
    overwrite: true
  });
});

function injectENVJson(fn, env, tree, files) {
  // TODO: real templating
  var envJsonString = function(){
    return JSON.stringify(fn(env));
  };

  var baseTag = function(){
    var envJSON      = fn(env);
    var baseURL      = cleanBaseURL(envJSON.baseURL);
    var locationType = envJSON.locationType;

    if (locationType === 'hash' || locationType === 'none') {
      return '';
    }

    if (baseURL) {
      return '<base href="' + baseURL + '" />';
    } else {
      return '';
    }
  };

  return replace(tree, {
    files: files,
    patterns: [{
      match: /\{\{ENV\}\}/g,
      replacement: envJsonString
    },
    {
      match: /\{\{BASE_TAG\}\}/g,
      replacement: baseTag
    }]
  });
}
<|endoftext|>


<commit_before>const async = require('async');
const childProcess = require('child_process');
const fs = require('fs');

const config = require('../config');

const GITHUB_TOKEN = process.env.GITHUB_TOKEN;

/**
 * Bump A-Frame Registry on changes to the registry.
 */
function bumpAframeRegistry (data) {
  if (!shouldBumpAframeRegistry(data)) { return Promise.resolve(false); }

  return new Promise(resolve => {
    console.log(`Bumping A-Frame Registry...`);
    async.series([
      execRegistryCommand('git pull --rebase origin master'),
      execRegistryCommand('node --max-old-space-size=200 /app/.heroku/node/bin/npm install'),
      execRegistryCommand(
        'node --max-old-space-size=200 /app/.heroku/node/bin/npm install --only="dev"'),
      execRegistryCommand('npm run config'),
      execRegistryCommand('npm run build'),
      execRegistryCommand('git add .'),
      execRegistryCommand('git commit -m "Bump Registry builds and site."'),
      execRegistryCommand(
        `git push https://${GITHUB_TOKEN}@github.com/${config.repoRegistry}.git master`)
    ], function asyncSeriesDone (err) {
      if (err) { return console.error(err); }
      console.log(`A-Frame Registry successfully bumped!`);
      resolve(true);
    });
  });
}
module.exports.bumpAframeRegistry= bumpAframeRegistry;

/**
 * Helper for async.js.
 */
function execRegistryCommand (command) {
  return callback => {
    console.log(`Running ${command}...`);
    childProcess.exec(command, {
      cwd: 'aframe-registry',
      stdio: 'inherit'
    }, (err, stdout, stderr) => {
      if (err) { console.error(err); }
      if (stderr) { console.error(stderr); }
      callback();
    });
  };
}

/**
 * Check if A-Frame commit has changes to the Registry.
 */
function shouldBumpAframeRegistry (data) {
  function commitHasRegistryChanges (commit) {
    return commit.modified.filter(function (file) {
      return file === 'registry.yml' || file === 'registry.json'
    }).length !== 0;
  }

  let hasRegistryChanges = false;
  data.commits.forEach(commit => {
    if (commitHasRegistryChanges(commit)) {
      hasRegistryChanges = true;
    }
  });

  return hasRegistryChanges;
}
module.exports.shouldBumpAframeRegistry = shouldBumpAframeRegistry;
<commit_msg>log stdout<commit_after>const async = require('async');
const childProcess = require('child_process');
const fs = require('fs');

const config = require('../config');

const GITHUB_TOKEN = process.env.GITHUB_TOKEN;

/**
 * Bump A-Frame Registry on changes to the registry.
 */
function bumpAframeRegistry (data) {
  if (!shouldBumpAframeRegistry(data)) { return Promise.resolve(false); }

  return new Promise(resolve => {
    console.log(`Bumping A-Frame Registry...`);
    async.series([
      execRegistryCommand('git pull --rebase origin master'),
      execRegistryCommand('node --max-old-space-size=200 /app/.heroku/node/bin/npm install'),
      execRegistryCommand(
        'node --max-old-space-size=200 /app/.heroku/node/bin/npm install --only="dev"'),
      execRegistryCommand('npm run config'),
      execRegistryCommand('npm run build'),
      execRegistryCommand('git add .'),
      execRegistryCommand('git commit -m "Bump Registry builds and site."'),
      execRegistryCommand(
        `git push https://${GITHUB_TOKEN}@github.com/${config.repoRegistry}.git master`)
    ], function asyncSeriesDone (err) {
      if (err) { return console.error(err); }
      console.log(`A-Frame Registry successfully bumped!`);
      resolve(true);
    });
  });
}
module.exports.bumpAframeRegistry= bumpAframeRegistry;

/**
 * Helper for async.js.
 */
function execRegistryCommand (command) {
  return callback => {
    console.log(`Running ${command}...`);
    childProcess.exec(command, {
      cwd: 'aframe-registry',
      stdio: 'inherit'
    }, (err, stdout, stderr) => {
      if (err) { console.error(err); }
      if (stderr) { console.error(stderr); }
      console.log(stdout);
      callback();
    });
  };
}

/**
 * Check if A-Frame commit has changes to the Registry.
 */
function shouldBumpAframeRegistry (data) {
  function commitHasRegistryChanges (commit) {
    return commit.modified.filter(function (file) {
      return file === 'registry.yml' || file === 'registry.json'
    }).length !== 0;
  }

  let hasRegistryChanges = false;
  data.commits.forEach(commit => {
    if (commitHasRegistryChanges(commit)) {
      hasRegistryChanges = true;
    }
  });

  return hasRegistryChanges;
}
module.exports.shouldBumpAframeRegistry = shouldBumpAframeRegistry;
<|endoftext|>


<commit_before>const webdriver = require('selenium-webdriver');
const bindAll = require('lodash.bindall');
require('chromedriver');

const headless = process.env.SMOKE_HEADLESS || false;
const remote = process.env.SMOKE_REMOTE || false;
const ci = process.env.CI || false;
const buildID = process.env.TRAVIS_BUILD_NUMBER;
const {SAUCE_USERNAME, SAUCE_ACCESS_KEY} = process.env;
const {By, Key, until} = webdriver;

const DEFAULT_TIMEOUT_MILLISECONDS = 20 * 1000;

class SeleniumHelper {
    constructor () {
        bindAll(this, [
            'buildDriver',
            'clickButton',
            'clickCss',
            'clickText',
            'clickXpath',
            'dragFromXpathToXpath',
            'findByCss',
            'findByXpath',
            'findText',
            'getKey',
            'getDriver',
            'getLogs',
            'getSauceDriver',
            'urlMatches',
            'waitUntilGone'
        ]);
    }
    buildDriver (name) {
        if (remote === 'true'){
            let nameToUse;
            if (ci === 'true'){
                nameToUse = 'travis ' + buildID + ' : ' + name;
            } else {
                nameToUse = name;
            }
            this.driver = this.getSauceDriver(SAUCE_USERNAME, SAUCE_ACCESS_KEY, nameToUse);
        } else {
            this.driver = this.getDriver();
        }
        return this.driver;
    }

    getDriver () {
        const chromeCapabilities = webdriver.Capabilities.chrome();
        let args = [];
        if (headless) {
            args.push('--headless');
            args.push('window-size=1024,1680');
            args.push('--no-sandbox');
        }
        chromeCapabilities.set('chromeOptions', {args});
        let driver = new webdriver.Builder()
            .forBrowser('chrome')
            .withCapabilities(chromeCapabilities)
            .build();
        return driver;
    }

    getSauceDriver (username, accessKey, name) {
        // Driver configs can be generated with the Sauce Platform Configurator
        // https://wiki.saucelabs.com/display/DOCS/Platform+Configurator
        let driverConfig = {
            browserName: 'chrome',
            platform: 'macOS 10.14',
            version: '84.0'
        };
        var driver = new webdriver.Builder()
            .withCapabilities({
                browserName: driverConfig.browserName,
                platform: driverConfig.platform,
                version: driverConfig.version,
                username: username,
                accessKey: accessKey,
                name: name
            })
            .usingServer(`http://${username}:${accessKey
            }@ondemand.saucelabs.com:80/wd/hub`)
            .build();
        return driver;
    }

    getKey (keyName) {
        return Key[keyName];
    }

    findByXpath (xpath, timeoutMessage = `findByXpath timed out for path: ${xpath}`) {
        return this.driver.wait(until.elementLocated(By.xpath(xpath)), DEFAULT_TIMEOUT_MILLISECONDS, timeoutMessage)
            .then(el => (
                this.driver.wait(el.isDisplayed(), DEFAULT_TIMEOUT_MILLISECONDS, `${xpath} is not visible`)
                    .then(() => el)
            ));
    }

    waitUntilGone (element) {
        return this.driver.wait(until.stalenessOf(element));
    }

    clickXpath (xpath) {
        return this.findByXpath(xpath).then(el => el.click());
    }

    clickText (text) {
        return this.clickXpath(`//*[contains(text(), '${text}')]`);
    }

    findText (text) {
        return this.driver.wait(until.elementLocated(By.xpath(`//*[contains(text(), '${text}')]`), 5 * 1000));
    }

    clickButton (text) {
        return this.clickXpath(`//button[contains(text(), '${text}')]`);
    }

    findByCss (css) {
        return this.driver.wait(until.elementLocated(By.css(css), 1000 * 5));
    }

    clickCss (css) {
        return this.findByCss(css).then(el => el.click());
    }

    dragFromXpathToXpath (startXpath, endXpath) {
        return this.findByXpath(startXpath).then(startEl => {
            return this.findByXpath(endXpath).then(endEl => {
                return this.driver.actions()
                    .dragAndDrop(startEl, endEl)
                    .perform();
            });
        });
    }

    urlMatches (regex) {
        return this.driver.wait(until.urlMatches(regex), 1000 * 5);
    }

    getLogs (whitelist) {
        return this.driver.manage()
            .logs()
            .get('browser')
            .then((entries) => {
                return entries.filter((entry) => {
                    const message = entry.message;
                    for (let i = 0; i < whitelist.length; i++) {
                        if (message.indexOf(whitelist[i]) !== -1) {
                            // eslint-disable-next-line no-console
                            // console.warn('Ignoring whitelisted error: ' + whitelist[i]);
                            return false;
                        } else if (entry.level !== 'SEVERE') {
                            // eslint-disable-next-line no-console
                            // console.warn('Ignoring non-SEVERE entry: ' + message);
                            return false;
                        }
                        return true;
                    }
                    return true;
                });
            });
    }

}

module.exports = SeleniumHelper;
<commit_msg>Pin chrome version for saucelabs to chromedriver version<commit_after>const webdriver = require('selenium-webdriver');
const bindAll = require('lodash.bindall');
require('chromedriver');

const headless = process.env.SMOKE_HEADLESS || false;
const remote = process.env.SMOKE_REMOTE || false;
const ci = process.env.CI || false;
const buildID = process.env.TRAVIS_BUILD_NUMBER;
const {SAUCE_USERNAME, SAUCE_ACCESS_KEY} = process.env;
const {By, Key, until} = webdriver;
const pkg = require('../../package.json');

const DEFAULT_TIMEOUT_MILLISECONDS = 20 * 1000;

class SeleniumHelper {
    constructor () {
        bindAll(this, [
            'buildDriver',
            'clickButton',
            'clickCss',
            'clickText',
            'clickXpath',
            'dragFromXpathToXpath',
            'findByCss',
            'findByXpath',
            'findText',
            'getKey',
            'getDriver',
            'getLogs',
            'getSauceDriver',
            'urlMatches',
            'waitUntilGone'
        ]);
    }
    buildDriver (name) {
        if (remote === 'true'){
            let nameToUse;
            if (ci === 'true'){
                nameToUse = 'travis ' + buildID + ' : ' + name;
            } else {
                nameToUse = name;
            }
            this.driver = this.getSauceDriver(SAUCE_USERNAME, SAUCE_ACCESS_KEY, nameToUse);
        } else {
            this.driver = this.getDriver();
        }
        return this.driver;
    }

    getDriver () {
        const chromeCapabilities = webdriver.Capabilities.chrome();
        let args = [];
        if (headless) {
            args.push('--headless');
            args.push('window-size=1024,1680');
            args.push('--no-sandbox');
        }
        chromeCapabilities.set('chromeOptions', {args});
        let driver = new webdriver.Builder()
            .forBrowser('chrome')
            .withCapabilities(chromeCapabilities)
            .build();
        return driver;
    }

    getChromeVersionNumber () {
        let chromedriverVersion = pkg.devDependencies.chromedriver;
        let versionFinder = /\d+\.\d+/;
        let versionArray = versionFinder.exec(chromedriverVersion);
        return versionArray[0];
    }

    getSauceDriver (username, accessKey, name) {
        let chromeVersion = this.getChromeVersionNumber();
        // Driver configs can be generated with the Sauce Platform Configurator
        // https://wiki.saucelabs.com/display/DOCS/Platform+Configurator
        let driverConfig = {
            browserName: 'chrome',
            platform: 'macOS 10.14',
            version: chromeVersion
        };
        var driver = new webdriver.Builder()
            .withCapabilities({
                browserName: driverConfig.browserName,
                platform: driverConfig.platform,
                version: driverConfig.version,
                username: username,
                accessKey: accessKey,
                name: name
            })
            .usingServer(`http://${username}:${accessKey
            }@ondemand.saucelabs.com:80/wd/hub`)
            .build();
        return driver;
    }

    getKey (keyName) {
        return Key[keyName];
    }

    findByXpath (xpath, timeoutMessage = `findByXpath timed out for path: ${xpath}`) {
        return this.driver.wait(until.elementLocated(By.xpath(xpath)), DEFAULT_TIMEOUT_MILLISECONDS, timeoutMessage)
            .then(el => (
                this.driver.wait(el.isDisplayed(), DEFAULT_TIMEOUT_MILLISECONDS, `${xpath} is not visible`)
                    .then(() => el)
            ));
    }

    waitUntilGone (element) {
        return this.driver.wait(until.stalenessOf(element));
    }

    clickXpath (xpath) {
        return this.findByXpath(xpath).then(el => el.click());
    }

    clickText (text) {
        return this.clickXpath(`//*[contains(text(), '${text}')]`);
    }

    findText (text) {
        return this.driver.wait(until.elementLocated(By.xpath(`//*[contains(text(), '${text}')]`), 5 * 1000));
    }

    clickButton (text) {
        return this.clickXpath(`//button[contains(text(), '${text}')]`);
    }

    findByCss (css) {
        return this.driver.wait(until.elementLocated(By.css(css), 1000 * 5));
    }

    clickCss (css) {
        return this.findByCss(css).then(el => el.click());
    }

    dragFromXpathToXpath (startXpath, endXpath) {
        return this.findByXpath(startXpath).then(startEl => {
            return this.findByXpath(endXpath).then(endEl => {
                return this.driver.actions()
                    .dragAndDrop(startEl, endEl)
                    .perform();
            });
        });
    }

    urlMatches (regex) {
        return this.driver.wait(until.urlMatches(regex), 1000 * 5);
    }

    getLogs (whitelist) {
        return this.driver.manage()
            .logs()
            .get('browser')
            .then((entries) => {
                return entries.filter((entry) => {
                    const message = entry.message;
                    for (let i = 0; i < whitelist.length; i++) {
                        if (message.indexOf(whitelist[i]) !== -1) {
                            // eslint-disable-next-line no-console
                            // console.warn('Ignoring whitelisted error: ' + whitelist[i]);
                            return false;
                        } else if (entry.level !== 'SEVERE') {
                            // eslint-disable-next-line no-console
                            // console.warn('Ignoring non-SEVERE entry: ' + message);
                            return false;
                        }
                        return true;
                    }
                    return true;
                });
            });
    }

}

module.exports = SeleniumHelper;
<|endoftext|>


<commit_before>var fs = require('fs'),
    async = require('async'),
    https = require('https');

describe('SSL Client certificates', function () {
    var server1, server2, server3;

    function createHttpsServerWithCerts (certs) {
        return https.createServer({
            key: fs.readFileSync(certs.key, 'utf8'),
            cert: fs.readFileSync(certs.cert, 'utf8'),
            ca: fs.readFileSync(certs.ca, 'utf8'),
            passphrase: 'password',
            requestCert: true,
            rejectUnauthorized: false
        }, function (req, res) {
            if (req.client.authorized) {
                res.writeHead(200, { 'Content-Type': 'text/plain' });
                res.end('authorized\n');
            }
            else {
                res.writeHead(401, { 'Content-Type': 'text/plain' });
                res.end('unauthorized\n');
            }
        });
    }

    before(function (done) {
        server1 = createHttpsServerWithCerts({
            key: 'test/fixtures/ssl/server.key',
            cert: 'test/fixtures/ssl/server.crt',
            ca: 'test/fixtures/ssl/ca.crt'
        });

        server2 = createHttpsServerWithCerts({
            key: 'test/fixtures/ssl/server2.key',
            cert: 'test/fixtures/ssl/server2.crt',
            ca: 'test/fixtures/ssl/ca2.crt'
        });

        server3 = createHttpsServerWithCerts({
            key: 'test/fixtures/ssl/server3.key',
            cert: 'test/fixtures/ssl/server3.crt',
            ca: 'test/fixtures/ssl/ca3.crt'
        });

        async.parallel([
            function (cb) {
                server1.listen(3000, cb);
            },
            function (cb) {
                server2.listen(3001, cb);
            },
            function (cb) {
                server3.listen(3002, cb);
            }
        ], function (err) {
            done(err);
        });
    });

    after(function (done) {
        async.parallel([
            function (cb) {
                server1.close(cb);
            },
            function (cb) {
                server2.close(cb);
            },
            function (cb) {
                server3.close(cb);
            }
        ], function (err) {
            done(err);
        });
    });

    // @todo: add .pfx, .pem tests as well
    it('should work correctly with standalone client certificates', function (done) {
        newman.run({
            collection: 'test/fixtures/run/ssl-client-cert.json',
            sslClientCert: 'test/fixtures/ssl/client.crt',
            sslClientKey: 'test/fixtures/ssl/client.key',
            sslClientPassphrase: 'password',
            insecure: true
        }, done);
    });

    it('should work correctly with multiple client certificates', function (done) {
        newman.run({
            collection: 'test/fixtures/run/ssl-client-cert-list.json',
            sslClientCertList: 'test/fixtures/files/ssl-client-cert-config.json',
            insecure: true
        }, done);
    });

    it('should give precedence to client cert list when both client cert options present', function (done) {
        newman.run({
            collection: 'test/fixtures/run/ssl-client-cert-list.json',
            sslClientCertList: 'test/fixtures/files/ssl-client-cert-config.json',
            sslClientCert: 'test/fixtures/ssl/client.crt',
            sslClientKey: 'test/fixtures/ssl/client.key',
            sslClientPassphrase: 'password',
            insecure: true
        }, done);
    });

    it('should fallback to individual client cert when multiple client cert don\'t match', function (done) {
        newman.run({
            collection: 'test/fixtures/run/ssl-client-cert.json',
            sslClientCertList: 'test/fixtures/files/ssl-client-cert-config.json',
            sslClientCert: 'test/fixtures/ssl/client.crt',
            sslClientKey: 'test/fixtures/ssl/client.key',
            sslClientPassphrase: 'password',
            insecure: true
        }, done);
    });
});
<commit_msg>Add tests for invalid cert config file in test/library<commit_after>var fs = require('fs'),
    async = require('async'),
    expect = require('chai').expect,
    https = require('https');

describe('SSL Client certificates', function () {
    var server1, server2, server3;

    function createHttpsServerWithCerts (certs) {
        return https.createServer({
            key: fs.readFileSync(certs.key, 'utf8'),
            cert: fs.readFileSync(certs.cert, 'utf8'),
            ca: fs.readFileSync(certs.ca, 'utf8'),
            passphrase: 'password',
            requestCert: true,
            rejectUnauthorized: false
        }, function (req, res) {
            if (req.client.authorized) {
                res.writeHead(200, { 'Content-Type': 'text/plain' });
                res.end('authorized\n');
            }
            else {
                res.writeHead(401, { 'Content-Type': 'text/plain' });
                res.end('unauthorized\n');
            }
        });
    }

    before(function (done) {
        server1 = createHttpsServerWithCerts({
            key: 'test/fixtures/ssl/server.key',
            cert: 'test/fixtures/ssl/server.crt',
            ca: 'test/fixtures/ssl/ca.crt'
        });

        server2 = createHttpsServerWithCerts({
            key: 'test/fixtures/ssl/server2.key',
            cert: 'test/fixtures/ssl/server2.crt',
            ca: 'test/fixtures/ssl/ca2.crt'
        });

        server3 = createHttpsServerWithCerts({
            key: 'test/fixtures/ssl/server3.key',
            cert: 'test/fixtures/ssl/server3.crt',
            ca: 'test/fixtures/ssl/ca3.crt'
        });

        async.parallel([
            function (cb) {
                server1.listen(3000, cb);
            },
            function (cb) {
                server2.listen(3001, cb);
            },
            function (cb) {
                server3.listen(3002, cb);
            }
        ], function (err) {
            done(err);
        });
    });

    after(function (done) {
        async.parallel([
            function (cb) {
                server1.close(cb);
            },
            function (cb) {
                server2.close(cb);
            },
            function (cb) {
                server3.close(cb);
            }
        ], function (err) {
            done(err);
        });
    });

    // @todo: add .pfx, .pem tests as well
    it('should work correctly with standalone client certificates', function (done) {
        newman.run({
            collection: 'test/fixtures/run/ssl-client-cert.json',
            sslClientCert: 'test/fixtures/ssl/client.crt',
            sslClientKey: 'test/fixtures/ssl/client.key',
            sslClientPassphrase: 'password',
            insecure: true
        }, done);
    });

    it('should work correctly with multiple client certificates', function (done) {
        newman.run({
            collection: 'test/fixtures/run/ssl-client-cert-list.json',
            sslClientCertList: 'test/fixtures/files/ssl-client-cert-config.json',
            insecure: true
        }, done);
    });

    it('should give precedence to client cert list when both client cert options present', function (done) {
        newman.run({
            collection: 'test/fixtures/run/ssl-client-cert-list.json',
            sslClientCertList: 'test/fixtures/files/ssl-client-cert-config.json',
            sslClientCert: 'test/fixtures/ssl/client.crt',
            sslClientKey: 'test/fixtures/ssl/client.key',
            sslClientPassphrase: 'password',
            insecure: true
        }, done);
    });

    it('should fallback to individual client cert when multiple client cert don\'t match', function (done) {
        newman.run({
            collection: 'test/fixtures/run/ssl-client-cert.json',
            sslClientCertList: 'test/fixtures/files/ssl-client-cert-config.json',
            sslClientCert: 'test/fixtures/ssl/client.crt',
            sslClientKey: 'test/fixtures/ssl/client.key',
            sslClientPassphrase: 'password',
            insecure: true
        }, done);
    });

    it('should bail out if unable to parse client certificate list', function (done) {
        newman.run({
            collection: 'test/fixtures/run/ssl-client-cert-list.json',
            sslClientCertList: 'invalid-cert-file.json', // using an invalid cert list
            insecure: true
        }, function (err) {
            expect(err).to.exist;
            expect(err.message).to.equal('newman: unable to read the ssl client certificates file.');
            done();
        });
    });

    it('should bail out if invalid client certificate list', function (done) {
        newman.run({
            collection: 'test/fixtures/run/ssl-client-cert-list.json',
            sslClientCertList: 'test/fixtures/run/ssl-client-cert.json', // using an invalid cert list
            insecure: true
        }, function (err) {
            expect(err).to.exist;
            expect(err.message).to.equal('newman: expected type for ssl client certificates list to be array.');
            done();
        });
    });
});
<|endoftext|>


<commit_before>import React, { PropTypes } from 'react';

import {
  CTASection,
  Footer,
  LoggedInContent,
  LoggedOutContent,
  PageHeader,
  PageHelmet,
  SideIconParagraphs,
  Terminal,
  TerminalSection
} from '../../components';

const Hosting = (props, { modals }) => {
  const { redirect_uri } = APP_CONFIG;
  console.log(redirect_uri);

  return (

      <PageHelmet
        title="Static Web Hosting for Developers"
        mixpanelTitle="Hosting"
        description="Secure, single-command web publishing for your applications."
      />
      <PageHeader
        headline={Static Web Hosting
for Developers}
        textline="Secure, single-command web publishing for your applications."
      >
        <LoggedOutContent>

            Get Started for Free

        </LoggedOutContent>
        <LoggedInContent>

            Go to Dashboard

        </LoggedInContent>

          30 days free • No credit card required

      </PageHeader>
      <TerminalSection
        variant="under-page-header"
        theme="hosting-publish"
      >
        <Terminal
          code={require('./syncano-hosting-publish.txt')}
          bottomShadow={true}
        />
      </TerminalSection>
      <SideIconParagraphs
        variant="top-spacing"
        theme="blue"
      >
        <SideIconParagraphs.Paragraph
          iconSrc={require('./simple-web-publishing-from-the-command-line.svg')}
          headline={Simple web publishing
from the command line}
          text={With the Syncano CLI, you can
            rapidly push your entire web app, or just individual files, with just a few commands. Take a look below to
            see just how simple it really is!}
        />
        <SideIconParagraphs.Paragraph
          iconSrc={require('./securely-delivered-content-worldwide.svg')}
          headline={Securely delivered
content worldwide}
          text={`SSL is a standard for web app security in today’s modern web. By hosting your app with Syn cano, you’ll
            have security built-in, creating a worry-free production environment!`}
        />
        <SideIconParagraphs.Paragraph
          iconSrc={require('./quick-rollbacks-to-undo-mistakes.svg')}
          headline="Quick rollbacks to undo mistakes"
          text={`Need to rollback to a previous version fast? The Syncano Platform allows for making switches between
            hosted sites so that you can easily control which version will be displayed. Never again will you regret
            pushing to production!`}
        />
        <SideIconParagraphs.Paragraph
          iconSrc={require('./scale-your-websites-on-demand.svg')}
          headline="Scale your websites on demand"
          text={`Each Syncano hosted site uses Amazon’s S3 platform for storage. This means all of your data and files
            are secure, and your web app is automatically highly-scalable, as well as extremely durable.`}
        />
      </SideIconParagraphs>
      <TerminalSection
        headline="Hosting Quickstart"
        textline="Learn how to start with Syncano Hosting in one minute!"
      >
        <Terminal code={require('./hosting-quickstart.txt')} />

          View Documentation

      </TerminalSection>
      <CTASection />

  );
};

Hosting.contextTypes = {
  modals: PropTypes.object
};

export default Hosting;
<commit_msg>[WEB-549] Add missing ogImageSrc and twitterImageSrc params<commit_after>import React, { PropTypes } from 'react';

import {
  CTASection,
  Footer,
  LoggedInContent,
  LoggedOutContent,
  PageHeader,
  PageHelmet,
  SideIconParagraphs,
  Terminal,
  TerminalSection
} from '../../components';

const Hosting = (props, { modals }) => {
  const { redirect_uri } = APP_CONFIG;

  return (

      <PageHelmet
        title="Static Web Hosting for Developers"
        mixpanelTitle="Hosting"
        description="Secure, single-command web publishing for your applications."
        ogImageSrc={`${redirect_uri}${require('./og-image.png')}`}
        twitterImageSrc={`${redirect_uri}${require('./twitter-image.png')}`}
      />
      <PageHeader
        headline={Static Web Hosting
for Developers}
        textline="Secure, single-command web publishing for your applications."
      >
        <LoggedOutContent>

            Get Started for Free

        </LoggedOutContent>
        <LoggedInContent>

            Go to Dashboard

        </LoggedInContent>

          30 days free • No credit card required

      </PageHeader>
      <TerminalSection
        variant="under-page-header"
        theme="hosting-publish"
      >
        <Terminal
          code={require('./syncano-hosting-publish.txt')}
          bottomShadow={true}
        />
      </TerminalSection>
      <SideIconParagraphs
        variant="top-spacing"
        theme="blue"
      >
        <SideIconParagraphs.Paragraph
          iconSrc={require('./simple-web-publishing-from-the-command-line.svg')}
          headline={Simple web publishing
from the command line}
          text={With the Syncano CLI, you can
            rapidly push your entire web app, or just individual files, with just a few commands. Take a look below to
            see just how simple it really is!}
        />
        <SideIconParagraphs.Paragraph
          iconSrc={require('./securely-delivered-content-worldwide.svg')}
          headline={Securely delivered
content worldwide}
          text={`SSL is a standard for web app security in today’s modern web. By hosting your app with Syn cano, you’ll
            have security built-in, creating a worry-free production environment!`}
        />
        <SideIconParagraphs.Paragraph
          iconSrc={require('./quick-rollbacks-to-undo-mistakes.svg')}
          headline="Quick rollbacks to undo mistakes"
          text={`Need to rollback to a previous version fast? The Syncano Platform allows for making switches between
            hosted sites so that you can easily control which version will be displayed. Never again will you regret
            pushing to production!`}
        />
        <SideIconParagraphs.Paragraph
          iconSrc={require('./scale-your-websites-on-demand.svg')}
          headline="Scale your websites on demand"
          text={`Each Syncano hosted site uses Amazon’s S3 platform for storage. This means all of your data and files
            are secure, and your web app is automatically highly-scalable, as well as extremely durable.`}
        />
      </SideIconParagraphs>
      <TerminalSection
        headline="Hosting Quickstart"
        textline="Learn how to start with Syncano Hosting in one minute!"
      >
        <Terminal code={require('./hosting-quickstart.txt')} />

          View Documentation

      </TerminalSection>
      <CTASection />

  );
};

Hosting.contextTypes = {
  modals: PropTypes.object
};

export default Hosting;
<|endoftext|>


<commit_before>/**
 * Talisman metrics/distance/levenshtein tests
 * ============================================
 *
 */
import assert from 'assert';
import levenshtein, {limited} from '../../../src/metrics/distance/levenshtein';

describe('levenshtein', function() {
  const tests = [
    [['b', 'o', 'o', 'k'], ['b', 'a', 'c', 'k'], 2],
    [['the', 'cat', 'eats', 'mouse'], ['the', 'mouse', 'likes', 'mouse'], 2],
    ['book', 'back', 2],
    ['bbbbookkkk', 'bbbbackkkk', 2],
    ['hello', 'helo', 1],
    ['good sir', 'baal', 8],
    ['say', 'shiver', 5],
    ['feature', 'get-project-features', 13],
    ['example', 'samples', 3],
    ['sturgeon', 'urgently', 6],
    ['levenshtein', 'frankenstein', 6],
    ['distance', 'difference', 5],
    ['a', 'b', 1],
    ['ab', 'ac', 1],
    ['ac', 'bc', 1],
    ['abc', 'axc', 1],
    ['xabxcdxxefxgx', '1ab2cd34ef5g6', 6],
    ['a', '', 1],
    ['ab', 'a', 1],
    ['ab', 'b', 1],
    ['abc', 'ac', 1],
    ['xabxcdxxefxgx', 'abcdefg', 6],
    ['', 'a', 1],
    ['a', 'ab', 1],
    ['b', 'ab', 1],
    ['ac', 'abc', 1],
    ['abcdefg', 'xabxcdxxefxgx', 6],
    ['', '', 0],
    ['a', 'a', 0],
    ['abc', 'abc', 0],
    ['', '', 0],
    ['a', '', 1],
    ['', 'a', 1],
    ['abc', '', 3],
    ['', 'abc', 3],
    ['因為我是中國人所以我會說中文', '因為我是英國人所以我會說英文', 2],
    ['因為我是中國人所以我會說中文'.split(''), '因為我是英國人所以我會說英文'.split(''), 2]
  ];

  it('should correctly compute the Levenshtein distance.', function() {
    tests.forEach(function([a, b, distance]) {
      assert.strictEqual(levenshtein(a, b), distance, `${a} <=> ${b}`);
    });
  });

  it('should be possible to use the limited version.', function() {
    tests.forEach(function([a, b, distance]) {
      assert.strictEqual(limited(2, a, b), distance > 2 ? Infinity : distance, `${a} <=> ${b}`);
    });
  });
});
<commit_msg>add test for emoji<commit_after>/**
 * Talisman metrics/distance/levenshtein tests
 * ============================================
 *
 */
import assert from 'assert';
import levenshtein, {limited} from '../../../src/metrics/distance/levenshtein';

describe('levenshtein', function() {
  const tests = [
    [['b', 'o', 'o', 'k'], ['b', 'a', 'c', 'k'], 2],
    [['the', 'cat', 'eats', 'mouse'], ['the', 'mouse', 'likes', 'mouse'], 2],
    ['book', 'back', 2],
    ['bbbbookkkk', 'bbbbackkkk', 2],
    ['hello', 'helo', 1],
    ['good sir', 'baal', 8],
    ['say', 'shiver', 5],
    ['feature', 'get-project-features', 13],
    ['example', 'samples', 3],
    ['sturgeon', 'urgently', 6],
    ['levenshtein', 'frankenstein', 6],
    ['distance', 'difference', 5],
    ['a', 'b', 1],
    ['ab', 'ac', 1],
    ['ac', 'bc', 1],
    ['abc', 'axc', 1],
    ['xabxcdxxefxgx', '1ab2cd34ef5g6', 6],
    ['a', '', 1],
    ['ab', 'a', 1],
    ['ab', 'b', 1],
    ['abc', 'ac', 1],
    ['xabxcdxxefxgx', 'abcdefg', 6],
    ['', 'a', 1],
    ['a', 'ab', 1],
    ['b', 'ab', 1],
    ['ac', 'abc', 1],
    ['abcdefg', 'xabxcdxxefxgx', 6],
    ['', '', 0],
    ['a', 'a', 0],
    ['abc', 'abc', 0],
    ['', '', 0],
    ['a', '', 1],
    ['', 'a', 1],
    ['abc', '', 3],
    ['', 'abc', 3],
    ['因為我是中國人所以我會說中文', '因為我是英國人所以我會說英文', 2],
    ['因為我是中國人所以我會說中文'.split(''), '因為我是英國人所以我會說英文'.split(''), 2],
    [['🔥', '👨👩👧👦'], ['🔥', '🌈'], 1]
  ];

  it('should correctly compute the Levenshtein distance.', function() {
    tests.forEach(function([a, b, distance]) {
      assert.strictEqual(levenshtein(a, b), distance, `${a} <=> ${b}`);
    });
  });

  it('should be possible to use the limited version.', function() {
    tests.forEach(function([a, b, distance]) {
      assert.strictEqual(limited(2, a, b), distance > 2 ? Infinity : distance, `${a} <=> ${b}`);
    });
  });
});
<|endoftext|>


<commit_before> Points = new Mongo.Collection("points");<commit_msg>Fix spacing<commit_after>Points = new Mongo.Collection("points");<|endoftext|>


<commit_before>var chalk = require('chalk');
var fs = require('fs');
var path = require('path');
var Promise = require('rsvp').Promise;
var DigitalOcean = require('do-wrapper');

var CREATE_NEW_DROPLET = 'Create a new droplet';

module.exports = {
  name: 'do:provision',

  description: 'Provisions a DigitalOcean Droplet for FastBoot',

  run: function() {
    console.log('Testing the provision command.');
    var ACCESS_TOKEN = process.env.DO_ACCESS_TOKEN;
    if (!ACCESS_TOKEN) {
      console.log('Access token not provided!');
      throw new Error('Environment Variable DO_ACCESS_TOKEN is not set!');
    }

    this.do = new DigitalOcean(ACCESS_TOKEN);

    this.do.account(function (err, res, body) {
      if(err) {
        console.log('Error thrown!');
        console.log(err);
      }
      console.log('This is the response!');
      console.log(body);

      return this.ui.writeLine(chalk.green('Provisioning Droplet for Fastboot\n'));
    });

  },
};

// For Distribution, default to installing on Ubuntu 14.04 x64.

function buildQuestions(droplets) {
  return [{
    name: 'droplet',
    message: 'Which DigitalOcean droplet would you like to use?',
    type: 'rawlist',
    choices: function() {
      choices = droplets.map(function(droplet) {
        return {
          name: '',
          value: {}
        };
      });

      choices.push(CREATE_NEW_DROPLET);

      return choices;
    }
  }, {
    name: 'environmentName',
    message: 'Which environment?',
    type: 'rawlist',
    choices: ['development', 'staging', 'production']
  }, {
    name: 'newDropletRegion',
    message: 'Which region do you want to create this droplet in?',
    type: 'rawlist',
    choices: function() {
      var choices = [];
      return choices;
    },
    when: function(answers) {
      return answers.droplet === CREATE_NEW_DROPLET;
    }
  }, {
    name: 'sshKeyLocation',
    message: 'Enter the path to the SSH key to be used with this droplet: ',
    type: 'input',
    when: function(answers) {
      return answers.droplet === CREATE_NEW_DROPLET;
    }
  }, {
    name: 'newDropletSize',
    message: 'What size should this droplet be? (Recommended Size - >= 1GB, 512MB requires a swapfile on the droplet)',
    choices: function() {
      var choices = [];
      return choices;
    },
    when: function(answers) {
      return answers.droplet === CREATE_NEW_DROPLET;
    }
  }, {
    name: 'newDropletName',
    message: 'What is the server name of the droplet?',
    type: 'input',
    when: function(aswers) {
      return answers.droplet === CREATE_NEW_DROPLET;
    }
    }
  ];
}
<commit_msg>Finish CLI UI for asking questions, work on what to do with answers next.<commit_after>var chalk = require('chalk');
var fs = require('fs');
var path = require('path');
var Promise = require('rsvp').Promise;
var DigitalOcean = require('do-wrapper');

var CREATE_NEW_DROPLET = 'Create a new droplet';

module.exports = {
  name: 'do:provision',

  description: 'Provisions a DigitalOcean Droplet for FastBoot',

  run: function() {
    var ACCESS_TOKEN = process.env.DO_ACCESS_TOKEN;
    if (!ACCESS_TOKEN) {
      console.log('Access token not provided!');
      throw new Error('Environment Variable DO_ACCESS_TOKEN is not set!');
    }

    var api = new DigitalOcean(ACCESS_TOKEN);
    var ui = this.ui;

    this.api = api;

    var dropletsPromise = new Promise(function(resolve, reject) {
      api.dropletsGetAll({}, function(err, res, body) {
        if (err) {
          reject(err);
        }

        resolve(body.droplets);
      });
    });

    var regionsPromise = new Promise(function(resolve, reject) {
      api.regionsGetAll({}, function(err, res, body) {
        if (err) {
          reject(err);
        }

        resolve(body.regions);
      });
    });

    var keysPromise = new Promise(function(resolve, reject) {
      api.accountGetKeys({}, function(err, res, body) {
        if (err) {
          reject(err);
        }

        resolve(body.ssh_keys);
      });
    });

    var dropletSizesPromise = new Promise(function(resolve, reject) {
      api.sizesGetAll({}, function(err, res, body) {
        if (err) {
          reject(err);
        }

        resolve(body.sizes);
      });
    });

    return Promise.all([dropletsPromise, regionsPromise, keysPromise, dropletSizesPromise]).then(function(values) {
      var droplets = values[0];
      var regions = values[1];
      var userKeys = values[2];
      var dropletSizes = values[3];
      this.droplets = droplets;
      this.regions = regions.filter(function(region) {
        return region.available === true;
      });
      this.userKeys = userKeys;
      this.dropletSizes = dropletSizes;

      this.ui.writeLine(chalk.green('Provisioning Droplet for Fastboost\n'));

      return this.askQuestions();
    }.bind(this));
  },
  askQuestions: function() {
    var ui = this.ui;
    var self = this;

    var questions = buildQuestions(this.droplets, this.regions, this.userKeys, this.dropletSizes);
    return ui.prompt(questions).then(function(answers) {
      self.answers = answers;
    });
  }
};

// For Distribution, default to installing on Ubuntu 14.04 x64.

function buildQuestions(droplets, regions, userKeys, dropletSizes) {
  return [{
    name: 'droplet',
    message: 'Which DigitalOcean droplet would you like to use?',
    type: 'rawlist',
    choices: function() {
      var choices = droplets.map(function(droplet) {
        return {
          name: droplet.name,
          value: droplet.slug,
        };
      });

      choices.push(CREATE_NEW_DROPLET);
      return choices;
    }
  }, {
    name: 'environmentName',
    message: 'Which environment?',
    type: 'rawlist',
    choices: ['development', 'staging', 'production']
  }, {
    name: 'newDropletRegion',
    message: 'Which region do you want to create this droplet in?',
    type: 'rawlist',
    choices: function() {
      var choices = regions.map(function(region) {
        return {
          name: region.name,
          value: region.slug,
          sizes: region.sizes,
        };
      });
      return choices;
    },
    when: function(answers) {
      return answers.droplet === CREATE_NEW_DROPLET;
    }
  }, {
    name: 'sshKeys',
    message: 'Which SSH keys do you want to use for this droplet?',
    type: 'checkbox',
    validate: function(input) {

      if (!!input) {
        return true;
      } else {
        return 'Please add at least one SSH key for the provisioning to work correctly.';
      }
    },
    choices: function() {
      var choices = userKeys.map(function(sshKey) {
        return {
          name: sshKey.name,
          value: sshKey.id,
        };
      });

      return choices;
    },
    when: function(answers) {
      return answers.droplet === CREATE_NEW_DROPLET;
    }
  }, {
    name: 'newDropletSize',
    message: 'What size should this droplet be? (At least 1GB recommended)',
    type: 'rawlist',
    choices: function() {
      var choices = dropletSizes.map(function(size) {
        return {
          name: size.slug + "/" +
            size.vcpus + " CPU(s) - " +
              size.disk + "GB SSD Disk ($" + size.price_monthly + "/mo)",
          value: size.slug,
        };
      });

      return choices;
    },
    when: function(answers) {
      return answers.droplet === CREATE_NEW_DROPLET;
    }
  }, {
    name: 'newDropletName',
    message: 'What should we name this droplet?',
    type: 'input',
    when: function(answers) {
      return answers.droplet === CREATE_NEW_DROPLET;
    }
  }
  ];
}
<|endoftext|>


<commit_before>// ==========================================
// BOWER: Uninstall API
// ==========================================
// Copyright 2012 Twitter, Inc
// Licensed under The MIT License
// http://opensource.org/licenses/MIT
// ==========================================

var Emitter  = require('events').EventEmitter;
var async    = require('async');
var nopt     = require('nopt');
var _        = require('lodash');

var template = require('../util/template');
var Manager  = require('../core/manager');
var save     = require('../util/save');
var help     = require('./help');

var shorthand   = { 'h': ['--help'], 'S': ['--save'] };
var optionTypes = { help: Boolean };

module.exports = function (names, options) {

  var packages, uninstallables;
  var emitter = new Emitter;
  var manager = new Manager;

  if (options.save) save.discard(emitter, manager, names);

  manager.on('data',  emitter.emit.bind(emitter, 'data'));
  manager.on('error', emitter.emit.bind(emitter, 'error'));

  var resolveLocal = function () {
    packages = _.flatten(_.values(manager.dependencies));

    uninstallables = packages.filter(function (pkg) {
      return _.include(names, pkg.name);
    });

    async.forEach(packages, function (pkg, next) {
      pkg.once('loadJSON', next).loadJSON();
    }, function () {
      showWarnings();
      uninstall();
    });
  };

  var showWarnings = function () {
    packages.forEach(function (pkg) {
      var conflicts = _.intersection(
        Object.keys(pkg.json.dependencies),
        _.pluck(uninstallables, 'name')
      );

      conflicts.forEach(function (conflictName) {
        template('warning-uninstall', {packageName: pkg.name, conflictName: conflictName})
          .on('data', emitter.emit.bind(emitter, 'data'));
      });
    });
  };

  var uninstall = function () {
    async.forEach(uninstallables, function (pkg, next) {
      pkg.on('uninstall', next).uninstall();
    }, emitter.emit.bind(emitter, 'end'));
  };

  manager.on('resolveLocal', resolveLocal).resolveLocal();

  return emitter;
};

module.exports.line = function (argv) {
  var options = nopt(optionTypes, shorthand, argv);
  if (options.help) return help('uninstall');
  var names   = options.argv.remain.slice(1);

  return module.exports(names, options)
};<commit_msg>if dependencies object is not present in json, don't try to warn<commit_after>// ==========================================
// BOWER: Uninstall API
// ==========================================
// Copyright 2012 Twitter, Inc
// Licensed under The MIT License
// http://opensource.org/licenses/MIT
// ==========================================

var Emitter  = require('events').EventEmitter;
var async    = require('async');
var nopt     = require('nopt');
var _        = require('lodash');

var template = require('../util/template');
var Manager  = require('../core/manager');
var save     = require('../util/save');
var help     = require('./help');

var shorthand   = { 'h': ['--help'], 'S': ['--save'] };
var optionTypes = { help: Boolean };

module.exports = function (names, options) {

  var packages, uninstallables;
  var emitter = new Emitter;
  var manager = new Manager;

  if (options.save) save.discard(emitter, manager, names);

  manager.on('data',  emitter.emit.bind(emitter, 'data'));
  manager.on('error', emitter.emit.bind(emitter, 'error'));

  var resolveLocal = function () {
    packages = _.flatten(_.values(manager.dependencies));

    uninstallables = packages.filter(function (pkg) {
      return _.include(names, pkg.name);
    });

    async.forEach(packages, function (pkg, next) {
      pkg.once('loadJSON', next).loadJSON();
    }, function () {
      showWarnings();
      uninstall();
    });
  };

  var showWarnings = function () {
    packages.forEach(function (pkg) {
      if (!pkg.json.dependencies) return;

      var conflicts = _.intersection(
        Object.keys(pkg.json.dependencies),
        _.pluck(uninstallables, 'name')
      );

      conflicts.forEach(function (conflictName) {
        template('warning-uninstall', {packageName: pkg.name, conflictName: conflictName})
          .on('data', emitter.emit.bind(emitter, 'data'));
      });
    });
  };

  var uninstall = function () {
    async.forEach(uninstallables, function (pkg, next) {
      pkg.on('uninstall', next).uninstall();
    }, emitter.emit.bind(emitter, 'end'));
  };

  manager.on('resolveLocal', resolveLocal).resolveLocal();

  return emitter;
};

module.exports.line = function (argv) {
  var options = nopt(optionTypes, shorthand, argv);
  if (options.help) return help('uninstall');
  var names   = options.argv.remain.slice(1);

  return module.exports(names, options)
};<|endoftext|>