diff --git a/.gitignore b/.gitignore index c00df45..5ccfde0 100755 --- a/.gitignore +++ b/.gitignore @@ -2,3 +2,5 @@ /promises_tests /main.js /tmp +/.idea +test/tests.js diff --git a/CHANGELOG.md b/CHANGELOG.md index e4b5b8d..51ab783 100755 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -1,2 +1,3 @@ + # Master Initial commit diff --git a/Gruntfile.js b/Gruntfile.js index 7396499..138f006 100755 --- a/Gruntfile.js +++ b/Gruntfile.js @@ -78,6 +78,20 @@ module.exports = function(grunt) { 'uglify:browserNoVersion' ]); + this.registerTask('coffeeTests',[ + 'clean:tests', + 'build', + 'coffeeify:tests', + 'watch:coffeeTests' + + ]); + this.registerTask('phantomTests',[ + 'clean:tests', + 'build', + 'coffeeify:tests', + 'mocha_phantomjs:phantom' + + ]); // Custom YUIDoc task this.registerTask('docs', ['yuidoc']); @@ -90,7 +104,8 @@ module.exports = function(grunt) { grunt.loadNpmTasks('grunt-mocha-test'); grunt.loadNpmTasks('grunt-contrib-yuidoc'); grunt.loadNpmTasks('grunt-release-it'); - + grunt.loadNpmTasks('grunt-contrib-coffeeify'); + grunt.loadNpmTasks('grunt-include-source'); // Merge config into emberConfig, overwriting existing settings grunt.initConfig(config); }; diff --git a/bower.json b/bower.json new file mode 100644 index 0000000..34c24d6 --- /dev/null +++ b/bower.json @@ -0,0 +1,21 @@ +{ + "name": "ember-share", + "description": "Integrate ShareDB 1.00 with Ember", + "main": "dist/ember-share.js", + "authors": [ + "Oren Griffin " + ], + "license": "MIT", + "keywords": [ + "ShareDB", + "ShareJS" + ], + "homepage": "https://github.com/Optibus/ember-share", + "ignore": [ + "**/.*", + "node_modules", + "bower_components", + "test", + "tests" + ] +} diff --git a/dist/commonjs/ember-share.js b/dist/commonjs/ember-share.js index 277b181..4b2be73 100644 --- a/dist/commonjs/ember-share.js +++ b/dist/commonjs/ember-share.js @@ -1,33 +1,16 @@ "use strict"; var ShareTextMixin = require("ember-share/mixins/share-text")["default"]; -var ShareProxy = require("ember-share/models/share-proxy")["default"]; -var ShareArray = require("ember-share/models/share-array")["default"]; +var ShareProxy = require("ember-share/models/model")["default"]; var Store = require("ember-share/store")["default"]; var Utils = require("ember-share/utils")["default"]; +var attrFunc = require("ember-share/attr")["default"]; +var belongsTo = require("ember-share/belongs-to")["default"]; -Ember.onLoad('Ember.Application', function(Application) { - Application.initializer({ - name: 'ember-share', - initialize : function(container, application){ - application.register('store:main', application.Store || StoreStore); - container.lookup('store:main'); - } - }); - Application.initializer({ - name: 'injectStore', - before : 'ember-share', - initialize : function(container, application) { - application.register('model:share-proxy',ShareProxy); - application.register('model:share-array',ShareArray); - application.inject('controller', 'store', 'store:main'); - application.inject('route', 'store', 'store:main'); - } - }); -}); - +var attr = attrFunc('_sdbProps') exports.ShareTextMixin = ShareTextMixin; exports.ShareProxy = ShareProxy; -exports.ShareArray = ShareArray; +exports.belongsTo = belongsTo; exports.Store = Store; -exports.Utils = Utils; \ No newline at end of file +exports.Utils = Utils; +exports.attr = attr; \ No newline at end of file diff --git a/dist/commonjs/ember-share/attr.js b/dist/commonjs/ember-share/attr.js new file mode 100644 index 0000000..5a37785 --- /dev/null +++ b/dist/commonjs/ember-share/attr.js @@ -0,0 +1,60 @@ +"use strict"; +var sillyFunction = function (value) {return value}; + +exports["default"] = function(sdbProps) { + return function() { + var options, + type; + options = {}; + type = null; + _.forEach(arguments, function(arg) { + if (_.isPlainObject(arg)) { + return options = arg; + } else { + if (_.isString(arg)) { + return type = arg.charAt(0).toUpperCase() + arg.slice(1); + } + } + }); + if (type != null && window[type] != null) { + var transfromToType = function (value) { + var newValue = new window[type](value) + if (type == 'Date') + return newValue + else + return newValue.valueOf() + }; + } else { + var transfromToType = sillyFunction + } + + return Ember.computed({ + get: function(k) { + this.get(sdbProps, true).addObject(k); + // return this.get(k, true); + var isSpecielKey = _.includes([ + '_isSDB', + '_sdbProps', + '_subProps', + 'doc', + '_prefix', + 'content', + '_idx', + '_root' + ], k); + + if (isSpecielKey || this._fullPath == null) + return transfromToType(this._get(k, true)) + else + return transfromToType(this._get(this._fullPath(k))) + + }, + set: function(k, v, isFromServer) { + // return this._super(p, oi) + var path = (k == null) ? this.get('_prefix') : ((k == '_idx' || !this._fullPath) ? k : this._fullPath(k)); + return this._set(path, v) + + } + }); + } +} \ No newline at end of file diff --git a/dist/commonjs/ember-share/belongs-to.js b/dist/commonjs/ember-share/belongs-to.js new file mode 100644 index 0000000..9d2ac2a --- /dev/null +++ b/dist/commonjs/ember-share/belongs-to.js @@ -0,0 +1,48 @@ +"use strict"; +exports["default"] = function(DS, modelName) { + // var options, type; + // options = {}; + // type = null; + // _.forEach(arguments, function(arg) { + // if (_.isPlainObject(arg)) { + // return options = arg; + // } else { + // if (_.isString(arg)) { + // return type = null; + // } + // } + // }); + var store = this.originalStore; + return Ember.computed({ + get: function(k) { + var ref; + + return store.findRecord(modelName, this.get(ref = "doc.data." + k)); + // return != null ? ref : Ember.get(options, 'defaultValue')); + }, + set: function(p, oi, isFromServer) { + return oi; + } + }); + } + + +// attr: -> +// options = {}; type = null +// _.forEach arguments, (arg) -> +// if _.isPlainObject(arg) +// options = arg +// else +// if _.isString arg +// type = null +// +// Ember.computed +// get: (k) -> +// @get "doc.data.#{k}" ? Ember.get(options, 'defaultValue') +// set: (p, oi, isFromServer) -> +// if type? +// oi = window[type.toUpperCase type] oi +// od = @get p +// p = p.split '.' +// @get('doc').submitOp [{p,od,oi}] +// oi \ No newline at end of file diff --git a/dist/commonjs/ember-share/models/base.js b/dist/commonjs/ember-share/models/base.js new file mode 100644 index 0000000..405b983 --- /dev/null +++ b/dist/commonjs/ember-share/models/base.js @@ -0,0 +1,143 @@ +"use strict"; +var UseSubsMixin = require("./use-subs-mixin")["default"]; +var SubMixin = require("./sub-mixin")["default"]; +var SDBSubArray = require("./sub-array")["default"]; +var subs = require("./subs-handler")["default"]; +var Utils = require("./utils")["default"]; + +var toJson = function(obj) { + return (obj == null) + ? void 0 + : JSON.parse(JSON.stringify(obj)); +}; + +var getPlainObject = function (value) { + if (value != null && !((typeof value == 'string') || (typeof value == 'number'))) + if (typeof value.toJson == 'function') + return value.toJson() + else + return toJson(value) + else { + return value + } +} + +// +// ShareDb Base Class +// +// Root and all subs (currently not arrays) inherit from base. +// +// + +var GetterSettersMixin = Ember.Mixin.create({ + + _get: function(k, selfCall) { + var firstValue = _.first(k.split('.')); + + if (k != '_sdbProps' && _.includes(this.get('_sdbProps'), firstValue)) { + var content = this.get("doc.data." + k); + return this.useSubs(content, k) + } else { + return this.get(k); + } + }, + + _set: function(path, oi) { + var firstValue = _.first(path.split('.')); + var self = this; + + if (Ember.get(this, '_prefix') == null) + this.get(firstValue); + + if (path != '_sdbProps' && _.includes(this.get('_sdbProps'), firstValue)) { + var od = getPlainObject(this._get(path)); + oi = getPlainObject(oi); + var p = path.split('.'); + var utils = Utils(this); + utils.removeChildren(path, true); + var op = { + p: p, + od: od, + oi: oi + }; + + if (od == null) + delete op.od; + + if (op.oi != op.od) { + this.get('doc').submitOp([op], function(err) { + self.get('_root', true).trigger('submitted', err); + }); + } + + return this.useSubs(oi,path); + } else { + return this.set(path, oi, true) + + } + } + +}); +var SDBBase = Ember.Object.extend(Ember.Evented, GetterSettersMixin, { + + _isSDB: true, + + notifyProperties: function notifyProperties(props) { + var self = this; + _.forEach(props, function(prop) { + self.notifyPropertyChange(prop) + }) + return this + }, + + notifyDidProperties: function notifyDidProperties(props) { + var self = this; + _.forEach(props, function(prop) { + self.propertyDidChange(prop) + }) + return this + }, + + notifyWillProperties: function notifyWillProperties(props) { + var self = this; + _.forEach(props, function(prop) { + self.propertyWillChange(prop) + }) + return this + }, + + deleteProperty: function deleteProperty(k) { + var doc = this.get('doc'); + var p = k.split('.'); + var od = getPlainObject(this.get(k)); + doc.submitOp([ + { + p: p, + od: od + } + ]); + }, + + setProperties: function setProperties(obj) { + var sdbProps = this.get('_sdbProps'); + var self = this; + var SDBpropsFromObj = _.filter(_.keys(obj), function(key) { + self.get(key); + return _.includes(sdbProps, key) + }); + var nonSDB = _.reject(_.keys(obj), function(key) { + return _.includes(sdbProps, key) + }); + this._super(_.pick(obj, nonSDB)); + _.forEach(SDBpropsFromObj, function(key) { + self.set(key, obj[key]) + }); + }, + +}); + +SDBBase = SDBBase.extend(UseSubsMixin); +subs.object = SDBBase.extend(SubMixin); +subs.array = SDBSubArray(SubMixin, GetterSettersMixin).extend(UseSubsMixin); + +exports["default"] = SDBBase \ No newline at end of file diff --git a/dist/commonjs/ember-share/models/model.js b/dist/commonjs/ember-share/models/model.js new file mode 100644 index 0000000..16a80a2 --- /dev/null +++ b/dist/commonjs/ember-share/models/model.js @@ -0,0 +1,67 @@ +"use strict"; +var Utils = require("./utils")["default"]; +var SDBBase = require("./base")["default"]; + +// +// ShareDb Ember Model Class +// +// extends Base. +// this is model has a recursive structure, getting an inner object or array will return +// a sub object which is conencted to its parent. +// an over view of the entire structure can be found here: +// https://www.gliffy.com/go/share/sn1ehtp86ywtwlvhsxid +// +// + +var SDBRoot = SDBBase.extend({ + unload: function() { + return this.get('_store').unload(this.get('_type'), this); + }, + + id: Ember.computed.reads('doc.id'), + + _childLimiations: (function() { + return [] + }).property(), + + _root: (function() { + return this + }).property(), + + _children: (function() { + return {} + }).property(), + + _sdbProps: (function () { + return [] + }).property(), + + setOpsInit: (function() { + var doc = this.get('doc', true); + var oldDoc = this.get('oldDoc'); + var utils = Utils(this); + + if (oldDoc) { + oldDoc.destroy(); + } + // doc.on('before op', utils.beforeAfter("Will")); + doc.on('before component', utils.beforeAfter("Will")); + doc.on('after component', utils.beforeAfter("Did")); + // doc.on('op', utils.beforeAfter("Did")); + + this.set('oldDoc', doc); + + }).observes('doc').on('init'), + + + willDestroy: function () { + var utils = Utils(this); + this._super.apply(this, arguments) + utils.removeChildren(); + console.log('destroying children'); + } + +}); + + +exports["default"] = SDBRoot \ No newline at end of file diff --git a/dist/commonjs/ember-share/models/share-array.js b/dist/commonjs/ember-share/models/share-array.js deleted file mode 100644 index 2439ae2..0000000 --- a/dist/commonjs/ember-share/models/share-array.js +++ /dev/null @@ -1,81 +0,0 @@ -"use strict"; -var ShareProxy = require("./share-proxy")["default"]; - -exports["default"] = Ember.Object.extend(Ember.MutableArray, { - _context: null, - _cache: null, - itemType: 'share-proxy', - init: function () { - this._cache = []; // cache wrapped objects - this._factory = this.container.lookupFactory('model:'+this.itemType); - // TODO subscribe to array ops on context - var _this = this; - this._context.on('delete', function (index, removed) { - _this.arrayContentWillChange(index, 1, 0); - - _this._cache.splice(index, 1); - - // update paths - var depth = _this._context.path.length; - _this._cache.forEach(function(item,idx){ - item._context.path[depth]= idx; - }) - _this.arrayContentDidChange(index, 1, 0); - }); - this._context.on('insert', function (index, value) { - _this.arrayContentWillChange(index, 0, 1); - - var model = _this._factory.create({ - _context: _this._context.createContextAt(index) - }); - - _this._cache.splice(index, 0, model); - // update paths - var depth = _this._context.path.length; - _this._cache.forEach(function(item,idx){ - item._context.path[depth]= idx; - }); - _this.arrayContentDidChange(index, 0, 1); - }); - }, - length: function () { - return this._context.get().length; - }.property().volatile(), - objectAt: function (index) { - if (this._cache[index] === undefined && this._context.get(index) !== undefined) { - this._cache[index] = this._factory.create({ - _context: this._context.createContextAt(index) - }); - } - return this._cache[index]; - }, - replace: function (index, length, objects) { - var objectsLength = objects.length; - var args = new Array(objectsLength+2); - var model; - args[0] = index; - args[1] = length; - - this.arrayContentWillChange(index, length, objectsLength); - - if (length > 0) { - this._context.remove([index], length); - } - - for (var i=0; i objects.length) + ? len + : objects.length; + for (var i = 0; i < iterationLength; i++) { + var newIndex = i + start; + var obj = objects.objectAt(i); + this._submitOp(newIndex, obj, (len > i + ? this.objectAt(newIndex) + : null)) + } + this.arrayContentDidChange(start, len, objects.length); + return this //._super(start, len, objects) + }, + + onChangeDoc: (function () { + // debugger + // this.set ('content', this.get('doc.data.' + this.get('_prefix'))) + // Ember.run.next (this, function () P{}) + this.replaceContent(this.get('doc.data.' + this.get('_prefix')), true) + }).observes('doc') + }); +} \ No newline at end of file diff --git a/dist/commonjs/ember-share/models/sub-mixin.js b/dist/commonjs/ember-share/models/sub-mixin.js new file mode 100644 index 0000000..ab4cbab --- /dev/null +++ b/dist/commonjs/ember-share/models/sub-mixin.js @@ -0,0 +1,175 @@ +"use strict"; +var Utils = require("./utils")["default"]; +var attrs = require("../attr")["default"]; + +var allButLast = function(arr) { + return arr.slice(0, arr.length - 1) +}; + +// +// Sub Mixin +// +// All subs use this mixin (Object and Array) +// +// + +exports["default"] = Ember.Mixin.create({ + + _children: (function() { + return {} + }).property(), + + _sdbProps: (function() { + return [] + }).property(), + + _subProps: (function() { + return [] + }).property(), + + doc: Ember.computed.reads('_root.doc'), + + createInnerAttrs: (function() { + var tempContent = Ember.get(this, 'tempContent'); + var self = this; + var attr = attrs('_subProps'); + var keys = []; + + _.forEach(tempContent, function(value, key) { + keys.push(key); + Ember.defineProperty(self, key, attr()); + }) + + Ember.get(this, '_subProps').addObjects(keys); + delete this['tempContent']; + }).on('init'), + + beforeFn: (function (){return []}).property(), + afterFn: (function (){return []}).property(), + + activateListeners: (function() { + var utils = Utils(this); + + var beforeFn = utils.beforeAfterChild("Will"); + var afterFn = utils.beforeAfterChild("Did"); + + if (this.has('before op')) { + this.off('before op', this.get('beforeFn').pop()) + } + if (this.has('op')) { + this.off('op', this.get('afterFn').pop()) + } + this.on('before op', beforeFn); + this.on('op', afterFn); + + this.get('beforeFn').push(beforeFn); + this.get('afterFn').push(afterFn); + + // }).on('init'), + }).observes('doc').on('init'), + + _fullPath: function(path) { + var prefix = Ember.get(this, '_prefix'); + var idx = Ember.get(this, '_idx'); + + if (prefix) { + if (idx != null) { + return prefix + '.' + idx + '.' + path + } else { + return prefix + '.' + path; + } + } else + return path; + } + , + + deleteProperty: function(k) { + this.removeKey(k); + return this._super(this._fullPath(k)) + }, + + replaceContent: function(content, noSet) { + this.notifyWillProperties(this.get('_subProps').toArray()); + var prefix = this.get('_prefix'); + var idx = this.get('_idx') + var path = (idx == null) ? prefix : prefix + '.' + idx + + if (!noSet) + this._set(path, content); + + var self = this; + var utils = Utils(this); + + utils.removeChildren(path); + + if (_.isEmpty(Object.keys(this))) { + Ember.setProperties(this, {tempContent: content}); + this.createInnerAttrs(); + + var notifyFather = function (prefixArr, keys) { + if (_.isEmpty(prefixArr)) + self.get('_root').notifyPropertyChange(keys.join('.')) + else { + var child = self.get['_children'][prefixArr.join('.')] + if (child != null) + child.notifyPropertyChange(prefixArr.join('.') + '.' + keys.join('.')) + else + keys.push(prefixArr.pop()); + notifyFather(prefixArr, keys); + } + }; + var prefixArr = prefix.split('.') + var key = prefixArr.pop() + + notifyFather(prefixArr, [key]); + } + else { + if (_.isPlainObject(content)) + var toDelete = _.difference(Object.keys(this), Object.keys(content)) + else + var toDelete = Object.keys(this); + + _.forEach(toDelete, function(prop) { + delete self[prop] + }); + this.get('_subProps').removeObjects(toDelete); + Ember.setProperties(this, {tempContent: content}); + this.createInnerAttrs(); + this.notifyDidProperties(this.get('_subProps').toArray()); + } + + return this + }, + + toJson: function() { + var idx = Ember.get(this, '_idx'), + k = Ember.get(this, '_prefix'); + var path = (idx == null) + ? k + : (k + '.' + idx); + return this.get('doc.data.' + path); + }, + + addKey: function (key) { + var attr = attrs('_subProps'); + if (!(this.get('_subProps').indexOf(key) > -1)) + Ember.defineProperty(this, key, attr()); + return this + }, + + removeKey: function (key) { + var attr = attrs('_subProps'); + var utils = Utils(this); + utils.removeChildren(key, true); + this.get('_subProps').removeObject(key); + delete this[key]; + return this + }, + + removeListeners: function () { + this.off('before op', this.get('beforeFn')) + this.off('op', this.get('afterFn')) + + } + +}) \ No newline at end of file diff --git a/dist/commonjs/ember-share/models/subs-handler.js b/dist/commonjs/ember-share/models/subs-handler.js new file mode 100644 index 0000000..f1b286f --- /dev/null +++ b/dist/commonjs/ember-share/models/subs-handler.js @@ -0,0 +1,13 @@ +"use strict"; +// +// Subs Handler +// +// since we have a recursive model structure there is a need for +// creating the subs in a common place and then reuse it in its own class. +// +// + +exports["default"] = { + object : {}, + array : {} +} \ No newline at end of file diff --git a/dist/commonjs/ember-share/models/use-subs-mixin.js b/dist/commonjs/ember-share/models/use-subs-mixin.js new file mode 100644 index 0000000..a67e07d --- /dev/null +++ b/dist/commonjs/ember-share/models/use-subs-mixin.js @@ -0,0 +1,60 @@ +"use strict"; +var subs = require("./subs-handler")["default"]; +var Utils = require("./utils")["default"];exports["default"] = Ember.Mixin.create({ + + useSubs: function useSubs(content, k, idx) { + var utils = Utils(this); + + if (utils.matchChildToLimitations(k)) + return content; + + if (_.isPlainObject(content)) { + content = { + tempContent: content + }; + var use = 'object' + + } else if (_.isArray(content)) { + content = { + content: content + }; + var use = 'array'; + } + if (use) { + var child, + _idx; + var path = (idx == null) ? k : (k + '.' + idx); + var ownPath = Ember.get(this, '_prefix'); + if ((_idx = Ember.get(this, '_idx')) != null) + ownPath += '.' + _idx; + if (path == ownPath) { + return this; + } + + var children = Ember.get(this, '_children'); + var childrenKeys = Object.keys(children); + + if (_.includes(childrenKeys, path)) + return children[path] + else + child = {}; + + var sub = subs[use].extend({ + // doc: this.get('doc'), + _children: Ember.get(this, '_children'), + _prefix: k, + _idx: idx, + _sdbProps: Ember.get(this, '_sdbProps'), + _root: Ember.get(this,'_root') + }); + + sub = sub.create(content); + + child[path] = sub; + _.assign(Ember.get(this, '_children'), child); + + return sub + } else + return content + } +}) \ No newline at end of file diff --git a/dist/commonjs/ember-share/models/utils.js b/dist/commonjs/ember-share/models/utils.js new file mode 100644 index 0000000..306ddd5 --- /dev/null +++ b/dist/commonjs/ember-share/models/utils.js @@ -0,0 +1,274 @@ +"use strict"; +exports["default"] = function(context) { + + return { + + isOpOnArray: function(op) { + return (op.ld != null) || (op.lm != null) || (op.li != null) + }, + + matchingPaths: function(as, bs) { + var counter = 0; + var higherLength = (as.length > bs.length) + ? as.length + : bs.length + while ((as[counter] == '*' || as[counter] == bs[counter]) && counter < higherLength) { + counter++ + } + return counter - (as.length / 1000) + }, + + matchChildToLimitations: function (key) { + var childLimiations = Ember.get(context, '_root._childLimiations'); + var prefix = Ember.get(context, '_prefix') + + if (prefix == null || key.match(prefix)) + prefix = key + else + prefix += '.' + key + + prefix = prefix.split('.'); + var self = this; + return _.some (childLimiations, function (_limit) { + var limit = _limit.split('/'); + return prefix.length == limit.length && Math.ceil(self.matchingPaths(limit, prefix)) == prefix.length + }) + }, + + prefixToChildLimiations: function (key) { + var childLimiations = Ember.get(context, '_root._childLimiations'); + var prefix = Ember.get(context, '_prefix') + + if (prefix == null || key.match(prefix)) + prefix = key + else + prefix += '.' + key + + prefix = prefix.split('.'); + var self = this, limiationsArray; + + var relevantLimitIndex = this.findMaxIndex(limiationsArray = _.map (childLimiations, function (_limit) { + var limit = _limit.split('/'); + var result = Math.ceil(self.matchingPaths(limit, prefix)) + return result < limit.length ? 0 : result + })); + if (relevantLimitIndex >= 0 && limiationsArray[relevantLimitIndex] > 0) { + var relevantLimit = childLimiations[relevantLimitIndex].split('/'); + var orignalPrefix; + var result = prefix.slice(0, Math.ceil(self.matchingPaths(relevantLimit, prefix)) ); + if (orignalPrefix = Ember.get(context, '_prefix')) { + orignalPrefix = orignalPrefix.split('.'); + return result.slice(orignalPrefix.length) + } else + return result.join('.'); + } + else { + return key; + } + + }, + + removeChildren: function (path, includeSelf) { + var children = Ember.get(context, '_children'); + var childrenKeys = Object.keys(children); + var prefix = context.get('_prefix'); + var utils = this; + + if ((prefix != null) && path && path.indexOf(prefix) != 0) { + path = prefix + '.' + path + } + + if (path) { + childrenKeys = _.reduce(childrenKeys, function(result, key) { + var matches = Math.ceil(utils.matchingPaths(key.split('.'), path.split('.'))) + if (includeSelf && (matches >= path.split('.').length) || + (!includeSelf && (matches > path.split('.').length))) + result.push(key); + return result + }, []); + } + + _.forEach (childrenKeys, function (key) { + children[key].destroy() + delete children[key] + }) + }, + + comparePathToPrefix: function(path, prefix) { + return Boolean(Math.ceil(this.matchingPaths(path.split('.'), prefix.split('.')))) + }, + + cutLast: function(path, op) { + var tempPath; + if (this.isOpOnArray(op) && !isNaN(+ _.last(path))) { + tempPath = _.clone(path); + tempPath.pop(); + } + return (tempPath) + ? tempPath + : path + }, + + comparePathToChildren: function(path, op) { + var utils = this; + var children = Ember.get(context, '_children'); + var childrenKeys = Object.keys(children); + var hasChildren = _.some(childrenKeys, function(childKey) { + var pathsCounter = utils.matchingPaths(childKey.split('.'), utils.cutLast(path, op)) + return Math.ceil(pathsCounter) == childKey.split('.').length + }); + return !Ember.isEmpty(childrenKeys) && hasChildren + }, + + triggerChildren: function(didWill, op, isFromClient) { + var newP = _.clone(op.p); + // var children = Ember.get(context, '_children'); + var children = context.get('_children'); + var childrenKeys = Object.keys(children); + if (Ember.isEmpty(childrenKeys)) + return; + var child, + utils = this; + var counterToChild = _.mapKeys(children, function(v, childKey) { + if (utils.isOpOnArray(op) && !isNaN(+ _.last(childKey.split('.')))) + return 0 + else + return utils.matchingPaths(utils.cutLast(childKey.split('.'), op), op.p) + }); + var toNumber = function(strings) { + return _.map(strings, function(s) { + return + s + }) + }; + var chosenChild = counterToChild[_.max(toNumber(Object.keys(counterToChild)))] + if (didWill == 'Will') + chosenChild.trigger('before op', [op], isFromClient); + if (didWill == 'Did') + chosenChild.trigger('op', [op], isFromClient); + } + , + + beforeAfter: function(didWill) { + var utils = this; + var ex; + return function(ops, isFromClient) { + // console.log( _.first (ops)); + + if (!isFromClient) { + _.forEach(ops, function(op) { + // if (didWill == 'Did') + // console.log(Ember.get(context,'_prefix') + ' recieved log'); + if (utils.comparePathToChildren(op.p, op)) { + utils.triggerChildren(didWill, op, isFromClient); + } else { + if (utils.isOpOnArray(op)) { + ex = utils.extractArrayPath(op); + + // console.log(Ember.get(context,'_prefix') + ' perform log'); + // console.log('op came to parent'); + context.get(ex.p)["arrayContent" + didWill + "Change"](ex.idx, ex.removeAmt, ex.addAmt) + } else { + context["property" + didWill + "Change"](utils.prefixToChildLimiations(op.p.join('.'))); + } + } + }); + } + }; + }, + + beforeAfterChild: function(didWill) { + var utils = this; + var ex, + prefix, + _idx; + return function(ops, isFromClient) { + if (((_idx = Ember.get(context, '_idx')) != null) || !isFromClient) { + _.forEach(ops, function(op) { + + if (op.p.join('.') == (prefix = Ember.get(context, '_prefix')) && didWill == 'Did') { + if (op.oi != null) { + context.replaceContent(op.oi, true) + } else { + if (op.od != null) { + var fatherPrefix = prefix.split('.'); + var key = fatherPrefix.pop(); + var father; + if (!_.isEmpty(fatherPrefix) && (father = context.get('_children.' + fatherPrefix.join('.')))) + father.removeKey(key); + else + context.get('_root').propertyDidChange(prefix) + } + } + } else { + var path = (_idx == null) + ? prefix.split('.') + : prefix.split('.').concat(String(_idx)); + var newP = _.difference(op.p, path); + if (utils.comparePathToPrefix(op.p.join('.'), prefix)) { + if (utils.isOpOnArray(op) && (Ember.get(context, '_idx') == null)) { + + var newOp = _.clone(op); + newOp.p = newP; + ex = utils.extractArrayPath(newOp); + + if (ex.p == "") + context["arrayContent" + didWill + "Change"](ex.idx, ex.removeAmt, ex.addAmt) + else + Ember.get(context, ex.p)["arrayContent" + didWill + "Change"](ex.idx, ex.removeAmt, ex.addAmt); + } + else { + if (newP.join('.') == '') { + + // delete self from father + if (false && _.isEmpty(newOp) && op.od && (op.oi == null) && (_.isEqual(op.od, context.toJson()))) { + var keyToRemove = path.pop(); + if (_.isEmpty(path)) { + utils.removeChildren(keyToRemove); + } + else { + var father = context.get('_children')[path.join('.')]; + father.removeKey (keyToRemove); + } + } + else { + context["property" + didWill + "Change"]('content'); + } + } + + else { + + if (op.oi && op.od == null) + context.addKey(_.first(newP)) + + if (op.od && op.oi == null) + context.removeKey(_.first(newP)) + + context["property" + didWill + "Change"](utils.prefixToChildLimiations(newP.join('.'))); + } + } + } + } + }); + } + } + }, + + findMaxIndex: function (arr) { + return arr.indexOf(_.max(arr)) + }, + + extractArrayPath: function(op) { + return { + idx: + _.last(op.p), + p: _.slice(op.p, 0, op.p.length - 1).join('.'), + addAmt: op.li != null + ? 1 + : 0, + removeAmt: op.ld != null + ? 1 + : 0 + } + } + + } +} \ No newline at end of file diff --git a/dist/commonjs/ember-share/store.js b/dist/commonjs/ember-share/store.js index 8f57035..18c0374 100644 --- a/dist/commonjs/ember-share/store.js +++ b/dist/commonjs/ember-share/store.js @@ -1,21 +1,93 @@ "use strict"; -/* global BCSocket:false, sharejs:false */ +/* global BCSocket:false, sharedb:false */ var guid = require("./utils").guid; var patchShare = require("./utils").patchShare; var Promise = Ember.RSVP.Promise; +var socketReadyState = [ + 'CONNECTING', + 'OPEN', + 'CLOSING', + 'CLOSE' +] -exports["default"] = Ember.Object.extend({ +exports["default"] = Ember.Object.extend(Ember.Evented, { socket: null, connection: null, - url : 'http://'+window.location.hostname, + + // port: 3000, + // url : 'https://qa-e.optibus.co', + url : window.location.hostname, init: function () { - this.checkConnection = Ember.Deferred.create({}); + var store = this; + + this.checkSocket = function () { + return new Promise(function (resolve, reject) { + + if (store.socket == null) { + store.one('connectionOpen', resolve); + } + else { + var checkState = function (state, cb) { + switch(state) { + case 'connected': + return resolve(); + case 'connecting': + return store.connection.once('connected', resolve); + default: cb(state) + } + } + var checkStateFail = function (state) { + switch(state) { + case 'closed': + return reject('connection closed'); + case 'disconnected': + return reject('connection disconnected'); + case 'stopped': + return reject('connection closing'); + } + } + var failed = false + checkState(store.connection.state, function(state){ + if (failed) + checkStateFail(state) + else + Ember.run.next (this, function () { + failed = true; + checkState(store.connection.state, checkStateFail) + }) + }) + + + } + }); + } + + this.checkConnection = function () { + return new Promise(function (resolve, reject) { + return store.checkSocket() + .then(function () { + return resolve() + if (store.authentication != null && store.isAuthenticated != null) { + if (store.isAuthenticated) return resolve(); + if (store.isAuthenticating) return store.one('authenticated', resolve); + if (!store.isAuthenticated) return store.authentication(store.connection.id) + // if (!store.isAuthenticating) return reject() + return reject('could not authenticat') + } else + return resolve() + }) + .catch(function (err) { + return reject(err) + }) + }); + }; + this.cache = {}; - if(!window.sharejs) + if(!window.sharedb) { - throw new Error("ShareJS client not included"); + throw new Error("sharedb client not included"); } if (window.BCSocket === undefined && window.Primus === undefined) { throw new Error("No Socket library included"); @@ -24,55 +96,100 @@ exports["default"] = Ember.Object.extend({ { this.beforeConnect() .then(function(){ - Ember.sendEvent(store,'connect'); + store.trigger('connect'); }); } else { - Ember.sendEvent(this,'connect'); + store.trigger('connect'); } }, - doConnect : function(){ + doConnect : function(options){ var store = this; - + if(window.BCSocket) { + this.setProperties(options); this.socket = new BCSocket(this.get('url'), {reconnect: true}); this.socket.onerror = function(err){ - Ember.sendEvent(store,'connectionError',[err]); + store.trigger('connectionError', [err]); + }; this.socket.onopen = function(){ - store.checkConnection.resolve(); - Ember.sendEvent(store,'connectionOpen'); + store.trigger('connectionOpen'); + }; this.socket.onclose = function(){ - Ember.sendEvent(store,'connectionEnd'); + store.trigger('connectionEnd'); }; } else if(window.Primus) { patchShare(); - this.socket = new Primus(this.get('url')); + this.setProperties(options); + var hostname = this.get('url'); + if (this.get('protocol')) + hostname = this.get('protocol') + '://' + hostname; + if (this.get("port")) + hostname += ':' + this.get('port'); + this.socket = new Primus(hostname); + // console.log('connection starting'); + this.socket.on('error', function error(err) { - Ember.sendEvent(store,'connectionError',[err]); + store.trigger('connectionError', [err]); }); this.socket.on('open', function() { - store.checkConnection.resolve(); - Ember.sendEvent(store,'connectionOpen'); + // console.log('connection open'); + store.trigger('connectionOpen'); }); this.socket.on('end', function() { - Ember.sendEvent(store,'connectionEnd'); + store.trigger('connectionEnd'); + }); + this.socket.on('close', function() { + store.trigger('connectionEnd'); }); } else { throw new Error("No Socket library included"); } - this.connection = new sharejs.Connection(this.socket); - + var oldHandleMessage = sharedb.Connection.prototype.handleMessage; + var oldSend = sharedb.Connection.prototype.send; + + store.on('connectionEnd', function () { + // console.log('ending connection'); + store.isAuthenticated = false + }) + + sharedb.Connection.prototype.handleMessage = function(message) { + var athenticating, handleMessageArgs; + handleMessageArgs = arguments; + // console.log(message.a); + var context = this; + oldHandleMessage.apply(context, handleMessageArgs); + if (message.a === 'init' && (typeof message.id === 'string') && message.protocol === 1 && typeof store.authenticate === 'function') { + store.isAuthenticating = true; + return store.authenticate(message.id) + .then(function() { + console.log('authenticated !'); + store.isAuthenticating = false; + store.isAuthenticated = true; + store.trigger('authenticated') + }) + .catch(function (err) { + store.isAuthenticating = false; + // store.socket.end() + // debugger + }) + } + }; + + this.connection = new sharedb.Connection(this.socket); + }.on('connect'), find: function (type, id) { + type = type.pluralize() var store = this; - return this.checkConnection + return this.checkConnection() .then(function(){ return store.findQuery(type, {_id: id}).then(function (models) { return models[0]; @@ -82,63 +199,143 @@ exports["default"] = Ember.Object.extend({ }); }, createRecord: function (type, data) { + var ref, path; + path = (ref = this._getPathForType(type)) ? ref : type.pluralize() + path = this._getPrefix(type) + path; + type = type.pluralize() var store = this; - return store.checkConnection + return store.checkConnection() .then(function(){ - var doc = store.connection.get(type, guid()); + var doc = store.connection.get(path, data.id == null ? guid() : data.id); return Promise.all([ store.whenReady(doc).then(function (doc) { return store.create(doc, data); }), store.subscribe(doc) ]).then(function () { - return store._createModel(type, doc); + var model = store._createModel(type, doc); + store._cacheFor(type).addObject(model); + return model }); }); }, - deleteRecord : function(model) { - // TODO: delete and cleanup caches - // model._context.context._doc.del() + deleteRecord : function(type, id) { + var cache = this._cacheFor(type.pluralize()); + var model = cache.findBy('id', id); + var doc = model.get('doc'); + return new Promise(function (resolve, reject) { + doc.del(function (err) { + if (err != null) + reject(err) + else { + resolve() + } + }); + }) + }, + findAndSubscribeQuery: function(type, query) { + type = type.pluralize() + var store = this; + var prefix = this._getPrefix(type); + store.cache[type] = [] + + return this.checkConnection() + .then(function(){ + return new Promise(function (resolve, reject) { + function fetchQueryCallback(err, results, extra) { + if (err !== null) { + return reject(err); + } + resolve(store._resolveModels(type, results)); + } + query = store.connection.createSubscribeQuery(prefix + type, query, null, fetchQueryCallback); + query.on('insert', function (docs) { + store._resolveModels(type, docs) + }); + query.on('remove', function (docs) { + for (var i = 0; i < docs.length; i++) { + var modelPromise = store._resolveModel(type, docs[i]); + modelPromise.then(function (model) { + store.unload(type, model) + }); + } + }); + }); + }); + }, + findRecord: function (type, id) { + var store = this; + return new Promise(function (resolve, reject){ + store.findQuery(type, {_id: id}) + .then(function(results){ + resolve(results[0]) + }) + .catch(function (err){ + reject(err) + }); + }) }, findQuery: function (type, query) { + // type = type.pluralize() + var ref, path; + path = (ref = this._getPathForType(type)) ? ref : type.pluralize() + path = this._getPrefix(type) + path; var store = this; - return this.checkConnection + store.cache[type.pluralize()] = [] + return this.checkConnection() .then(function(){ return new Promise(function (resolve, reject) { function fetchQueryCallback(err, results, extra) { - if (err !== undefined) { + if (err !== null) { return reject(err); } resolve(store._resolveModels(type, results)); } - store.connection.createFetchQuery(type, query, null, fetchQueryCallback); + store.connection.createFetchQuery(path, query, null, fetchQueryCallback); }); }); }, - findAll: function (type) { + findAll: function (type, query) { + type = type.pluralize() throw new Error('findAll not implemented'); // TODO this.connection subscribe style query }, _cacheFor: function (type) { + type = type.pluralize() var cache = this.cache[type]; if (cache === undefined) { - this.cache[type] = cache = {}; + this.cache[type] = cache = []; } return cache; }, + _getPathForType: function (type) { + var Adapter = this.container.lookupFactory('adapter:' + type.singularize()); + if (Adapter) + return Adapter.create().pathForType(); + }, + _getPrefix: function (type) { + var Adapter = this.container.lookupFactory('adapter:' + type.singularize()); + var prefix; + if (Adapter) + prefix = Adapter.create().get('prefix'); + if (!prefix) prefix = ''; + return prefix + }, _factoryFor: function (type) { - return this.container.lookupFactory('model:'+type); + var ref; + var modelStr = (ref = this.get('modelStr')) ? ref : 'model-sdb' + return this.container.lookupFactory(modelStr + ':'+ type.singularize()); }, _createModel: function (type, doc) { - var cache = this._cacheFor(type); var modelClass = this._factoryFor(type); + type = type.pluralize() if(modelClass) { var model = modelClass.create({ - id: doc.name, - _context: doc.createContext().createContextAt() + doc: doc, + _type: type, + _store: this }); - cache[doc.name] = model; return model; } else @@ -147,8 +344,9 @@ exports["default"] = Ember.Object.extend({ } }, _resolveModel: function (type, doc) { - var cache = this._cacheFor(type); - var model = cache[doc.name]; + var cache = this._cacheFor(type.pluralize()); + var id = Ember.get(doc, 'id') || Ember.get(doc, '_id'); + var model = cache.findBy('id', id); if (model !== undefined) { return Promise.resolve(model); } @@ -158,24 +356,68 @@ exports["default"] = Ember.Object.extend({ }); }, _resolveModels: function (type, docs) { + // type = type.pluralize() + var store = this; + var cache = this._cacheFor(type.pluralize()); var promises = new Array(docs.length); for (var i=0; i + // options = {}; type = null + // _.forEach arguments, (arg) -> + // if _.isPlainObject(arg) + // options = arg + // else + // if _.isString arg + // type = null + // + // Ember.computed + // get: (k) -> + // @get "doc.data.#{k}" ? Ember.get(options, 'defaultValue') + // set: (p, oi, isFromServer) -> + // if type? + // oi = window[type.toUpperCase type] oi + // od = @get p + // p = p.split '.' + // @get('doc').submitOp [{p,od,oi}] + // oi }); define("ember-share/mixins/share-text", ["../utils","exports"], @@ -147,216 +246,1005 @@ define("ember-share/mixins/share-text", } }); }); -define("ember-share/models/share-array", - ["./share-proxy","exports"], - function(__dependency1__, __exports__) { +define("ember-share/models/base", + ["./use-subs-mixin","./sub-mixin","./sub-array","./subs-handler","./utils","exports"], + function(__dependency1__, __dependency2__, __dependency3__, __dependency4__, __dependency5__, __exports__) { "use strict"; - var ShareProxy = __dependency1__["default"]; + var UseSubsMixin = __dependency1__["default"]; + var SubMixin = __dependency2__["default"]; + var SDBSubArray = __dependency3__["default"]; + var subs = __dependency4__["default"]; + var Utils = __dependency5__["default"]; - __exports__["default"] = Ember.Object.extend(Ember.MutableArray, { - _context: null, - _cache: null, - itemType: 'share-proxy', - init: function () { - this._cache = []; // cache wrapped objects - this._factory = this.container.lookupFactory('model:'+this.itemType); - // TODO subscribe to array ops on context - var _this = this; - this._context.on('delete', function (index, removed) { - _this.arrayContentWillChange(index, 1, 0); - - _this._cache.splice(index, 1); - - // update paths - var depth = _this._context.path.length; - _this._cache.forEach(function(item,idx){ - item._context.path[depth]= idx; - }) - _this.arrayContentDidChange(index, 1, 0); - }); - this._context.on('insert', function (index, value) { - _this.arrayContentWillChange(index, 0, 1); + var toJson = function(obj) { + return (obj == null) + ? void 0 + : JSON.parse(JSON.stringify(obj)); + }; - var model = _this._factory.create({ - _context: _this._context.createContextAt(index) - }); + var getPlainObject = function (value) { + if (value != null && !((typeof value == 'string') || (typeof value == 'number'))) + if (typeof value.toJson == 'function') + return value.toJson() + else + return toJson(value) + else { + return value + } + } - _this._cache.splice(index, 0, model); - // update paths - var depth = _this._context.path.length; - _this._cache.forEach(function(item,idx){ - item._context.path[depth]= idx; - }); - _this.arrayContentDidChange(index, 0, 1); - }); - }, - length: function () { - return this._context.get().length; - }.property().volatile(), - objectAt: function (index) { - if (this._cache[index] === undefined && this._context.get(index) !== undefined) { - this._cache[index] = this._factory.create({ - _context: this._context.createContextAt(index) - }); - } - return this._cache[index]; - }, - replace: function (index, length, objects) { - var objectsLength = objects.length; - var args = new Array(objectsLength+2); - var model; - args[0] = index; - args[1] = length; + // + // ShareDb Base Class + // + // Root and all subs (currently not arrays) inherit from base. + // + // - this.arrayContentWillChange(index, length, objectsLength); + var GetterSettersMixin = Ember.Mixin.create({ - if (length > 0) { - this._context.remove([index], length); - } + _get: function(k, selfCall) { + var firstValue = _.first(k.split('.')); - for (var i=0; i objects.length) + ? len + : objects.length; + for (var i = 0; i < iterationLength; i++) { + var newIndex = i + start; + var obj = objects.objectAt(i); + this._submitOp(newIndex, obj, (len > i + ? this.objectAt(newIndex) + : null)) + } + this.arrayContentDidChange(start, len, objects.length); + return this //._super(start, len, objects) + }, + + onChangeDoc: (function () { + // debugger + // this.set ('content', this.get('doc.data.' + this.get('_prefix'))) + // Ember.run.next (this, function () P{}) + this.replaceContent(this.get('doc.data.' + this.get('_prefix')), true) + }).observes('doc') + }); + } + }); +define("ember-share/models/sub-mixin", + ["./utils","../attr","exports"], + function(__dependency1__, __dependency2__, __exports__) { + "use strict"; + var Utils = __dependency1__["default"]; + var attrs = __dependency2__["default"]; + + var allButLast = function(arr) { + return arr.slice(0, arr.length - 1) + }; + + // + // Sub Mixin + // + // All subs use this mixin (Object and Array) + // + // + + __exports__["default"] = Ember.Mixin.create({ + + _children: (function() { + return {} + }).property(), + + _sdbProps: (function() { + return [] + }).property(), + + _subProps: (function() { + return [] + }).property(), + + doc: Ember.computed.reads('_root.doc'), + + createInnerAttrs: (function() { + var tempContent = Ember.get(this, 'tempContent'); + var self = this; + var attr = attrs('_subProps'); + var keys = []; + + _.forEach(tempContent, function(value, key) { + keys.push(key); + Ember.defineProperty(self, key, attr()); + }) + + Ember.get(this, '_subProps').addObjects(keys); + delete this['tempContent']; + }).on('init'), + + beforeFn: (function (){return []}).property(), + afterFn: (function (){return []}).property(), + + activateListeners: (function() { + var utils = Utils(this); + + var beforeFn = utils.beforeAfterChild("Will"); + var afterFn = utils.beforeAfterChild("Did"); + + if (this.has('before op')) { + this.off('before op', this.get('beforeFn').pop()) + } + if (this.has('op')) { + this.off('op', this.get('afterFn').pop()) + } + this.on('before op', beforeFn); + this.on('op', afterFn); + + this.get('beforeFn').push(beforeFn); + this.get('afterFn').push(afterFn); + + // }).on('init'), + }).observes('doc').on('init'), + + _fullPath: function(path) { + var prefix = Ember.get(this, '_prefix'); + var idx = Ember.get(this, '_idx'); + + if (prefix) { + if (idx != null) { + return prefix + '.' + idx + '.' + path + } else { + return prefix + '.' + path; + } + } else + return path; + } + , + + deleteProperty: function(k) { + this.removeKey(k); + return this._super(this._fullPath(k)) + }, + + replaceContent: function(content, noSet) { + this.notifyWillProperties(this.get('_subProps').toArray()); + var prefix = this.get('_prefix'); + var idx = this.get('_idx') + var path = (idx == null) ? prefix : prefix + '.' + idx + + if (!noSet) + this._set(path, content); + + var self = this; + var utils = Utils(this); + + utils.removeChildren(path); + + if (_.isEmpty(Object.keys(this))) { + Ember.setProperties(this, {tempContent: content}); + this.createInnerAttrs(); + + var notifyFather = function (prefixArr, keys) { + if (_.isEmpty(prefixArr)) + self.get('_root').notifyPropertyChange(keys.join('.')) + else { + var child = self.get['_children'][prefixArr.join('.')] + if (child != null) + child.notifyPropertyChange(prefixArr.join('.') + '.' + keys.join('.')) + else + keys.push(prefixArr.pop()); + notifyFather(prefixArr, keys); + } + }; + var prefixArr = prefix.split('.') + var key = prefixArr.pop() + + notifyFather(prefixArr, [key]); + } + else { + if (_.isPlainObject(content)) + var toDelete = _.difference(Object.keys(this), Object.keys(content)) + else + var toDelete = Object.keys(this); + + _.forEach(toDelete, function(prop) { + delete self[prop] + }); + this.get('_subProps').removeObjects(toDelete); + Ember.setProperties(this, {tempContent: content}); + this.createInnerAttrs(); + this.notifyDidProperties(this.get('_subProps').toArray()); + } + + return this + }, + + toJson: function() { + var idx = Ember.get(this, '_idx'), + k = Ember.get(this, '_prefix'); + var path = (idx == null) + ? k + : (k + '.' + idx); + return this.get('doc.data.' + path); + }, + + addKey: function (key) { + var attr = attrs('_subProps'); + if (!(this.get('_subProps').indexOf(key) > -1)) + Ember.defineProperty(this, key, attr()); + return this + }, + + removeKey: function (key) { + var attr = attrs('_subProps'); + var utils = Utils(this); + utils.removeChildren(key, true); + this.get('_subProps').removeObject(key); + delete this[key]; + return this + }, + + removeListeners: function () { + this.off('before op', this.get('beforeFn')) + this.off('op', this.get('afterFn')) + + } + + }) }); -define("ember-share/models/share-proxy", +define("ember-share/models/subs-handler", ["exports"], function(__exports__) { "use strict"; - var isArray = Array.isArray || function (obj) { - return obj instanceof Array; - }; + // + // Subs Handler + // + // since we have a recursive model structure there is a need for + // creating the subs in a common place and then reuse it in its own class. + // + // - __exports__["default"] = Ember.Object.extend({ - _context: null, - _cache: null, - init: function () { - this._cache = {}; // allows old value to be seen on willChange event - var _this = this; - this._context.on('replace', function (key, oldValue, newValue) { - _this.propertyWillChange(key); - _this._cache[key] = _this.wrapObject(key, newValue); - _this.propertyDidChange(key); - }); - this._context.on('insert', function (key, value) { - _this.propertyWillChange(key); - _this._cache[key] = _this.wrapObject(key, value); - _this.propertyDidChange(key); - }); - this._context.on('child op', function (key, op) { - // handle add operations - if(key.length === 1 && op.na) - { - _this.propertyWillChange(key[0]); - _this._cache[key] = (_this._cache[key[0]] || _this.get(key[0]) || 0) + op.na; - _this.propertyDidChange(key[0]); - } - }); - }, - unknownProperty: function (key) { - var value = this._cache[key]; - if (value === undefined) { - value = this._cache[key] = this.wrapObject(key, this._context.get([key])); - } - return value; - }, - setUnknownProperty: function (key, value) { - if (this._cache[key] !== value) { - this.propertyWillChange(key); - this._cache[key] = this.wrapObject(key, value); - this._context.set([key], value); - this.propertyDidChange(key); - } - }, - wrapObject: function (key, value) { - if (value !== null && typeof value === 'object') { - var type = this.wrapLookup(key,value); - var factory = this.container.lookupFactory('model:'+type); - return factory.create({ - _context: this._context.createContextAt(key) - }); - } - return value; - }, - wrapLookup : function(key,value) { - return value.type || (isArray(value) ? 'share-array' : 'share-proxy'); - }, - willDestroy: function () { - this._cache = null; - this._context.destroy(); - this._context = null; - }, - toJSON: function () { - return this._context.get(); - }, - incrementProperty: function(key, increment) { - if (Ember.isNone(increment)) { increment = 1; } - Ember.assert("Must pass a numeric value to incrementProperty", (!isNaN(parseFloat(increment)) && isFinite(increment))); - this.propertyWillChange(key); - this._cache[key] = (this._cache[key] || this.get(key) || 0) + increment; - if(this._context.get([key]) !== undefined) - { - this._context.add([key], increment); - } - else - { - this._context.set([key], this._cache[key]); - } - this.propertyDidChange(key); - return this._cache[key]; - }, - decrementProperty: function(key, decrement) { - if (Ember.isNone(decrement)) { decrement = 1; } - Ember.assert("Must pass a numeric value to decrementProperty", (!isNaN(parseFloat(decrement)) && isFinite(decrement))); - this.propertyWillChange(key); - this._cache[key] = (this._cache[key] || this.get(key) || 0) - decrement; - if(this._context.get([key]) !== undefined) - { - this._context.add([key], -1 * decrement); - } - else - { - this._context.set([key], this._cache[key]); - } - this.propertyDidChange(key); - return this._cache[key]; - }, - }); + __exports__["default"] = { + object : {}, + array : {} + } + }); +define("ember-share/models/use-subs-mixin", + ["./subs-handler","./utils","exports"], + function(__dependency1__, __dependency2__, __exports__) { + "use strict"; + var subs = __dependency1__["default"]; + var Utils = __dependency2__["default"];__exports__["default"] = Ember.Mixin.create({ + + useSubs: function useSubs(content, k, idx) { + var utils = Utils(this); + + if (utils.matchChildToLimitations(k)) + return content; + + if (_.isPlainObject(content)) { + content = { + tempContent: content + }; + var use = 'object' + + } else if (_.isArray(content)) { + content = { + content: content + }; + var use = 'array'; + } + if (use) { + var child, + _idx; + var path = (idx == null) ? k : (k + '.' + idx); + var ownPath = Ember.get(this, '_prefix'); + if ((_idx = Ember.get(this, '_idx')) != null) + ownPath += '.' + _idx; + if (path == ownPath) { + return this; + } + + var children = Ember.get(this, '_children'); + var childrenKeys = Object.keys(children); + + if (_.includes(childrenKeys, path)) + return children[path] + else + child = {}; + + var sub = subs[use].extend({ + // doc: this.get('doc'), + _children: Ember.get(this, '_children'), + _prefix: k, + _idx: idx, + _sdbProps: Ember.get(this, '_sdbProps'), + _root: Ember.get(this,'_root') + }); + + sub = sub.create(content); + + child[path] = sub; + _.assign(Ember.get(this, '_children'), child); + + return sub + } else + return content + } + }) + }); +define("ember-share/models/utils", + ["exports"], + function(__exports__) { + "use strict"; + __exports__["default"] = function(context) { + + return { + + isOpOnArray: function(op) { + return (op.ld != null) || (op.lm != null) || (op.li != null) + }, + + matchingPaths: function(as, bs) { + var counter = 0; + var higherLength = (as.length > bs.length) + ? as.length + : bs.length + while ((as[counter] == '*' || as[counter] == bs[counter]) && counter < higherLength) { + counter++ + } + return counter - (as.length / 1000) + }, + + matchChildToLimitations: function (key) { + var childLimiations = Ember.get(context, '_root._childLimiations'); + var prefix = Ember.get(context, '_prefix') + + if (prefix == null || key.match(prefix)) + prefix = key + else + prefix += '.' + key + + prefix = prefix.split('.'); + var self = this; + return _.some (childLimiations, function (_limit) { + var limit = _limit.split('/'); + return prefix.length == limit.length && Math.ceil(self.matchingPaths(limit, prefix)) == prefix.length + }) + }, + + prefixToChildLimiations: function (key) { + var childLimiations = Ember.get(context, '_root._childLimiations'); + var prefix = Ember.get(context, '_prefix') + + if (prefix == null || key.match(prefix)) + prefix = key + else + prefix += '.' + key + + prefix = prefix.split('.'); + var self = this, limiationsArray; + + var relevantLimitIndex = this.findMaxIndex(limiationsArray = _.map (childLimiations, function (_limit) { + var limit = _limit.split('/'); + var result = Math.ceil(self.matchingPaths(limit, prefix)) + return result < limit.length ? 0 : result + })); + if (relevantLimitIndex >= 0 && limiationsArray[relevantLimitIndex] > 0) { + var relevantLimit = childLimiations[relevantLimitIndex].split('/'); + var orignalPrefix; + var result = prefix.slice(0, Math.ceil(self.matchingPaths(relevantLimit, prefix)) ); + if (orignalPrefix = Ember.get(context, '_prefix')) { + orignalPrefix = orignalPrefix.split('.'); + return result.slice(orignalPrefix.length) + } else + return result.join('.'); + } + else { + return key; + } + + }, + + removeChildren: function (path, includeSelf) { + var children = Ember.get(context, '_children'); + var childrenKeys = Object.keys(children); + var prefix = context.get('_prefix'); + var utils = this; + + if ((prefix != null) && path && path.indexOf(prefix) != 0) { + path = prefix + '.' + path + } + + if (path) { + childrenKeys = _.reduce(childrenKeys, function(result, key) { + var matches = Math.ceil(utils.matchingPaths(key.split('.'), path.split('.'))) + if (includeSelf && (matches >= path.split('.').length) || + (!includeSelf && (matches > path.split('.').length))) + result.push(key); + return result + }, []); + } + + _.forEach (childrenKeys, function (key) { + children[key].destroy() + delete children[key] + }) + }, + + comparePathToPrefix: function(path, prefix) { + return Boolean(Math.ceil(this.matchingPaths(path.split('.'), prefix.split('.')))) + }, + + cutLast: function(path, op) { + var tempPath; + if (this.isOpOnArray(op) && !isNaN(+ _.last(path))) { + tempPath = _.clone(path); + tempPath.pop(); + } + return (tempPath) + ? tempPath + : path + }, + + comparePathToChildren: function(path, op) { + var utils = this; + var children = Ember.get(context, '_children'); + var childrenKeys = Object.keys(children); + var hasChildren = _.some(childrenKeys, function(childKey) { + var pathsCounter = utils.matchingPaths(childKey.split('.'), utils.cutLast(path, op)) + return Math.ceil(pathsCounter) == childKey.split('.').length + }); + return !Ember.isEmpty(childrenKeys) && hasChildren + }, + + triggerChildren: function(didWill, op, isFromClient) { + var newP = _.clone(op.p); + // var children = Ember.get(context, '_children'); + var children = context.get('_children'); + var childrenKeys = Object.keys(children); + if (Ember.isEmpty(childrenKeys)) + return; + var child, + utils = this; + var counterToChild = _.mapKeys(children, function(v, childKey) { + if (utils.isOpOnArray(op) && !isNaN(+ _.last(childKey.split('.')))) + return 0 + else + return utils.matchingPaths(utils.cutLast(childKey.split('.'), op), op.p) + }); + var toNumber = function(strings) { + return _.map(strings, function(s) { + return + s + }) + }; + var chosenChild = counterToChild[_.max(toNumber(Object.keys(counterToChild)))] + if (didWill == 'Will') + chosenChild.trigger('before op', [op], isFromClient); + if (didWill == 'Did') + chosenChild.trigger('op', [op], isFromClient); + } + , + + beforeAfter: function(didWill) { + var utils = this; + var ex; + return function(ops, isFromClient) { + // console.log( _.first (ops)); + + if (!isFromClient) { + _.forEach(ops, function(op) { + // if (didWill == 'Did') + // console.log(Ember.get(context,'_prefix') + ' recieved log'); + if (utils.comparePathToChildren(op.p, op)) { + utils.triggerChildren(didWill, op, isFromClient); + } else { + if (utils.isOpOnArray(op)) { + ex = utils.extractArrayPath(op); + + // console.log(Ember.get(context,'_prefix') + ' perform log'); + // console.log('op came to parent'); + context.get(ex.p)["arrayContent" + didWill + "Change"](ex.idx, ex.removeAmt, ex.addAmt) + } else { + context["property" + didWill + "Change"](utils.prefixToChildLimiations(op.p.join('.'))); + } + } + }); + } + }; + }, + + beforeAfterChild: function(didWill) { + var utils = this; + var ex, + prefix, + _idx; + return function(ops, isFromClient) { + if (((_idx = Ember.get(context, '_idx')) != null) || !isFromClient) { + _.forEach(ops, function(op) { + + if (op.p.join('.') == (prefix = Ember.get(context, '_prefix')) && didWill == 'Did') { + if (op.oi != null) { + context.replaceContent(op.oi, true) + } else { + if (op.od != null) { + var fatherPrefix = prefix.split('.'); + var key = fatherPrefix.pop(); + var father; + if (!_.isEmpty(fatherPrefix) && (father = context.get('_children.' + fatherPrefix.join('.')))) + father.removeKey(key); + else + context.get('_root').propertyDidChange(prefix) + } + } + } else { + var path = (_idx == null) + ? prefix.split('.') + : prefix.split('.').concat(String(_idx)); + var newP = _.difference(op.p, path); + if (utils.comparePathToPrefix(op.p.join('.'), prefix)) { + if (utils.isOpOnArray(op) && (Ember.get(context, '_idx') == null)) { + + var newOp = _.clone(op); + newOp.p = newP; + ex = utils.extractArrayPath(newOp); + + if (ex.p == "") + context["arrayContent" + didWill + "Change"](ex.idx, ex.removeAmt, ex.addAmt) + else + Ember.get(context, ex.p)["arrayContent" + didWill + "Change"](ex.idx, ex.removeAmt, ex.addAmt); + } + else { + if (newP.join('.') == '') { + + // delete self from father + if (false && _.isEmpty(newOp) && op.od && (op.oi == null) && (_.isEqual(op.od, context.toJson()))) { + var keyToRemove = path.pop(); + if (_.isEmpty(path)) { + utils.removeChildren(keyToRemove); + } + else { + var father = context.get('_children')[path.join('.')]; + father.removeKey (keyToRemove); + } + } + else { + context["property" + didWill + "Change"]('content'); + } + } + + else { + + if (op.oi && op.od == null) + context.addKey(_.first(newP)) + + if (op.od && op.oi == null) + context.removeKey(_.first(newP)) + + context["property" + didWill + "Change"](utils.prefixToChildLimiations(newP.join('.'))); + } + } + } + } + }); + } + } + }, + + findMaxIndex: function (arr) { + return arr.indexOf(_.max(arr)) + }, + + extractArrayPath: function(op) { + return { + idx: + _.last(op.p), + p: _.slice(op.p, 0, op.p.length - 1).join('.'), + addAmt: op.li != null + ? 1 + : 0, + removeAmt: op.ld != null + ? 1 + : 0 + } + } + + } + } }); define("ember-share/store", ["./utils","exports"], function(__dependency1__, __exports__) { "use strict"; - /* global BCSocket:false, sharejs:false */ + /* global BCSocket:false, sharedb:false */ var guid = __dependency1__.guid; var patchShare = __dependency1__.patchShare; var Promise = Ember.RSVP.Promise; + var socketReadyState = [ + 'CONNECTING', + 'OPEN', + 'CLOSING', + 'CLOSE' + ] - __exports__["default"] = Ember.Object.extend({ + __exports__["default"] = Ember.Object.extend(Ember.Evented, { socket: null, connection: null, - url : 'http://'+window.location.hostname, + + // port: 3000, + // url : 'https://qa-e.optibus.co', + url : window.location.hostname, init: function () { - this.checkConnection = Ember.Deferred.create({}); + var store = this; + + this.checkSocket = function () { + return new Promise(function (resolve, reject) { + + if (store.socket == null) { + store.one('connectionOpen', resolve); + } + else { + var checkState = function (state, cb) { + switch(state) { + case 'connected': + return resolve(); + case 'connecting': + return store.connection.once('connected', resolve); + default: cb(state) + } + } + var checkStateFail = function (state) { + switch(state) { + case 'closed': + return reject('connection closed'); + case 'disconnected': + return reject('connection disconnected'); + case 'stopped': + return reject('connection closing'); + } + } + var failed = false + checkState(store.connection.state, function(state){ + if (failed) + checkStateFail(state) + else + Ember.run.next (this, function () { + failed = true; + checkState(store.connection.state, checkStateFail) + }) + }) + + + } + }); + } + + this.checkConnection = function () { + return new Promise(function (resolve, reject) { + return store.checkSocket() + .then(function () { + return resolve() + if (store.authentication != null && store.isAuthenticated != null) { + if (store.isAuthenticated) return resolve(); + if (store.isAuthenticating) return store.one('authenticated', resolve); + if (!store.isAuthenticated) return store.authentication(store.connection.id) + // if (!store.isAuthenticating) return reject() + return reject('could not authenticat') + } else + return resolve() + }) + .catch(function (err) { + return reject(err) + }) + }); + }; + this.cache = {}; - if(!window.sharejs) + if(!window.sharedb) { - throw new Error("ShareJS client not included"); + throw new Error("sharedb client not included"); } if (window.BCSocket === undefined && window.Primus === undefined) { throw new Error("No Socket library included"); @@ -365,55 +1253,100 @@ define("ember-share/store", { this.beforeConnect() .then(function(){ - Ember.sendEvent(store,'connect'); + store.trigger('connect'); }); } else { - Ember.sendEvent(this,'connect'); + store.trigger('connect'); } }, - doConnect : function(){ + doConnect : function(options){ var store = this; - + if(window.BCSocket) { + this.setProperties(options); this.socket = new BCSocket(this.get('url'), {reconnect: true}); this.socket.onerror = function(err){ - Ember.sendEvent(store,'connectionError',[err]); + store.trigger('connectionError', [err]); + }; this.socket.onopen = function(){ - store.checkConnection.resolve(); - Ember.sendEvent(store,'connectionOpen'); + store.trigger('connectionOpen'); + }; this.socket.onclose = function(){ - Ember.sendEvent(store,'connectionEnd'); + store.trigger('connectionEnd'); }; } else if(window.Primus) { patchShare(); - this.socket = new Primus(this.get('url')); + this.setProperties(options); + var hostname = this.get('url'); + if (this.get('protocol')) + hostname = this.get('protocol') + '://' + hostname; + if (this.get("port")) + hostname += ':' + this.get('port'); + this.socket = new Primus(hostname); + // console.log('connection starting'); + this.socket.on('error', function error(err) { - Ember.sendEvent(store,'connectionError',[err]); + store.trigger('connectionError', [err]); }); this.socket.on('open', function() { - store.checkConnection.resolve(); - Ember.sendEvent(store,'connectionOpen'); + // console.log('connection open'); + store.trigger('connectionOpen'); }); this.socket.on('end', function() { - Ember.sendEvent(store,'connectionEnd'); + store.trigger('connectionEnd'); + }); + this.socket.on('close', function() { + store.trigger('connectionEnd'); }); } else { throw new Error("No Socket library included"); } - this.connection = new sharejs.Connection(this.socket); - + var oldHandleMessage = sharedb.Connection.prototype.handleMessage; + var oldSend = sharedb.Connection.prototype.send; + + store.on('connectionEnd', function () { + // console.log('ending connection'); + store.isAuthenticated = false + }) + + sharedb.Connection.prototype.handleMessage = function(message) { + var athenticating, handleMessageArgs; + handleMessageArgs = arguments; + // console.log(message.a); + var context = this; + oldHandleMessage.apply(context, handleMessageArgs); + if (message.a === 'init' && (typeof message.id === 'string') && message.protocol === 1 && typeof store.authenticate === 'function') { + store.isAuthenticating = true; + return store.authenticate(message.id) + .then(function() { + console.log('authenticated !'); + store.isAuthenticating = false; + store.isAuthenticated = true; + store.trigger('authenticated') + }) + .catch(function (err) { + store.isAuthenticating = false; + // store.socket.end() + // debugger + }) + } + }; + + this.connection = new sharedb.Connection(this.socket); + }.on('connect'), find: function (type, id) { + type = type.pluralize() var store = this; - return this.checkConnection + return this.checkConnection() .then(function(){ return store.findQuery(type, {_id: id}).then(function (models) { return models[0]; @@ -423,63 +1356,143 @@ define("ember-share/store", }); }, createRecord: function (type, data) { + var ref, path; + path = (ref = this._getPathForType(type)) ? ref : type.pluralize() + path = this._getPrefix(type) + path; + type = type.pluralize() var store = this; - return store.checkConnection + return store.checkConnection() .then(function(){ - var doc = store.connection.get(type, guid()); + var doc = store.connection.get(path, data.id == null ? guid() : data.id); return Promise.all([ store.whenReady(doc).then(function (doc) { return store.create(doc, data); }), store.subscribe(doc) ]).then(function () { - return store._createModel(type, doc); + var model = store._createModel(type, doc); + store._cacheFor(type).addObject(model); + return model }); }); }, - deleteRecord : function(model) { - // TODO: delete and cleanup caches - // model._context.context._doc.del() + deleteRecord : function(type, id) { + var cache = this._cacheFor(type.pluralize()); + var model = cache.findBy('id', id); + var doc = model.get('doc'); + return new Promise(function (resolve, reject) { + doc.del(function (err) { + if (err != null) + reject(err) + else { + resolve() + } + }); + }) + }, + findAndSubscribeQuery: function(type, query) { + type = type.pluralize() + var store = this; + var prefix = this._getPrefix(type); + store.cache[type] = [] + + return this.checkConnection() + .then(function(){ + return new Promise(function (resolve, reject) { + function fetchQueryCallback(err, results, extra) { + if (err !== null) { + return reject(err); + } + resolve(store._resolveModels(type, results)); + } + query = store.connection.createSubscribeQuery(prefix + type, query, null, fetchQueryCallback); + query.on('insert', function (docs) { + store._resolveModels(type, docs) + }); + query.on('remove', function (docs) { + for (var i = 0; i < docs.length; i++) { + var modelPromise = store._resolveModel(type, docs[i]); + modelPromise.then(function (model) { + store.unload(type, model) + }); + } + }); + }); + }); + }, + findRecord: function (type, id) { + var store = this; + return new Promise(function (resolve, reject){ + store.findQuery(type, {_id: id}) + .then(function(results){ + resolve(results[0]) + }) + .catch(function (err){ + reject(err) + }); + }) }, findQuery: function (type, query) { + // type = type.pluralize() + var ref, path; + path = (ref = this._getPathForType(type)) ? ref : type.pluralize() + path = this._getPrefix(type) + path; var store = this; - return this.checkConnection + store.cache[type.pluralize()] = [] + return this.checkConnection() .then(function(){ return new Promise(function (resolve, reject) { function fetchQueryCallback(err, results, extra) { - if (err !== undefined) { + if (err !== null) { return reject(err); } resolve(store._resolveModels(type, results)); } - store.connection.createFetchQuery(type, query, null, fetchQueryCallback); + store.connection.createFetchQuery(path, query, null, fetchQueryCallback); }); }); }, - findAll: function (type) { + findAll: function (type, query) { + type = type.pluralize() throw new Error('findAll not implemented'); // TODO this.connection subscribe style query }, _cacheFor: function (type) { + type = type.pluralize() var cache = this.cache[type]; if (cache === undefined) { - this.cache[type] = cache = {}; + this.cache[type] = cache = []; } return cache; }, + _getPathForType: function (type) { + var Adapter = this.container.lookupFactory('adapter:' + type.singularize()); + if (Adapter) + return Adapter.create().pathForType(); + }, + _getPrefix: function (type) { + var Adapter = this.container.lookupFactory('adapter:' + type.singularize()); + var prefix; + if (Adapter) + prefix = Adapter.create().get('prefix'); + if (!prefix) prefix = ''; + return prefix + }, _factoryFor: function (type) { - return this.container.lookupFactory('model:'+type); + var ref; + var modelStr = (ref = this.get('modelStr')) ? ref : 'model-sdb' + return this.container.lookupFactory(modelStr + ':'+ type.singularize()); }, _createModel: function (type, doc) { - var cache = this._cacheFor(type); var modelClass = this._factoryFor(type); + type = type.pluralize() if(modelClass) { var model = modelClass.create({ - id: doc.name, - _context: doc.createContext().createContextAt() + doc: doc, + _type: type, + _store: this }); - cache[doc.name] = model; return model; } else @@ -488,8 +1501,9 @@ define("ember-share/store", } }, _resolveModel: function (type, doc) { - var cache = this._cacheFor(type); - var model = cache[doc.name]; + var cache = this._cacheFor(type.pluralize()); + var id = Ember.get(doc, 'id') || Ember.get(doc, '_id'); + var model = cache.findBy('id', id); if (model !== undefined) { return Promise.resolve(model); } @@ -499,24 +1513,68 @@ define("ember-share/store", }); }, _resolveModels: function (type, docs) { + // type = type.pluralize() + var store = this; + var cache = this._cacheFor(type.pluralize()); var promises = new Array(docs.length); for (var i=0; i + // options = {}; type = null + // _.forEach arguments, (arg) -> + // if _.isPlainObject(arg) + // options = arg + // else + // if _.isString arg + // type = null + // + // Ember.computed + // get: (k) -> + // @get "doc.data.#{k}" ? Ember.get(options, 'defaultValue') + // set: (p, oi, isFromServer) -> + // if type? + // oi = window[type.toUpperCase type] oi + // od = @get p + // p = p.split '.' + // @get('doc').submitOp [{p,od,oi}] + // oi }); define("ember-share/mixins/share-text", ["../utils","exports"], @@ -202,216 +247,1005 @@ define("ember-share/mixins/share-text", } }); }); -define("ember-share/models/share-array", - ["./share-proxy","exports"], - function(__dependency1__, __exports__) { +define("ember-share/models/base", + ["./use-subs-mixin","./sub-mixin","./sub-array","./subs-handler","./utils","exports"], + function(__dependency1__, __dependency2__, __dependency3__, __dependency4__, __dependency5__, __exports__) { "use strict"; - var ShareProxy = __dependency1__["default"]; + var UseSubsMixin = __dependency1__["default"]; + var SubMixin = __dependency2__["default"]; + var SDBSubArray = __dependency3__["default"]; + var subs = __dependency4__["default"]; + var Utils = __dependency5__["default"]; - __exports__["default"] = Ember.Object.extend(Ember.MutableArray, { - _context: null, - _cache: null, - itemType: 'share-proxy', - init: function () { - this._cache = []; // cache wrapped objects - this._factory = this.container.lookupFactory('model:'+this.itemType); - // TODO subscribe to array ops on context - var _this = this; - this._context.on('delete', function (index, removed) { - _this.arrayContentWillChange(index, 1, 0); - - _this._cache.splice(index, 1); - - // update paths - var depth = _this._context.path.length; - _this._cache.forEach(function(item,idx){ - item._context.path[depth]= idx; - }) - _this.arrayContentDidChange(index, 1, 0); - }); - this._context.on('insert', function (index, value) { - _this.arrayContentWillChange(index, 0, 1); + var toJson = function(obj) { + return (obj == null) + ? void 0 + : JSON.parse(JSON.stringify(obj)); + }; - var model = _this._factory.create({ - _context: _this._context.createContextAt(index) - }); + var getPlainObject = function (value) { + if (value != null && !((typeof value == 'string') || (typeof value == 'number'))) + if (typeof value.toJson == 'function') + return value.toJson() + else + return toJson(value) + else { + return value + } + } - _this._cache.splice(index, 0, model); - // update paths - var depth = _this._context.path.length; - _this._cache.forEach(function(item,idx){ - item._context.path[depth]= idx; - }); - _this.arrayContentDidChange(index, 0, 1); - }); - }, - length: function () { - return this._context.get().length; - }.property().volatile(), - objectAt: function (index) { - if (this._cache[index] === undefined && this._context.get(index) !== undefined) { - this._cache[index] = this._factory.create({ - _context: this._context.createContextAt(index) - }); - } - return this._cache[index]; - }, - replace: function (index, length, objects) { - var objectsLength = objects.length; - var args = new Array(objectsLength+2); - var model; - args[0] = index; - args[1] = length; + // + // ShareDb Base Class + // + // Root and all subs (currently not arrays) inherit from base. + // + // - this.arrayContentWillChange(index, length, objectsLength); + var GetterSettersMixin = Ember.Mixin.create({ - if (length > 0) { - this._context.remove([index], length); - } + _get: function(k, selfCall) { + var firstValue = _.first(k.split('.')); - for (var i=0; i objects.length) + ? len + : objects.length; + for (var i = 0; i < iterationLength; i++) { + var newIndex = i + start; + var obj = objects.objectAt(i); + this._submitOp(newIndex, obj, (len > i + ? this.objectAt(newIndex) + : null)) + } + this.arrayContentDidChange(start, len, objects.length); + return this //._super(start, len, objects) + }, + + onChangeDoc: (function () { + // debugger + // this.set ('content', this.get('doc.data.' + this.get('_prefix'))) + // Ember.run.next (this, function () P{}) + this.replaceContent(this.get('doc.data.' + this.get('_prefix')), true) + }).observes('doc') + }); + } + }); +define("ember-share/models/sub-mixin", + ["./utils","../attr","exports"], + function(__dependency1__, __dependency2__, __exports__) { + "use strict"; + var Utils = __dependency1__["default"]; + var attrs = __dependency2__["default"]; + + var allButLast = function(arr) { + return arr.slice(0, arr.length - 1) + }; + + // + // Sub Mixin + // + // All subs use this mixin (Object and Array) + // + // + + __exports__["default"] = Ember.Mixin.create({ + + _children: (function() { + return {} + }).property(), + + _sdbProps: (function() { + return [] + }).property(), + + _subProps: (function() { + return [] + }).property(), + + doc: Ember.computed.reads('_root.doc'), + + createInnerAttrs: (function() { + var tempContent = Ember.get(this, 'tempContent'); + var self = this; + var attr = attrs('_subProps'); + var keys = []; + + _.forEach(tempContent, function(value, key) { + keys.push(key); + Ember.defineProperty(self, key, attr()); + }) + + Ember.get(this, '_subProps').addObjects(keys); + delete this['tempContent']; + }).on('init'), + + beforeFn: (function (){return []}).property(), + afterFn: (function (){return []}).property(), + + activateListeners: (function() { + var utils = Utils(this); + + var beforeFn = utils.beforeAfterChild("Will"); + var afterFn = utils.beforeAfterChild("Did"); + + if (this.has('before op')) { + this.off('before op', this.get('beforeFn').pop()) + } + if (this.has('op')) { + this.off('op', this.get('afterFn').pop()) + } + this.on('before op', beforeFn); + this.on('op', afterFn); + + this.get('beforeFn').push(beforeFn); + this.get('afterFn').push(afterFn); + + // }).on('init'), + }).observes('doc').on('init'), + + _fullPath: function(path) { + var prefix = Ember.get(this, '_prefix'); + var idx = Ember.get(this, '_idx'); + + if (prefix) { + if (idx != null) { + return prefix + '.' + idx + '.' + path + } else { + return prefix + '.' + path; + } + } else + return path; + } + , + + deleteProperty: function(k) { + this.removeKey(k); + return this._super(this._fullPath(k)) + }, + + replaceContent: function(content, noSet) { + this.notifyWillProperties(this.get('_subProps').toArray()); + var prefix = this.get('_prefix'); + var idx = this.get('_idx') + var path = (idx == null) ? prefix : prefix + '.' + idx + + if (!noSet) + this._set(path, content); + + var self = this; + var utils = Utils(this); + + utils.removeChildren(path); + + if (_.isEmpty(Object.keys(this))) { + Ember.setProperties(this, {tempContent: content}); + this.createInnerAttrs(); + + var notifyFather = function (prefixArr, keys) { + if (_.isEmpty(prefixArr)) + self.get('_root').notifyPropertyChange(keys.join('.')) + else { + var child = self.get['_children'][prefixArr.join('.')] + if (child != null) + child.notifyPropertyChange(prefixArr.join('.') + '.' + keys.join('.')) + else + keys.push(prefixArr.pop()); + notifyFather(prefixArr, keys); + } + }; + var prefixArr = prefix.split('.') + var key = prefixArr.pop() + + notifyFather(prefixArr, [key]); + } + else { + if (_.isPlainObject(content)) + var toDelete = _.difference(Object.keys(this), Object.keys(content)) + else + var toDelete = Object.keys(this); + + _.forEach(toDelete, function(prop) { + delete self[prop] + }); + this.get('_subProps').removeObjects(toDelete); + Ember.setProperties(this, {tempContent: content}); + this.createInnerAttrs(); + this.notifyDidProperties(this.get('_subProps').toArray()); + } + + return this + }, + + toJson: function() { + var idx = Ember.get(this, '_idx'), + k = Ember.get(this, '_prefix'); + var path = (idx == null) + ? k + : (k + '.' + idx); + return this.get('doc.data.' + path); + }, + + addKey: function (key) { + var attr = attrs('_subProps'); + if (!(this.get('_subProps').indexOf(key) > -1)) + Ember.defineProperty(this, key, attr()); + return this + }, + + removeKey: function (key) { + var attr = attrs('_subProps'); + var utils = Utils(this); + utils.removeChildren(key, true); + this.get('_subProps').removeObject(key); + delete this[key]; + return this + }, + + removeListeners: function () { + this.off('before op', this.get('beforeFn')) + this.off('op', this.get('afterFn')) + + } + + }) + }); +define("ember-share/models/subs-handler", ["exports"], function(__exports__) { "use strict"; - var isArray = Array.isArray || function (obj) { - return obj instanceof Array; - }; + // + // Subs Handler + // + // since we have a recursive model structure there is a need for + // creating the subs in a common place and then reuse it in its own class. + // + // - __exports__["default"] = Ember.Object.extend({ - _context: null, - _cache: null, - init: function () { - this._cache = {}; // allows old value to be seen on willChange event - var _this = this; - this._context.on('replace', function (key, oldValue, newValue) { - _this.propertyWillChange(key); - _this._cache[key] = _this.wrapObject(key, newValue); - _this.propertyDidChange(key); - }); - this._context.on('insert', function (key, value) { - _this.propertyWillChange(key); - _this._cache[key] = _this.wrapObject(key, value); - _this.propertyDidChange(key); - }); - this._context.on('child op', function (key, op) { - // handle add operations - if(key.length === 1 && op.na) - { - _this.propertyWillChange(key[0]); - _this._cache[key] = (_this._cache[key[0]] || _this.get(key[0]) || 0) + op.na; - _this.propertyDidChange(key[0]); - } - }); - }, - unknownProperty: function (key) { - var value = this._cache[key]; - if (value === undefined) { - value = this._cache[key] = this.wrapObject(key, this._context.get([key])); - } - return value; - }, - setUnknownProperty: function (key, value) { - if (this._cache[key] !== value) { - this.propertyWillChange(key); - this._cache[key] = this.wrapObject(key, value); - this._context.set([key], value); - this.propertyDidChange(key); - } - }, - wrapObject: function (key, value) { - if (value !== null && typeof value === 'object') { - var type = this.wrapLookup(key,value); - var factory = this.container.lookupFactory('model:'+type); - return factory.create({ - _context: this._context.createContextAt(key) - }); - } - return value; - }, - wrapLookup : function(key,value) { - return value.type || (isArray(value) ? 'share-array' : 'share-proxy'); - }, - willDestroy: function () { - this._cache = null; - this._context.destroy(); - this._context = null; - }, - toJSON: function () { - return this._context.get(); - }, - incrementProperty: function(key, increment) { - if (Ember.isNone(increment)) { increment = 1; } - Ember.assert("Must pass a numeric value to incrementProperty", (!isNaN(parseFloat(increment)) && isFinite(increment))); - this.propertyWillChange(key); - this._cache[key] = (this._cache[key] || this.get(key) || 0) + increment; - if(this._context.get([key]) !== undefined) - { - this._context.add([key], increment); - } - else - { - this._context.set([key], this._cache[key]); - } - this.propertyDidChange(key); - return this._cache[key]; - }, - decrementProperty: function(key, decrement) { - if (Ember.isNone(decrement)) { decrement = 1; } - Ember.assert("Must pass a numeric value to decrementProperty", (!isNaN(parseFloat(decrement)) && isFinite(decrement))); - this.propertyWillChange(key); - this._cache[key] = (this._cache[key] || this.get(key) || 0) - decrement; - if(this._context.get([key]) !== undefined) - { - this._context.add([key], -1 * decrement); - } - else - { - this._context.set([key], this._cache[key]); - } - this.propertyDidChange(key); - return this._cache[key]; - }, - }); + __exports__["default"] = { + object : {}, + array : {} + } + }); +define("ember-share/models/use-subs-mixin", + ["./subs-handler","./utils","exports"], + function(__dependency1__, __dependency2__, __exports__) { + "use strict"; + var subs = __dependency1__["default"]; + var Utils = __dependency2__["default"];__exports__["default"] = Ember.Mixin.create({ + + useSubs: function useSubs(content, k, idx) { + var utils = Utils(this); + + if (utils.matchChildToLimitations(k)) + return content; + + if (_.isPlainObject(content)) { + content = { + tempContent: content + }; + var use = 'object' + + } else if (_.isArray(content)) { + content = { + content: content + }; + var use = 'array'; + } + if (use) { + var child, + _idx; + var path = (idx == null) ? k : (k + '.' + idx); + var ownPath = Ember.get(this, '_prefix'); + if ((_idx = Ember.get(this, '_idx')) != null) + ownPath += '.' + _idx; + if (path == ownPath) { + return this; + } + + var children = Ember.get(this, '_children'); + var childrenKeys = Object.keys(children); + + if (_.includes(childrenKeys, path)) + return children[path] + else + child = {}; + + var sub = subs[use].extend({ + // doc: this.get('doc'), + _children: Ember.get(this, '_children'), + _prefix: k, + _idx: idx, + _sdbProps: Ember.get(this, '_sdbProps'), + _root: Ember.get(this,'_root') + }); + + sub = sub.create(content); + + child[path] = sub; + _.assign(Ember.get(this, '_children'), child); + + return sub + } else + return content + } + }) + }); +define("ember-share/models/utils", + ["exports"], + function(__exports__) { + "use strict"; + __exports__["default"] = function(context) { + + return { + + isOpOnArray: function(op) { + return (op.ld != null) || (op.lm != null) || (op.li != null) + }, + + matchingPaths: function(as, bs) { + var counter = 0; + var higherLength = (as.length > bs.length) + ? as.length + : bs.length + while ((as[counter] == '*' || as[counter] == bs[counter]) && counter < higherLength) { + counter++ + } + return counter - (as.length / 1000) + }, + + matchChildToLimitations: function (key) { + var childLimiations = Ember.get(context, '_root._childLimiations'); + var prefix = Ember.get(context, '_prefix') + + if (prefix == null || key.match(prefix)) + prefix = key + else + prefix += '.' + key + + prefix = prefix.split('.'); + var self = this; + return _.some (childLimiations, function (_limit) { + var limit = _limit.split('/'); + return prefix.length == limit.length && Math.ceil(self.matchingPaths(limit, prefix)) == prefix.length + }) + }, + + prefixToChildLimiations: function (key) { + var childLimiations = Ember.get(context, '_root._childLimiations'); + var prefix = Ember.get(context, '_prefix') + + if (prefix == null || key.match(prefix)) + prefix = key + else + prefix += '.' + key + + prefix = prefix.split('.'); + var self = this, limiationsArray; + + var relevantLimitIndex = this.findMaxIndex(limiationsArray = _.map (childLimiations, function (_limit) { + var limit = _limit.split('/'); + var result = Math.ceil(self.matchingPaths(limit, prefix)) + return result < limit.length ? 0 : result + })); + if (relevantLimitIndex >= 0 && limiationsArray[relevantLimitIndex] > 0) { + var relevantLimit = childLimiations[relevantLimitIndex].split('/'); + var orignalPrefix; + var result = prefix.slice(0, Math.ceil(self.matchingPaths(relevantLimit, prefix)) ); + if (orignalPrefix = Ember.get(context, '_prefix')) { + orignalPrefix = orignalPrefix.split('.'); + return result.slice(orignalPrefix.length) + } else + return result.join('.'); + } + else { + return key; + } + + }, + + removeChildren: function (path, includeSelf) { + var children = Ember.get(context, '_children'); + var childrenKeys = Object.keys(children); + var prefix = context.get('_prefix'); + var utils = this; + + if ((prefix != null) && path && path.indexOf(prefix) != 0) { + path = prefix + '.' + path + } + + if (path) { + childrenKeys = _.reduce(childrenKeys, function(result, key) { + var matches = Math.ceil(utils.matchingPaths(key.split('.'), path.split('.'))) + if (includeSelf && (matches >= path.split('.').length) || + (!includeSelf && (matches > path.split('.').length))) + result.push(key); + return result + }, []); + } + + _.forEach (childrenKeys, function (key) { + children[key].destroy() + delete children[key] + }) + }, + + comparePathToPrefix: function(path, prefix) { + return Boolean(Math.ceil(this.matchingPaths(path.split('.'), prefix.split('.')))) + }, + + cutLast: function(path, op) { + var tempPath; + if (this.isOpOnArray(op) && !isNaN(+ _.last(path))) { + tempPath = _.clone(path); + tempPath.pop(); + } + return (tempPath) + ? tempPath + : path + }, + + comparePathToChildren: function(path, op) { + var utils = this; + var children = Ember.get(context, '_children'); + var childrenKeys = Object.keys(children); + var hasChildren = _.some(childrenKeys, function(childKey) { + var pathsCounter = utils.matchingPaths(childKey.split('.'), utils.cutLast(path, op)) + return Math.ceil(pathsCounter) == childKey.split('.').length + }); + return !Ember.isEmpty(childrenKeys) && hasChildren + }, + + triggerChildren: function(didWill, op, isFromClient) { + var newP = _.clone(op.p); + // var children = Ember.get(context, '_children'); + var children = context.get('_children'); + var childrenKeys = Object.keys(children); + if (Ember.isEmpty(childrenKeys)) + return; + var child, + utils = this; + var counterToChild = _.mapKeys(children, function(v, childKey) { + if (utils.isOpOnArray(op) && !isNaN(+ _.last(childKey.split('.')))) + return 0 + else + return utils.matchingPaths(utils.cutLast(childKey.split('.'), op), op.p) + }); + var toNumber = function(strings) { + return _.map(strings, function(s) { + return + s + }) + }; + var chosenChild = counterToChild[_.max(toNumber(Object.keys(counterToChild)))] + if (didWill == 'Will') + chosenChild.trigger('before op', [op], isFromClient); + if (didWill == 'Did') + chosenChild.trigger('op', [op], isFromClient); + } + , + + beforeAfter: function(didWill) { + var utils = this; + var ex; + return function(ops, isFromClient) { + // console.log( _.first (ops)); + + if (!isFromClient) { + _.forEach(ops, function(op) { + // if (didWill == 'Did') + // console.log(Ember.get(context,'_prefix') + ' recieved log'); + if (utils.comparePathToChildren(op.p, op)) { + utils.triggerChildren(didWill, op, isFromClient); + } else { + if (utils.isOpOnArray(op)) { + ex = utils.extractArrayPath(op); + + // console.log(Ember.get(context,'_prefix') + ' perform log'); + // console.log('op came to parent'); + context.get(ex.p)["arrayContent" + didWill + "Change"](ex.idx, ex.removeAmt, ex.addAmt) + } else { + context["property" + didWill + "Change"](utils.prefixToChildLimiations(op.p.join('.'))); + } + } + }); + } + }; + }, + + beforeAfterChild: function(didWill) { + var utils = this; + var ex, + prefix, + _idx; + return function(ops, isFromClient) { + if (((_idx = Ember.get(context, '_idx')) != null) || !isFromClient) { + _.forEach(ops, function(op) { + + if (op.p.join('.') == (prefix = Ember.get(context, '_prefix')) && didWill == 'Did') { + if (op.oi != null) { + context.replaceContent(op.oi, true) + } else { + if (op.od != null) { + var fatherPrefix = prefix.split('.'); + var key = fatherPrefix.pop(); + var father; + if (!_.isEmpty(fatherPrefix) && (father = context.get('_children.' + fatherPrefix.join('.')))) + father.removeKey(key); + else + context.get('_root').propertyDidChange(prefix) + } + } + } else { + var path = (_idx == null) + ? prefix.split('.') + : prefix.split('.').concat(String(_idx)); + var newP = _.difference(op.p, path); + if (utils.comparePathToPrefix(op.p.join('.'), prefix)) { + if (utils.isOpOnArray(op) && (Ember.get(context, '_idx') == null)) { + + var newOp = _.clone(op); + newOp.p = newP; + ex = utils.extractArrayPath(newOp); + + if (ex.p == "") + context["arrayContent" + didWill + "Change"](ex.idx, ex.removeAmt, ex.addAmt) + else + Ember.get(context, ex.p)["arrayContent" + didWill + "Change"](ex.idx, ex.removeAmt, ex.addAmt); + } + else { + if (newP.join('.') == '') { + + // delete self from father + if (false && _.isEmpty(newOp) && op.od && (op.oi == null) && (_.isEqual(op.od, context.toJson()))) { + var keyToRemove = path.pop(); + if (_.isEmpty(path)) { + utils.removeChildren(keyToRemove); + } + else { + var father = context.get('_children')[path.join('.')]; + father.removeKey (keyToRemove); + } + } + else { + context["property" + didWill + "Change"]('content'); + } + } + + else { + + if (op.oi && op.od == null) + context.addKey(_.first(newP)) + + if (op.od && op.oi == null) + context.removeKey(_.first(newP)) + + context["property" + didWill + "Change"](utils.prefixToChildLimiations(newP.join('.'))); + } + } + } + } + }); + } + } + }, + + findMaxIndex: function (arr) { + return arr.indexOf(_.max(arr)) + }, + + extractArrayPath: function(op) { + return { + idx: + _.last(op.p), + p: _.slice(op.p, 0, op.p.length - 1).join('.'), + addAmt: op.li != null + ? 1 + : 0, + removeAmt: op.ld != null + ? 1 + : 0 + } + } + + } + } }); define("ember-share/store", ["./utils","exports"], function(__dependency1__, __exports__) { "use strict"; - /* global BCSocket:false, sharejs:false */ + /* global BCSocket:false, sharedb:false */ var guid = __dependency1__.guid; var patchShare = __dependency1__.patchShare; var Promise = Ember.RSVP.Promise; + var socketReadyState = [ + 'CONNECTING', + 'OPEN', + 'CLOSING', + 'CLOSE' + ] - __exports__["default"] = Ember.Object.extend({ + __exports__["default"] = Ember.Object.extend(Ember.Evented, { socket: null, connection: null, - url : 'http://'+window.location.hostname, + + // port: 3000, + // url : 'https://qa-e.optibus.co', + url : window.location.hostname, init: function () { - this.checkConnection = Ember.Deferred.create({}); + var store = this; + + this.checkSocket = function () { + return new Promise(function (resolve, reject) { + + if (store.socket == null) { + store.one('connectionOpen', resolve); + } + else { + var checkState = function (state, cb) { + switch(state) { + case 'connected': + return resolve(); + case 'connecting': + return store.connection.once('connected', resolve); + default: cb(state) + } + } + var checkStateFail = function (state) { + switch(state) { + case 'closed': + return reject('connection closed'); + case 'disconnected': + return reject('connection disconnected'); + case 'stopped': + return reject('connection closing'); + } + } + var failed = false + checkState(store.connection.state, function(state){ + if (failed) + checkStateFail(state) + else + Ember.run.next (this, function () { + failed = true; + checkState(store.connection.state, checkStateFail) + }) + }) + + + } + }); + } + + this.checkConnection = function () { + return new Promise(function (resolve, reject) { + return store.checkSocket() + .then(function () { + return resolve() + if (store.authentication != null && store.isAuthenticated != null) { + if (store.isAuthenticated) return resolve(); + if (store.isAuthenticating) return store.one('authenticated', resolve); + if (!store.isAuthenticated) return store.authentication(store.connection.id) + // if (!store.isAuthenticating) return reject() + return reject('could not authenticat') + } else + return resolve() + }) + .catch(function (err) { + return reject(err) + }) + }); + }; + this.cache = {}; - if(!window.sharejs) + if(!window.sharedb) { - throw new Error("ShareJS client not included"); + throw new Error("sharedb client not included"); } if (window.BCSocket === undefined && window.Primus === undefined) { throw new Error("No Socket library included"); @@ -420,55 +1254,100 @@ define("ember-share/store", { this.beforeConnect() .then(function(){ - Ember.sendEvent(store,'connect'); + store.trigger('connect'); }); } else { - Ember.sendEvent(this,'connect'); + store.trigger('connect'); } }, - doConnect : function(){ + doConnect : function(options){ var store = this; - + if(window.BCSocket) { + this.setProperties(options); this.socket = new BCSocket(this.get('url'), {reconnect: true}); this.socket.onerror = function(err){ - Ember.sendEvent(store,'connectionError',[err]); + store.trigger('connectionError', [err]); + }; this.socket.onopen = function(){ - store.checkConnection.resolve(); - Ember.sendEvent(store,'connectionOpen'); + store.trigger('connectionOpen'); + }; this.socket.onclose = function(){ - Ember.sendEvent(store,'connectionEnd'); + store.trigger('connectionEnd'); }; } else if(window.Primus) { patchShare(); - this.socket = new Primus(this.get('url')); + this.setProperties(options); + var hostname = this.get('url'); + if (this.get('protocol')) + hostname = this.get('protocol') + '://' + hostname; + if (this.get("port")) + hostname += ':' + this.get('port'); + this.socket = new Primus(hostname); + // console.log('connection starting'); + this.socket.on('error', function error(err) { - Ember.sendEvent(store,'connectionError',[err]); + store.trigger('connectionError', [err]); }); this.socket.on('open', function() { - store.checkConnection.resolve(); - Ember.sendEvent(store,'connectionOpen'); + // console.log('connection open'); + store.trigger('connectionOpen'); }); this.socket.on('end', function() { - Ember.sendEvent(store,'connectionEnd'); + store.trigger('connectionEnd'); + }); + this.socket.on('close', function() { + store.trigger('connectionEnd'); }); } else { throw new Error("No Socket library included"); } - this.connection = new sharejs.Connection(this.socket); - + var oldHandleMessage = sharedb.Connection.prototype.handleMessage; + var oldSend = sharedb.Connection.prototype.send; + + store.on('connectionEnd', function () { + // console.log('ending connection'); + store.isAuthenticated = false + }) + + sharedb.Connection.prototype.handleMessage = function(message) { + var athenticating, handleMessageArgs; + handleMessageArgs = arguments; + // console.log(message.a); + var context = this; + oldHandleMessage.apply(context, handleMessageArgs); + if (message.a === 'init' && (typeof message.id === 'string') && message.protocol === 1 && typeof store.authenticate === 'function') { + store.isAuthenticating = true; + return store.authenticate(message.id) + .then(function() { + console.log('authenticated !'); + store.isAuthenticating = false; + store.isAuthenticated = true; + store.trigger('authenticated') + }) + .catch(function (err) { + store.isAuthenticating = false; + // store.socket.end() + // debugger + }) + } + }; + + this.connection = new sharedb.Connection(this.socket); + }.on('connect'), find: function (type, id) { + type = type.pluralize() var store = this; - return this.checkConnection + return this.checkConnection() .then(function(){ return store.findQuery(type, {_id: id}).then(function (models) { return models[0]; @@ -478,63 +1357,143 @@ define("ember-share/store", }); }, createRecord: function (type, data) { + var ref, path; + path = (ref = this._getPathForType(type)) ? ref : type.pluralize() + path = this._getPrefix(type) + path; + type = type.pluralize() var store = this; - return store.checkConnection + return store.checkConnection() .then(function(){ - var doc = store.connection.get(type, guid()); + var doc = store.connection.get(path, data.id == null ? guid() : data.id); return Promise.all([ store.whenReady(doc).then(function (doc) { return store.create(doc, data); }), store.subscribe(doc) ]).then(function () { - return store._createModel(type, doc); + var model = store._createModel(type, doc); + store._cacheFor(type).addObject(model); + return model }); }); }, - deleteRecord : function(model) { - // TODO: delete and cleanup caches - // model._context.context._doc.del() + deleteRecord : function(type, id) { + var cache = this._cacheFor(type.pluralize()); + var model = cache.findBy('id', id); + var doc = model.get('doc'); + return new Promise(function (resolve, reject) { + doc.del(function (err) { + if (err != null) + reject(err) + else { + resolve() + } + }); + }) + }, + findAndSubscribeQuery: function(type, query) { + type = type.pluralize() + var store = this; + var prefix = this._getPrefix(type); + store.cache[type] = [] + + return this.checkConnection() + .then(function(){ + return new Promise(function (resolve, reject) { + function fetchQueryCallback(err, results, extra) { + if (err !== null) { + return reject(err); + } + resolve(store._resolveModels(type, results)); + } + query = store.connection.createSubscribeQuery(prefix + type, query, null, fetchQueryCallback); + query.on('insert', function (docs) { + store._resolveModels(type, docs) + }); + query.on('remove', function (docs) { + for (var i = 0; i < docs.length; i++) { + var modelPromise = store._resolveModel(type, docs[i]); + modelPromise.then(function (model) { + store.unload(type, model) + }); + } + }); + }); + }); + }, + findRecord: function (type, id) { + var store = this; + return new Promise(function (resolve, reject){ + store.findQuery(type, {_id: id}) + .then(function(results){ + resolve(results[0]) + }) + .catch(function (err){ + reject(err) + }); + }) }, findQuery: function (type, query) { + // type = type.pluralize() + var ref, path; + path = (ref = this._getPathForType(type)) ? ref : type.pluralize() + path = this._getPrefix(type) + path; var store = this; - return this.checkConnection + store.cache[type.pluralize()] = [] + return this.checkConnection() .then(function(){ return new Promise(function (resolve, reject) { function fetchQueryCallback(err, results, extra) { - if (err !== undefined) { + if (err !== null) { return reject(err); } resolve(store._resolveModels(type, results)); } - store.connection.createFetchQuery(type, query, null, fetchQueryCallback); + store.connection.createFetchQuery(path, query, null, fetchQueryCallback); }); }); }, - findAll: function (type) { + findAll: function (type, query) { + type = type.pluralize() throw new Error('findAll not implemented'); // TODO this.connection subscribe style query }, _cacheFor: function (type) { + type = type.pluralize() var cache = this.cache[type]; if (cache === undefined) { - this.cache[type] = cache = {}; + this.cache[type] = cache = []; } return cache; }, + _getPathForType: function (type) { + var Adapter = this.container.lookupFactory('adapter:' + type.singularize()); + if (Adapter) + return Adapter.create().pathForType(); + }, + _getPrefix: function (type) { + var Adapter = this.container.lookupFactory('adapter:' + type.singularize()); + var prefix; + if (Adapter) + prefix = Adapter.create().get('prefix'); + if (!prefix) prefix = ''; + return prefix + }, _factoryFor: function (type) { - return this.container.lookupFactory('model:'+type); + var ref; + var modelStr = (ref = this.get('modelStr')) ? ref : 'model-sdb' + return this.container.lookupFactory(modelStr + ':'+ type.singularize()); }, _createModel: function (type, doc) { - var cache = this._cacheFor(type); var modelClass = this._factoryFor(type); + type = type.pluralize() if(modelClass) { var model = modelClass.create({ - id: doc.name, - _context: doc.createContext().createContextAt() + doc: doc, + _type: type, + _store: this }); - cache[doc.name] = model; return model; } else @@ -543,8 +1502,9 @@ define("ember-share/store", } }, _resolveModel: function (type, doc) { - var cache = this._cacheFor(type); - var model = cache[doc.name]; + var cache = this._cacheFor(type.pluralize()); + var id = Ember.get(doc, 'id') || Ember.get(doc, '_id'); + var model = cache.findBy('id', id); if (model !== undefined) { return Promise.resolve(model); } @@ -554,24 +1514,68 @@ define("ember-share/store", }); }, _resolveModels: function (type, docs) { + // type = type.pluralize() + var store = this; + var cache = this._cacheFor(type.pluralize()); var promises = new Array(docs.length); for (var i=0; ie;e++){var g=c[e];if(".."===g)d.pop();else{if("."===g)continue;d.push(g)}}return d.join("/")}if(d[b])return d[b];if(d[b]={},!a[b])throw new Error("Could not find module "+b);for(var f,g=a[b],h=g.deps,i=g.callback,j=[],k=0,l=h.length;l>k;k++)j.push("exports"===h[k]?f={}:c(e(h[k])));var m=i.apply(this,j);return d[b]=f||m},c.entries=a}(),b("ember-share",["ember-share/mixins/share-text","ember-share/models/share-proxy","ember-share/models/share-array","ember-share/store","ember-share/utils","exports"],function(a,b,c,d,e,f){"use strict";var g=a["default"],h=b["default"],i=c["default"],j=d["default"],k=e["default"];Ember.onLoad("Ember.Application",function(a){a.initializer({name:"ember-share",initialize:function(a,b){b.register("store:main",b.Store||StoreStore),a.lookup("store:main")}}),a.initializer({name:"injectStore",before:"ember-share",initialize:function(a,b){b.register("model:share-proxy",h),b.register("model:share-array",i),b.inject("controller","store","store:main"),b.inject("route","store","store:main")}})}),f.ShareTextMixin=g,f.ShareProxy=h,f.ShareArray=i,f.Store=j,f.Utils=k}),b("ember-share/mixins/share-text",["../utils","exports"],function(a,b){"use strict";var c=(a.isArray,a.diff);b["default"]=Ember.Mixin.create({textKeys:[],triggerEvents:!1,textEvents:function(){this._textContexts=new Array(this.textKeys.length),this._handlers=new Array(2*this._textContexts.length);for(var a=0;a=0?this.textOp(a,b):this._super(a,b)},textOp:function(a,b){if(void 0!==this._context.get()){this.propertyWillChange(a);var d=c.diff(this._cache[a]||"",b.replace(/\r\n/g,"\n"));this._cache[a]=b.replace(/\r\n/g,"\n");for(var e=0,f=0;f0&&this._context.remove([a],b);for(var f=0;d>f;f++)this._context.insert([a+f],c[f]),e[2+f]=this._factory.create({id:c[f].id,_context:this._context.createContextAt(a+f)});this._cache.splice.apply(this._cache,e),this.arrayContentDidChange(a,b,d)},toJSON:function(){return this._context.get()}})}),b("ember-share/models/share-proxy",["exports"],function(a){"use strict";var b=Array.isArray||function(a){return a instanceof Array};a["default"]=Ember.Object.extend({_context:null,_cache:null,init:function(){this._cache={};var a=this;this._context.on("replace",function(b,c,d){a.propertyWillChange(b),a._cache[b]=a.wrapObject(b,d),a.propertyDidChange(b)}),this._context.on("insert",function(b,c){a.propertyWillChange(b),a._cache[b]=a.wrapObject(b,c),a.propertyDidChange(b)}),this._context.on("child op",function(b,c){1===b.length&&c.na&&(a.propertyWillChange(b[0]),a._cache[b]=(a._cache[b[0]]||a.get(b[0])||0)+c.na,a.propertyDidChange(b[0]))})},unknownProperty:function(a){var b=this._cache[a];return void 0===b&&(b=this._cache[a]=this.wrapObject(a,this._context.get([a]))),b},setUnknownProperty:function(a,b){this._cache[a]!==b&&(this.propertyWillChange(a),this._cache[a]=this.wrapObject(a,b),this._context.set([a],b),this.propertyDidChange(a))},wrapObject:function(a,b){if(null!==b&&"object"==typeof b){var c=this.wrapLookup(a,b),d=this.container.lookupFactory("model:"+c);return d.create({_context:this._context.createContextAt(a)})}return b},wrapLookup:function(a,c){return c.type||(b(c)?"share-array":"share-proxy")},willDestroy:function(){this._cache=null,this._context.destroy(),this._context=null},toJSON:function(){return this._context.get()},incrementProperty:function(a,b){return Ember.isNone(b)&&(b=1),Ember.assert("Must pass a numeric value to incrementProperty",!isNaN(parseFloat(b))&&isFinite(b)),this.propertyWillChange(a),this._cache[a]=(this._cache[a]||this.get(a)||0)+b,void 0!==this._context.get([a])?this._context.add([a],b):this._context.set([a],this._cache[a]),this.propertyDidChange(a),this._cache[a]},decrementProperty:function(a,b){return Ember.isNone(b)&&(b=1),Ember.assert("Must pass a numeric value to decrementProperty",!isNaN(parseFloat(b))&&isFinite(b)),this.propertyWillChange(a),this._cache[a]=(this._cache[a]||this.get(a)||0)-b,void 0!==this._context.get([a])?this._context.add([a],-1*b):this._context.set([a],this._cache[a]),this.propertyDidChange(a),this._cache[a]}})}),b("ember-share/store",["./utils","exports"],function(a,b){"use strict";var c=a.guid,d=a.patchShare,e=Ember.RSVP.Promise;b["default"]=Ember.Object.extend({socket:null,connection:null,url:"http://"+window.location.hostname,init:function(){this.checkConnection=Ember.Deferred.create({});var a=this;if(this.cache={},!window.sharejs)throw new Error("ShareJS client not included");if(void 0===window.BCSocket&&void 0===window.Primus)throw new Error("No Socket library included");this.beforeConnect?this.beforeConnect().then(function(){Ember.sendEvent(a,"connect")}):Ember.sendEvent(this,"connect")},doConnect:function(){var a=this;if(window.BCSocket)this.socket=new BCSocket(this.get("url"),{reconnect:!0}),this.socket.onerror=function(b){Ember.sendEvent(a,"connectionError",[b])},this.socket.onopen=function(){a.checkConnection.resolve(),Ember.sendEvent(a,"connectionOpen")},this.socket.onclose=function(){Ember.sendEvent(a,"connectionEnd")};else{if(!window.Primus)throw new Error("No Socket library included");d(),this.socket=new Primus(this.get("url")),this.socket.on("error",function(b){Ember.sendEvent(a,"connectionError",[b])}),this.socket.on("open",function(){a.checkConnection.resolve(),Ember.sendEvent(a,"connectionOpen")}),this.socket.on("end",function(){Ember.sendEvent(a,"connectionEnd")})}this.connection=new sharejs.Connection(this.socket)}.on("connect"),find:function(a,b){var c=this;return this.checkConnection.then(function(){return c.findQuery(a,{_id:b}).then(function(a){return a[0]},function(a){return a})})},createRecord:function(a,b){var d=this;return d.checkConnection.then(function(){var f=d.connection.get(a,c());return e.all([d.whenReady(f).then(function(a){return d.create(a,b)}),d.subscribe(f)]).then(function(){return d._createModel(a,f)})})},deleteRecord:function(){},findQuery:function(a,b){var c=this;return this.checkConnection.then(function(){return new e(function(d,e){function f(b,f){return void 0!==b?e(b):void d(c._resolveModels(a,f))}c.connection.createFetchQuery(a,b,null,f)})})},findAll:function(){throw new Error("findAll not implemented")},_cacheFor:function(a){var b=this.cache[a];return void 0===b&&(this.cache[a]=b={}),b},_factoryFor:function(a){return this.container.lookupFactory("model:"+a)},_createModel:function(a,b){var c=this._cacheFor(a),d=this._factoryFor(a);if(d){var e=d.create({id:b.name,_context:b.createContext().createContextAt()});return c[b.name]=e,e}throw new Error("Cannot find model for "+a)},_resolveModel:function(a,b){var c=this._cacheFor(a),d=c[b.name];if(void 0!==d)return e.resolve(d);var f=this;return f.subscribe(b).then(function(b){return f._createModel(a,b)})},_resolveModels:function(a,b){for(var c=new Array(b.length),d=0;d=d&&h+1>=e)return g[0].components;for(var i=1;f>=i;i++)for(var j=-1*i;i>=j;j+=2){var k,l=g[j-1],m=g[j+1];h=(m?m.newPos:0)-j,l&&(g[j-1]=void 0);var n=l&&l.newPos+1=0&&e>h;if(n||o){if(!n||o&&l.newPos=d&&h+1>=e)return k.components;g[j]=k}else g[j]=void 0}},pushComponent:function(a,b,c,d){var e=a[a.length-1];e&&e.added===c&&e.removed===d?a[a.length-1]={value:this.join(e.value,b),added:c,removed:d}:a.push({value:b,added:c,removed:d})},extractCommon:function(a,b,c,d){for(var e=b.length,f=c.length,g=a.newPos,h=g-d;e>g+1&&f>h+1&&this.equals(b[g+1],c[h+1]);)g++,h++,this.pushComponent(a.components,b[g],void 0,void 0);return a.newPos=g,h},equals:function(a,b){var c=/\S/;return!this.ignoreWhitespace||c.test(a)||c.test(b)?a===b:!0},join:function(a,b){return a+b},tokenize:function(a){return a}};var f=Array.isArray||function(a){return a instanceof Array},g=new e(!1);a.guid=b,a.diff=g,a.isArray=f,a.patchShare=d}),a.EmberShare=c("ember-share")}(window); \ No newline at end of file +!function(a){define("ember-share",["ember-share/mixins/share-text","ember-share/models/model","ember-share/store","ember-share/utils","ember-share/attr","ember-share/belongs-to","exports"],function(a,b,c,d,e,f,g){"use strict";var h=a["default"],i=b["default"],j=c["default"],k=d["default"],l=e["default"],m=f["default"],n=l("_sdbProps");g.ShareTextMixin=h,g.ShareProxy=i,g.belongsTo=m,g.Store=j,g.Utils=k,g.attr=n}),define("ember-share/attr",["exports"],function(a){"use strict";var b=function(a){return a};a["default"]=function(a){return function(){var c,d;if(c={},d=null,_.forEach(arguments,function(a){return _.isPlainObject(a)?c=a:_.isString(a)?d=a.charAt(0).toUpperCase()+a.slice(1):void 0}),null!=d&&null!=window[d])var e=function(a){var b=new window[d](a);return"Date"==d?b:b.valueOf()};else var e=b;return Ember.computed({get:function(b){this.get(a,!0).addObject(b);var c=_.includes(["_isSDB","_sdbProps","_subProps","doc","_prefix","content","_idx","_root"],b);return e(c||null==this._fullPath?this._get(b,!0):this._get(this._fullPath(b)))},set:function(a,b,c){var d=null==a?this.get("_prefix"):"_idx"!=a&&this._fullPath?this._fullPath(a):a;return this._set(d,b)}})}}}),define("ember-share/belongs-to",["exports"],function(a){"use strict";a["default"]=function(a,b){var c=this.originalStore;return Ember.computed({get:function(a){var d;return c.findRecord(b,this.get(d="doc.data."+a))},set:function(a,b,c){return b}})}}),define("ember-share/mixins/share-text",["../utils","exports"],function(a,b){"use strict";var c=(a.isArray,a.diff);b["default"]=Ember.Mixin.create({textKeys:[],triggerEvents:!1,textEvents:function(){this._textContexts=new Array(this.textKeys.length),this._handlers=new Array(2*this._textContexts.length);for(var a=0;a=0?this.textOp(a,b):this._super(a,b)},textOp:function(a,b){if(void 0!==this._context.get()){this.propertyWillChange(a);var d=c.diff(this._cache[a]||"",b.replace(/\r\n/g,"\n"));this._cache[a]=b.replace(/\r\n/g,"\n");for(var e=0,f=0;f=a||b&&f>a)){var g=f+i+c,j=e[d];delete e[d];var k={};k[h(d,g)]=j,_.assign(e,k),Ember.set(j,"_idx",g)}}),this._super.apply(this,arguments)},replaceContent:function(a,b){var c=Ember.get(this,"_prefix"),d=Ember.get(this,"_children");return _.forEach(this.toArray(),function(b,e){var f=d[c+"."+e];null!=f&&(null!=a[e]?f.replaceContent(a[e],!0):(delete d[c+"."+e],f.destroy()))}),b||this._set(c,a),Ember.set(this,"content",a),this},_submitOp:function(a,b,c){var d=this.get("_prefix").split("."),e={p:d.concat(a)};return null!=b&&(e.li=b),null!=c&&(e.ld=c),null!=b||null!=c?this.get("doc").submitOp([e]):void 0},objectAt:function(a){var b=this._super(a),c=this.get("_prefix");return this.useSubs(b,c,a)},toJson:function(){return _.map(this.toArray(),function(a){return"string"==typeof a||"number"==typeof a?a:a.toJson()})},_replace:function(a,b,c){this.arrayContentWillChange(a,b,c.length);for(var d=b>c.length?b:c.length,e=0;d>e;e++){var f=e+a,g=c.objectAt(e);this._submitOp(f,g,b>e?this.objectAt(f):null)}return this.arrayContentDidChange(a,b,c.length),this},onChangeDoc:function(){this.replaceContent(this.get("doc.data."+this.get("_prefix")),!0)}.observes("doc")})}}),define("ember-share/models/sub-mixin",["./utils","../attr","exports"],function(a,b,c){"use strict";var d=a["default"],e=b["default"];c["default"]=Ember.Mixin.create({_children:function(){return{}}.property(),_sdbProps:function(){return[]}.property(),_subProps:function(){return[]}.property(),doc:Ember.computed.reads("_root.doc"),createInnerAttrs:function(){var a=Ember.get(this,"tempContent"),b=this,c=e("_subProps"),d=[];_.forEach(a,function(a,e){d.push(e),Ember.defineProperty(b,e,c())}),Ember.get(this,"_subProps").addObjects(d),delete this.tempContent}.on("init"),beforeFn:function(){return[]}.property(),afterFn:function(){return[]}.property(),activateListeners:function(){var a=d(this),b=a.beforeAfterChild("Will"),c=a.beforeAfterChild("Did");this.has("before op")&&this.off("before op",this.get("beforeFn").pop()),this.has("op")&&this.off("op",this.get("afterFn").pop()),this.on("before op",b),this.on("op",c),this.get("beforeFn").push(b),this.get("afterFn").push(c)}.observes("doc").on("init"),_fullPath:function(a){var b=Ember.get(this,"_prefix"),c=Ember.get(this,"_idx");return b?null!=c?b+"."+c+"."+a:b+"."+a:a},deleteProperty:function(a){return this.removeKey(a),this._super(this._fullPath(a))},replaceContent:function(a,b){this.notifyWillProperties(this.get("_subProps").toArray());var c=this.get("_prefix"),e=this.get("_idx"),f=null==e?c:c+"."+e;b||this._set(f,a);var g=this,h=d(this);if(h.removeChildren(f),_.isEmpty(Object.keys(this))){Ember.setProperties(this,{tempContent:a}),this.createInnerAttrs();var i=function(a,b){if(_.isEmpty(a))g.get("_root").notifyPropertyChange(b.join("."));else{var c=g.get._children[a.join(".")];null!=c?c.notifyPropertyChange(a.join(".")+"."+b.join(".")):b.push(a.pop()),i(a,b)}},j=c.split("."),k=j.pop();i(j,[k])}else{if(_.isPlainObject(a))var l=_.difference(Object.keys(this),Object.keys(a));else var l=Object.keys(this);_.forEach(l,function(a){delete g[a]}),this.get("_subProps").removeObjects(l),Ember.setProperties(this,{tempContent:a}),this.createInnerAttrs(),this.notifyDidProperties(this.get("_subProps").toArray())}return this},toJson:function(){var a=Ember.get(this,"_idx"),b=Ember.get(this,"_prefix"),c=null==a?b:b+"."+a;return this.get("doc.data."+c)},addKey:function(a){var b=e("_subProps");return this.get("_subProps").indexOf(a)>-1||Ember.defineProperty(this,a,b()),this},removeKey:function(a){var b=(e("_subProps"),d(this));return b.removeChildren(a,!0),this.get("_subProps").removeObject(a),delete this[a],this},removeListeners:function(){this.off("before op",this.get("beforeFn")),this.off("op",this.get("afterFn"))}})}),define("ember-share/models/subs-handler",["exports"],function(a){"use strict";a["default"]={object:{},array:{}}}),define("ember-share/models/use-subs-mixin",["./subs-handler","./utils","exports"],function(a,b,c){"use strict";var d=a["default"],e=b["default"];c["default"]=Ember.Mixin.create({useSubs:function(a,b,c){var f=e(this);if(f.matchChildToLimitations(b))return a;if(_.isPlainObject(a)){a={tempContent:a};var g="object"}else if(_.isArray(a)){a={content:a};var g="array"}if(g){var h,i,j=null==c?b:b+"."+c,k=Ember.get(this,"_prefix");if(null!=(i=Ember.get(this,"_idx"))&&(k+="."+i),j==k)return this;var l=Ember.get(this,"_children"),m=Object.keys(l);if(_.includes(m,j))return l[j];h={};var n=d[g].extend({_children:Ember.get(this,"_children"),_prefix:b,_idx:c,_sdbProps:Ember.get(this,"_sdbProps"),_root:Ember.get(this,"_root")});return n=n.create(a),h[j]=n,_.assign(Ember.get(this,"_children"),h),n}return a}})}),define("ember-share/models/utils",["exports"],function(a){"use strict";a["default"]=function(a){return{isOpOnArray:function(a){return null!=a.ld||null!=a.lm||null!=a.li},matchingPaths:function(a,b){for(var c=0,d=a.length>b.length?a.length:b.length;("*"==a[c]||a[c]==b[c])&&d>c;)c++;return c-a.length/1e3},matchChildToLimitations:function(b){var c=Ember.get(a,"_root._childLimiations"),d=Ember.get(a,"_prefix");null==d||b.match(d)?d=b:d+="."+b,d=d.split(".");var e=this;return _.some(c,function(a){var b=a.split("/");return d.length==b.length&&Math.ceil(e.matchingPaths(b,d))==d.length})},prefixToChildLimiations:function(b){var c=Ember.get(a,"_root._childLimiations"),d=Ember.get(a,"_prefix");null==d||b.match(d)?d=b:d+="."+b,d=d.split(".");var e,f=this,g=this.findMaxIndex(e=_.map(c,function(a){var b=a.split("/"),c=Math.ceil(f.matchingPaths(b,d));return c=0&&e[g]>0){var h,i=c[g].split("/"),j=d.slice(0,Math.ceil(f.matchingPaths(i,d)));return(h=Ember.get(a,"_prefix"))?(h=h.split("."),j.slice(h.length)):j.join(".")}return b},removeChildren:function(b,c){var d=Ember.get(a,"_children"),e=Object.keys(d),f=a.get("_prefix"),g=this;null!=f&&b&&0!=b.indexOf(f)&&(b=f+"."+b),b&&(e=_.reduce(e,function(a,d){var e=Math.ceil(g.matchingPaths(d.split("."),b.split(".")));return(c&&e>=b.split(".").length||!c&&e>b.split(".").length)&&a.push(d),a},[])),_.forEach(e,function(a){d[a].destroy(),delete d[a]})},comparePathToPrefix:function(a,b){return Boolean(Math.ceil(this.matchingPaths(a.split("."),b.split("."))))},cutLast:function(a,b){var c;return this.isOpOnArray(b)&&!isNaN(+_.last(a))&&(c=_.clone(a),c.pop()),c?c:a},comparePathToChildren:function(b,c){var d=this,e=Ember.get(a,"_children"),f=Object.keys(e),g=_.some(f,function(a){var e=d.matchingPaths(a.split("."),d.cutLast(b,c));return Math.ceil(e)==a.split(".").length});return!Ember.isEmpty(f)&&g},triggerChildren:function(b,c,d){var e=(_.clone(c.p),a.get("_children")),f=Object.keys(e);if(!Ember.isEmpty(f)){var g=this,h=_.mapKeys(e,function(a,b){return g.isOpOnArray(c)&&!isNaN(+_.last(b.split(".")))?0:g.matchingPaths(g.cutLast(b.split("."),c),c.p)}),i=function(a){return _.map(a,function(a){return+a})},j=h[_.max(i(Object.keys(h)))];"Will"==b&&j.trigger("before op",[c],d),"Did"==b&&j.trigger("op",[c],d)}},beforeAfter:function(b){var c,d=this;return function(e,f){f||_.forEach(e,function(e){d.comparePathToChildren(e.p,e)?d.triggerChildren(b,e,f):d.isOpOnArray(e)?(c=d.extractArrayPath(e),a.get(c.p)["arrayContent"+b+"Change"](c.idx,c.removeAmt,c.addAmt)):a["property"+b+"Change"](d.prefixToChildLimiations(e.p.join(".")))})}},beforeAfterChild:function(b){var c,d,e,f=this;return function(g,h){null==(e=Ember.get(a,"_idx"))&&h||_.forEach(g,function(g){if(g.p.join(".")==(d=Ember.get(a,"_prefix"))&&"Did"==b){if(null!=g.oi)a.replaceContent(g.oi,!0);else if(null!=g.od){var h,i=d.split("."),j=i.pop();!_.isEmpty(i)&&(h=a.get("_children."+i.join(".")))?h.removeKey(j):a.get("_root").propertyDidChange(d)}}else{var k=null==e?d.split("."):d.split(".").concat(String(e)),l=_.difference(g.p,k);if(f.comparePathToPrefix(g.p.join("."),d))if(f.isOpOnArray(g)&&null==Ember.get(a,"_idx")){var m=_.clone(g);m.p=l,c=f.extractArrayPath(m),""==c.p?a["arrayContent"+b+"Change"](c.idx,c.removeAmt,c.addAmt):Ember.get(a,c.p)["arrayContent"+b+"Change"](c.idx,c.removeAmt,c.addAmt)}else if(""==l.join(".")){var h;a["property"+b+"Change"]("content")}else g.oi&&null==g.od&&a.addKey(_.first(l)),g.od&&null==g.oi&&a.removeKey(_.first(l)),a["property"+b+"Change"](f.prefixToChildLimiations(l.join(".")))}})}},findMaxIndex:function(a){return a.indexOf(_.max(a))},extractArrayPath:function(a){return{idx:+_.last(a.p),p:_.slice(a.p,0,a.p.length-1).join("."),addAmt:null!=a.li?1:0,removeAmt:null!=a.ld?1:0}}}}}),define("ember-share/store",["./utils","exports"],function(a,b){"use strict";var c=a.guid,d=a.patchShare,e=Ember.RSVP.Promise;b["default"]=Ember.Object.extend(Ember.Evented,{socket:null,connection:null,url:window.location.hostname,init:function(){var a=this;if(this.checkSocket=function(){return new e(function(b,c){if(null==a.socket)a.one("connectionOpen",b);else{var d=function(c,d){switch(c){case"connected":return b();case"connecting":return a.connection.once("connected",b);default:d(c)}},e=function(a){switch(a){case"closed":return c("connection closed");case"disconnected":return c("connection disconnected");case"stopped":return c("connection closing")}},f=!1;d(a.connection.state,function(b){f?e(b):Ember.run.next(this,function(){f=!0,d(a.connection.state,e)})})}})},this.checkConnection=function(){return new e(function(b,c){return a.checkSocket().then(function(){return b()})["catch"](function(a){return c(a)})})},this.cache={},!window.sharedb)throw new Error("sharedb client not included");if(void 0===window.BCSocket&&void 0===window.Primus)throw new Error("No Socket library included");this.beforeConnect?this.beforeConnect().then(function(){a.trigger("connect")}):a.trigger("connect")},doConnect:function(a){var b=this;if(window.BCSocket)this.setProperties(a),this.socket=new BCSocket(this.get("url"),{reconnect:!0}),this.socket.onerror=function(a){b.trigger("connectionError",[a])},this.socket.onopen=function(){b.trigger("connectionOpen")},this.socket.onclose=function(){b.trigger("connectionEnd")};else{if(!window.Primus)throw new Error("No Socket library included");d(),this.setProperties(a);var c=this.get("url");this.get("protocol")&&(c=this.get("protocol")+"://"+c),this.get("port")&&(c+=":"+this.get("port")),this.socket=new Primus(c),this.socket.on("error",function(a){b.trigger("connectionError",[a])}),this.socket.on("open",function(){b.trigger("connectionOpen")}),this.socket.on("end",function(){b.trigger("connectionEnd")}),this.socket.on("close",function(){b.trigger("connectionEnd")})}var e=sharedb.Connection.prototype.handleMessage;sharedb.Connection.prototype.send;b.on("connectionEnd",function(){b.isAuthenticated=!1}),sharedb.Connection.prototype.handleMessage=function(a){var c;c=arguments;var d=this;return e.apply(d,c),"init"===a.a&&"string"==typeof a.id&&1===a.protocol&&"function"==typeof b.authenticate?(b.isAuthenticating=!0,b.authenticate(a.id).then(function(){console.log("authenticated !"),b.isAuthenticating=!1,b.isAuthenticated=!0,b.trigger("authenticated")})["catch"](function(a){b.isAuthenticating=!1})):void 0},this.connection=new sharedb.Connection(this.socket)}.on("connect"),find:function(a,b){a=a.pluralize();var c=this;return this.checkConnection().then(function(){return c.findQuery(a,{_id:b}).then(function(a){return a[0]},function(a){return a})})},createRecord:function(a,b){var d,f;f=(d=this._getPathForType(a))?d:a.pluralize(),f=this._getPrefix(a)+f,a=a.pluralize();var g=this;return g.checkConnection().then(function(){var d=g.connection.get(f,null==b.id?c():b.id);return e.all([g.whenReady(d).then(function(a){return g.create(a,b)}),g.subscribe(d)]).then(function(){var b=g._createModel(a,d);return g._cacheFor(a).addObject(b),b})})},deleteRecord:function(a,b){var c=this._cacheFor(a.pluralize()),d=c.findBy("id",b),f=d.get("doc");return new e(function(a,b){f.del(function(c){null!=c?b(c):a()})})},findAndSubscribeQuery:function(a,b){a=a.pluralize();var c=this,d=this._getPrefix(a);return c.cache[a]=[],this.checkConnection().then(function(){return new e(function(e,f){function g(b,d,g){return null!==b?f(b):void e(c._resolveModels(a,d))}b=c.connection.createSubscribeQuery(d+a,b,null,g),b.on("insert",function(b){c._resolveModels(a,b)}),b.on("remove",function(b){for(var d=0;d=d&&h+1>=e)return g[0].components;for(var i=1;f>=i;i++)for(var j=-1*i;i>=j;j+=2){var k,l=g[j-1],m=g[j+1];h=(m?m.newPos:0)-j,l&&(g[j-1]=void 0);var n=l&&l.newPos+1=0&&e>h;if(n||o){if(!n||o&&l.newPos=d&&h+1>=e)return k.components;g[j]=k}else g[j]=void 0}},pushComponent:function(a,b,c,d){var e=a[a.length-1];e&&e.added===c&&e.removed===d?a[a.length-1]={value:this.join(e.value,b),added:c,removed:d}:a.push({value:b,added:c,removed:d})},extractCommon:function(a,b,c,d){for(var e=b.length,f=c.length,g=a.newPos,h=g-d;e>g+1&&f>h+1&&this.equals(b[g+1],c[h+1]);)g++,h++,this.pushComponent(a.components,b[g],void 0,void 0);return a.newPos=g,h},equals:function(a,b){var c=/\S/;return!this.ignoreWhitespace||c.test(a)||c.test(b)?a===b:!0},join:function(a,b){return a+b},tokenize:function(a){return a}};var f=Array.isArray||function(a){return a instanceof Array},g=new e(!1);a.guid=b,a.diff=g,a.isArray=f,a.patchShare=d}),a.EmberShare=require("ember-share")}(window); \ No newline at end of file diff --git a/dist/ember-share.amd.js b/dist/ember-share.amd.js index 9398fb1..951c28e 100644 --- a/dist/ember-share.amd.js +++ b/dist/ember-share.amd.js @@ -1,39 +1,138 @@ define("ember-share", - ["ember-share/mixins/share-text","ember-share/models/share-proxy","ember-share/models/share-array","ember-share/store","ember-share/utils","exports"], - function(__dependency1__, __dependency2__, __dependency3__, __dependency4__, __dependency5__, __exports__) { + ["ember-share/mixins/share-text","ember-share/models/model","ember-share/store","ember-share/utils","ember-share/attr","ember-share/belongs-to","exports"], + function(__dependency1__, __dependency2__, __dependency3__, __dependency4__, __dependency5__, __dependency6__, __exports__) { "use strict"; var ShareTextMixin = __dependency1__["default"]; var ShareProxy = __dependency2__["default"]; - var ShareArray = __dependency3__["default"]; - var Store = __dependency4__["default"]; - var Utils = __dependency5__["default"]; - - Ember.onLoad('Ember.Application', function(Application) { - Application.initializer({ - name: 'ember-share', - initialize : function(container, application){ - application.register('store:main', application.Store || StoreStore); - container.lookup('store:main'); - } - }); - Application.initializer({ - name: 'injectStore', - before : 'ember-share', - initialize : function(container, application) { - application.register('model:share-proxy',ShareProxy); - application.register('model:share-array',ShareArray); - application.inject('controller', 'store', 'store:main'); - application.inject('route', 'store', 'store:main'); - } - }); - }); + var Store = __dependency3__["default"]; + var Utils = __dependency4__["default"]; + var attrFunc = __dependency5__["default"]; + var belongsTo = __dependency6__["default"]; + var attr = attrFunc('_sdbProps') __exports__.ShareTextMixin = ShareTextMixin; __exports__.ShareProxy = ShareProxy; - __exports__.ShareArray = ShareArray; + __exports__.belongsTo = belongsTo; __exports__.Store = Store; __exports__.Utils = Utils; + __exports__.attr = attr; + }); +define("ember-share/attr", + ["exports"], + function(__exports__) { + "use strict"; + var sillyFunction = function (value) {return value}; + + __exports__["default"] = function(sdbProps) { + return function() { + var options, + type; + options = {}; + type = null; + _.forEach(arguments, function(arg) { + if (_.isPlainObject(arg)) { + return options = arg; + } else { + if (_.isString(arg)) { + return type = arg.charAt(0).toUpperCase() + arg.slice(1); + } + } + }); + if (type != null && window[type] != null) { + var transfromToType = function (value) { + var newValue = new window[type](value) + if (type == 'Date') + return newValue + else + return newValue.valueOf() + }; + } else { + var transfromToType = sillyFunction + } + + return Ember.computed({ + get: function(k) { + this.get(sdbProps, true).addObject(k); + // return this.get(k, true); + var isSpecielKey = _.includes([ + '_isSDB', + '_sdbProps', + '_subProps', + 'doc', + '_prefix', + 'content', + '_idx', + '_root' + ], k); + + if (isSpecielKey || this._fullPath == null) + return transfromToType(this._get(k, true)) + else + return transfromToType(this._get(this._fullPath(k))) + + }, + set: function(k, v, isFromServer) { + // return this._super(p, oi) + var path = (k == null) ? this.get('_prefix') : ((k == '_idx' || !this._fullPath) ? k : this._fullPath(k)); + return this._set(path, v) + + } + }); + } + } + }); +define("ember-share/belongs-to", + ["exports"], + function(__exports__) { + "use strict"; + __exports__["default"] = function(DS, modelName) { + // var options, type; + // options = {}; + // type = null; + // _.forEach(arguments, function(arg) { + // if (_.isPlainObject(arg)) { + // return options = arg; + // } else { + // if (_.isString(arg)) { + // return type = null; + // } + // } + // }); + var store = this.originalStore; + return Ember.computed({ + get: function(k) { + var ref; + + return store.findRecord(modelName, this.get(ref = "doc.data." + k)); + // return != null ? ref : Ember.get(options, 'defaultValue')); + }, + set: function(p, oi, isFromServer) { + return oi; + } + }); + } + + + // attr: -> + // options = {}; type = null + // _.forEach arguments, (arg) -> + // if _.isPlainObject(arg) + // options = arg + // else + // if _.isString arg + // type = null + // + // Ember.computed + // get: (k) -> + // @get "doc.data.#{k}" ? Ember.get(options, 'defaultValue') + // set: (p, oi, isFromServer) -> + // if type? + // oi = window[type.toUpperCase type] oi + // od = @get p + // p = p.split '.' + // @get('doc').submitOp [{p,od,oi}] + // oi }); define("ember-share/mixins/share-text", ["../utils","exports"], @@ -147,216 +246,1005 @@ define("ember-share/mixins/share-text", } }); }); -define("ember-share/models/share-array", - ["./share-proxy","exports"], - function(__dependency1__, __exports__) { +define("ember-share/models/base", + ["./use-subs-mixin","./sub-mixin","./sub-array","./subs-handler","./utils","exports"], + function(__dependency1__, __dependency2__, __dependency3__, __dependency4__, __dependency5__, __exports__) { "use strict"; - var ShareProxy = __dependency1__["default"]; + var UseSubsMixin = __dependency1__["default"]; + var SubMixin = __dependency2__["default"]; + var SDBSubArray = __dependency3__["default"]; + var subs = __dependency4__["default"]; + var Utils = __dependency5__["default"]; - __exports__["default"] = Ember.Object.extend(Ember.MutableArray, { - _context: null, - _cache: null, - itemType: 'share-proxy', - init: function () { - this._cache = []; // cache wrapped objects - this._factory = this.container.lookupFactory('model:'+this.itemType); - // TODO subscribe to array ops on context - var _this = this; - this._context.on('delete', function (index, removed) { - _this.arrayContentWillChange(index, 1, 0); - - _this._cache.splice(index, 1); - - // update paths - var depth = _this._context.path.length; - _this._cache.forEach(function(item,idx){ - item._context.path[depth]= idx; - }) - _this.arrayContentDidChange(index, 1, 0); - }); - this._context.on('insert', function (index, value) { - _this.arrayContentWillChange(index, 0, 1); + var toJson = function(obj) { + return (obj == null) + ? void 0 + : JSON.parse(JSON.stringify(obj)); + }; - var model = _this._factory.create({ - _context: _this._context.createContextAt(index) - }); + var getPlainObject = function (value) { + if (value != null && !((typeof value == 'string') || (typeof value == 'number'))) + if (typeof value.toJson == 'function') + return value.toJson() + else + return toJson(value) + else { + return value + } + } - _this._cache.splice(index, 0, model); - // update paths - var depth = _this._context.path.length; - _this._cache.forEach(function(item,idx){ - item._context.path[depth]= idx; - }); - _this.arrayContentDidChange(index, 0, 1); - }); - }, - length: function () { - return this._context.get().length; - }.property().volatile(), - objectAt: function (index) { - if (this._cache[index] === undefined && this._context.get(index) !== undefined) { - this._cache[index] = this._factory.create({ - _context: this._context.createContextAt(index) - }); - } - return this._cache[index]; - }, - replace: function (index, length, objects) { - var objectsLength = objects.length; - var args = new Array(objectsLength+2); - var model; - args[0] = index; - args[1] = length; + // + // ShareDb Base Class + // + // Root and all subs (currently not arrays) inherit from base. + // + // - this.arrayContentWillChange(index, length, objectsLength); + var GetterSettersMixin = Ember.Mixin.create({ - if (length > 0) { - this._context.remove([index], length); - } + _get: function(k, selfCall) { + var firstValue = _.first(k.split('.')); - for (var i=0; i objects.length) + ? len + : objects.length; + for (var i = 0; i < iterationLength; i++) { + var newIndex = i + start; + var obj = objects.objectAt(i); + this._submitOp(newIndex, obj, (len > i + ? this.objectAt(newIndex) + : null)) + } + this.arrayContentDidChange(start, len, objects.length); + return this //._super(start, len, objects) + }, + + onChangeDoc: (function () { + // debugger + // this.set ('content', this.get('doc.data.' + this.get('_prefix'))) + // Ember.run.next (this, function () P{}) + this.replaceContent(this.get('doc.data.' + this.get('_prefix')), true) + }).observes('doc') + }); + } + }); +define("ember-share/models/sub-mixin", + ["./utils","../attr","exports"], + function(__dependency1__, __dependency2__, __exports__) { + "use strict"; + var Utils = __dependency1__["default"]; + var attrs = __dependency2__["default"]; + + var allButLast = function(arr) { + return arr.slice(0, arr.length - 1) + }; + + // + // Sub Mixin + // + // All subs use this mixin (Object and Array) + // + // + + __exports__["default"] = Ember.Mixin.create({ + + _children: (function() { + return {} + }).property(), + + _sdbProps: (function() { + return [] + }).property(), + + _subProps: (function() { + return [] + }).property(), + + doc: Ember.computed.reads('_root.doc'), + + createInnerAttrs: (function() { + var tempContent = Ember.get(this, 'tempContent'); + var self = this; + var attr = attrs('_subProps'); + var keys = []; + + _.forEach(tempContent, function(value, key) { + keys.push(key); + Ember.defineProperty(self, key, attr()); + }) + + Ember.get(this, '_subProps').addObjects(keys); + delete this['tempContent']; + }).on('init'), + + beforeFn: (function (){return []}).property(), + afterFn: (function (){return []}).property(), + + activateListeners: (function() { + var utils = Utils(this); + + var beforeFn = utils.beforeAfterChild("Will"); + var afterFn = utils.beforeAfterChild("Did"); + + if (this.has('before op')) { + this.off('before op', this.get('beforeFn').pop()) + } + if (this.has('op')) { + this.off('op', this.get('afterFn').pop()) + } + this.on('before op', beforeFn); + this.on('op', afterFn); + + this.get('beforeFn').push(beforeFn); + this.get('afterFn').push(afterFn); + + // }).on('init'), + }).observes('doc').on('init'), + + _fullPath: function(path) { + var prefix = Ember.get(this, '_prefix'); + var idx = Ember.get(this, '_idx'); + + if (prefix) { + if (idx != null) { + return prefix + '.' + idx + '.' + path + } else { + return prefix + '.' + path; + } + } else + return path; + } + , + + deleteProperty: function(k) { + this.removeKey(k); + return this._super(this._fullPath(k)) + }, + + replaceContent: function(content, noSet) { + this.notifyWillProperties(this.get('_subProps').toArray()); + var prefix = this.get('_prefix'); + var idx = this.get('_idx') + var path = (idx == null) ? prefix : prefix + '.' + idx + + if (!noSet) + this._set(path, content); + + var self = this; + var utils = Utils(this); + + utils.removeChildren(path); + + if (_.isEmpty(Object.keys(this))) { + Ember.setProperties(this, {tempContent: content}); + this.createInnerAttrs(); + + var notifyFather = function (prefixArr, keys) { + if (_.isEmpty(prefixArr)) + self.get('_root').notifyPropertyChange(keys.join('.')) + else { + var child = self.get['_children'][prefixArr.join('.')] + if (child != null) + child.notifyPropertyChange(prefixArr.join('.') + '.' + keys.join('.')) + else + keys.push(prefixArr.pop()); + notifyFather(prefixArr, keys); + } + }; + var prefixArr = prefix.split('.') + var key = prefixArr.pop() + + notifyFather(prefixArr, [key]); + } + else { + if (_.isPlainObject(content)) + var toDelete = _.difference(Object.keys(this), Object.keys(content)) + else + var toDelete = Object.keys(this); + + _.forEach(toDelete, function(prop) { + delete self[prop] + }); + this.get('_subProps').removeObjects(toDelete); + Ember.setProperties(this, {tempContent: content}); + this.createInnerAttrs(); + this.notifyDidProperties(this.get('_subProps').toArray()); + } + + return this + }, + + toJson: function() { + var idx = Ember.get(this, '_idx'), + k = Ember.get(this, '_prefix'); + var path = (idx == null) + ? k + : (k + '.' + idx); + return this.get('doc.data.' + path); + }, + + addKey: function (key) { + var attr = attrs('_subProps'); + if (!(this.get('_subProps').indexOf(key) > -1)) + Ember.defineProperty(this, key, attr()); + return this + }, + + removeKey: function (key) { + var attr = attrs('_subProps'); + var utils = Utils(this); + utils.removeChildren(key, true); + this.get('_subProps').removeObject(key); + delete this[key]; + return this + }, + + removeListeners: function () { + this.off('before op', this.get('beforeFn')) + this.off('op', this.get('afterFn')) + + } + + }) }); -define("ember-share/models/share-proxy", +define("ember-share/models/subs-handler", ["exports"], function(__exports__) { "use strict"; - var isArray = Array.isArray || function (obj) { - return obj instanceof Array; - }; + // + // Subs Handler + // + // since we have a recursive model structure there is a need for + // creating the subs in a common place and then reuse it in its own class. + // + // - __exports__["default"] = Ember.Object.extend({ - _context: null, - _cache: null, - init: function () { - this._cache = {}; // allows old value to be seen on willChange event - var _this = this; - this._context.on('replace', function (key, oldValue, newValue) { - _this.propertyWillChange(key); - _this._cache[key] = _this.wrapObject(key, newValue); - _this.propertyDidChange(key); - }); - this._context.on('insert', function (key, value) { - _this.propertyWillChange(key); - _this._cache[key] = _this.wrapObject(key, value); - _this.propertyDidChange(key); - }); - this._context.on('child op', function (key, op) { - // handle add operations - if(key.length === 1 && op.na) - { - _this.propertyWillChange(key[0]); - _this._cache[key] = (_this._cache[key[0]] || _this.get(key[0]) || 0) + op.na; - _this.propertyDidChange(key[0]); - } - }); - }, - unknownProperty: function (key) { - var value = this._cache[key]; - if (value === undefined) { - value = this._cache[key] = this.wrapObject(key, this._context.get([key])); - } - return value; - }, - setUnknownProperty: function (key, value) { - if (this._cache[key] !== value) { - this.propertyWillChange(key); - this._cache[key] = this.wrapObject(key, value); - this._context.set([key], value); - this.propertyDidChange(key); - } - }, - wrapObject: function (key, value) { - if (value !== null && typeof value === 'object') { - var type = this.wrapLookup(key,value); - var factory = this.container.lookupFactory('model:'+type); - return factory.create({ - _context: this._context.createContextAt(key) - }); - } - return value; - }, - wrapLookup : function(key,value) { - return value.type || (isArray(value) ? 'share-array' : 'share-proxy'); - }, - willDestroy: function () { - this._cache = null; - this._context.destroy(); - this._context = null; - }, - toJSON: function () { - return this._context.get(); - }, - incrementProperty: function(key, increment) { - if (Ember.isNone(increment)) { increment = 1; } - Ember.assert("Must pass a numeric value to incrementProperty", (!isNaN(parseFloat(increment)) && isFinite(increment))); - this.propertyWillChange(key); - this._cache[key] = (this._cache[key] || this.get(key) || 0) + increment; - if(this._context.get([key]) !== undefined) - { - this._context.add([key], increment); - } - else - { - this._context.set([key], this._cache[key]); - } - this.propertyDidChange(key); - return this._cache[key]; - }, - decrementProperty: function(key, decrement) { - if (Ember.isNone(decrement)) { decrement = 1; } - Ember.assert("Must pass a numeric value to decrementProperty", (!isNaN(parseFloat(decrement)) && isFinite(decrement))); - this.propertyWillChange(key); - this._cache[key] = (this._cache[key] || this.get(key) || 0) - decrement; - if(this._context.get([key]) !== undefined) - { - this._context.add([key], -1 * decrement); - } - else - { - this._context.set([key], this._cache[key]); - } - this.propertyDidChange(key); - return this._cache[key]; - }, - }); + __exports__["default"] = { + object : {}, + array : {} + } + }); +define("ember-share/models/use-subs-mixin", + ["./subs-handler","./utils","exports"], + function(__dependency1__, __dependency2__, __exports__) { + "use strict"; + var subs = __dependency1__["default"]; + var Utils = __dependency2__["default"];__exports__["default"] = Ember.Mixin.create({ + + useSubs: function useSubs(content, k, idx) { + var utils = Utils(this); + + if (utils.matchChildToLimitations(k)) + return content; + + if (_.isPlainObject(content)) { + content = { + tempContent: content + }; + var use = 'object' + + } else if (_.isArray(content)) { + content = { + content: content + }; + var use = 'array'; + } + if (use) { + var child, + _idx; + var path = (idx == null) ? k : (k + '.' + idx); + var ownPath = Ember.get(this, '_prefix'); + if ((_idx = Ember.get(this, '_idx')) != null) + ownPath += '.' + _idx; + if (path == ownPath) { + return this; + } + + var children = Ember.get(this, '_children'); + var childrenKeys = Object.keys(children); + + if (_.includes(childrenKeys, path)) + return children[path] + else + child = {}; + + var sub = subs[use].extend({ + // doc: this.get('doc'), + _children: Ember.get(this, '_children'), + _prefix: k, + _idx: idx, + _sdbProps: Ember.get(this, '_sdbProps'), + _root: Ember.get(this,'_root') + }); + + sub = sub.create(content); + + child[path] = sub; + _.assign(Ember.get(this, '_children'), child); + + return sub + } else + return content + } + }) + }); +define("ember-share/models/utils", + ["exports"], + function(__exports__) { + "use strict"; + __exports__["default"] = function(context) { + + return { + + isOpOnArray: function(op) { + return (op.ld != null) || (op.lm != null) || (op.li != null) + }, + + matchingPaths: function(as, bs) { + var counter = 0; + var higherLength = (as.length > bs.length) + ? as.length + : bs.length + while ((as[counter] == '*' || as[counter] == bs[counter]) && counter < higherLength) { + counter++ + } + return counter - (as.length / 1000) + }, + + matchChildToLimitations: function (key) { + var childLimiations = Ember.get(context, '_root._childLimiations'); + var prefix = Ember.get(context, '_prefix') + + if (prefix == null || key.match(prefix)) + prefix = key + else + prefix += '.' + key + + prefix = prefix.split('.'); + var self = this; + return _.some (childLimiations, function (_limit) { + var limit = _limit.split('/'); + return prefix.length == limit.length && Math.ceil(self.matchingPaths(limit, prefix)) == prefix.length + }) + }, + + prefixToChildLimiations: function (key) { + var childLimiations = Ember.get(context, '_root._childLimiations'); + var prefix = Ember.get(context, '_prefix') + + if (prefix == null || key.match(prefix)) + prefix = key + else + prefix += '.' + key + + prefix = prefix.split('.'); + var self = this, limiationsArray; + + var relevantLimitIndex = this.findMaxIndex(limiationsArray = _.map (childLimiations, function (_limit) { + var limit = _limit.split('/'); + var result = Math.ceil(self.matchingPaths(limit, prefix)) + return result < limit.length ? 0 : result + })); + if (relevantLimitIndex >= 0 && limiationsArray[relevantLimitIndex] > 0) { + var relevantLimit = childLimiations[relevantLimitIndex].split('/'); + var orignalPrefix; + var result = prefix.slice(0, Math.ceil(self.matchingPaths(relevantLimit, prefix)) ); + if (orignalPrefix = Ember.get(context, '_prefix')) { + orignalPrefix = orignalPrefix.split('.'); + return result.slice(orignalPrefix.length) + } else + return result.join('.'); + } + else { + return key; + } + + }, + + removeChildren: function (path, includeSelf) { + var children = Ember.get(context, '_children'); + var childrenKeys = Object.keys(children); + var prefix = context.get('_prefix'); + var utils = this; + + if ((prefix != null) && path && path.indexOf(prefix) != 0) { + path = prefix + '.' + path + } + + if (path) { + childrenKeys = _.reduce(childrenKeys, function(result, key) { + var matches = Math.ceil(utils.matchingPaths(key.split('.'), path.split('.'))) + if (includeSelf && (matches >= path.split('.').length) || + (!includeSelf && (matches > path.split('.').length))) + result.push(key); + return result + }, []); + } + + _.forEach (childrenKeys, function (key) { + children[key].destroy() + delete children[key] + }) + }, + + comparePathToPrefix: function(path, prefix) { + return Boolean(Math.ceil(this.matchingPaths(path.split('.'), prefix.split('.')))) + }, + + cutLast: function(path, op) { + var tempPath; + if (this.isOpOnArray(op) && !isNaN(+ _.last(path))) { + tempPath = _.clone(path); + tempPath.pop(); + } + return (tempPath) + ? tempPath + : path + }, + + comparePathToChildren: function(path, op) { + var utils = this; + var children = Ember.get(context, '_children'); + var childrenKeys = Object.keys(children); + var hasChildren = _.some(childrenKeys, function(childKey) { + var pathsCounter = utils.matchingPaths(childKey.split('.'), utils.cutLast(path, op)) + return Math.ceil(pathsCounter) == childKey.split('.').length + }); + return !Ember.isEmpty(childrenKeys) && hasChildren + }, + + triggerChildren: function(didWill, op, isFromClient) { + var newP = _.clone(op.p); + // var children = Ember.get(context, '_children'); + var children = context.get('_children'); + var childrenKeys = Object.keys(children); + if (Ember.isEmpty(childrenKeys)) + return; + var child, + utils = this; + var counterToChild = _.mapKeys(children, function(v, childKey) { + if (utils.isOpOnArray(op) && !isNaN(+ _.last(childKey.split('.')))) + return 0 + else + return utils.matchingPaths(utils.cutLast(childKey.split('.'), op), op.p) + }); + var toNumber = function(strings) { + return _.map(strings, function(s) { + return + s + }) + }; + var chosenChild = counterToChild[_.max(toNumber(Object.keys(counterToChild)))] + if (didWill == 'Will') + chosenChild.trigger('before op', [op], isFromClient); + if (didWill == 'Did') + chosenChild.trigger('op', [op], isFromClient); + } + , + + beforeAfter: function(didWill) { + var utils = this; + var ex; + return function(ops, isFromClient) { + // console.log( _.first (ops)); + + if (!isFromClient) { + _.forEach(ops, function(op) { + // if (didWill == 'Did') + // console.log(Ember.get(context,'_prefix') + ' recieved log'); + if (utils.comparePathToChildren(op.p, op)) { + utils.triggerChildren(didWill, op, isFromClient); + } else { + if (utils.isOpOnArray(op)) { + ex = utils.extractArrayPath(op); + + // console.log(Ember.get(context,'_prefix') + ' perform log'); + // console.log('op came to parent'); + context.get(ex.p)["arrayContent" + didWill + "Change"](ex.idx, ex.removeAmt, ex.addAmt) + } else { + context["property" + didWill + "Change"](utils.prefixToChildLimiations(op.p.join('.'))); + } + } + }); + } + }; + }, + + beforeAfterChild: function(didWill) { + var utils = this; + var ex, + prefix, + _idx; + return function(ops, isFromClient) { + if (((_idx = Ember.get(context, '_idx')) != null) || !isFromClient) { + _.forEach(ops, function(op) { + + if (op.p.join('.') == (prefix = Ember.get(context, '_prefix')) && didWill == 'Did') { + if (op.oi != null) { + context.replaceContent(op.oi, true) + } else { + if (op.od != null) { + var fatherPrefix = prefix.split('.'); + var key = fatherPrefix.pop(); + var father; + if (!_.isEmpty(fatherPrefix) && (father = context.get('_children.' + fatherPrefix.join('.')))) + father.removeKey(key); + else + context.get('_root').propertyDidChange(prefix) + } + } + } else { + var path = (_idx == null) + ? prefix.split('.') + : prefix.split('.').concat(String(_idx)); + var newP = _.difference(op.p, path); + if (utils.comparePathToPrefix(op.p.join('.'), prefix)) { + if (utils.isOpOnArray(op) && (Ember.get(context, '_idx') == null)) { + + var newOp = _.clone(op); + newOp.p = newP; + ex = utils.extractArrayPath(newOp); + + if (ex.p == "") + context["arrayContent" + didWill + "Change"](ex.idx, ex.removeAmt, ex.addAmt) + else + Ember.get(context, ex.p)["arrayContent" + didWill + "Change"](ex.idx, ex.removeAmt, ex.addAmt); + } + else { + if (newP.join('.') == '') { + + // delete self from father + if (false && _.isEmpty(newOp) && op.od && (op.oi == null) && (_.isEqual(op.od, context.toJson()))) { + var keyToRemove = path.pop(); + if (_.isEmpty(path)) { + utils.removeChildren(keyToRemove); + } + else { + var father = context.get('_children')[path.join('.')]; + father.removeKey (keyToRemove); + } + } + else { + context["property" + didWill + "Change"]('content'); + } + } + + else { + + if (op.oi && op.od == null) + context.addKey(_.first(newP)) + + if (op.od && op.oi == null) + context.removeKey(_.first(newP)) + + context["property" + didWill + "Change"](utils.prefixToChildLimiations(newP.join('.'))); + } + } + } + } + }); + } + } + }, + + findMaxIndex: function (arr) { + return arr.indexOf(_.max(arr)) + }, + + extractArrayPath: function(op) { + return { + idx: + _.last(op.p), + p: _.slice(op.p, 0, op.p.length - 1).join('.'), + addAmt: op.li != null + ? 1 + : 0, + removeAmt: op.ld != null + ? 1 + : 0 + } + } + + } + } }); define("ember-share/store", ["./utils","exports"], function(__dependency1__, __exports__) { "use strict"; - /* global BCSocket:false, sharejs:false */ + /* global BCSocket:false, sharedb:false */ var guid = __dependency1__.guid; var patchShare = __dependency1__.patchShare; var Promise = Ember.RSVP.Promise; + var socketReadyState = [ + 'CONNECTING', + 'OPEN', + 'CLOSING', + 'CLOSE' + ] - __exports__["default"] = Ember.Object.extend({ + __exports__["default"] = Ember.Object.extend(Ember.Evented, { socket: null, connection: null, - url : 'http://'+window.location.hostname, + + // port: 3000, + // url : 'https://qa-e.optibus.co', + url : window.location.hostname, init: function () { - this.checkConnection = Ember.Deferred.create({}); + var store = this; + + this.checkSocket = function () { + return new Promise(function (resolve, reject) { + + if (store.socket == null) { + store.one('connectionOpen', resolve); + } + else { + var checkState = function (state, cb) { + switch(state) { + case 'connected': + return resolve(); + case 'connecting': + return store.connection.once('connected', resolve); + default: cb(state) + } + } + var checkStateFail = function (state) { + switch(state) { + case 'closed': + return reject('connection closed'); + case 'disconnected': + return reject('connection disconnected'); + case 'stopped': + return reject('connection closing'); + } + } + var failed = false + checkState(store.connection.state, function(state){ + if (failed) + checkStateFail(state) + else + Ember.run.next (this, function () { + failed = true; + checkState(store.connection.state, checkStateFail) + }) + }) + + + } + }); + } + + this.checkConnection = function () { + return new Promise(function (resolve, reject) { + return store.checkSocket() + .then(function () { + return resolve() + if (store.authentication != null && store.isAuthenticated != null) { + if (store.isAuthenticated) return resolve(); + if (store.isAuthenticating) return store.one('authenticated', resolve); + if (!store.isAuthenticated) return store.authentication(store.connection.id) + // if (!store.isAuthenticating) return reject() + return reject('could not authenticat') + } else + return resolve() + }) + .catch(function (err) { + return reject(err) + }) + }); + }; + this.cache = {}; - if(!window.sharejs) + if(!window.sharedb) { - throw new Error("ShareJS client not included"); + throw new Error("sharedb client not included"); } if (window.BCSocket === undefined && window.Primus === undefined) { throw new Error("No Socket library included"); @@ -365,55 +1253,100 @@ define("ember-share/store", { this.beforeConnect() .then(function(){ - Ember.sendEvent(store,'connect'); + store.trigger('connect'); }); } else { - Ember.sendEvent(this,'connect'); + store.trigger('connect'); } }, - doConnect : function(){ + doConnect : function(options){ var store = this; - + if(window.BCSocket) { + this.setProperties(options); this.socket = new BCSocket(this.get('url'), {reconnect: true}); this.socket.onerror = function(err){ - Ember.sendEvent(store,'connectionError',[err]); + store.trigger('connectionError', [err]); + }; this.socket.onopen = function(){ - store.checkConnection.resolve(); - Ember.sendEvent(store,'connectionOpen'); + store.trigger('connectionOpen'); + }; this.socket.onclose = function(){ - Ember.sendEvent(store,'connectionEnd'); + store.trigger('connectionEnd'); }; } else if(window.Primus) { patchShare(); - this.socket = new Primus(this.get('url')); + this.setProperties(options); + var hostname = this.get('url'); + if (this.get('protocol')) + hostname = this.get('protocol') + '://' + hostname; + if (this.get("port")) + hostname += ':' + this.get('port'); + this.socket = new Primus(hostname); + // console.log('connection starting'); + this.socket.on('error', function error(err) { - Ember.sendEvent(store,'connectionError',[err]); + store.trigger('connectionError', [err]); }); this.socket.on('open', function() { - store.checkConnection.resolve(); - Ember.sendEvent(store,'connectionOpen'); + // console.log('connection open'); + store.trigger('connectionOpen'); }); this.socket.on('end', function() { - Ember.sendEvent(store,'connectionEnd'); + store.trigger('connectionEnd'); + }); + this.socket.on('close', function() { + store.trigger('connectionEnd'); }); } else { throw new Error("No Socket library included"); } - this.connection = new sharejs.Connection(this.socket); - + var oldHandleMessage = sharedb.Connection.prototype.handleMessage; + var oldSend = sharedb.Connection.prototype.send; + + store.on('connectionEnd', function () { + // console.log('ending connection'); + store.isAuthenticated = false + }) + + sharedb.Connection.prototype.handleMessage = function(message) { + var athenticating, handleMessageArgs; + handleMessageArgs = arguments; + // console.log(message.a); + var context = this; + oldHandleMessage.apply(context, handleMessageArgs); + if (message.a === 'init' && (typeof message.id === 'string') && message.protocol === 1 && typeof store.authenticate === 'function') { + store.isAuthenticating = true; + return store.authenticate(message.id) + .then(function() { + console.log('authenticated !'); + store.isAuthenticating = false; + store.isAuthenticated = true; + store.trigger('authenticated') + }) + .catch(function (err) { + store.isAuthenticating = false; + // store.socket.end() + // debugger + }) + } + }; + + this.connection = new sharedb.Connection(this.socket); + }.on('connect'), find: function (type, id) { + type = type.pluralize() var store = this; - return this.checkConnection + return this.checkConnection() .then(function(){ return store.findQuery(type, {_id: id}).then(function (models) { return models[0]; @@ -423,63 +1356,143 @@ define("ember-share/store", }); }, createRecord: function (type, data) { + var ref, path; + path = (ref = this._getPathForType(type)) ? ref : type.pluralize() + path = this._getPrefix(type) + path; + type = type.pluralize() var store = this; - return store.checkConnection + return store.checkConnection() .then(function(){ - var doc = store.connection.get(type, guid()); + var doc = store.connection.get(path, data.id == null ? guid() : data.id); return Promise.all([ store.whenReady(doc).then(function (doc) { return store.create(doc, data); }), store.subscribe(doc) ]).then(function () { - return store._createModel(type, doc); + var model = store._createModel(type, doc); + store._cacheFor(type).addObject(model); + return model }); }); }, - deleteRecord : function(model) { - // TODO: delete and cleanup caches - // model._context.context._doc.del() + deleteRecord : function(type, id) { + var cache = this._cacheFor(type.pluralize()); + var model = cache.findBy('id', id); + var doc = model.get('doc'); + return new Promise(function (resolve, reject) { + doc.del(function (err) { + if (err != null) + reject(err) + else { + resolve() + } + }); + }) + }, + findAndSubscribeQuery: function(type, query) { + type = type.pluralize() + var store = this; + var prefix = this._getPrefix(type); + store.cache[type] = [] + + return this.checkConnection() + .then(function(){ + return new Promise(function (resolve, reject) { + function fetchQueryCallback(err, results, extra) { + if (err !== null) { + return reject(err); + } + resolve(store._resolveModels(type, results)); + } + query = store.connection.createSubscribeQuery(prefix + type, query, null, fetchQueryCallback); + query.on('insert', function (docs) { + store._resolveModels(type, docs) + }); + query.on('remove', function (docs) { + for (var i = 0; i < docs.length; i++) { + var modelPromise = store._resolveModel(type, docs[i]); + modelPromise.then(function (model) { + store.unload(type, model) + }); + } + }); + }); + }); + }, + findRecord: function (type, id) { + var store = this; + return new Promise(function (resolve, reject){ + store.findQuery(type, {_id: id}) + .then(function(results){ + resolve(results[0]) + }) + .catch(function (err){ + reject(err) + }); + }) }, findQuery: function (type, query) { + // type = type.pluralize() + var ref, path; + path = (ref = this._getPathForType(type)) ? ref : type.pluralize() + path = this._getPrefix(type) + path; var store = this; - return this.checkConnection + store.cache[type.pluralize()] = [] + return this.checkConnection() .then(function(){ return new Promise(function (resolve, reject) { function fetchQueryCallback(err, results, extra) { - if (err !== undefined) { + if (err !== null) { return reject(err); } resolve(store._resolveModels(type, results)); } - store.connection.createFetchQuery(type, query, null, fetchQueryCallback); + store.connection.createFetchQuery(path, query, null, fetchQueryCallback); }); }); }, - findAll: function (type) { + findAll: function (type, query) { + type = type.pluralize() throw new Error('findAll not implemented'); // TODO this.connection subscribe style query }, _cacheFor: function (type) { + type = type.pluralize() var cache = this.cache[type]; if (cache === undefined) { - this.cache[type] = cache = {}; + this.cache[type] = cache = []; } return cache; }, + _getPathForType: function (type) { + var Adapter = this.container.lookupFactory('adapter:' + type.singularize()); + if (Adapter) + return Adapter.create().pathForType(); + }, + _getPrefix: function (type) { + var Adapter = this.container.lookupFactory('adapter:' + type.singularize()); + var prefix; + if (Adapter) + prefix = Adapter.create().get('prefix'); + if (!prefix) prefix = ''; + return prefix + }, _factoryFor: function (type) { - return this.container.lookupFactory('model:'+type); + var ref; + var modelStr = (ref = this.get('modelStr')) ? ref : 'model-sdb' + return this.container.lookupFactory(modelStr + ':'+ type.singularize()); }, _createModel: function (type, doc) { - var cache = this._cacheFor(type); var modelClass = this._factoryFor(type); + type = type.pluralize() if(modelClass) { var model = modelClass.create({ - id: doc.name, - _context: doc.createContext().createContextAt() + doc: doc, + _type: type, + _store: this }); - cache[doc.name] = model; return model; } else @@ -488,8 +1501,9 @@ define("ember-share/store", } }, _resolveModel: function (type, doc) { - var cache = this._cacheFor(type); - var model = cache[doc.name]; + var cache = this._cacheFor(type.pluralize()); + var id = Ember.get(doc, 'id') || Ember.get(doc, '_id'); + var model = cache.findBy('id', id); if (model !== undefined) { return Promise.resolve(model); } @@ -499,24 +1513,68 @@ define("ember-share/store", }); }, _resolveModels: function (type, docs) { + // type = type.pluralize() + var store = this; + var cache = this._cacheFor(type.pluralize()); var promises = new Array(docs.length); for (var i=0; i + // options = {}; type = null + // _.forEach arguments, (arg) -> + // if _.isPlainObject(arg) + // options = arg + // else + // if _.isString arg + // type = null + // + // Ember.computed + // get: (k) -> + // @get "doc.data.#{k}" ? Ember.get(options, 'defaultValue') + // set: (p, oi, isFromServer) -> + // if type? + // oi = window[type.toUpperCase type] oi + // od = @get p + // p = p.split '.' + // @get('doc').submitOp [{p,od,oi}] + // oi }); define("ember-share/mixins/share-text", ["../utils","exports"], @@ -202,216 +247,1005 @@ define("ember-share/mixins/share-text", } }); }); -define("ember-share/models/share-array", - ["./share-proxy","exports"], - function(__dependency1__, __exports__) { +define("ember-share/models/base", + ["./use-subs-mixin","./sub-mixin","./sub-array","./subs-handler","./utils","exports"], + function(__dependency1__, __dependency2__, __dependency3__, __dependency4__, __dependency5__, __exports__) { "use strict"; - var ShareProxy = __dependency1__["default"]; + var UseSubsMixin = __dependency1__["default"]; + var SubMixin = __dependency2__["default"]; + var SDBSubArray = __dependency3__["default"]; + var subs = __dependency4__["default"]; + var Utils = __dependency5__["default"]; - __exports__["default"] = Ember.Object.extend(Ember.MutableArray, { - _context: null, - _cache: null, - itemType: 'share-proxy', - init: function () { - this._cache = []; // cache wrapped objects - this._factory = this.container.lookupFactory('model:'+this.itemType); - // TODO subscribe to array ops on context - var _this = this; - this._context.on('delete', function (index, removed) { - _this.arrayContentWillChange(index, 1, 0); - - _this._cache.splice(index, 1); - - // update paths - var depth = _this._context.path.length; - _this._cache.forEach(function(item,idx){ - item._context.path[depth]= idx; - }) - _this.arrayContentDidChange(index, 1, 0); - }); - this._context.on('insert', function (index, value) { - _this.arrayContentWillChange(index, 0, 1); + var toJson = function(obj) { + return (obj == null) + ? void 0 + : JSON.parse(JSON.stringify(obj)); + }; - var model = _this._factory.create({ - _context: _this._context.createContextAt(index) - }); + var getPlainObject = function (value) { + if (value != null && !((typeof value == 'string') || (typeof value == 'number'))) + if (typeof value.toJson == 'function') + return value.toJson() + else + return toJson(value) + else { + return value + } + } - _this._cache.splice(index, 0, model); - // update paths - var depth = _this._context.path.length; - _this._cache.forEach(function(item,idx){ - item._context.path[depth]= idx; - }); - _this.arrayContentDidChange(index, 0, 1); - }); - }, - length: function () { - return this._context.get().length; - }.property().volatile(), - objectAt: function (index) { - if (this._cache[index] === undefined && this._context.get(index) !== undefined) { - this._cache[index] = this._factory.create({ - _context: this._context.createContextAt(index) - }); - } - return this._cache[index]; - }, - replace: function (index, length, objects) { - var objectsLength = objects.length; - var args = new Array(objectsLength+2); - var model; - args[0] = index; - args[1] = length; + // + // ShareDb Base Class + // + // Root and all subs (currently not arrays) inherit from base. + // + // - this.arrayContentWillChange(index, length, objectsLength); + var GetterSettersMixin = Ember.Mixin.create({ - if (length > 0) { - this._context.remove([index], length); - } + _get: function(k, selfCall) { + var firstValue = _.first(k.split('.')); - for (var i=0; i objects.length) + ? len + : objects.length; + for (var i = 0; i < iterationLength; i++) { + var newIndex = i + start; + var obj = objects.objectAt(i); + this._submitOp(newIndex, obj, (len > i + ? this.objectAt(newIndex) + : null)) + } + this.arrayContentDidChange(start, len, objects.length); + return this //._super(start, len, objects) + }, + + onChangeDoc: (function () { + // debugger + // this.set ('content', this.get('doc.data.' + this.get('_prefix'))) + // Ember.run.next (this, function () P{}) + this.replaceContent(this.get('doc.data.' + this.get('_prefix')), true) + }).observes('doc') + }); + } + }); +define("ember-share/models/sub-mixin", + ["./utils","../attr","exports"], + function(__dependency1__, __dependency2__, __exports__) { + "use strict"; + var Utils = __dependency1__["default"]; + var attrs = __dependency2__["default"]; + + var allButLast = function(arr) { + return arr.slice(0, arr.length - 1) + }; + + // + // Sub Mixin + // + // All subs use this mixin (Object and Array) + // + // + + __exports__["default"] = Ember.Mixin.create({ + + _children: (function() { + return {} + }).property(), + + _sdbProps: (function() { + return [] + }).property(), + + _subProps: (function() { + return [] + }).property(), + + doc: Ember.computed.reads('_root.doc'), + + createInnerAttrs: (function() { + var tempContent = Ember.get(this, 'tempContent'); + var self = this; + var attr = attrs('_subProps'); + var keys = []; + + _.forEach(tempContent, function(value, key) { + keys.push(key); + Ember.defineProperty(self, key, attr()); + }) + + Ember.get(this, '_subProps').addObjects(keys); + delete this['tempContent']; + }).on('init'), + + beforeFn: (function (){return []}).property(), + afterFn: (function (){return []}).property(), + + activateListeners: (function() { + var utils = Utils(this); + + var beforeFn = utils.beforeAfterChild("Will"); + var afterFn = utils.beforeAfterChild("Did"); + + if (this.has('before op')) { + this.off('before op', this.get('beforeFn').pop()) + } + if (this.has('op')) { + this.off('op', this.get('afterFn').pop()) + } + this.on('before op', beforeFn); + this.on('op', afterFn); + + this.get('beforeFn').push(beforeFn); + this.get('afterFn').push(afterFn); + + // }).on('init'), + }).observes('doc').on('init'), + + _fullPath: function(path) { + var prefix = Ember.get(this, '_prefix'); + var idx = Ember.get(this, '_idx'); + + if (prefix) { + if (idx != null) { + return prefix + '.' + idx + '.' + path + } else { + return prefix + '.' + path; + } + } else + return path; + } + , + + deleteProperty: function(k) { + this.removeKey(k); + return this._super(this._fullPath(k)) + }, + + replaceContent: function(content, noSet) { + this.notifyWillProperties(this.get('_subProps').toArray()); + var prefix = this.get('_prefix'); + var idx = this.get('_idx') + var path = (idx == null) ? prefix : prefix + '.' + idx + + if (!noSet) + this._set(path, content); + + var self = this; + var utils = Utils(this); + + utils.removeChildren(path); + + if (_.isEmpty(Object.keys(this))) { + Ember.setProperties(this, {tempContent: content}); + this.createInnerAttrs(); + + var notifyFather = function (prefixArr, keys) { + if (_.isEmpty(prefixArr)) + self.get('_root').notifyPropertyChange(keys.join('.')) + else { + var child = self.get['_children'][prefixArr.join('.')] + if (child != null) + child.notifyPropertyChange(prefixArr.join('.') + '.' + keys.join('.')) + else + keys.push(prefixArr.pop()); + notifyFather(prefixArr, keys); + } + }; + var prefixArr = prefix.split('.') + var key = prefixArr.pop() + + notifyFather(prefixArr, [key]); + } + else { + if (_.isPlainObject(content)) + var toDelete = _.difference(Object.keys(this), Object.keys(content)) + else + var toDelete = Object.keys(this); + + _.forEach(toDelete, function(prop) { + delete self[prop] + }); + this.get('_subProps').removeObjects(toDelete); + Ember.setProperties(this, {tempContent: content}); + this.createInnerAttrs(); + this.notifyDidProperties(this.get('_subProps').toArray()); + } + + return this + }, + + toJson: function() { + var idx = Ember.get(this, '_idx'), + k = Ember.get(this, '_prefix'); + var path = (idx == null) + ? k + : (k + '.' + idx); + return this.get('doc.data.' + path); + }, + + addKey: function (key) { + var attr = attrs('_subProps'); + if (!(this.get('_subProps').indexOf(key) > -1)) + Ember.defineProperty(this, key, attr()); + return this + }, + + removeKey: function (key) { + var attr = attrs('_subProps'); + var utils = Utils(this); + utils.removeChildren(key, true); + this.get('_subProps').removeObject(key); + delete this[key]; + return this + }, + + removeListeners: function () { + this.off('before op', this.get('beforeFn')) + this.off('op', this.get('afterFn')) + + } + + }) + }); +define("ember-share/models/subs-handler", ["exports"], function(__exports__) { "use strict"; - var isArray = Array.isArray || function (obj) { - return obj instanceof Array; - }; + // + // Subs Handler + // + // since we have a recursive model structure there is a need for + // creating the subs in a common place and then reuse it in its own class. + // + // - __exports__["default"] = Ember.Object.extend({ - _context: null, - _cache: null, - init: function () { - this._cache = {}; // allows old value to be seen on willChange event - var _this = this; - this._context.on('replace', function (key, oldValue, newValue) { - _this.propertyWillChange(key); - _this._cache[key] = _this.wrapObject(key, newValue); - _this.propertyDidChange(key); - }); - this._context.on('insert', function (key, value) { - _this.propertyWillChange(key); - _this._cache[key] = _this.wrapObject(key, value); - _this.propertyDidChange(key); - }); - this._context.on('child op', function (key, op) { - // handle add operations - if(key.length === 1 && op.na) - { - _this.propertyWillChange(key[0]); - _this._cache[key] = (_this._cache[key[0]] || _this.get(key[0]) || 0) + op.na; - _this.propertyDidChange(key[0]); - } - }); - }, - unknownProperty: function (key) { - var value = this._cache[key]; - if (value === undefined) { - value = this._cache[key] = this.wrapObject(key, this._context.get([key])); - } - return value; - }, - setUnknownProperty: function (key, value) { - if (this._cache[key] !== value) { - this.propertyWillChange(key); - this._cache[key] = this.wrapObject(key, value); - this._context.set([key], value); - this.propertyDidChange(key); - } - }, - wrapObject: function (key, value) { - if (value !== null && typeof value === 'object') { - var type = this.wrapLookup(key,value); - var factory = this.container.lookupFactory('model:'+type); - return factory.create({ - _context: this._context.createContextAt(key) - }); - } - return value; - }, - wrapLookup : function(key,value) { - return value.type || (isArray(value) ? 'share-array' : 'share-proxy'); - }, - willDestroy: function () { - this._cache = null; - this._context.destroy(); - this._context = null; - }, - toJSON: function () { - return this._context.get(); - }, - incrementProperty: function(key, increment) { - if (Ember.isNone(increment)) { increment = 1; } - Ember.assert("Must pass a numeric value to incrementProperty", (!isNaN(parseFloat(increment)) && isFinite(increment))); - this.propertyWillChange(key); - this._cache[key] = (this._cache[key] || this.get(key) || 0) + increment; - if(this._context.get([key]) !== undefined) - { - this._context.add([key], increment); - } - else - { - this._context.set([key], this._cache[key]); - } - this.propertyDidChange(key); - return this._cache[key]; - }, - decrementProperty: function(key, decrement) { - if (Ember.isNone(decrement)) { decrement = 1; } - Ember.assert("Must pass a numeric value to decrementProperty", (!isNaN(parseFloat(decrement)) && isFinite(decrement))); - this.propertyWillChange(key); - this._cache[key] = (this._cache[key] || this.get(key) || 0) - decrement; - if(this._context.get([key]) !== undefined) - { - this._context.add([key], -1 * decrement); - } - else - { - this._context.set([key], this._cache[key]); - } - this.propertyDidChange(key); - return this._cache[key]; - }, - }); + __exports__["default"] = { + object : {}, + array : {} + } + }); +define("ember-share/models/use-subs-mixin", + ["./subs-handler","./utils","exports"], + function(__dependency1__, __dependency2__, __exports__) { + "use strict"; + var subs = __dependency1__["default"]; + var Utils = __dependency2__["default"];__exports__["default"] = Ember.Mixin.create({ + + useSubs: function useSubs(content, k, idx) { + var utils = Utils(this); + + if (utils.matchChildToLimitations(k)) + return content; + + if (_.isPlainObject(content)) { + content = { + tempContent: content + }; + var use = 'object' + + } else if (_.isArray(content)) { + content = { + content: content + }; + var use = 'array'; + } + if (use) { + var child, + _idx; + var path = (idx == null) ? k : (k + '.' + idx); + var ownPath = Ember.get(this, '_prefix'); + if ((_idx = Ember.get(this, '_idx')) != null) + ownPath += '.' + _idx; + if (path == ownPath) { + return this; + } + + var children = Ember.get(this, '_children'); + var childrenKeys = Object.keys(children); + + if (_.includes(childrenKeys, path)) + return children[path] + else + child = {}; + + var sub = subs[use].extend({ + // doc: this.get('doc'), + _children: Ember.get(this, '_children'), + _prefix: k, + _idx: idx, + _sdbProps: Ember.get(this, '_sdbProps'), + _root: Ember.get(this,'_root') + }); + + sub = sub.create(content); + + child[path] = sub; + _.assign(Ember.get(this, '_children'), child); + + return sub + } else + return content + } + }) + }); +define("ember-share/models/utils", + ["exports"], + function(__exports__) { + "use strict"; + __exports__["default"] = function(context) { + + return { + + isOpOnArray: function(op) { + return (op.ld != null) || (op.lm != null) || (op.li != null) + }, + + matchingPaths: function(as, bs) { + var counter = 0; + var higherLength = (as.length > bs.length) + ? as.length + : bs.length + while ((as[counter] == '*' || as[counter] == bs[counter]) && counter < higherLength) { + counter++ + } + return counter - (as.length / 1000) + }, + + matchChildToLimitations: function (key) { + var childLimiations = Ember.get(context, '_root._childLimiations'); + var prefix = Ember.get(context, '_prefix') + + if (prefix == null || key.match(prefix)) + prefix = key + else + prefix += '.' + key + + prefix = prefix.split('.'); + var self = this; + return _.some (childLimiations, function (_limit) { + var limit = _limit.split('/'); + return prefix.length == limit.length && Math.ceil(self.matchingPaths(limit, prefix)) == prefix.length + }) + }, + + prefixToChildLimiations: function (key) { + var childLimiations = Ember.get(context, '_root._childLimiations'); + var prefix = Ember.get(context, '_prefix') + + if (prefix == null || key.match(prefix)) + prefix = key + else + prefix += '.' + key + + prefix = prefix.split('.'); + var self = this, limiationsArray; + + var relevantLimitIndex = this.findMaxIndex(limiationsArray = _.map (childLimiations, function (_limit) { + var limit = _limit.split('/'); + var result = Math.ceil(self.matchingPaths(limit, prefix)) + return result < limit.length ? 0 : result + })); + if (relevantLimitIndex >= 0 && limiationsArray[relevantLimitIndex] > 0) { + var relevantLimit = childLimiations[relevantLimitIndex].split('/'); + var orignalPrefix; + var result = prefix.slice(0, Math.ceil(self.matchingPaths(relevantLimit, prefix)) ); + if (orignalPrefix = Ember.get(context, '_prefix')) { + orignalPrefix = orignalPrefix.split('.'); + return result.slice(orignalPrefix.length) + } else + return result.join('.'); + } + else { + return key; + } + + }, + + removeChildren: function (path, includeSelf) { + var children = Ember.get(context, '_children'); + var childrenKeys = Object.keys(children); + var prefix = context.get('_prefix'); + var utils = this; + + if ((prefix != null) && path && path.indexOf(prefix) != 0) { + path = prefix + '.' + path + } + + if (path) { + childrenKeys = _.reduce(childrenKeys, function(result, key) { + var matches = Math.ceil(utils.matchingPaths(key.split('.'), path.split('.'))) + if (includeSelf && (matches >= path.split('.').length) || + (!includeSelf && (matches > path.split('.').length))) + result.push(key); + return result + }, []); + } + + _.forEach (childrenKeys, function (key) { + children[key].destroy() + delete children[key] + }) + }, + + comparePathToPrefix: function(path, prefix) { + return Boolean(Math.ceil(this.matchingPaths(path.split('.'), prefix.split('.')))) + }, + + cutLast: function(path, op) { + var tempPath; + if (this.isOpOnArray(op) && !isNaN(+ _.last(path))) { + tempPath = _.clone(path); + tempPath.pop(); + } + return (tempPath) + ? tempPath + : path + }, + + comparePathToChildren: function(path, op) { + var utils = this; + var children = Ember.get(context, '_children'); + var childrenKeys = Object.keys(children); + var hasChildren = _.some(childrenKeys, function(childKey) { + var pathsCounter = utils.matchingPaths(childKey.split('.'), utils.cutLast(path, op)) + return Math.ceil(pathsCounter) == childKey.split('.').length + }); + return !Ember.isEmpty(childrenKeys) && hasChildren + }, + + triggerChildren: function(didWill, op, isFromClient) { + var newP = _.clone(op.p); + // var children = Ember.get(context, '_children'); + var children = context.get('_children'); + var childrenKeys = Object.keys(children); + if (Ember.isEmpty(childrenKeys)) + return; + var child, + utils = this; + var counterToChild = _.mapKeys(children, function(v, childKey) { + if (utils.isOpOnArray(op) && !isNaN(+ _.last(childKey.split('.')))) + return 0 + else + return utils.matchingPaths(utils.cutLast(childKey.split('.'), op), op.p) + }); + var toNumber = function(strings) { + return _.map(strings, function(s) { + return + s + }) + }; + var chosenChild = counterToChild[_.max(toNumber(Object.keys(counterToChild)))] + if (didWill == 'Will') + chosenChild.trigger('before op', [op], isFromClient); + if (didWill == 'Did') + chosenChild.trigger('op', [op], isFromClient); + } + , + + beforeAfter: function(didWill) { + var utils = this; + var ex; + return function(ops, isFromClient) { + // console.log( _.first (ops)); + + if (!isFromClient) { + _.forEach(ops, function(op) { + // if (didWill == 'Did') + // console.log(Ember.get(context,'_prefix') + ' recieved log'); + if (utils.comparePathToChildren(op.p, op)) { + utils.triggerChildren(didWill, op, isFromClient); + } else { + if (utils.isOpOnArray(op)) { + ex = utils.extractArrayPath(op); + + // console.log(Ember.get(context,'_prefix') + ' perform log'); + // console.log('op came to parent'); + context.get(ex.p)["arrayContent" + didWill + "Change"](ex.idx, ex.removeAmt, ex.addAmt) + } else { + context["property" + didWill + "Change"](utils.prefixToChildLimiations(op.p.join('.'))); + } + } + }); + } + }; + }, + + beforeAfterChild: function(didWill) { + var utils = this; + var ex, + prefix, + _idx; + return function(ops, isFromClient) { + if (((_idx = Ember.get(context, '_idx')) != null) || !isFromClient) { + _.forEach(ops, function(op) { + + if (op.p.join('.') == (prefix = Ember.get(context, '_prefix')) && didWill == 'Did') { + if (op.oi != null) { + context.replaceContent(op.oi, true) + } else { + if (op.od != null) { + var fatherPrefix = prefix.split('.'); + var key = fatherPrefix.pop(); + var father; + if (!_.isEmpty(fatherPrefix) && (father = context.get('_children.' + fatherPrefix.join('.')))) + father.removeKey(key); + else + context.get('_root').propertyDidChange(prefix) + } + } + } else { + var path = (_idx == null) + ? prefix.split('.') + : prefix.split('.').concat(String(_idx)); + var newP = _.difference(op.p, path); + if (utils.comparePathToPrefix(op.p.join('.'), prefix)) { + if (utils.isOpOnArray(op) && (Ember.get(context, '_idx') == null)) { + + var newOp = _.clone(op); + newOp.p = newP; + ex = utils.extractArrayPath(newOp); + + if (ex.p == "") + context["arrayContent" + didWill + "Change"](ex.idx, ex.removeAmt, ex.addAmt) + else + Ember.get(context, ex.p)["arrayContent" + didWill + "Change"](ex.idx, ex.removeAmt, ex.addAmt); + } + else { + if (newP.join('.') == '') { + + // delete self from father + if (false && _.isEmpty(newOp) && op.od && (op.oi == null) && (_.isEqual(op.od, context.toJson()))) { + var keyToRemove = path.pop(); + if (_.isEmpty(path)) { + utils.removeChildren(keyToRemove); + } + else { + var father = context.get('_children')[path.join('.')]; + father.removeKey (keyToRemove); + } + } + else { + context["property" + didWill + "Change"]('content'); + } + } + + else { + + if (op.oi && op.od == null) + context.addKey(_.first(newP)) + + if (op.od && op.oi == null) + context.removeKey(_.first(newP)) + + context["property" + didWill + "Change"](utils.prefixToChildLimiations(newP.join('.'))); + } + } + } + } + }); + } + } + }, + + findMaxIndex: function (arr) { + return arr.indexOf(_.max(arr)) + }, + + extractArrayPath: function(op) { + return { + idx: + _.last(op.p), + p: _.slice(op.p, 0, op.p.length - 1).join('.'), + addAmt: op.li != null + ? 1 + : 0, + removeAmt: op.ld != null + ? 1 + : 0 + } + } + + } + } }); define("ember-share/store", ["./utils","exports"], function(__dependency1__, __exports__) { "use strict"; - /* global BCSocket:false, sharejs:false */ + /* global BCSocket:false, sharedb:false */ var guid = __dependency1__.guid; var patchShare = __dependency1__.patchShare; var Promise = Ember.RSVP.Promise; + var socketReadyState = [ + 'CONNECTING', + 'OPEN', + 'CLOSING', + 'CLOSE' + ] - __exports__["default"] = Ember.Object.extend({ + __exports__["default"] = Ember.Object.extend(Ember.Evented, { socket: null, connection: null, - url : 'http://'+window.location.hostname, + + // port: 3000, + // url : 'https://qa-e.optibus.co', + url : window.location.hostname, init: function () { - this.checkConnection = Ember.Deferred.create({}); + var store = this; + + this.checkSocket = function () { + return new Promise(function (resolve, reject) { + + if (store.socket == null) { + store.one('connectionOpen', resolve); + } + else { + var checkState = function (state, cb) { + switch(state) { + case 'connected': + return resolve(); + case 'connecting': + return store.connection.once('connected', resolve); + default: cb(state) + } + } + var checkStateFail = function (state) { + switch(state) { + case 'closed': + return reject('connection closed'); + case 'disconnected': + return reject('connection disconnected'); + case 'stopped': + return reject('connection closing'); + } + } + var failed = false + checkState(store.connection.state, function(state){ + if (failed) + checkStateFail(state) + else + Ember.run.next (this, function () { + failed = true; + checkState(store.connection.state, checkStateFail) + }) + }) + + + } + }); + } + + this.checkConnection = function () { + return new Promise(function (resolve, reject) { + return store.checkSocket() + .then(function () { + return resolve() + if (store.authentication != null && store.isAuthenticated != null) { + if (store.isAuthenticated) return resolve(); + if (store.isAuthenticating) return store.one('authenticated', resolve); + if (!store.isAuthenticated) return store.authentication(store.connection.id) + // if (!store.isAuthenticating) return reject() + return reject('could not authenticat') + } else + return resolve() + }) + .catch(function (err) { + return reject(err) + }) + }); + }; + this.cache = {}; - if(!window.sharejs) + if(!window.sharedb) { - throw new Error("ShareJS client not included"); + throw new Error("sharedb client not included"); } if (window.BCSocket === undefined && window.Primus === undefined) { throw new Error("No Socket library included"); @@ -420,55 +1254,100 @@ define("ember-share/store", { this.beforeConnect() .then(function(){ - Ember.sendEvent(store,'connect'); + store.trigger('connect'); }); } else { - Ember.sendEvent(this,'connect'); + store.trigger('connect'); } }, - doConnect : function(){ + doConnect : function(options){ var store = this; - + if(window.BCSocket) { + this.setProperties(options); this.socket = new BCSocket(this.get('url'), {reconnect: true}); this.socket.onerror = function(err){ - Ember.sendEvent(store,'connectionError',[err]); + store.trigger('connectionError', [err]); + }; this.socket.onopen = function(){ - store.checkConnection.resolve(); - Ember.sendEvent(store,'connectionOpen'); + store.trigger('connectionOpen'); + }; this.socket.onclose = function(){ - Ember.sendEvent(store,'connectionEnd'); + store.trigger('connectionEnd'); }; } else if(window.Primus) { patchShare(); - this.socket = new Primus(this.get('url')); + this.setProperties(options); + var hostname = this.get('url'); + if (this.get('protocol')) + hostname = this.get('protocol') + '://' + hostname; + if (this.get("port")) + hostname += ':' + this.get('port'); + this.socket = new Primus(hostname); + // console.log('connection starting'); + this.socket.on('error', function error(err) { - Ember.sendEvent(store,'connectionError',[err]); + store.trigger('connectionError', [err]); }); this.socket.on('open', function() { - store.checkConnection.resolve(); - Ember.sendEvent(store,'connectionOpen'); + // console.log('connection open'); + store.trigger('connectionOpen'); }); this.socket.on('end', function() { - Ember.sendEvent(store,'connectionEnd'); + store.trigger('connectionEnd'); + }); + this.socket.on('close', function() { + store.trigger('connectionEnd'); }); } else { throw new Error("No Socket library included"); } - this.connection = new sharejs.Connection(this.socket); - + var oldHandleMessage = sharedb.Connection.prototype.handleMessage; + var oldSend = sharedb.Connection.prototype.send; + + store.on('connectionEnd', function () { + // console.log('ending connection'); + store.isAuthenticated = false + }) + + sharedb.Connection.prototype.handleMessage = function(message) { + var athenticating, handleMessageArgs; + handleMessageArgs = arguments; + // console.log(message.a); + var context = this; + oldHandleMessage.apply(context, handleMessageArgs); + if (message.a === 'init' && (typeof message.id === 'string') && message.protocol === 1 && typeof store.authenticate === 'function') { + store.isAuthenticating = true; + return store.authenticate(message.id) + .then(function() { + console.log('authenticated !'); + store.isAuthenticating = false; + store.isAuthenticated = true; + store.trigger('authenticated') + }) + .catch(function (err) { + store.isAuthenticating = false; + // store.socket.end() + // debugger + }) + } + }; + + this.connection = new sharedb.Connection(this.socket); + }.on('connect'), find: function (type, id) { + type = type.pluralize() var store = this; - return this.checkConnection + return this.checkConnection() .then(function(){ return store.findQuery(type, {_id: id}).then(function (models) { return models[0]; @@ -478,63 +1357,143 @@ define("ember-share/store", }); }, createRecord: function (type, data) { + var ref, path; + path = (ref = this._getPathForType(type)) ? ref : type.pluralize() + path = this._getPrefix(type) + path; + type = type.pluralize() var store = this; - return store.checkConnection + return store.checkConnection() .then(function(){ - var doc = store.connection.get(type, guid()); + var doc = store.connection.get(path, data.id == null ? guid() : data.id); return Promise.all([ store.whenReady(doc).then(function (doc) { return store.create(doc, data); }), store.subscribe(doc) ]).then(function () { - return store._createModel(type, doc); + var model = store._createModel(type, doc); + store._cacheFor(type).addObject(model); + return model }); }); }, - deleteRecord : function(model) { - // TODO: delete and cleanup caches - // model._context.context._doc.del() + deleteRecord : function(type, id) { + var cache = this._cacheFor(type.pluralize()); + var model = cache.findBy('id', id); + var doc = model.get('doc'); + return new Promise(function (resolve, reject) { + doc.del(function (err) { + if (err != null) + reject(err) + else { + resolve() + } + }); + }) + }, + findAndSubscribeQuery: function(type, query) { + type = type.pluralize() + var store = this; + var prefix = this._getPrefix(type); + store.cache[type] = [] + + return this.checkConnection() + .then(function(){ + return new Promise(function (resolve, reject) { + function fetchQueryCallback(err, results, extra) { + if (err !== null) { + return reject(err); + } + resolve(store._resolveModels(type, results)); + } + query = store.connection.createSubscribeQuery(prefix + type, query, null, fetchQueryCallback); + query.on('insert', function (docs) { + store._resolveModels(type, docs) + }); + query.on('remove', function (docs) { + for (var i = 0; i < docs.length; i++) { + var modelPromise = store._resolveModel(type, docs[i]); + modelPromise.then(function (model) { + store.unload(type, model) + }); + } + }); + }); + }); + }, + findRecord: function (type, id) { + var store = this; + return new Promise(function (resolve, reject){ + store.findQuery(type, {_id: id}) + .then(function(results){ + resolve(results[0]) + }) + .catch(function (err){ + reject(err) + }); + }) }, findQuery: function (type, query) { + // type = type.pluralize() + var ref, path; + path = (ref = this._getPathForType(type)) ? ref : type.pluralize() + path = this._getPrefix(type) + path; var store = this; - return this.checkConnection + store.cache[type.pluralize()] = [] + return this.checkConnection() .then(function(){ return new Promise(function (resolve, reject) { function fetchQueryCallback(err, results, extra) { - if (err !== undefined) { + if (err !== null) { return reject(err); } resolve(store._resolveModels(type, results)); } - store.connection.createFetchQuery(type, query, null, fetchQueryCallback); + store.connection.createFetchQuery(path, query, null, fetchQueryCallback); }); }); }, - findAll: function (type) { + findAll: function (type, query) { + type = type.pluralize() throw new Error('findAll not implemented'); // TODO this.connection subscribe style query }, _cacheFor: function (type) { + type = type.pluralize() var cache = this.cache[type]; if (cache === undefined) { - this.cache[type] = cache = {}; + this.cache[type] = cache = []; } return cache; }, + _getPathForType: function (type) { + var Adapter = this.container.lookupFactory('adapter:' + type.singularize()); + if (Adapter) + return Adapter.create().pathForType(); + }, + _getPrefix: function (type) { + var Adapter = this.container.lookupFactory('adapter:' + type.singularize()); + var prefix; + if (Adapter) + prefix = Adapter.create().get('prefix'); + if (!prefix) prefix = ''; + return prefix + }, _factoryFor: function (type) { - return this.container.lookupFactory('model:'+type); + var ref; + var modelStr = (ref = this.get('modelStr')) ? ref : 'model-sdb' + return this.container.lookupFactory(modelStr + ':'+ type.singularize()); }, _createModel: function (type, doc) { - var cache = this._cacheFor(type); var modelClass = this._factoryFor(type); + type = type.pluralize() if(modelClass) { var model = modelClass.create({ - id: doc.name, - _context: doc.createContext().createContextAt() + doc: doc, + _type: type, + _store: this }); - cache[doc.name] = model; return model; } else @@ -543,8 +1502,9 @@ define("ember-share/store", } }, _resolveModel: function (type, doc) { - var cache = this._cacheFor(type); - var model = cache[doc.name]; + var cache = this._cacheFor(type.pluralize()); + var id = Ember.get(doc, 'id') || Ember.get(doc, '_id'); + var model = cache.findBy('id', id); if (model !== undefined) { return Promise.resolve(model); } @@ -554,24 +1514,68 @@ define("ember-share/store", }); }, _resolveModels: function (type, docs) { + // type = type.pluralize() + var store = this; + var cache = this._cacheFor(type.pluralize()); var promises = new Array(docs.length); for (var i=0; i +// options = {}; type = null +// _.forEach arguments, (arg) -> +// if _.isPlainObject(arg) +// options = arg +// else +// if _.isString arg +// type = null +// +// Ember.computed +// get: (k) -> +// @get "doc.data.#{k}" ? Ember.get(options, 'defaultValue') +// set: (p, oi, isFromServer) -> +// if type? +// oi = window[type.toUpperCase type] oi +// od = @get p +// p = p.split '.' +// @get('doc').submitOp [{p,od,oi}] +// oi diff --git a/lib/ember-share/models/base.js b/lib/ember-share/models/base.js new file mode 100644 index 0000000..3a331a4 --- /dev/null +++ b/lib/ember-share/models/base.js @@ -0,0 +1,142 @@ +import UseSubsMixin from './use-subs-mixin'; +import SubMixin from './sub-mixin'; +import SDBSubArray from './sub-array'; +import subs from './subs-handler'; +import Utils from './utils'; + +var toJson = function(obj) { + return (obj == null) + ? void 0 + : JSON.parse(JSON.stringify(obj)); +}; + +var getPlainObject = function (value) { + if (value != null && !((typeof value == 'string') || (typeof value == 'number'))) + if (typeof value.toJson == 'function') + return value.toJson() + else + return toJson(value) + else { + return value + } +} + +// +// ShareDb Base Class +// +// Root and all subs (currently not arrays) inherit from base. +// +// + +var GetterSettersMixin = Ember.Mixin.create({ + + _get: function(k, selfCall) { + var firstValue = _.first(k.split('.')); + + if (k != '_sdbProps' && _.includes(this.get('_sdbProps'), firstValue)) { + var content = this.get("doc.data." + k); + return this.useSubs(content, k) + } else { + return this.get(k); + } + }, + + _set: function(path, oi) { + var firstValue = _.first(path.split('.')); + var self = this; + + if (Ember.get(this, '_prefix') == null) + this.get(firstValue); + + if (path != '_sdbProps' && _.includes(this.get('_sdbProps'), firstValue)) { + var od = getPlainObject(this._get(path)); + oi = getPlainObject(oi); + var p = path.split('.'); + var utils = Utils(this); + utils.removeChildren(path, true); + var op = { + p: p, + od: od, + oi: oi + }; + + if (od == null) + delete op.od; + + if (op.oi != op.od) { + this.get('doc').submitOp([op], function(err) { + self.get('_root', true).trigger('submitted', err); + }); + } + + return this.useSubs(oi,path); + } else { + return this.set(path, oi, true) + + } + } + +}); +var SDBBase = Ember.Object.extend(Ember.Evented, GetterSettersMixin, { + + _isSDB: true, + + notifyProperties: function notifyProperties(props) { + var self = this; + _.forEach(props, function(prop) { + self.notifyPropertyChange(prop) + }) + return this + }, + + notifyDidProperties: function notifyDidProperties(props) { + var self = this; + _.forEach(props, function(prop) { + self.propertyDidChange(prop) + }) + return this + }, + + notifyWillProperties: function notifyWillProperties(props) { + var self = this; + _.forEach(props, function(prop) { + self.propertyWillChange(prop) + }) + return this + }, + + deleteProperty: function deleteProperty(k) { + var doc = this.get('doc'); + var p = k.split('.'); + var od = getPlainObject(this.get(k)); + doc.submitOp([ + { + p: p, + od: od + } + ]); + }, + + setProperties: function setProperties(obj) { + var sdbProps = this.get('_sdbProps'); + var self = this; + var SDBpropsFromObj = _.filter(_.keys(obj), function(key) { + self.get(key); + return _.includes(sdbProps, key) + }); + var nonSDB = _.reject(_.keys(obj), function(key) { + return _.includes(sdbProps, key) + }); + this._super(_.pick(obj, nonSDB)); + _.forEach(SDBpropsFromObj, function(key) { + self.set(key, obj[key]) + }); + }, + +}); + +SDBBase = SDBBase.extend(UseSubsMixin); +subs.object = SDBBase.extend(SubMixin); +subs.array = SDBSubArray(SubMixin, GetterSettersMixin).extend(UseSubsMixin); + +export default SDBBase diff --git a/lib/ember-share/models/model.js b/lib/ember-share/models/model.js new file mode 100755 index 0000000..c52dc54 --- /dev/null +++ b/lib/ember-share/models/model.js @@ -0,0 +1,66 @@ +import Utils from './utils'; +import SDBBase from './base'; + +// +// ShareDb Ember Model Class +// +// extends Base. +// this is model has a recursive structure, getting an inner object or array will return +// a sub object which is conencted to its parent. +// an over view of the entire structure can be found here: +// https://www.gliffy.com/go/share/sn1ehtp86ywtwlvhsxid +// +// + +var SDBRoot = SDBBase.extend({ + unload: function() { + return this.get('_store').unload(this.get('_type'), this); + }, + + id: Ember.computed.reads('doc.id'), + + _childLimiations: (function() { + return [] + }).property(), + + _root: (function() { + return this + }).property(), + + _children: (function() { + return {} + }).property(), + + _sdbProps: (function () { + return [] + }).property(), + + setOpsInit: (function() { + var doc = this.get('doc', true); + var oldDoc = this.get('oldDoc'); + var utils = Utils(this); + + if (oldDoc) { + oldDoc.destroy(); + } + // doc.on('before op', utils.beforeAfter("Will")); + doc.on('before component', utils.beforeAfter("Will")); + doc.on('after component', utils.beforeAfter("Did")); + // doc.on('op', utils.beforeAfter("Did")); + + this.set('oldDoc', doc); + + }).observes('doc').on('init'), + + + willDestroy: function () { + var utils = Utils(this); + this._super.apply(this, arguments) + utils.removeChildren(); + console.log('destroying children'); + } + +}); + + +export default SDBRoot diff --git a/lib/ember-share/models/share-proxy.js b/lib/ember-share/models/share-proxy.js deleted file mode 100755 index f98c0c2..0000000 --- a/lib/ember-share/models/share-proxy.js +++ /dev/null @@ -1,99 +0,0 @@ -var isArray = Array.isArray || function (obj) { - return obj instanceof Array; -}; - -export default Ember.Object.extend({ - _context: null, - _cache: null, - init: function () { - this._cache = {}; // allows old value to be seen on willChange event - var _this = this; - this._context.on('replace', function (key, oldValue, newValue) { - _this.propertyWillChange(key); - _this._cache[key] = _this.wrapObject(key, newValue); - _this.propertyDidChange(key); - }); - this._context.on('insert', function (key, value) { - _this.propertyWillChange(key); - _this._cache[key] = _this.wrapObject(key, value); - _this.propertyDidChange(key); - }); - this._context.on('child op', function (key, op) { - // handle add operations - if(key.length === 1 && op.na) - { - _this.propertyWillChange(key[0]); - _this._cache[key] = (_this._cache[key[0]] || _this.get(key[0]) || 0) + op.na; - _this.propertyDidChange(key[0]); - } - }); - }, - unknownProperty: function (key) { - var value = this._cache[key]; - if (value === undefined) { - value = this._cache[key] = this.wrapObject(key, this._context.get([key])); - } - return value; - }, - setUnknownProperty: function (key, value) { - if (this._cache[key] !== value) { - this.propertyWillChange(key); - this._cache[key] = this.wrapObject(key, value); - this._context.set([key], value); - this.propertyDidChange(key); - } - }, - wrapObject: function (key, value) { - if (value !== null && typeof value === 'object') { - var type = this.wrapLookup(key,value); - var factory = this.container.lookupFactory('model:'+type); - return factory.create({ - _context: this._context.createContextAt(key) - }); - } - return value; - }, - wrapLookup : function(key,value) { - return value.type || (isArray(value) ? 'share-array' : 'share-proxy'); - }, - willDestroy: function () { - this._cache = null; - this._context.destroy(); - this._context = null; - }, - toJSON: function () { - return this._context.get(); - }, - incrementProperty: function(key, increment) { - if (Ember.isNone(increment)) { increment = 1; } - Ember.assert("Must pass a numeric value to incrementProperty", (!isNaN(parseFloat(increment)) && isFinite(increment))); - this.propertyWillChange(key); - this._cache[key] = (this._cache[key] || this.get(key) || 0) + increment; - if(this._context.get([key]) !== undefined) - { - this._context.add([key], increment); - } - else - { - this._context.set([key], this._cache[key]); - } - this.propertyDidChange(key); - return this._cache[key]; - }, - decrementProperty: function(key, decrement) { - if (Ember.isNone(decrement)) { decrement = 1; } - Ember.assert("Must pass a numeric value to decrementProperty", (!isNaN(parseFloat(decrement)) && isFinite(decrement))); - this.propertyWillChange(key); - this._cache[key] = (this._cache[key] || this.get(key) || 0) - decrement; - if(this._context.get([key]) !== undefined) - { - this._context.add([key], -1 * decrement); - } - else - { - this._context.set([key], this._cache[key]); - } - this.propertyDidChange(key); - return this._cache[key]; - }, -}); diff --git a/lib/ember-share/models/sub-array.js b/lib/ember-share/models/sub-array.js new file mode 100644 index 0000000..a477f01 --- /dev/null +++ b/lib/ember-share/models/sub-array.js @@ -0,0 +1,145 @@ +import SubMixin from './sub-mixin'; +import SDBBase from './base'; + +var allButLast = function(arr) { + return arr.slice(0, arr.length - 1) +}; + +// +// Sub Array Class +// +// this is An Ember Array Proxy, uses sub mixin and 'Use Sub Mixin' +// +// + +export default function(SubMixin, GetterSettersMixin) { + return Ember.ArrayProxy.extend(Ember.Evented, SubMixin, GetterSettersMixin, { + + _isArrayProxy: true, + + arrayContentDidChange: function(startIdx, removeAmt, addAmt) { + var _removeAmt = (removeAmt == null) ? 0 : removeAmt * -1; + if (!!(_removeAmt + (addAmt == null) ? 0 : addAmt)) + Ember.get(this, 'content').propertyDidChange('lastObject'); + return this._super.apply(this, arguments) + }, + + arrayContentWillChange: function(startIdx, removeAmt, addAmt) { + var children = Ember.get(this, '_children'); + var childrenKeys = Object.keys(children); + var prefix = Ember.get(this, '_prefix'); + var self = this; + var replaceLastIdx = function(str, idx) { + var arr = allButLast(str.split('.')) + return arr.join('.') + '.' + idx + } + var _removeAmt = (removeAmt == null) ? 0 : removeAmt * -1; + addAmt = (addAmt == null) ? 0 : addAmt; + if (!!(_removeAmt + addAmt)) + Ember.get(this, 'content').propertyWillChange('lastObject'); + childrenKeys = _.reduce(childrenKeys, function(result, key) { + if (allButLast(key.split('.')).join('.') == prefix) + result.push(key); + return result + }, []); + _.forEach(childrenKeys, function(childKey) { + var idx = +_.last(childKey); + if (!isNaN(idx)) + if (addAmt && (startIdx <= idx) || removeAmt && (startIdx < idx)) { + var newIdx = idx + _removeAmt + addAmt; + var child = children[childKey]; + delete children[childKey]; + var tempChild = {}; + tempChild[replaceLastIdx(childKey, newIdx)] = child + _.assign(children, tempChild); + Ember.set(child, '_idx', newIdx); + }; + }); + return this._super.apply(this, arguments) + }, + + // useSubs: + + replaceContent: function(content, noSet) { + var removeAmt, + addAmt, + prefix = Ember.get(this, '_prefix'); + + var children = Ember.get(this, '_children'); + _.forEach(this.toArray(), function(value, index) { + var child = children[prefix + '.' + index]; + if (child != null) + if (content[index] != null) + child.replaceContent(content[index], true) + else { + delete children[prefix + '.' + index] + child.destroy() + } + }); + + if (!noSet) + this._set(prefix, content); + + Ember.set(this, 'content', content); + return this + }, + + _submitOp: function(p, li, ld) { + var path = this.get('_prefix').split('.'); + var op = { + p: path.concat(p) + }; + + if (li != null) + op.li = li; + + if (ld != null) + op.ld = ld; + + if (li != null || ld != null) { + // console.log(op); + return this.get('doc').submitOp([op]); + + } + }, + + objectAt: function(idx) { + var content = this._super(idx); + var prefix = this.get('_prefix'); + return this.useSubs(content, prefix, idx) + }, + + toJson: function() { + var self = this; + return _.map(this.toArray(), function(value) { + if ((typeof value == 'string') || (typeof value == 'number')) + return value + else + return value.toJson() + }) + }, + + _replace: function(start, len, objects) { + this.arrayContentWillChange(start, len, objects.length); + var iterationLength = (len > objects.length) + ? len + : objects.length; + for (var i = 0; i < iterationLength; i++) { + var newIndex = i + start; + var obj = objects.objectAt(i); + this._submitOp(newIndex, obj, (len > i + ? this.objectAt(newIndex) + : null)) + } + this.arrayContentDidChange(start, len, objects.length); + return this //._super(start, len, objects) + }, + + onChangeDoc: (function () { + // debugger + // this.set ('content', this.get('doc.data.' + this.get('_prefix'))) + // Ember.run.next (this, function () P{}) + this.replaceContent(this.get('doc.data.' + this.get('_prefix')), true) + }).observes('doc') + }); +} diff --git a/lib/ember-share/models/sub-mixin.js b/lib/ember-share/models/sub-mixin.js new file mode 100644 index 0000000..85f1c01 --- /dev/null +++ b/lib/ember-share/models/sub-mixin.js @@ -0,0 +1,174 @@ +import Utils from './utils'; +import attrs from '../attr'; + +var allButLast = function(arr) { + return arr.slice(0, arr.length - 1) +}; + +// +// Sub Mixin +// +// All subs use this mixin (Object and Array) +// +// + +export default Ember.Mixin.create({ + + _children: (function() { + return {} + }).property(), + + _sdbProps: (function() { + return [] + }).property(), + + _subProps: (function() { + return [] + }).property(), + + doc: Ember.computed.reads('_root.doc'), + + createInnerAttrs: (function() { + var tempContent = Ember.get(this, 'tempContent'); + var self = this; + var attr = attrs('_subProps'); + var keys = []; + + _.forEach(tempContent, function(value, key) { + keys.push(key); + Ember.defineProperty(self, key, attr()); + }) + + Ember.get(this, '_subProps').addObjects(keys); + delete this['tempContent']; + }).on('init'), + + beforeFn: (function (){return []}).property(), + afterFn: (function (){return []}).property(), + + activateListeners: (function() { + var utils = Utils(this); + + var beforeFn = utils.beforeAfterChild("Will"); + var afterFn = utils.beforeAfterChild("Did"); + + if (this.has('before op')) { + this.off('before op', this.get('beforeFn').pop()) + } + if (this.has('op')) { + this.off('op', this.get('afterFn').pop()) + } + this.on('before op', beforeFn); + this.on('op', afterFn); + + this.get('beforeFn').push(beforeFn); + this.get('afterFn').push(afterFn); + + // }).on('init'), + }).observes('doc').on('init'), + + _fullPath: function(path) { + var prefix = Ember.get(this, '_prefix'); + var idx = Ember.get(this, '_idx'); + + if (prefix) { + if (idx != null) { + return prefix + '.' + idx + '.' + path + } else { + return prefix + '.' + path; + } + } else + return path; + } + , + + deleteProperty: function(k) { + this.removeKey(k); + return this._super(this._fullPath(k)) + }, + + replaceContent: function(content, noSet) { + this.notifyWillProperties(this.get('_subProps').toArray()); + var prefix = this.get('_prefix'); + var idx = this.get('_idx') + var path = (idx == null) ? prefix : prefix + '.' + idx + + if (!noSet) + this._set(path, content); + + var self = this; + var utils = Utils(this); + + utils.removeChildren(path); + + if (_.isEmpty(Object.keys(this))) { + Ember.setProperties(this, {tempContent: content}); + this.createInnerAttrs(); + + var notifyFather = function (prefixArr, keys) { + if (_.isEmpty(prefixArr)) + self.get('_root').notifyPropertyChange(keys.join('.')) + else { + var child = self.get['_children'][prefixArr.join('.')] + if (child != null) + child.notifyPropertyChange(prefixArr.join('.') + '.' + keys.join('.')) + else + keys.push(prefixArr.pop()); + notifyFather(prefixArr, keys); + } + }; + var prefixArr = prefix.split('.') + var key = prefixArr.pop() + + notifyFather(prefixArr, [key]); + } + else { + if (_.isPlainObject(content)) + var toDelete = _.difference(Object.keys(this), Object.keys(content)) + else + var toDelete = Object.keys(this); + + _.forEach(toDelete, function(prop) { + delete self[prop] + }); + this.get('_subProps').removeObjects(toDelete); + Ember.setProperties(this, {tempContent: content}); + this.createInnerAttrs(); + this.notifyDidProperties(this.get('_subProps').toArray()); + } + + return this + }, + + toJson: function() { + var idx = Ember.get(this, '_idx'), + k = Ember.get(this, '_prefix'); + var path = (idx == null) + ? k + : (k + '.' + idx); + return this.get('doc.data.' + path); + }, + + addKey: function (key) { + var attr = attrs('_subProps'); + if (!(this.get('_subProps').indexOf(key) > -1)) + Ember.defineProperty(this, key, attr()); + return this + }, + + removeKey: function (key) { + var attr = attrs('_subProps'); + var utils = Utils(this); + utils.removeChildren(key, true); + this.get('_subProps').removeObject(key); + delete this[key]; + return this + }, + + removeListeners: function () { + this.off('before op', this.get('beforeFn')) + this.off('op', this.get('afterFn')) + + } + +}) diff --git a/lib/ember-share/models/subs-handler.js b/lib/ember-share/models/subs-handler.js new file mode 100644 index 0000000..c6a0805 --- /dev/null +++ b/lib/ember-share/models/subs-handler.js @@ -0,0 +1,12 @@ +// +// Subs Handler +// +// since we have a recursive model structure there is a need for +// creating the subs in a common place and then reuse it in its own class. +// +// + +export default { + object : {}, + array : {} +} diff --git a/lib/ember-share/models/use-subs-mixin.js b/lib/ember-share/models/use-subs-mixin.js new file mode 100644 index 0000000..25710d6 --- /dev/null +++ b/lib/ember-share/models/use-subs-mixin.js @@ -0,0 +1,69 @@ +import subs from './subs-handler'; +import Utils from './utils' + + +// +// Use Subs Mixin +// +// Used by Base and array (all). +// +// + +export default Ember.Mixin.create({ + + useSubs: function useSubs(content, k, idx) { + var utils = Utils(this); + + if (utils.matchChildToLimitations(k)) + return content; + + if (_.isPlainObject(content)) { + content = { + tempContent: content + }; + var use = 'object' + + } else if (_.isArray(content)) { + content = { + content: content + }; + var use = 'array'; + } + if (use) { + var child, + _idx; + var path = (idx == null) ? k : (k + '.' + idx); + var ownPath = Ember.get(this, '_prefix'); + if ((_idx = Ember.get(this, '_idx')) != null) + ownPath += '.' + _idx; + if (path == ownPath) { + return this; + } + + var children = Ember.get(this, '_children'); + var childrenKeys = Object.keys(children); + + if (_.includes(childrenKeys, path)) + return children[path] + else + child = {}; + + var sub = subs[use].extend({ + // doc: this.get('doc'), + _children: Ember.get(this, '_children'), + _prefix: k, + _idx: idx, + _sdbProps: Ember.get(this, '_sdbProps'), + _root: Ember.get(this,'_root') + }); + + sub = sub.create(content); + + child[path] = sub; + _.assign(Ember.get(this, '_children'), child); + + return sub + } else + return content + } +}) diff --git a/lib/ember-share/models/utils.js b/lib/ember-share/models/utils.js new file mode 100644 index 0000000..bd2cb60 --- /dev/null +++ b/lib/ember-share/models/utils.js @@ -0,0 +1,273 @@ +export default function(context) { + + return { + + isOpOnArray: function(op) { + return (op.ld != null) || (op.lm != null) || (op.li != null) + }, + + matchingPaths: function(as, bs) { + var counter = 0; + var higherLength = (as.length > bs.length) + ? as.length + : bs.length + while ((as[counter] == '*' || as[counter] == bs[counter]) && counter < higherLength) { + counter++ + } + return counter - (as.length / 1000) + }, + + matchChildToLimitations: function (key) { + var childLimiations = Ember.get(context, '_root._childLimiations'); + var prefix = Ember.get(context, '_prefix') + + if (prefix == null || key.match(prefix)) + prefix = key + else + prefix += '.' + key + + prefix = prefix.split('.'); + var self = this; + return _.some (childLimiations, function (_limit) { + var limit = _limit.split('/'); + return prefix.length == limit.length && Math.ceil(self.matchingPaths(limit, prefix)) == prefix.length + }) + }, + + prefixToChildLimiations: function (key) { + var childLimiations = Ember.get(context, '_root._childLimiations'); + var prefix = Ember.get(context, '_prefix') + + if (prefix == null || key.match(prefix)) + prefix = key + else + prefix += '.' + key + + prefix = prefix.split('.'); + var self = this, limiationsArray; + + var relevantLimitIndex = this.findMaxIndex(limiationsArray = _.map (childLimiations, function (_limit) { + var limit = _limit.split('/'); + var result = Math.ceil(self.matchingPaths(limit, prefix)) + return result < limit.length ? 0 : result + })); + if (relevantLimitIndex >= 0 && limiationsArray[relevantLimitIndex] > 0) { + var relevantLimit = childLimiations[relevantLimitIndex].split('/'); + var orignalPrefix; + var result = prefix.slice(0, Math.ceil(self.matchingPaths(relevantLimit, prefix)) ); + if (orignalPrefix = Ember.get(context, '_prefix')) { + orignalPrefix = orignalPrefix.split('.'); + return result.slice(orignalPrefix.length) + } else + return result.join('.'); + } + else { + return key; + } + + }, + + removeChildren: function (path, includeSelf) { + var children = Ember.get(context, '_children'); + var childrenKeys = Object.keys(children); + var prefix = context.get('_prefix'); + var utils = this; + + if ((prefix != null) && path && path.indexOf(prefix) != 0) { + path = prefix + '.' + path + } + + if (path) { + childrenKeys = _.reduce(childrenKeys, function(result, key) { + var matches = Math.ceil(utils.matchingPaths(key.split('.'), path.split('.'))) + if (includeSelf && (matches >= path.split('.').length) || + (!includeSelf && (matches > path.split('.').length))) + result.push(key); + return result + }, []); + } + + _.forEach (childrenKeys, function (key) { + children[key].destroy() + delete children[key] + }) + }, + + comparePathToPrefix: function(path, prefix) { + return Boolean(Math.ceil(this.matchingPaths(path.split('.'), prefix.split('.')))) + }, + + cutLast: function(path, op) { + var tempPath; + if (this.isOpOnArray(op) && !isNaN(+ _.last(path))) { + tempPath = _.clone(path); + tempPath.pop(); + } + return (tempPath) + ? tempPath + : path + }, + + comparePathToChildren: function(path, op) { + var utils = this; + var children = Ember.get(context, '_children'); + var childrenKeys = Object.keys(children); + var hasChildren = _.some(childrenKeys, function(childKey) { + var pathsCounter = utils.matchingPaths(childKey.split('.'), utils.cutLast(path, op)) + return Math.ceil(pathsCounter) == childKey.split('.').length + }); + return !Ember.isEmpty(childrenKeys) && hasChildren + }, + + triggerChildren: function(didWill, op, isFromClient) { + var newP = _.clone(op.p); + // var children = Ember.get(context, '_children'); + var children = context.get('_children'); + var childrenKeys = Object.keys(children); + if (Ember.isEmpty(childrenKeys)) + return; + var child, + utils = this; + var counterToChild = _.mapKeys(children, function(v, childKey) { + if (utils.isOpOnArray(op) && !isNaN(+ _.last(childKey.split('.')))) + return 0 + else + return utils.matchingPaths(utils.cutLast(childKey.split('.'), op), op.p) + }); + var toNumber = function(strings) { + return _.map(strings, function(s) { + return + s + }) + }; + var chosenChild = counterToChild[_.max(toNumber(Object.keys(counterToChild)))] + if (didWill == 'Will') + chosenChild.trigger('before op', [op], isFromClient); + if (didWill == 'Did') + chosenChild.trigger('op', [op], isFromClient); + } + , + + beforeAfter: function(didWill) { + var utils = this; + var ex; + return function(ops, isFromClient) { + // console.log( _.first (ops)); + + if (!isFromClient) { + _.forEach(ops, function(op) { + // if (didWill == 'Did') + // console.log(Ember.get(context,'_prefix') + ' recieved log'); + if (utils.comparePathToChildren(op.p, op)) { + utils.triggerChildren(didWill, op, isFromClient); + } else { + if (utils.isOpOnArray(op)) { + ex = utils.extractArrayPath(op); + + // console.log(Ember.get(context,'_prefix') + ' perform log'); + // console.log('op came to parent'); + context.get(ex.p)["arrayContent" + didWill + "Change"](ex.idx, ex.removeAmt, ex.addAmt) + } else { + context["property" + didWill + "Change"](utils.prefixToChildLimiations(op.p.join('.'))); + } + } + }); + } + }; + }, + + beforeAfterChild: function(didWill) { + var utils = this; + var ex, + prefix, + _idx; + return function(ops, isFromClient) { + if (((_idx = Ember.get(context, '_idx')) != null) || !isFromClient) { + _.forEach(ops, function(op) { + + if (op.p.join('.') == (prefix = Ember.get(context, '_prefix')) && didWill == 'Did') { + if (op.oi != null) { + context.replaceContent(op.oi, true) + } else { + if (op.od != null) { + var fatherPrefix = prefix.split('.'); + var key = fatherPrefix.pop(); + var father; + if (!_.isEmpty(fatherPrefix) && (father = context.get('_children.' + fatherPrefix.join('.')))) + father.removeKey(key); + else + context.get('_root').propertyDidChange(prefix) + } + } + } else { + var path = (_idx == null) + ? prefix.split('.') + : prefix.split('.').concat(String(_idx)); + var newP = _.difference(op.p, path); + if (utils.comparePathToPrefix(op.p.join('.'), prefix)) { + if (utils.isOpOnArray(op) && (Ember.get(context, '_idx') == null)) { + + var newOp = _.clone(op); + newOp.p = newP; + ex = utils.extractArrayPath(newOp); + + if (ex.p == "") + context["arrayContent" + didWill + "Change"](ex.idx, ex.removeAmt, ex.addAmt) + else + Ember.get(context, ex.p)["arrayContent" + didWill + "Change"](ex.idx, ex.removeAmt, ex.addAmt); + } + else { + if (newP.join('.') == '') { + + // delete self from father + if (false && _.isEmpty(newOp) && op.od && (op.oi == null) && (_.isEqual(op.od, context.toJson()))) { + var keyToRemove = path.pop(); + if (_.isEmpty(path)) { + utils.removeChildren(keyToRemove); + } + else { + var father = context.get('_children')[path.join('.')]; + father.removeKey (keyToRemove); + } + } + else { + context["property" + didWill + "Change"]('content'); + } + } + + else { + + if (op.oi && op.od == null) + context.addKey(_.first(newP)) + + if (op.od && op.oi == null) + context.removeKey(_.first(newP)) + + context["property" + didWill + "Change"](utils.prefixToChildLimiations(newP.join('.'))); + } + } + } + } + }); + } + } + }, + + findMaxIndex: function (arr) { + return arr.indexOf(_.max(arr)) + }, + + extractArrayPath: function(op) { + return { + idx: + _.last(op.p), + p: _.slice(op.p, 0, op.p.length - 1).join('.'), + addAmt: op.li != null + ? 1 + : 0, + removeAmt: op.ld != null + ? 1 + : 0 + } + } + + } +} diff --git a/lib/ember-share/store.js b/lib/ember-share/store.js index 5f690e7..95a7f33 100755 --- a/lib/ember-share/store.js +++ b/lib/ember-share/store.js @@ -1,19 +1,91 @@ -/* global BCSocket:false, sharejs:false */ +/* global BCSocket:false, sharedb:false */ import { guid, patchShare } from './utils'; var Promise = Ember.RSVP.Promise; +var socketReadyState = [ + 'CONNECTING', + 'OPEN', + 'CLOSING', + 'CLOSE' +] -export default Ember.Object.extend({ +export default Ember.Object.extend(Ember.Evented, { socket: null, connection: null, - url : 'http://'+window.location.hostname, + + // port: 3000, + // url : 'https://qa-e.optibus.co', + url : window.location.hostname, init: function () { - this.checkConnection = Ember.Deferred.create({}); + var store = this; + + this.checkSocket = function () { + return new Promise(function (resolve, reject) { + + if (store.socket == null) { + store.one('connectionOpen', resolve); + } + else { + var checkState = function (state, cb) { + switch(state) { + case 'connected': + return resolve(); + case 'connecting': + return store.connection.once('connected', resolve); + default: cb(state) + } + } + var checkStateFail = function (state) { + switch(state) { + case 'closed': + return reject('connection closed'); + case 'disconnected': + return reject('connection disconnected'); + case 'stopped': + return reject('connection closing'); + } + } + var failed = false + checkState(store.connection.state, function(state){ + if (failed) + checkStateFail(state) + else + Ember.run.next (this, function () { + failed = true; + checkState(store.connection.state, checkStateFail) + }) + }) + + + } + }); + } + + this.checkConnection = function () { + return new Promise(function (resolve, reject) { + return store.checkSocket() + .then(function () { + return resolve() + if (store.authentication != null && store.isAuthenticated != null) { + if (store.isAuthenticated) return resolve(); + if (store.isAuthenticating) return store.one('authenticated', resolve); + if (!store.isAuthenticated) return store.authentication(store.connection.id) + // if (!store.isAuthenticating) return reject() + return reject('could not authenticat') + } else + return resolve() + }) + .catch(function (err) { + return reject(err) + }) + }); + }; + this.cache = {}; - if(!window.sharejs) + if(!window.sharedb) { - throw new Error("ShareJS client not included"); + throw new Error("sharedb client not included"); } if (window.BCSocket === undefined && window.Primus === undefined) { throw new Error("No Socket library included"); @@ -22,55 +94,100 @@ export default Ember.Object.extend({ { this.beforeConnect() .then(function(){ - Ember.sendEvent(store,'connect'); + store.trigger('connect'); }); } else { - Ember.sendEvent(this,'connect'); + store.trigger('connect'); } }, - doConnect : function(){ + doConnect : function(options){ var store = this; - + if(window.BCSocket) { + this.setProperties(options); this.socket = new BCSocket(this.get('url'), {reconnect: true}); this.socket.onerror = function(err){ - Ember.sendEvent(store,'connectionError',[err]); + store.trigger('connectionError', [err]); + }; this.socket.onopen = function(){ - store.checkConnection.resolve(); - Ember.sendEvent(store,'connectionOpen'); + store.trigger('connectionOpen'); + }; this.socket.onclose = function(){ - Ember.sendEvent(store,'connectionEnd'); + store.trigger('connectionEnd'); }; } else if(window.Primus) { patchShare(); - this.socket = new Primus(this.get('url')); + this.setProperties(options); + var hostname = this.get('url'); + if (this.get('protocol')) + hostname = this.get('protocol') + '://' + hostname; + if (this.get("port")) + hostname += ':' + this.get('port'); + this.socket = new Primus(hostname); + // console.log('connection starting'); + this.socket.on('error', function error(err) { - Ember.sendEvent(store,'connectionError',[err]); + store.trigger('connectionError', [err]); }); this.socket.on('open', function() { - store.checkConnection.resolve(); - Ember.sendEvent(store,'connectionOpen'); + // console.log('connection open'); + store.trigger('connectionOpen'); }); this.socket.on('end', function() { - Ember.sendEvent(store,'connectionEnd'); + store.trigger('connectionEnd'); + }); + this.socket.on('close', function() { + store.trigger('connectionEnd'); }); } else { throw new Error("No Socket library included"); } - this.connection = new sharejs.Connection(this.socket); - + var oldHandleMessage = sharedb.Connection.prototype.handleMessage; + var oldSend = sharedb.Connection.prototype.send; + + store.on('connectionEnd', function () { + // console.log('ending connection'); + store.isAuthenticated = false + }) + + sharedb.Connection.prototype.handleMessage = function(message) { + var athenticating, handleMessageArgs; + handleMessageArgs = arguments; + // console.log(message.a); + var context = this; + oldHandleMessage.apply(context, handleMessageArgs); + if (message.a === 'init' && (typeof message.id === 'string') && message.protocol === 1 && typeof store.authenticate === 'function') { + store.isAuthenticating = true; + return store.authenticate(message.id) + .then(function() { + console.log('authenticated !'); + store.isAuthenticating = false; + store.isAuthenticated = true; + store.trigger('authenticated') + }) + .catch(function (err) { + store.isAuthenticating = false; + // store.socket.end() + // debugger + }) + } + }; + + this.connection = new sharedb.Connection(this.socket); + }.on('connect'), find: function (type, id) { + type = type.pluralize() var store = this; - return this.checkConnection + return this.checkConnection() .then(function(){ return store.findQuery(type, {_id: id}).then(function (models) { return models[0]; @@ -80,63 +197,143 @@ export default Ember.Object.extend({ }); }, createRecord: function (type, data) { + var ref, path; + path = (ref = this._getPathForType(type)) ? ref : type.pluralize() + path = this._getPrefix(type) + path; + type = type.pluralize() var store = this; - return store.checkConnection + return store.checkConnection() .then(function(){ - var doc = store.connection.get(type, guid()); + var doc = store.connection.get(path, data.id == null ? guid() : data.id); return Promise.all([ store.whenReady(doc).then(function (doc) { return store.create(doc, data); }), store.subscribe(doc) ]).then(function () { - return store._createModel(type, doc); + var model = store._createModel(type, doc); + store._cacheFor(type).addObject(model); + return model }); }); }, - deleteRecord : function(model) { - // TODO: delete and cleanup caches - // model._context.context._doc.del() + deleteRecord : function(type, id) { + var cache = this._cacheFor(type.pluralize()); + var model = cache.findBy('id', id); + var doc = model.get('doc'); + return new Promise(function (resolve, reject) { + doc.del(function (err) { + if (err != null) + reject(err) + else { + resolve() + } + }); + }) + }, + findAndSubscribeQuery: function(type, query) { + type = type.pluralize() + var store = this; + var prefix = this._getPrefix(type); + store.cache[type] = [] + + return this.checkConnection() + .then(function(){ + return new Promise(function (resolve, reject) { + function fetchQueryCallback(err, results, extra) { + if (err !== null) { + return reject(err); + } + resolve(store._resolveModels(type, results)); + } + query = store.connection.createSubscribeQuery(prefix + type, query, null, fetchQueryCallback); + query.on('insert', function (docs) { + store._resolveModels(type, docs) + }); + query.on('remove', function (docs) { + for (var i = 0; i < docs.length; i++) { + var modelPromise = store._resolveModel(type, docs[i]); + modelPromise.then(function (model) { + store.unload(type, model) + }); + } + }); + }); + }); + }, + findRecord: function (type, id) { + var store = this; + return new Promise(function (resolve, reject){ + store.findQuery(type, {_id: id}) + .then(function(results){ + resolve(results[0]) + }) + .catch(function (err){ + reject(err) + }); + }) }, findQuery: function (type, query) { + // type = type.pluralize() + var ref, path; + path = (ref = this._getPathForType(type)) ? ref : type.pluralize() + path = this._getPrefix(type) + path; var store = this; - return this.checkConnection + store.cache[type.pluralize()] = [] + return this.checkConnection() .then(function(){ return new Promise(function (resolve, reject) { function fetchQueryCallback(err, results, extra) { - if (err !== undefined) { + if (err !== null) { return reject(err); } resolve(store._resolveModels(type, results)); } - store.connection.createFetchQuery(type, query, null, fetchQueryCallback); + store.connection.createFetchQuery(path, query, null, fetchQueryCallback); }); }); }, - findAll: function (type) { + findAll: function (type, query) { + type = type.pluralize() throw new Error('findAll not implemented'); // TODO this.connection subscribe style query }, _cacheFor: function (type) { + type = type.pluralize() var cache = this.cache[type]; if (cache === undefined) { - this.cache[type] = cache = {}; + this.cache[type] = cache = []; } return cache; }, + _getPathForType: function (type) { + var Adapter = this.container.lookupFactory('adapter:' + type.singularize()); + if (Adapter) + return Adapter.create().pathForType(); + }, + _getPrefix: function (type) { + var Adapter = this.container.lookupFactory('adapter:' + type.singularize()); + var prefix; + if (Adapter) + prefix = Adapter.create().get('prefix'); + if (!prefix) prefix = ''; + return prefix + }, _factoryFor: function (type) { - return this.container.lookupFactory('model:'+type); + var ref; + var modelStr = (ref = this.get('modelStr')) ? ref : 'model-sdb' + return this.container.lookupFactory(modelStr + ':'+ type.singularize()); }, _createModel: function (type, doc) { - var cache = this._cacheFor(type); var modelClass = this._factoryFor(type); + type = type.pluralize() if(modelClass) { var model = modelClass.create({ - id: doc.name, - _context: doc.createContext().createContextAt() + doc: doc, + _type: type, + _store: this }); - cache[doc.name] = model; return model; } else @@ -145,8 +342,9 @@ export default Ember.Object.extend({ } }, _resolveModel: function (type, doc) { - var cache = this._cacheFor(type); - var model = cache[doc.name]; + var cache = this._cacheFor(type.pluralize()); + var id = Ember.get(doc, 'id') || Ember.get(doc, '_id'); + var model = cache.findBy('id', id); if (model !== undefined) { return Promise.resolve(model); } @@ -156,24 +354,68 @@ export default Ember.Object.extend({ }); }, _resolveModels: function (type, docs) { + // type = type.pluralize() + var store = this; + var cache = this._cacheFor(type.pluralize()); var promises = new Array(docs.length); for (var i=0; i + + allowCrossDomain = (req, res, next) -> + res.header('Access-Control-Allow-Origin', '*') + res.header('Access-Control-Allow-Methods', 'GET,PUT,POST,DELETE') + res.header('Access-Control-Allow-Headers', 'Content-Type') + + next() + + app.use allowCrossDomain + app.use bodyParser.json() + app.use bodyParser.urlencoded extended: true + app.use express.static __dirname + '/public' + + server = app.listen 3333, -> + console.log '' + console.log 'ShareDB OP Tests Webserver Running on port 3333!' + console.log '' + + share = shareDb.init server + SDBConnection = share.connect() + + app.post '/op', (req, res) -> + {id, op, collection} = req.body + # console.log op + doc = SDBConnection.get collection, id + doc.fetch (err) -> + return res.send errorFetch: err if err? + try + doc.submitOp [op], (err) -> + + if err? + res.send errorSubmit: err + else + res.send msg: 'Success' + + catch error + console.log error + res.send errors: error diff --git a/tasks/server/primus-stream.coffee b/tasks/server/primus-stream.coffee new file mode 100644 index 0000000..cf1baa4 --- /dev/null +++ b/tasks/server/primus-stream.coffee @@ -0,0 +1,23 @@ +Duplex = require('stream').Duplex + + +module.exports = (spark) -> + stream = new Duplex objectMode: true + + stream._write = (chunk, encoding, callback) -> + if spark.state != 'closed' + spark.write chunk + callback() + + stream._read = -> + + stream.headers = spark.headers + stream.remoteAddress = stream.address + spark.on 'data', (data) -> stream.push JSON.parse data + stream.on 'error', (msg) -> spark.emit 'error', msg + spark.on 'end', (reason) -> + stream.emit 'close' + stream.emit 'end' + stream.end() + + stream diff --git a/tasks/server/public/primus.js b/tasks/server/public/primus.js new file mode 100644 index 0000000..e69de29 diff --git a/tasks/server/public/share-client.js b/tasks/server/public/share-client.js new file mode 100644 index 0000000..5b5dd3c --- /dev/null +++ b/tasks/server/public/share-client.js @@ -0,0 +1,2 @@ +!function t(e,i,n){function r(o,l){if(!i[o]){if(!e[o]){var h="function"==typeof require&&require;if(!l&&h)return h(o,!0);if(s)return s(o,!0);var c=new Error("Cannot find module '"+o+"'");throw c.code="MODULE_NOT_FOUND",c}var p=i[o]={exports:{}};e[o][0].call(p.exports,function(t){var i=e[o][1][t];return r(i?i:t)},p,p.exports,t,e,i,n)}return i[o].exports}for(var s="function"==typeof require&&require,o=0;o0&&this._events[t].length>i&&(this._events[t].warned=!0,console.error("(node) warning: possible EventEmitter memory leak detected. %d listeners added. Use emitter.setMaxListeners() to increase limit.",this._events[t].length),"function"==typeof console.trace&&console.trace())),this},n.prototype.on=n.prototype.addListener,n.prototype.once=function(t,e){function i(){this.removeListener(t,i),n||(n=!0,e.apply(this,arguments))}if(!r(e))throw TypeError("listener must be a function");var n=!1;return i.listener=e,this.on(t,i),this},n.prototype.removeListener=function(t,e){var i,n,s,l;if(!r(e))throw TypeError("listener must be a function");if(!this._events||!this._events[t])return this;if(i=this._events[t],s=i.length,n=-1,i===e||r(i.listener)&&i.listener===e)delete this._events[t],this._events.removeListener&&this.emit("removeListener",t,e);else if(o(i)){for(l=s;l-- >0;)if(i[l]===e||i[l].listener&&i[l].listener===e){n=l;break}if(n<0)return this;1===i.length?(i.length=0,delete this._events[t]):i.splice(n,1),this._events.removeListener&&this.emit("removeListener",t,e)}return this},n.prototype.removeAllListeners=function(t){var e,i;if(!this._events)return this;if(!this._events.removeListener)return 0===arguments.length?this._events={}:this._events[t]&&delete this._events[t],this;if(0===arguments.length){for(e in this._events)"removeListener"!==e&&this.removeAllListeners(e);return this.removeAllListeners("removeListener"),this._events={},this}if(i=this._events[t],r(i))this.removeListener(t,i);else if(i)for(;i.length;)this.removeListener(t,i[i.length-1]);return delete this._events[t],this},n.prototype.listeners=function(t){var e;return e=this._events&&this._events[t]?r(this._events[t])?[this._events[t]]:this._events[t].slice():[]},n.prototype.listenerCount=function(t){if(this._events){var e=this._events[t];if(r(e))return 1;if(e)return e.length}return 0},n.listenerCount=function(t,e){return t.listenerCount(e)}},{}],2:[function(t,e,i){"use strict";function n(t){t&&s(this,"message",{configurable:!0,value:t,writable:!0});var e=this.constructor.name;e&&e!==this.name&&s(this,"name",{configurable:!0,value:e,writable:!0}),o(this,this.constructor)}function r(t,e){if(null==e||e===Error)e=n;else if("function"!=typeof e)throw new TypeError("super_ should be a function");var i;if("string"==typeof t)i=t,t=function(){e.apply(this,arguments)},l&&(l(t,i),i=null);else if("function"!=typeof t)throw new TypeError("constructor should be either a string or a function");t.super_=t.super=e;var r={constructor:{configurable:!0,value:t,writable:!0}};return null!=i&&(r.name={configurable:!0,value:i,writable:!0}),t.prototype=Object.create(e.prototype,r),t}var s=Object.defineProperty,o=Error.captureStackTrace;o||(o=function(t){var e=new Error;s(t,"stack",{configurable:!0,get:function(){var t=e.stack;return s(this,"stack",{value:t}),t},set:function(e){s(t,"stack",{configurable:!0,value:e,writable:!0})}})}),n.prototype=Object.create(Error.prototype,{constructor:{configurable:!0,value:n,writable:!0}});var l=function(){function t(t,e){return s(t,"name",{configurable:!0,value:e})}try{var e=function(){};if(t(e,"foo"),"foo"===e.name)return t}catch(t){}}();i=e.exports=r,i.BaseError=n},{}],3:[function(t,e,i){function n(t,e,i,n){var r=function(t,i,n,r){e(n,t,i,"left"),e(r,i,t,"right")},s=t.transformX=function(t,e){i(t),i(e);for(var o=[],l=0;l=n||s!==e.p[r])return null}return i},h.canOpAffectPath=function(t,e){return null!=h.commonLengthForOps({p:e},t)},h.transformComponent=function(t,e,i,s){e=l(e);var o=h.commonLengthForOps(i,e),p=h.commonLengthForOps(e,i),a=e.p.length,u=i.p.length;if((null!=e.na||e.t)&&a++,(null!=i.na||i.t)&&u++,null!=p&&u>a&&e.p[p]==i.p[p])if(void 0!==e.ld){var f=l(i);f.p=f.p.slice(a),e.ld=h.apply(l(e.ld),[f])}else if(void 0!==e.od){var f=l(i);f.p=f.p.slice(a),e.od=h.apply(l(e.od),[f])}if(null!=o){var d=a==u,f=i;if(null==e.si&&null==e.sd||null==i.si&&null==i.sd||(n(e),f=l(i),n(f)),f.t&&c[f.t]){if(e.t&&e.t===f.t){var v=c[e.t].transform(e.o,f.o,s);if(v.length>0)if(null!=e.si||null!=e.sd)for(var g=e.p,y=0;y_&&e.p[o]--,m>w?e.p[o]++:m===w&&_>w&&(e.p[o]++,m===b&&e.lm++),b>_?e.lm--:b===_&&b>m&&e.lm--,b>w?e.lm++:b===w&&(w>_&&b>m||w<_&&bm?e.lm++:b===_&&e.lm--)}else if(void 0!==e.li&&void 0===e.ld&&d){var m=i.p[o],b=i.lm;g=e.p[o],g>m&&e.p[o]--,g>b&&e.p[o]++}else{var m=i.p[o],b=i.lm;g=e.p[o],g===m?e.p[o]=b:(g>m&&e.p[o]--,g>b?e.p[o]++:g===b&&m>b&&e.p[o]++)}else if(void 0!==i.oi&&void 0!==i.od){if(e.p[o]===i.p[o]){if(void 0===e.oi||!d)return t;if("right"===s)return t;e.od=i.oi}}else if(void 0!==i.oi){if(void 0!==e.oi&&e.p[o]===i.p[o]){if("left"!==s)return t;h.append(t,{p:e.p,od:i.oi})}}else if(void 0!==i.od&&e.p[o]==i.p[o]){if(!d)return t;if(void 0===e.oi)return t;delete e.od}}return h.append(t,e),t},t("./bootstrapTransform")(h,h.transformComponent,h.checkValidOp,h.append);var a=t("./text0");h.registerSubtype(a),e.exports=h},{"./bootstrapTransform":3,"./text0":6}],6:[function(t,e,i){var n=e.exports={name:"text0",uri:"http://sharejs.org/types/textv0",create:function(t){if(null!=t&&"string"!=typeof t)throw new Error("Initial data must be a string");return t||""}},r=function(t,e,i){return t.slice(0,e)+i+t.slice(e)},s=function(t){if("number"!=typeof t.p)throw new Error("component missing position field");if("string"==typeof t.i==("string"==typeof t.d))throw new Error("component needs an i or d field");if(t.p<0)throw new Error("position cannot be negative")},o=function(t){for(var e=0;e=i.p+i.d.length)l(t,{d:e.d,p:e.p-i.d.length});else if(e.p+e.d.length<=i.p)l(t,e);else{var o={d:"",p:e.p};e.pi.p+i.d.length&&(o.d+=e.d.slice(i.p+i.d.length-e.p));var c=Math.max(e.p,i.p),p=Math.min(e.p+e.d.length,i.p+i.d.length),a=e.d.slice(c-e.p,p-e.p),u=i.d.slice(c-i.p,p-i.p);if(a!==u)throw new Error("Delete ops delete different text in the same region of the document");""!==o.d&&(o.p=h(o.p,i),l(t,o))}return t},p=function(t){return null!=t.i?{d:t.i,p:t.p}:{i:t.d,p:t.p}};n.invert=function(t){t=t.slice().reverse();for(var e=0;e1)for(var i=1;ithis.version?this.fetch(e):e&&e()}if(this.version>t.v)return e&&e();this.version=t.v;var n=void 0===t.type?p.defaultType:t.type;this._setType(n),this.data=this.type&&this.type.deserialize?this.type.deserialize(t.data):t.data,this.emit("load"),e&&e()},n.prototype.whenNothingPending=function(t){return this.hasPending()?void this.once("nothing pending",t):void t()},n.prototype.hasPending=function(){return!!(this.inflightOp||this.pendingOps.length||this.inflightFetch.length||this.inflightSubscribe.length||this.inflightUnsubscribe.length||this.pendingFetch.length)},n.prototype.hasWritePending=function(){return!(!this.inflightOp&&!this.pendingOps.length)},n.prototype._emitNothingPending=function(){this.hasWritePending()||(this.emit("no write pending"),this.hasPending()||this.emit("nothing pending"))},n.prototype._emitResponseError=function(t,e){return e?(e(t),void this._emitNothingPending()):(this._emitNothingPending(),void this.emit("error",t))},n.prototype._handleFetch=function(t,e){var i=this.inflightFetch.shift();return t?this._emitResponseError(t,i):(this.ingestSnapshot(e,i),void this._emitNothingPending())},n.prototype._handleSubscribe=function(t,e){var i=this.inflightSubscribe.shift();return t?this._emitResponseError(t,i):(this.wantSubscribe&&(this.subscribed=!0),this.ingestSnapshot(e,i),void this._emitNothingPending())},n.prototype._handleUnsubscribe=function(t){var e=this.inflightUnsubscribe.shift();return t?this._emitResponseError(t,e):(e&&e(),void this._emitNothingPending())},n.prototype._handleOp=function(t,e){if(t)return this.inflightOp?(4002===t.code&&(t=null),this._rollback(t)):this.emit("error",t);if(this.inflightOp&&e.src===this.inflightOp.src&&e.seq===this.inflightOp.seq)return void this._opAcknowledged(e);if(null==this.version||e.v>this.version)return void this.fetch();if(!(e.v1){this.applyStack||(this.applyStack=[]);for(var n=this.applyStack.length,r=0;r0)return void(this.applyStack.length=t);var e=this.applyStack[0];if(this.applyStack=null,e){var i=this.pendingOps.indexOf(e);if(i!==-1)for(var n=this.pendingOps.splice(i),i=0;i + + jsDir = __dirname + '/public/' + primusPath = __dirname + '/public' + '/primus.js' + shareDbPath = __dirname + '/public' + '/share-client.js' + + primus = null + + createClients: (server) -> + + # shareDb client + createDirs = (dir) -> fs.mkdirSync dir unless fs.existsSync dir + createDirs __dirname + '/public' + createDirs jsDir + fs.writeFile "#{shareDbPath}-temp", "window.sharedb = require('../../../node_modules/sharedb/lib/client');", 'utf-8' + browserify.add "#{shareDbPath}-temp" + browserify.bundle (err, buf) => + fs.writeFile shareDbPath, (@minify buf.toString()), 'utf-8' + + # primus client + primus = new Primus(server, {transformer: 'websockets', parser:'JSON' }) + fs.writeFile primusPath, (@minify primus.library().toString()), 'utf-8' + + + init: (server, cb) -> + + @createClients(server) + + shareDb = new ShareDB() + + primus.on 'connection', (spark) -> + shareDb.listen(primusStream spark) + + shareDb + + minify:(orig_code) -> + uglifyJs.minify orig_code, fromString: true + .code diff --git a/test/coffee/mock-model/cson.coffee b/test/coffee/mock-model/cson.coffee new file mode 100644 index 0000000..20d1e00 --- /dev/null +++ b/test/coffee/mock-model/cson.coffee @@ -0,0 +1,70 @@ +module.exports = -> + order: ['a', 'b', 'c'] + limitedObject: + some: + data: 1 + log: [1, 2, 3] + preferences: [ + pref1: + allowDeadHeads: true + , + pref2: + allowDeadHeads: false + ] + revision: 1 + name: 'my mocked schedule' + createdAt: 'Mon Mar 27 2017 14:42:07 GMT+0300 (IDT)' + broken: false + duties: + a: + id: 'a' + stats: + cost: 2234 + penalty: 346 + schedule_events: [ + type: 'service' + startTime: '11:00' + endTime: '13:00' + , + type: 'pull in' + startTime: '11:00' + endTime: '14:00' + ] + + b: + id: 'b' + stats: + cost: 825 + penalty: 89345 + schedule_events: [ + type: 'service' + startTime: '11:00' + endTime: '12:00' + , + type: 'pull in' + startTime: '11:00' + endTime: '12:00' + ] + + c: + id: 'c' + stats: + cost: 89234 + penalty: 89345 + schedule_events: [ + type: 'service' + startTime: '11:00' + endTime: '12:00' + , + type: 'pull in' + startTime: '11:00' + endTime: '12:00' + ] + d: + id: 'd' + schedule_events: [ + index: 1 + service_trip: + startTime: 1 + endTime: 2 + ] diff --git a/test/coffee/mock-model/schedule.coffee b/test/coffee/mock-model/schedule.coffee new file mode 100644 index 0000000..b39fd95 --- /dev/null +++ b/test/coffee/mock-model/schedule.coffee @@ -0,0 +1,28 @@ +# import model from './sdb-model' +model = require './sdb-model' +json = require 'node_modules/ot-json0/lib/json0' +data = require './cson' + + +module.exports = -> + + + model.create + + doc: + id: 'abcd' + listeners: {} + + on: (event, fn) -> + @listeners[event] = [] if (_.isEmpty @listeners[event]) + @listeners[event].push fn + + opsSent: [] + + submitOp: (op) -> + _.forEach @listeners['before op'], (fn) -> fn op, true + json.apply @data, op + @opsSent.push op + _.forEach @listeners['op'], (fn) -> fn op, true + + data: data() diff --git a/test/coffee/mock-model/sdb-model.coffee b/test/coffee/mock-model/sdb-model.coffee new file mode 100644 index 0000000..5b9d9cf --- /dev/null +++ b/test/coffee/mock-model/sdb-model.coffee @@ -0,0 +1,39 @@ +# import ShareProxy from 'ember-share/models/share-proxy' +# import attr from 'ember-share/attr' + +SDB = require('commonjs/ember-share') +ShareProxy = SDB.ShareProxy +attr = SDB.attr + +module.exports = ShareProxy.extend + # _childLimiations: [ + # 'duties/*/schedule_events' + # ] + log: attr() + # scheduleSet: belongsTo DS, 'scheduleSet', async: true + # dataset: belongsTo DS, 'tripsSchedule/dataset', async: true + vehicles: attr() + duties: attr() + relief_vehicles: attr() + stats: attr() + day: attr() + createdAt: attr 'date' + unsaved: attr 'boolean' + discarded: attr 'boolean' + trips: attr() + routes: attr() + stops: attr() + preferences: attr() + order: attr() + broken: attr 'boolean' + + # not in use yet + createdBy: attr() + revision: attr() + name: attr() + updatedAt: attr() + updatedBy: attr() + + limitedObject: attr() + + _childLimiations: ['limitedObject', 'preferences', 'duties/*/schedule_events'] diff --git a/test/coffee/model-tests.coffee b/test/coffee/model-tests.coffee new file mode 100644 index 0000000..13e39ec --- /dev/null +++ b/test/coffee/model-tests.coffee @@ -0,0 +1,271 @@ + +scheduleCreator = require './mock-model/schedule' + + +assert = chai.assert + +module.exports = -> + + describe 'Model', -> + schedule = null + + toJson = (obj) -> JSON.parse JSON.stringify obj + + beforeEach -> + schedule = scheduleCreator() + + afterEach -> + schedule = null + + it 'test type of attribute Date', -> + date = schedule.get 'createdAt' + assert.typeOf (date.getDate), 'function' + + it 'test type of attribute Boolean', -> + broken = schedule.get 'broken' + assert.isBoolean broken + assert.equal broken, false + + it 'Get name', -> + name = schedule.get 'name' + assert.equal name, 'my mocked schedule' + + it 'Get id', -> + assert.equal 'abcd', schedule.get 'id' + + it 'Set name', -> + schedule.set 'name', 'new Name' + newName = schedule.get 'name' + assert.equal newName, 'new Name' + opShouldBeSent = [ p:['name'], oi: 'new Name', od: 'my mocked schedule'] + assert.deepEqual schedule.get('doc.opsSent')[0], opShouldBeSent + + it 'SetProperties', -> + newProps = name: 'tests', revision: 2, mock: 'mock' + schedule.setProperties newProps + newName = schedule.get 'name' + assert.equal newName, 'tests' + newRevision = schedule.get 'revision' + assert.equal newRevision, 2 + newMock = schedule.get 'mock' + assert.equal newMock, 'mock' + opShouldBeSent = [ p:['name'], oi: 'tests', od: 'my mocked schedule'] + assert.deepEqual schedule.get('doc.opsSent')[0], opShouldBeSent + opShouldBeSent = [ p:['revision'], oi: 2, od: 1] + assert.deepEqual schedule.get('doc.opsSent')[1], opShouldBeSent + assert.isUndefined schedule.get('doc.opsSent')[2] + + it 'New schedule', -> + # this tests the before each, that we actually got a new schedule when started the test + assert.equal schedule.get('name'), 'my mocked schedule' + + it 'Get nested', -> + cost = schedule.get 'duties.a.stats.cost' + assert.equal cost, 2234 + + it 'Set nested', -> + schedule.set 'duties.a.stats.cost', 666 + cost = schedule.get 'duties.a.stats.cost' + assert.equal cost, 666 + opShouldBeSent = [ p:['duties', 'a', 'stats', 'cost'], oi: 666, od: 2234] + assert.deepEqual schedule.get('doc.opsSent')[0], opShouldBeSent + + it 'Nested get', -> + duty = schedule.get 'duties.a' + cost = duty.get 'stats.cost' + assert.equal cost, 2234 + assert.isUndefined schedule.get('doc.opsSent')[0] + + it 'Nested set', -> + duty = schedule.get 'duties.a' + duty.set 'stats.cost', 666 + cost = schedule.get 'duties.a.stats.cost' + assert.equal cost, 666 + opShouldBeSent = [ p:['duties', 'a', 'stats', 'cost'], oi: 666, od: 2234] + assert.deepEqual schedule.get('doc.opsSent')[0], opShouldBeSent + + it 'Object Proxy (inner) get', -> + duty = schedule.get 'duties.a' + proxiedDuty = Ember.ObjectProxy.create content: duty + cost = proxiedDuty.get 'stats.cost' + assert.equal cost, 2234 + assert.isUndefined schedule.get('doc.opsSent')[0] + + it 'Object Proxy (inner) nested set', -> + duty = schedule.get 'duties.a' + proxiedDuty = Ember.ObjectProxy.create content: duty + proxiedDuty.set 'stats.cost', 666 + cost = schedule.get 'duties.a.stats.cost' + assert.equal cost, 666 + opShouldBeSent = [ p:['duties', 'a', 'stats', 'cost'], oi: 666, od: 2234] + assert.deepEqual schedule.get('doc.opsSent')[0], opShouldBeSent + + it 'Object Proxy (inner with content) set', -> + duty = schedule.get 'duties.a' + proxiedDuty = Ember.ObjectProxy.create content: duty + proxiedDuty.set 'content.id', 'z' + newId = schedule.get 'duties.a.id' + assert.equal newId, 'z' + opShouldBeSent = [ p:['duties', 'a', 'id'], oi: 'z', od: 'a'] + assert.deepEqual schedule.get('doc.opsSent')[0], opShouldBeSent + + it 'Object Proxy (inner with content) nested set', -> + duty = schedule.get 'duties.a' + proxiedDuty = Ember.ObjectProxy.create content: duty + proxiedDuty.set 'content.stats.cost', 666 + cost = schedule.get 'duties.a.stats.cost' + assert.equal cost, 666 + opShouldBeSent = [ p:['duties', 'a', 'stats', 'cost'], oi: 666, od: 2234] + assert.deepEqual schedule.get('doc.opsSent')[0], opShouldBeSent + assert.isUndefined schedule.get('doc.opsSent')[1] + + it 'Object Proxy replace content', -> + oldDuty = duty = schedule.get 'duties.a' + oldDuty = oldDuty.toJson() + proxiedDuty = Ember.ObjectProxy.create content: duty + + newDuty = + stats: + cost: 1111 + penalty: 222 + schedule_events: [ ] + proxiedDuty.get 'stats' + proxiedDuty.get 'schedule_events' + content = proxiedDuty.get 'content' + content.replaceContent newDuty + a = (proxiedDuty.get 'content').toJson() + assert.deepEqual newDuty, a + opShouldBeSent = [ p:['duties', 'a'], oi: newDuty, od: oldDuty] + assert.deepEqual schedule.get('doc.opsSent')[0], opShouldBeSent + assert.isUndefined schedule.get('doc.opsSent')[1] + + it 'Model as Proxy get', -> + proxiedSchedule = Ember.ObjectProxy.create content: schedule + cost = proxiedSchedule.get 'duties.a.stats.cost' + assert.equal cost, 2234 + + it 'Model as Proxy set', -> + proxiedSchedule = Ember.ObjectProxy.create content: schedule + proxiedSchedule.set 'duties.a.stats.cost', 666 + cost = proxiedSchedule.get 'duties.a.stats.cost' + assert.equal cost, 666 + opShouldBeSent = [ p:['duties', 'a', 'stats', 'cost'], oi: 666, od: 2234] + assert.deepEqual schedule.get('doc.opsSent')[0], opShouldBeSent + + it 'Model as Proxy set random prop', -> + proxiedSchedule = Ember.ObjectProxy.create content: schedule + proxiedSchedule.set 'randomProp', 666 + assert.isUndefined schedule.get('doc.opsSent')[0] + + it 'Array addObject (same)', -> + order = schedule.get 'order' + order.addObject 'c' + newOrder = schedule.get 'order' + assert.isUndefined schedule.get('doc.opsSent')[0] + assert.deepEqual ['a', 'b', 'c'], (toJson newOrder.get 'content') + + it 'Array addObject (new)', -> + order = schedule.get 'order' + order.addObject 'd' + newOrder = schedule.get 'order' + assert.deepEqual ['a', 'b', 'c', 'd'], (toJson newOrder.get 'content') + opShouldBeSent = [ p:['order', 3], li: 'd'] + assert.deepEqual schedule.get('doc.opsSent')[0], opShouldBeSent + + it 'Array addObjects', -> + order = schedule.get 'order' + order.addObjects ['d', 'e'] + newOrder = schedule.get 'order' + assert.deepEqual ['a', 'b', 'c', 'd', 'e'], (toJson newOrder.get 'content') + opShouldBeSent = [ p:['order', 3], li: 'd'] + assert.deepEqual schedule.get('doc.opsSent')[0], opShouldBeSent + opShouldBeSent = [ p:['order', 4], li: 'e'] + assert.deepEqual schedule.get('doc.opsSent')[1], opShouldBeSent + + it 'Array shiftObject', -> + order = schedule.get 'order' + order.shiftObject() + newOrder = schedule.get 'order' + assert.deepEqual ['b', 'c'], (toJson newOrder.get 'content') + opShouldBeSent = [ p:['order', 0], ld: 'a'] + assert.deepEqual schedule.get('doc.opsSent')[0], opShouldBeSent + + it 'Nested Array addObject (new)', -> + events = schedule.get 'duties.a.schedule_events' + newEvent = + type: 'custom' + events.addObject newEvent + newEvents = schedule.get 'duties.a.schedule_events' + assert.equal 3, (toJson newEvents.get 'content').length + opShouldBeSent = [ p:['duties', 'a', 'schedule_events', 2], li: newEvent] + assert.deepEqual schedule.get('doc.opsSent')[0], opShouldBeSent + + it 'Nested Array get', -> + events = schedule.get 'duties.a.schedule_events' + serviceTrip = events.objectAt(0) + assert.equal 'service', (serviceTrip.get 'type') + + it 'Nested Array set', -> + events = schedule.get 'duties.a.schedule_events' + serviceTrip = events.objectAt(0) + serviceTrip.set 'type', 'idle' + assert.equal 'idle', (serviceTrip.get 'type') + opShouldBeSent = [ p:['duties', 'a', 'schedule_events', '0', 'type'], od: 'service', oi: 'idle'] + assert.deepEqual schedule.get('doc.opsSent')[0], opShouldBeSent + + it 'Nested Array changed index after insert', -> + events = schedule.get 'duties.a.schedule_events' + serviceTrip = events.objectAt(0) + newEvent = type: 'custom' + events.unshiftObject newEvent + opShouldBeSent = [ p:['duties', 'a', 'schedule_events', 0], li: newEvent] + assert.deepEqual schedule.get('doc.opsSent')[0], opShouldBeSent + serviceTrip.set 'type', 'idle' + assert.equal 'idle', (serviceTrip.get 'type') + opShouldBeSent = [ p:['duties', 'a', 'schedule_events', '1', 'type'], od: 'service', oi: 'idle'] + assert.deepEqual schedule.get('doc.opsSent')[1], opShouldBeSent + + it 'Replace Array Simple Array', -> + order = schedule.get('order') + order.replaceContent ['f'] + assert.equal 1, order.get('content.length') + + opShouldBeSent = [ p:['order'], od: ['a', 'b', 'c'], oi: ['f']] + assert.deepEqual schedule.get('doc.opsSent')[0], opShouldBeSent + + it 'Replace Array Objects', -> + oldEvents = [ + type: 'service' + startTime: '11:00' + endTime: '13:00' + , + type: 'pull in' + startTime: '11:00' + endTime: '14:00' + ] + newEvents = [ + a: 'a' + ] + events = schedule.get('duties.a.schedule_events') + service = events.objectAt 0 + idleTrip = events.objectAt 1 + events.replaceContent newEvents + assert.equal 1, events.get('content.length') + + opShouldBeSent = [ p:['duties','a','schedule_events'], od: oldEvents, oi: newEvents] + a = toJson(schedule.get('doc.opsSent')[0]) + b = toJson(opShouldBeSent) + assert.deepEqual a, b + assert.equal 'a', service.get('a') + + it 'Add property', -> + newDuty = + id: 'f' + stats: 's' + schedule_events: [] + + duties = schedule.get('duties') + duties.addKey 'f' + schedule.set "duties.f", newDuty + opShouldBeSent = [ p:[ 'duties', 'f'], oi: newDuty ] + assert.deepEqual schedule.get('doc.opsSent')[0], opShouldBeSent diff --git a/test/coffee/server-tests.coffee b/test/coffee/server-tests.coffee new file mode 100644 index 0000000..4b9ea01 --- /dev/null +++ b/test/coffee/server-tests.coffee @@ -0,0 +1,381 @@ +modelData = require './mock-model/cson' +SDB = require('commonjs/ember-share') +sdbModel = require './mock-model/sdb-model' + + +assert = chai.assert + +module.exports = -> + + describe 'Server', -> + + App = null + ShareStore = null + schedule = null + + toJson = (obj) -> JSON.parse JSON.stringify obj + + postJson = (url, data, delay) -> + ajaxCall = new Promise (resolve, reject) -> + $.ajax + type: "POST", + url: "http://localhost:3333/#{url}" + data: data + success: (response) -> + setTimeout (-> resolve response), delay + error: reject + dataType: 'json' + + createDoc = (cb) -> + json = _.assign {}, modelData(), id: "test-#{new Date().getTime()}" + ShareStore.createRecord 'schedules', json + .then (scheduleCreated) -> + schedule = scheduleCreated + cb() + .catch cb + + deleteDoc = (cb) -> + ShareStore.deleteRecord 'schedules', Ember.get(schedule, 'id') + .then cb + .catch cb + + before (done) -> + Ember.Application.initializer + name: 'api-adapter' + initialize: (_, app) -> + SDB.Store.reopen + url: 'localhost' + port: 3333 + protocol: 'http' + modelStr: 'model' + app.register 'ShareStore:main', SDB.Store + app.inject 'controller', 'ShareStore', 'ShareStore:main' + app.inject 'route', 'ShareStore', 'ShareStore:main' + + App = Ember.Application.create() + App.Schedule = sdbModel + App.ApplicationController = Ember.Controller.extend + initShareStore: (-> + ShareStore = @ShareStore + @ShareStore.checkConnection().then done + ).on 'init' + App.initialize() + + beforeEach createDoc + + afterEach deleteDoc + + createDataOp = (op) -> + id: schedule.get 'id' + collection: 'schedules' + op: op + + it 'set', (done) -> + Obj = Ember.Object.extend + schedule: schedule + cost: Ember.computed.oneWay 'schedule.duties.a.stats.cost' + obj = Obj.create() + + cost = obj.get 'cost' + + dutyA = schedule.get 'duties.a' + statsA = dutyA.get 'stats' + + assert.equal cost, 2234 + + op = p:['duties', 'a', 'stats', 'cost'], oi: 666, od: 2234 + + postJson 'op/', createDataOp(op), 0 + .then (response) -> + assert.equal response?.msg, 'Success' + newCost = obj.get 'cost' + assert.equal newCost, 666 + done() + .catch done + + it 'Proxy a new duty', (done) -> + oldDuty = (schedule.get 'duties.a').toJson() + + newDuty = + stats: + cost: "1111" + penalty: "222" + schedule_events: ['a'] + + proxiedDuty = Ember.ObjectProxy.create + content: schedule.get 'duties.a' + + op = p:['duties', 'a'], oi: newDuty, od: oldDuty + + postJson 'op/', createDataOp(op), 0 + .then (response) -> + assert.equal response?.msg, 'Success' + changedDuty = (proxiedDuty.get 'content').toJson() + assert.deepEqual newDuty, changedDuty + done() + .catch done + + + + it 'Proxy inner properties - array', (done) -> + secondEvent = + type: 'pull in' + startTime: '11:00' + endTime: '14:00' + + vord = Ember.ObjectProxy.extend + events: Ember.computed.map 'schedule_events', (event) -> event + + proxiedDuty = vord.create + content: schedule.get 'duties.a' + + eventLengthBefore = proxiedDuty.get 'events.length' + + op = p:['duties', 'a', 'schedule_events', '1'], ld: secondEvent + + postJson 'op/', createDataOp(op), 100 + .then (response) -> + assert.equal response?.msg, 'Success' + eventLengthAfter = proxiedDuty.get 'events.length' + assert.notEqual eventLengthBefore, eventLengthAfter + done() + .catch done + + it 'two arrays', (done) -> + order = schedule.get 'order' + log = schedule.get 'log' + + op = p:['log', 0], li: 0 + + postJson 'op/', createDataOp(op), 0 + .then (response) -> + assert.equal response?.msg, 'Success' + assert.equal 4, log.get('content.length') + done() + .catch done + + + it 'many logs', (done) -> + @timeout 5000 + logNumber = [0..20] + promises = [] + invoke = (arr) -> _.map arr, (fn) -> fn() + + obj = Ember.Object.extend + _log: (-> + log = @get 'job.log' + if (@get 'job.log.content.length') is 3 + 'start' + else + log.get 'content.lastObject' + ).property 'job.log.[]' + + obj = obj.create job: schedule + + _.forEach logNumber, (n) -> + tempObj = number: n, test: n*4 + promises.push -> + postJson 'op/', createDataOp(p:['log', (n + 3)], li: tempObj), 100 + + start = promises.slice 0, 4 + middle = promises.slice 4, 10 + end = promises.slice 10, 20 + startLog = null; endLog = null ; middleLog = null + + Promise.all invoke start + + .then (msgs) -> + assert.isTrue _.every msgs, (msgObj) -> msgObj.msg is 'Success' + startLog = obj.get '_log' + Promise.all invoke middle + + .then (msgs) -> + assert.isTrue _.every msgs, (msgObj) -> msgObj.msg is 'Success' + middleLog = obj.get '_log' + assert.notDeepEqual startLog, middleLog + Promise.all invoke end + + .then (msgs) -> + assert.isTrue _.every msgs, (msgObj) -> msgObj.msg is 'Success' + endLog = obj.get '_log' + assert.notDeepEqual middleLog, endLog + done() + + .catch done + + it 'get inner id', (done) -> + Vord = Ember.Object.extend + id: (-> + @get 'b.id' + ).property 'b.id' + + proxiedDuty = Vord.create + b: schedule.get 'duties.d' + + idBefore = proxiedDuty.get 'id' + + op = + p: ['duties', 'd', 'id'] + od: 'd' + oi: 'e' + + postJson 'op/', createDataOp(op), 0 + .then (response) -> + assert.equal response?.msg, 'Success' + assert.equal response?.msg, 'Success' + idAfter = proxiedDuty.get 'id' + assert.notEqual idAfter, idBefore + done() + .catch done + + it 'Proxy inner properties - array - object', (done) -> + serviceEvent = + startTime: 1 + endTime: 2 + + vord = Ember.ObjectProxy.extend + events: Ember.computed.map 'schedule_events', (event) -> event + + proxiedDuty = vord.create + content: schedule.get 'duties.d' + + innerEvent = proxiedDuty.get 'events.0' + + op = + p: ['duties', 'd', 'schedule_events', '0', 'service_trip'] + od: serviceEvent + + postJson 'op/', createDataOp(op), 0 + .then (response) -> + assert.equal response?.msg, 'Success' + assert.deepEqual innerEvent, index: 1 + done() + .catch done + + it 'Proxy replace array 1', (done) -> + @timeout 5000 + startScheduleEvents = [ + type: 'service' + startTime: '11:00' + endTime: '13:00' + , + type: 'pull in' + startTime: '11:00' + endTime: '14:00' + ] + + endScheduleEvents = ['a', 'b', 'c'] + + op = + p: ['duties', 'a', 'schedule_events'] + od: startScheduleEvents + oi: endScheduleEvents + + + eventsWasCalledCounter = 0 + Obj = Ember.Object.extend + events: (-> + eventsWasCalledCounter++ + @get('duty.schedule_events') + ).property 'duty.schedule_events.[]' + + obj = Obj.create duty: schedule.get 'duties.a' + obj.get 'events' + + postJson 'op/', createDataOp(op), 200 + .then (response) -> + assert.equal response?.msg, 'Success' + a = obj.get('events').toArray() + assert.deepEqual endScheduleEvents, a + assert.equal eventsWasCalledCounter, 2 + done() + .catch done + + it 'Add property', (done) -> + newDuty = + id: 'f' + stats: 's' + + op = p:[ 'duties', 'f'], oi: newDuty + + duties = schedule.get 'duties' + + postJson 'op/', createDataOp(op), 100 + .then (response) -> + assert.equal response?.msg, 'Success' + dutyF = duties.get 'f' + assert.deepEqual dutyF.toJson(), newDuty + done() + .catch done + + it 'Remove property', (done) -> + dutyA = schedule.get 'duties.a' + + op = p:[ 'duties', 'a'], od: dutyA.toJson() + + duties = schedule.get 'duties' + + postJson 'op/', createDataOp(op), 100 + .then (response) -> + assert.equal response?.msg, 'Success' + assert.isUndefined duties.get 'a' + done() + .catch done + + it 'Child Limiations (Object)', (done) -> + + Obj = Ember.Object.extend + limitedObject: (-> + console.log 'should happen twice' + @get 'schedule.limitedObject.some.data' + ).property 'schedule.limitedObject' + + obj = Obj.create {schedule} + obj.get 'limitedObject' + + op = p:[ 'limitedObject', 'some', 'data'], oi: 2, od: 1 + + postJson 'op/', createDataOp(op), 100 + .then (response) -> + assert.equal response?.msg, 'Success' + assert.equal obj.get('limitedObject'), 2 + done() + .catch done + + it 'Child Limiations (unscheduled)', (done) -> + + Obj = Ember.Object.extend + scheduled: (-> + console.log 'should happen twice' + @get 'schedule.duties.a.unscheduled' + ).property 'schedule.duties.a.unscheduled' + + obj = Obj.create {schedule} + obj.get 'scheduled' + + op = p:[ 'duties', 'a', 'unscheduled'], oi: true + + postJson 'op/', createDataOp(op), 100 + .then (response) -> + assert.equal response?.msg, 'Success' + assert.equal obj.get('scheduled'), 'true' + done() + .catch done + + # it 'Child Limiations (Array)', (done) -> + # Obj = Ember.Object.extend + # allowDeadHeads: (-> + # console.log 'get perform' + # @get 'schedule.preferences.0.pref1.allowDeadHeads' + # ).property 'schedule.limitedObject' + # obj = Obj.create {schedule} + # console.log obj.get 'allowDeadHeads' + # op = p:[ 'preferences', 0, 'pref1', 'allowDeadHeads'], oi: false, od: true + # + # postJson 'op/', createDataOp(op), 100 + # .then (response) -> + # assert.equal response?.msg, 'Success' + # console.log obj.get 'allowDeadHeads' + # assert.isFalse obj.get('allowDeadHeads') + # done() + # .catch done diff --git a/test/coffee/tests.coffee b/test/coffee/tests.coffee new file mode 100644 index 0000000..9225dd2 --- /dev/null +++ b/test/coffee/tests.coffee @@ -0,0 +1,5 @@ +# modelTests = require './model-tests' +serverTests = require './server-tests' + +# modelTests() +serverTests() diff --git a/test/index.html b/test/index.html index 2d7c977..df3ebeb 100755 --- a/test/index.html +++ b/test/index.html @@ -6,16 +6,21 @@
- - - - - - + + + + + - + + + + + + + - + diff --git a/test/primus.js b/test/primus.js new file mode 100644 index 0000000..3dd02fa --- /dev/null +++ b/test/primus.js @@ -0,0 +1,3333 @@ +(function UMDish(name, context, definition, plugins) { + context[name] = definition.call(context); + for (var i = 0; i < plugins.length; i++) { + plugins[i](context[name]) + } + if (typeof module !== "undefined" && module.exports) { + module.exports = context[name]; + } else if (typeof define === "function" && define.amd) { + define(function reference() { return context[name]; }); + } +})("Primus", this || {}, function wrapper() { + var define, module, exports + , Primus = (function e(t,n,r){function s(o,u){if(!n[o]){if(!t[o]){var a=typeof require=="function"&&require;if(!u&&a)return a(o,!0);if(i)return i(o,!0);var f=new Error("Cannot find module '"+o+"'");throw f.code="MODULE_NOT_FOUND",f}var l=n[o]={exports:{}};t[o][0].call(l.exports,function(e){var n=t[o][1][e];return s(n?n:e)},l,l.exports,e,t,n,r)}return n[o].exports}var i=typeof require=="function"&&require;for(var o=0;o 10000 || !(match = regex.exec(ms))) return 0; + + amount = parseFloat(match[1]); + + switch (match[2].toLowerCase()) { + case 'years': + case 'year': + case 'yrs': + case 'yr': + case 'y': + return amount * year; + + case 'weeks': + case 'week': + case 'wks': + case 'wk': + case 'w': + return amount * week; + + case 'days': + case 'day': + case 'd': + return amount * day; + + case 'hours': + case 'hour': + case 'hrs': + case 'hr': + case 'h': + return amount * hour; + + case 'minutes': + case 'minute': + case 'mins': + case 'min': + case 'm': + return amount * minute; + + case 'seconds': + case 'second': + case 'secs': + case 'sec': + case 's': + return amount * second; + + default: + return amount; + } +}; + +},{}],6:[function(_dereq_,module,exports){ +'use strict'; + +/** + * Wrap callbacks to prevent double execution. + * + * @param {Function} fn Function that should only be called once. + * @returns {Function} A wrapped callback which prevents execution. + * @api public + */ +module.exports = function one(fn) { + var called = 0 + , value; + + /** + * The function that prevents double execution. + * + * @api private + */ + function onetime() { + if (called) return value; + + called = 1; + value = fn.apply(this, arguments); + fn = null; + + return value; + } + + // + // To make debugging more easy we want to use the name of the supplied + // function. So when you look at the functions that are assigned to event + // listeners you don't see a load of `onetime` functions but actually the + // names of the functions that this module will call. + // + onetime.displayName = fn.displayName || fn.name || onetime.displayName || onetime.name; + return onetime; +}; + +},{}],7:[function(_dereq_,module,exports){ +'use strict'; + +var has = Object.prototype.hasOwnProperty; + +/** + * Simple query string parser. + * + * @param {String} query The query string that needs to be parsed. + * @returns {Object} + * @api public + */ +function querystring(query) { + var parser = /([^=?&]+)=?([^&]*)/g + , result = {} + , part; + + // + // Little nifty parsing hack, leverage the fact that RegExp.exec increments + // the lastIndex property so we can continue executing this loop until we've + // parsed all results. + // + for (; + part = parser.exec(query); + result[decodeURIComponent(part[1])] = decodeURIComponent(part[2]) + ); + + return result; +} + +/** + * Transform a query string to an object. + * + * @param {Object} obj Object that should be transformed. + * @param {String} prefix Optional prefix. + * @returns {String} + * @api public + */ +function querystringify(obj, prefix) { + prefix = prefix || ''; + + var pairs = []; + + // + // Optionally prefix with a '?' if needed + // + if ('string' !== typeof prefix) prefix = '?'; + + for (var key in obj) { + if (has.call(obj, key)) { + pairs.push(encodeURIComponent(key) +'='+ encodeURIComponent(obj[key])); + } + } + + return pairs.length ? prefix + pairs.join('&') : ''; +} + +// +// Expose the module. +// +exports.stringify = querystringify; +exports.parse = querystring; + +},{}],8:[function(_dereq_,module,exports){ +'use strict'; + +var EventEmitter = _dereq_('eventemitter3') + , millisecond = _dereq_('millisecond') + , destroy = _dereq_('demolish') + , Tick = _dereq_('tick-tock') + , one = _dereq_('one-time'); + +/** + * Returns sane defaults about a given value. + * + * @param {String} name Name of property we want. + * @param {Recovery} selfie Recovery instance that got created. + * @param {Object} opts User supplied options we want to check. + * @returns {Number} Some default value. + * @api private + */ +function defaults(name, selfie, opts) { + return millisecond( + name in opts ? opts[name] : (name in selfie ? selfie[name] : Recovery[name]) + ); +} + +/** + * Attempt to recover your connection with reconnection attempt. + * + * @constructor + * @param {Object} options Configuration + * @api public + */ +function Recovery(options) { + var recovery = this; + + if (!(recovery instanceof Recovery)) return new Recovery(options); + + options = options || {}; + + recovery.attempt = null; // Stores the current reconnect attempt. + recovery._fn = null; // Stores the callback. + + recovery['reconnect timeout'] = defaults('reconnect timeout', recovery, options); + recovery.retries = defaults('retries', recovery, options); + recovery.factor = defaults('factor', recovery, options); + recovery.max = defaults('max', recovery, options); + recovery.min = defaults('min', recovery, options); + recovery.timers = new Tick(recovery); +} + +Recovery.prototype = new EventEmitter(); +Recovery.prototype.constructor = Recovery; + +Recovery['reconnect timeout'] = '30 seconds'; // Maximum time to wait for an answer. +Recovery.max = Infinity; // Maximum delay. +Recovery.min = '500 ms'; // Minimum delay. +Recovery.retries = 10; // Maximum amount of retries. +Recovery.factor = 2; // Exponential back off factor. + +/** + * Start a new reconnect procedure. + * + * @returns {Recovery} + * @api public + */ +Recovery.prototype.reconnect = function reconnect() { + var recovery = this; + + return recovery.backoff(function backedoff(err, opts) { + opts.duration = (+new Date()) - opts.start; + + if (err) return recovery.emit('reconnect failed', err, opts); + + recovery.emit('reconnected', opts); + }, recovery.attempt); +}; + +/** + * Exponential back off algorithm for retry operations. It uses a randomized + * retry so we don't DDOS our server when it goes down under pressure. + * + * @param {Function} fn Callback to be called after the timeout. + * @param {Object} opts Options for configuring the timeout. + * @returns {Recovery} + * @api private + */ +Recovery.prototype.backoff = function backoff(fn, opts) { + var recovery = this; + + opts = opts || recovery.attempt || {}; + + // + // Bailout when we already have a back off process running. We shouldn't call + // the callback then. + // + if (opts.backoff) return recovery; + + opts['reconnect timeout'] = defaults('reconnect timeout', recovery, opts); + opts.retries = defaults('retries', recovery, opts); + opts.factor = defaults('factor', recovery, opts); + opts.max = defaults('max', recovery, opts); + opts.min = defaults('min', recovery, opts); + + opts.start = +opts.start || +new Date(); + opts.duration = +opts.duration || 0; + opts.attempt = +opts.attempt || 0; + + // + // Bailout if we are about to make too much attempts. + // + if (opts.attempt === opts.retries) { + fn.call(recovery, new Error('Unable to recover'), opts); + return recovery; + } + + // + // Prevent duplicate back off attempts using the same options object and + // increment our attempt as we're about to have another go at this thing. + // + opts.backoff = true; + opts.attempt++; + + recovery.attempt = opts; + + // + // Calculate the timeout, but make it randomly so we don't retry connections + // at the same interval and defeat the purpose. This exponential back off is + // based on the work of: + // + // http://dthain.blogspot.nl/2009/02/exponential-backoff-in-distributed.html + // + opts.scheduled = opts.attempt !== 1 + ? Math.min(Math.round( + (Math.random() + 1) * opts.min * Math.pow(opts.factor, opts.attempt - 1) + ), opts.max) + : opts.min; + + recovery.timers.setTimeout('reconnect', function delay() { + opts.duration = (+new Date()) - opts.start; + opts.backoff = false; + recovery.timers.clear('reconnect, timeout'); + + // + // Create a `one` function which can only be called once. So we can use the + // same function for different types of invocations to create a much better + // and usable API. + // + var connect = recovery._fn = one(function connect(err) { + recovery.reset(); + + if (err) return recovery.backoff(fn, opts); + + fn.call(recovery, undefined, opts); + }); + + recovery.emit('reconnect', opts, connect); + recovery.timers.setTimeout('timeout', function timeout() { + var err = new Error('Failed to reconnect in a timely manner'); + opts.duration = (+new Date()) - opts.start; + + recovery.emit('reconnect timeout', err, opts); + connect(err); + }, opts['reconnect timeout']); + }, opts.scheduled); + + // + // Emit a `reconnecting` event with current reconnect options. This allows + // them to update the UI and provide their users with feedback. + // + recovery.emit('reconnect scheduled', opts); + + return recovery; +}; + +/** + * Check if the reconnection process is currently reconnecting. + * + * @returns {Boolean} + * @api public + */ +Recovery.prototype.reconnecting = function reconnecting() { + return !!this.attempt; +}; + +/** + * Tell our reconnection procedure that we're passed. + * + * @param {Error} err Reconnection failed. + * @returns {Recovery} + * @api public + */ +Recovery.prototype.reconnected = function reconnected(err) { + if (this._fn) this._fn(err); + return this; +}; + +/** + * Reset the reconnection attempt so it can be re-used again. + * + * @returns {Recovery} + * @api public + */ +Recovery.prototype.reset = function reset() { + this._fn = this.attempt = null; + this.timers.clear('reconnect, timeout'); + + return this; +}; + +/** + * Clean up the instance. + * + * @type {Function} + * @returns {Boolean} + * @api public + */ +Recovery.prototype.destroy = destroy('timers attempt _fn'); + +// +// Expose the module. +// +module.exports = Recovery; + +},{"demolish":1,"eventemitter3":9,"millisecond":5,"one-time":6,"tick-tock":11}],9:[function(_dereq_,module,exports){ +'use strict'; + +// +// We store our EE objects in a plain object whose properties are event names. +// If `Object.create(null)` is not supported we prefix the event names with a +// `~` to make sure that the built-in object properties are not overridden or +// used as an attack vector. +// We also assume that `Object.create(null)` is available when the event name +// is an ES6 Symbol. +// +var prefix = typeof Object.create !== 'function' ? '~' : false; + +/** + * Representation of a single EventEmitter function. + * + * @param {Function} fn Event handler to be called. + * @param {Mixed} context Context for function execution. + * @param {Boolean} once Only emit once + * @api private + */ +function EE(fn, context, once) { + this.fn = fn; + this.context = context; + this.once = once || false; +} + +/** + * Minimal EventEmitter interface that is molded against the Node.js + * EventEmitter interface. + * + * @constructor + * @api public + */ +function EventEmitter() { /* Nothing to set */ } + +/** + * Holds the assigned EventEmitters by name. + * + * @type {Object} + * @private + */ +EventEmitter.prototype._events = undefined; + +/** + * Return a list of assigned event listeners. + * + * @param {String} event The events that should be listed. + * @param {Boolean} exists We only need to know if there are listeners. + * @returns {Array|Boolean} + * @api public + */ +EventEmitter.prototype.listeners = function listeners(event, exists) { + var evt = prefix ? prefix + event : event + , available = this._events && this._events[evt]; + + if (exists) return !!available; + if (!available) return []; + if (available.fn) return [available.fn]; + + for (var i = 0, l = available.length, ee = new Array(l); i < l; i++) { + ee[i] = available[i].fn; + } + + return ee; +}; + +/** + * Emit an event to all registered event listeners. + * + * @param {String} event The name of the event. + * @returns {Boolean} Indication if we've emitted an event. + * @api public + */ +EventEmitter.prototype.emit = function emit(event, a1, a2, a3, a4, a5) { + var evt = prefix ? prefix + event : event; + + if (!this._events || !this._events[evt]) return false; + + var listeners = this._events[evt] + , len = arguments.length + , args + , i; + + if ('function' === typeof listeners.fn) { + if (listeners.once) this.removeListener(event, listeners.fn, undefined, true); + + switch (len) { + case 1: return listeners.fn.call(listeners.context), true; + case 2: return listeners.fn.call(listeners.context, a1), true; + case 3: return listeners.fn.call(listeners.context, a1, a2), true; + case 4: return listeners.fn.call(listeners.context, a1, a2, a3), true; + case 5: return listeners.fn.call(listeners.context, a1, a2, a3, a4), true; + case 6: return listeners.fn.call(listeners.context, a1, a2, a3, a4, a5), true; + } + + for (i = 1, args = new Array(len -1); i < len; i++) { + args[i - 1] = arguments[i]; + } + + listeners.fn.apply(listeners.context, args); + } else { + var length = listeners.length + , j; + + for (i = 0; i < length; i++) { + if (listeners[i].once) this.removeListener(event, listeners[i].fn, undefined, true); + + switch (len) { + case 1: listeners[i].fn.call(listeners[i].context); break; + case 2: listeners[i].fn.call(listeners[i].context, a1); break; + case 3: listeners[i].fn.call(listeners[i].context, a1, a2); break; + default: + if (!args) for (j = 1, args = new Array(len -1); j < len; j++) { + args[j - 1] = arguments[j]; + } + + listeners[i].fn.apply(listeners[i].context, args); + } + } + } + + return true; +}; + +/** + * Register a new EventListener for the given event. + * + * @param {String} event Name of the event. + * @param {Functon} fn Callback function. + * @param {Mixed} context The context of the function. + * @api public + */ +EventEmitter.prototype.on = function on(event, fn, context) { + var listener = new EE(fn, context || this) + , evt = prefix ? prefix + event : event; + + if (!this._events) this._events = prefix ? {} : Object.create(null); + if (!this._events[evt]) this._events[evt] = listener; + else { + if (!this._events[evt].fn) this._events[evt].push(listener); + else this._events[evt] = [ + this._events[evt], listener + ]; + } + + return this; +}; + +/** + * Add an EventListener that's only called once. + * + * @param {String} event Name of the event. + * @param {Function} fn Callback function. + * @param {Mixed} context The context of the function. + * @api public + */ +EventEmitter.prototype.once = function once(event, fn, context) { + var listener = new EE(fn, context || this, true) + , evt = prefix ? prefix + event : event; + + if (!this._events) this._events = prefix ? {} : Object.create(null); + if (!this._events[evt]) this._events[evt] = listener; + else { + if (!this._events[evt].fn) this._events[evt].push(listener); + else this._events[evt] = [ + this._events[evt], listener + ]; + } + + return this; +}; + +/** + * Remove event listeners. + * + * @param {String} event The event we want to remove. + * @param {Function} fn The listener that we need to find. + * @param {Mixed} context Only remove listeners matching this context. + * @param {Boolean} once Only remove once listeners. + * @api public + */ +EventEmitter.prototype.removeListener = function removeListener(event, fn, context, once) { + var evt = prefix ? prefix + event : event; + + if (!this._events || !this._events[evt]) return this; + + var listeners = this._events[evt] + , events = []; + + if (fn) { + if (listeners.fn) { + if ( + listeners.fn !== fn + || (once && !listeners.once) + || (context && listeners.context !== context) + ) { + events.push(listeners); + } + } else { + for (var i = 0, length = listeners.length; i < length; i++) { + if ( + listeners[i].fn !== fn + || (once && !listeners[i].once) + || (context && listeners[i].context !== context) + ) { + events.push(listeners[i]); + } + } + } + } + + // + // Reset the array, or remove it completely if we have no more listeners. + // + if (events.length) { + this._events[evt] = events.length === 1 ? events[0] : events; + } else { + delete this._events[evt]; + } + + return this; +}; + +/** + * Remove all listeners or only the listeners for the specified event. + * + * @param {String} event The event want to remove all listeners for. + * @api public + */ +EventEmitter.prototype.removeAllListeners = function removeAllListeners(event) { + if (!this._events) return this; + + if (event) delete this._events[prefix ? prefix + event : event]; + else this._events = prefix ? {} : Object.create(null); + + return this; +}; + +// +// Alias methods names because people roll like that. +// +EventEmitter.prototype.off = EventEmitter.prototype.removeListener; +EventEmitter.prototype.addListener = EventEmitter.prototype.on; + +// +// This function doesn't apply anymore. +// +EventEmitter.prototype.setMaxListeners = function setMaxListeners() { + return this; +}; + +// +// Expose the prefix. +// +EventEmitter.prefixed = prefix; + +// +// Expose the module. +// +if ('undefined' !== typeof module) { + module.exports = EventEmitter; +} + +},{}],10:[function(_dereq_,module,exports){ +'use strict'; + +/** + * Check if we're required to add a port number. + * + * @see https://url.spec.whatwg.org/#default-port + * @param {Number|String} port Port number we need to check + * @param {String} protocol Protocol we need to check against. + * @returns {Boolean} Is it a default port for the given protocol + * @api private + */ +module.exports = function required(port, protocol) { + protocol = protocol.split(':')[0]; + port = +port; + + if (!port) return false; + + switch (protocol) { + case 'http': + case 'ws': + return port !== 80; + + case 'https': + case 'wss': + return port !== 443; + + case 'ftp': + return port !== 21; + + case 'gopher': + return port !== 70; + + case 'file': + return false; + } + + return port !== 0; +}; + +},{}],11:[function(_dereq_,module,exports){ +'use strict'; + +var has = Object.prototype.hasOwnProperty + , ms = _dereq_('millisecond'); + +/** + * Timer instance. + * + * @constructor + * @param {Object} timer New timer instance. + * @param {Function} clear Clears the timer instance. + * @param {Function} duration Duration of the timer. + * @param {Function} fn The functions that need to be executed. + * @api private + */ +function Timer(timer, clear, duration, fn) { + this.start = +(new Date()); + this.duration = duration; + this.clear = clear; + this.timer = timer; + this.fns = [fn]; +} + +/** + * Calculate the time left for a given timer. + * + * @returns {Number} Time in milliseconds. + * @api public + */ +Timer.prototype.remaining = function remaining() { + return this.duration - this.taken(); +}; + +/** + * Calculate the amount of time it has taken since we've set the timer. + * + * @returns {Number} + * @api public + */ +Timer.prototype.taken = function taken() { + return +(new Date()) - this.start; +}; + +/** + * Custom wrappers for the various of clear{whatever} functions. We cannot + * invoke them directly as this will cause thrown errors in Google Chrome with + * an Illegal Invocation Error + * + * @see #2 + * @type {Function} + * @api private + */ +function unsetTimeout(id) { clearTimeout(id); } +function unsetInterval(id) { clearInterval(id); } +function unsetImmediate(id) { clearImmediate(id); } + +/** + * Simple timer management. + * + * @constructor + * @param {Mixed} context Context of the callbacks that we execute. + * @api public + */ +function Tick(context) { + if (!(this instanceof Tick)) return new Tick(context); + + this.timers = {}; + this.context = context || this; +} + +/** + * Return a function which will just iterate over all assigned callbacks and + * optionally clear the timers from memory if needed. + * + * @param {String} name Name of the timer we need to execute. + * @param {Boolean} clear Also clear from memory. + * @returns {Function} + * @api private + */ +Tick.prototype.tock = function ticktock(name, clear) { + var tock = this; + + return function tickedtock() { + if (!(name in tock.timers)) return; + + var timer = tock.timers[name] + , fns = timer.fns.slice() + , l = fns.length + , i = 0; + + if (clear) tock.clear(name); + else tock.start = +new Date(); + + for (; i < l; i++) { + fns[i].call(tock.context); + } + }; +}; + +/** + * Add a new timeout. + * + * @param {String} name Name of the timer. + * @param {Function} fn Completion callback. + * @param {Mixed} time Duration of the timer. + * @returns {Tick} + * @api public + */ +Tick.prototype.setTimeout = function timeout(name, fn, time) { + var tick = this + , tock; + + if (tick.timers[name]) { + tick.timers[name].fns.push(fn); + return tick; + } + + tock = ms(time); + tick.timers[name] = new Timer( + setTimeout(tick.tock(name, true), ms(time)), + unsetTimeout, + tock, + fn + ); + + return tick; +}; + +/** + * Add a new interval. + * + * @param {String} name Name of the timer. + * @param {Function} fn Completion callback. + * @param {Mixed} time Interval of the timer. + * @returns {Tick} + * @api public + */ +Tick.prototype.setInterval = function interval(name, fn, time) { + var tick = this + , tock; + + if (tick.timers[name]) { + tick.timers[name].fns.push(fn); + return tick; + } + + tock = ms(time); + tick.timers[name] = new Timer( + setInterval(tick.tock(name), ms(time)), + unsetInterval, + tock, + fn + ); + + return tick; +}; + +/** + * Add a new setImmediate. + * + * @param {String} name Name of the timer. + * @param {Function} fn Completion callback. + * @returns {Tick} + * @api public + */ +Tick.prototype.setImmediate = function immediate(name, fn) { + var tick = this; + + if ('function' !== typeof setImmediate) return tick.setTimeout(name, fn, 0); + + if (tick.timers[name]) { + tick.timers[name].fns.push(fn); + return tick; + } + + tick.timers[name] = new Timer( + setImmediate(tick.tock(name, true)), + unsetImmediate, + 0, + fn + ); + + return tick; +}; + +/** + * Check if we have a timer set. + * + * @param {String} name + * @returns {Boolean} + * @api public + */ +Tick.prototype.active = function active(name) { + return name in this.timers; +}; + +/** + * Properly clean up all timeout references. If no arguments are supplied we + * will attempt to clear every single timer that is present. + * + * @param {Arguments} ..args.. The names of the timeouts we need to clear + * @returns {Tick} + * @api public + */ +Tick.prototype.clear = function clear() { + var args = arguments.length ? arguments : [] + , tick = this + , timer, i, l; + + if (args.length === 1 && 'string' === typeof args[0]) { + args = args[0].split(/[, ]+/); + } + + if (!args.length) { + for (timer in tick.timers) { + if (has.call(tick.timers, timer)) args.push(timer); + } + } + + for (i = 0, l = args.length; i < l; i++) { + timer = tick.timers[args[i]]; + + if (!timer) continue; + timer.clear(timer.timer); + + timer.fns = timer.timer = timer.clear = null; + delete tick.timers[args[i]]; + } + + return tick; +}; + +/** + * Adjust a timeout or interval to a new duration. + * + * @returns {Tick} + * @api public + */ +Tick.prototype.adjust = function adjust(name, time) { + var interval + , tick = this + , tock = ms(time) + , timer = tick.timers[name]; + + if (!timer) return tick; + + interval = timer.clear === unsetInterval; + timer.clear(timer.timer); + timer.start = +(new Date()); + timer.duration = tock; + timer.timer = (interval ? setInterval : setTimeout)(tick.tock(name, !interval), tock); + + return tick; +}; + +/** + * We will no longer use this module, prepare your self for global cleanups. + * + * @returns {Boolean} + * @api public + */ +Tick.prototype.end = Tick.prototype.destroy = function end() { + if (!this.context) return false; + + this.clear(); + this.context = this.timers = null; + + return true; +}; + +// +// Expose the timer factory. +// +Tick.Timer = Timer; +module.exports = Tick; + +},{"millisecond":5}],12:[function(_dereq_,module,exports){ +'use strict'; + +var required = _dereq_('requires-port') + , lolcation = _dereq_('./lolcation') + , qs = _dereq_('querystringify') + , protocolre = /^([a-z][a-z0-9.+-]*:)?(\/\/)?([\S\s]*)/i; + +/** + * These are the parse rules for the URL parser, it informs the parser + * about: + * + * 0. The char it Needs to parse, if it's a string it should be done using + * indexOf, RegExp using exec and NaN means set as current value. + * 1. The property we should set when parsing this value. + * 2. Indication if it's backwards or forward parsing, when set as number it's + * the value of extra chars that should be split off. + * 3. Inherit from location if non existing in the parser. + * 4. `toLowerCase` the resulting value. + */ +var rules = [ + ['#', 'hash'], // Extract from the back. + ['?', 'query'], // Extract from the back. + ['/', 'pathname'], // Extract from the back. + ['@', 'auth', 1], // Extract from the front. + [NaN, 'host', undefined, 1, 1], // Set left over value. + [/:(\d+)$/, 'port', undefined, 1], // RegExp the back. + [NaN, 'hostname', undefined, 1, 1] // Set left over. +]; + +/** + * @typedef ProtocolExtract + * @type Object + * @property {String} protocol Protocol matched in the URL, in lowercase. + * @property {Boolean} slashes `true` if protocol is followed by "//", else `false`. + * @property {String} rest Rest of the URL that is not part of the protocol. + */ + +/** + * Extract protocol information from a URL with/without double slash ("//"). + * + * @param {String} address URL we want to extract from. + * @return {ProtocolExtract} Extracted information. + * @api private + */ +function extractProtocol(address) { + var match = protocolre.exec(address); + + return { + protocol: match[1] ? match[1].toLowerCase() : '', + slashes: !!match[2], + rest: match[3] + }; +} + +/** + * Resolve a relative URL pathname against a base URL pathname. + * + * @param {String} relative Pathname of the relative URL. + * @param {String} base Pathname of the base URL. + * @return {String} Resolved pathname. + * @api private + */ +function resolve(relative, base) { + var path = (base || '/').split('/').slice(0, -1).concat(relative.split('/')) + , i = path.length + , last = path[i - 1] + , unshift = false + , up = 0; + + while (i--) { + if (path[i] === '.') { + path.splice(i, 1); + } else if (path[i] === '..') { + path.splice(i, 1); + up++; + } else if (up) { + if (i === 0) unshift = true; + path.splice(i, 1); + up--; + } + } + + if (unshift) path.unshift(''); + if (last === '.' || last === '..') path.push(''); + + return path.join('/'); +} + +/** + * The actual URL instance. Instead of returning an object we've opted-in to + * create an actual constructor as it's much more memory efficient and + * faster and it pleases my OCD. + * + * @constructor + * @param {String} address URL we want to parse. + * @param {Object|String} location Location defaults for relative paths. + * @param {Boolean|Function} parser Parser for the query string. + * @api public + */ +function URL(address, location, parser) { + if (!(this instanceof URL)) { + return new URL(address, location, parser); + } + + var relative, extracted, parse, instruction, index, key + , instructions = rules.slice() + , type = typeof location + , url = this + , i = 0; + + // + // The following if statements allows this module two have compatibility with + // 2 different API: + // + // 1. Node.js's `url.parse` api which accepts a URL, boolean as arguments + // where the boolean indicates that the query string should also be parsed. + // + // 2. The `URL` interface of the browser which accepts a URL, object as + // arguments. The supplied object will be used as default values / fall-back + // for relative paths. + // + if ('object' !== type && 'string' !== type) { + parser = location; + location = null; + } + + if (parser && 'function' !== typeof parser) parser = qs.parse; + + location = lolcation(location); + + // + // Extract protocol information before running the instructions. + // + extracted = extractProtocol(address || ''); + relative = !extracted.protocol && !extracted.slashes; + url.slashes = extracted.slashes || relative && location.slashes; + url.protocol = extracted.protocol || location.protocol || ''; + address = extracted.rest; + + // + // When the authority component is absent the URL starts with a path + // component. + // + if (!extracted.slashes) instructions[2] = [/(.*)/, 'pathname']; + + for (; i < instructions.length; i++) { + instruction = instructions[i]; + parse = instruction[0]; + key = instruction[1]; + + if (parse !== parse) { + url[key] = address; + } else if ('string' === typeof parse) { + if (~(index = address.indexOf(parse))) { + if ('number' === typeof instruction[2]) { + url[key] = address.slice(0, index); + address = address.slice(index + instruction[2]); + } else { + url[key] = address.slice(index); + address = address.slice(0, index); + } + } + } else if (index = parse.exec(address)) { + url[key] = index[1]; + address = address.slice(0, index.index); + } + + url[key] = url[key] || ( + relative && instruction[3] ? location[key] || '' : '' + ); + + // + // Hostname, host and protocol should be lowercased so they can be used to + // create a proper `origin`. + // + if (instruction[4]) url[key] = url[key].toLowerCase(); + } + + // + // Also parse the supplied query string in to an object. If we're supplied + // with a custom parser as function use that instead of the default build-in + // parser. + // + if (parser) url.query = parser(url.query); + + // + // If the URL is relative, resolve the pathname against the base URL. + // + if ( + relative + && location.slashes + && url.pathname.charAt(0) !== '/' + && (url.pathname !== '' || location.pathname !== '') + ) { + url.pathname = resolve(url.pathname, location.pathname); + } + + // + // We should not add port numbers if they are already the default port number + // for a given protocol. As the host also contains the port number we're going + // override it with the hostname which contains no port number. + // + if (!required(url.port, url.protocol)) { + url.host = url.hostname; + url.port = ''; + } + + // + // Parse down the `auth` for the username and password. + // + url.username = url.password = ''; + if (url.auth) { + instruction = url.auth.split(':'); + url.username = instruction[0] || ''; + url.password = instruction[1] || ''; + } + + url.origin = url.protocol && url.host && url.protocol !== 'file:' + ? url.protocol +'//'+ url.host + : 'null'; + + // + // The href is just the compiled result. + // + url.href = url.toString(); +} + +/** + * This is convenience method for changing properties in the URL instance to + * insure that they all propagate correctly. + * + * @param {String} part Property we need to adjust. + * @param {Mixed} value The newly assigned value. + * @param {Boolean|Function} fn When setting the query, it will be the function + * used to parse the query. + * When setting the protocol, double slash will be + * removed from the final url if it is true. + * @returns {URL} + * @api public + */ +URL.prototype.set = function set(part, value, fn) { + var url = this; + + switch (part) { + case 'query': + if ('string' === typeof value && value.length) { + value = (fn || qs.parse)(value); + } + + url[part] = value; + break; + + case 'port': + url[part] = value; + + if (!required(value, url.protocol)) { + url.host = url.hostname; + url[part] = ''; + } else if (value) { + url.host = url.hostname +':'+ value; + } + + break; + + case 'hostname': + url[part] = value; + + if (url.port) value += ':'+ url.port; + url.host = value; + break; + + case 'host': + url[part] = value; + + if (/:\d+$/.test(value)) { + value = value.split(':'); + url.port = value.pop(); + url.hostname = value.join(':'); + } else { + url.hostname = value; + url.port = ''; + } + + break; + + case 'protocol': + url.protocol = value.toLowerCase(); + url.slashes = !fn; + break; + + case 'pathname': + url.pathname = value.length && value.charAt(0) !== '/' ? '/' + value : value; + + break; + + default: + url[part] = value; + } + + for (var i = 0; i < rules.length; i++) { + var ins = rules[i]; + + if (ins[4]) url[ins[1]] = url[ins[1]].toLowerCase(); + } + + url.origin = url.protocol && url.host && url.protocol !== 'file:' + ? url.protocol +'//'+ url.host + : 'null'; + + url.href = url.toString(); + + return url; +}; + +/** + * Transform the properties back in to a valid and full URL string. + * + * @param {Function} stringify Optional query stringify function. + * @returns {String} + * @api public + */ +URL.prototype.toString = function toString(stringify) { + if (!stringify || 'function' !== typeof stringify) stringify = qs.stringify; + + var query + , url = this + , protocol = url.protocol; + + if (protocol && protocol.charAt(protocol.length - 1) !== ':') protocol += ':'; + + var result = protocol + (url.slashes ? '//' : ''); + + if (url.username) { + result += url.username; + if (url.password) result += ':'+ url.password; + result += '@'; + } + + result += url.host + url.pathname; + + query = 'object' === typeof url.query ? stringify(url.query) : url.query; + if (query) result += '?' !== query.charAt(0) ? '?'+ query : query; + + if (url.hash) result += url.hash; + + return result; +}; + +// +// Expose the URL parser and some additional properties that might be useful for +// others or testing. +// +URL.extractProtocol = extractProtocol; +URL.location = lolcation; +URL.qs = qs; + +module.exports = URL; + +},{"./lolcation":13,"querystringify":7,"requires-port":10}],13:[function(_dereq_,module,exports){ +(function (global){ +'use strict'; + +var slashes = /^[A-Za-z][A-Za-z0-9+-.]*:\/\//; + +/** + * These properties should not be copied or inherited from. This is only needed + * for all non blob URL's as a blob URL does not include a hash, only the + * origin. + * + * @type {Object} + * @private + */ +var ignore = { hash: 1, query: 1 } + , URL; + +/** + * The location object differs when your code is loaded through a normal page, + * Worker or through a worker using a blob. And with the blobble begins the + * trouble as the location object will contain the URL of the blob, not the + * location of the page where our code is loaded in. The actual origin is + * encoded in the `pathname` so we can thankfully generate a good "default" + * location from it so we can generate proper relative URL's again. + * + * @param {Object|String} loc Optional default location object. + * @returns {Object} lolcation object. + * @api public + */ +module.exports = function lolcation(loc) { + loc = loc || global.location || {}; + URL = URL || _dereq_('./'); + + var finaldestination = {} + , type = typeof loc + , key; + + if ('blob:' === loc.protocol) { + finaldestination = new URL(unescape(loc.pathname), {}); + } else if ('string' === type) { + finaldestination = new URL(loc, {}); + for (key in ignore) delete finaldestination[key]; + } else if ('object' === type) { + for (key in loc) { + if (key in ignore) continue; + finaldestination[key] = loc[key]; + } + + if (finaldestination.slashes === undefined) { + finaldestination.slashes = slashes.test(loc.href); + } + } + + return finaldestination; +}; + +}).call(this,typeof global !== "undefined" ? global : typeof self !== "undefined" ? self : typeof window !== "undefined" ? window : {}) +},{"./":12}],14:[function(_dereq_,module,exports){ +'use strict'; + +var alphabet = '0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz-_'.split('') + , length = 64 + , map = {} + , seed = 0 + , i = 0 + , prev; + +/** + * Return a string representing the specified number. + * + * @param {Number} num The number to convert. + * @returns {String} The string representation of the number. + * @api public + */ +function encode(num) { + var encoded = ''; + + do { + encoded = alphabet[num % length] + encoded; + num = Math.floor(num / length); + } while (num > 0); + + return encoded; +} + +/** + * Return the integer value specified by the given string. + * + * @param {String} str The string to convert. + * @returns {Number} The integer value represented by the string. + * @api public + */ +function decode(str) { + var decoded = 0; + + for (i = 0; i < str.length; i++) { + decoded = decoded * length + map[str.charAt(i)]; + } + + return decoded; +} + +/** + * Yeast: A tiny growing id generator. + * + * @returns {String} A unique id. + * @api public + */ +function yeast() { + var now = encode(+new Date()); + + if (now !== prev) return seed = 0, prev = now; + return now +'.'+ encode(seed++); +} + +// +// Map each character to its index. +// +for (; i < length; i++) map[alphabet[i]] = i; + +// +// Expose the `yeast`, `encode` and `decode` functions. +// +yeast.encode = encode; +yeast.decode = decode; +module.exports = yeast; + +},{}],15:[function(_dereq_,module,exports){ +/*globals require, define */ +'use strict'; + +var EventEmitter = _dereq_('eventemitter3') + , TickTock = _dereq_('tick-tock') + , Recovery = _dereq_('recovery') + , qs = _dereq_('querystringify') + , inherits = _dereq_('inherits') + , destroy = _dereq_('demolish') + , yeast = _dereq_('yeast') + , u2028 = /\u2028/g + , u2029 = /\u2029/g; + +/** + * Context assertion, ensure that some of our public Primus methods are called + * with the correct context to ensure that + * + * @param {Primus} self The context of the function. + * @param {String} method The method name. + * @api private + */ +function context(self, method) { + if (self instanceof Primus) return; + + var failure = new Error('Primus#'+ method + '\'s context should called with a Primus instance'); + + if ('function' !== typeof self.listeners || !self.listeners('error').length) { + throw failure; + } + + self.emit('error', failure); +} + +// +// Sets the default connection URL, it uses the default origin of the browser +// when supported but degrades for older browsers. In Node.js, we cannot guess +// where the user wants to connect to, so we just default to localhost. +// +var defaultUrl; + +try { + if (location.origin) { + defaultUrl = location.origin; + } else { + defaultUrl = location.protocol +'//'+ location.host; + } +} catch (e) { + defaultUrl = 'http://127.0.0.1'; +} + +/** + * Primus is a real-time library agnostic framework for establishing real-time + * connections with servers. + * + * Options: + * - reconnect, configuration for the reconnect process. + * - manual, don't automatically call `.open` to start the connection. + * - websockets, force the use of WebSockets, even when you should avoid them. + * - timeout, connect timeout, server didn't respond in a timely manner. + * - ping, The heartbeat interval for sending a ping packet to the server. + * - pong, The heartbeat timeout for receiving a response to the ping. + * - network, Use network events as leading method for network connection drops. + * - strategy, Reconnection strategies. + * - transport, Transport options. + * - url, uri, The URL to use connect with the server. + * + * @constructor + * @param {String} url The URL of your server. + * @param {Object} options The configuration. + * @api public + */ +function Primus(url, options) { + if (!(this instanceof Primus)) return new Primus(url, options); + + Primus.Stream.call(this); + + if ('function' !== typeof this.client) { + var message = 'The client library has not been compiled correctly, ' + + 'see https://github.com/primus/primus#client-library for more details'; + return this.critical(new Error(message)); + } + + if ('object' === typeof url) { + options = url; + url = options.url || options.uri || defaultUrl; + } else { + options = options || {}; + } + + var primus = this; + + // The maximum number of messages that can be placed in queue. + options.queueSize = 'queueSize' in options ? options.queueSize : Infinity; + + // Connection timeout duration. + options.timeout = 'timeout' in options ? options.timeout : 10e3; + + // Stores the back off configuration. + options.reconnect = 'reconnect' in options ? options.reconnect : {}; + + // Heartbeat ping interval. + options.ping = 'ping' in options ? options.ping : 25000; + + // Heartbeat pong response timeout. + options.pong = 'pong' in options ? options.pong : 10e3; + + // Reconnect strategies. + options.strategy = 'strategy' in options ? options.strategy : []; + + // Custom transport options. + options.transport = 'transport' in options ? options.transport : {}; + + primus.buffer = []; // Stores premature send data. + primus.writable = true; // Silly stream compatibility. + primus.readable = true; // Silly stream compatibility. + primus.url = primus.parse(url || defaultUrl); // Parse the URL to a readable format. + primus.readyState = Primus.CLOSED; // The readyState of the connection. + primus.options = options; // Reference to the supplied options. + primus.timers = new TickTock(this); // Contains all our timers. + primus.socket = null; // Reference to the internal connection. + primus.latency = 0; // Latency between messages. + primus.disconnect = false; // Did we receive a disconnect packet? + primus.transport = options.transport; // Transport options. + primus.transformers = { // Message transformers. + outgoing: [], + incoming: [] + }; + + // + // Create our reconnection instance. + // + primus.recovery = new Recovery(options.reconnect); + + // + // Parse the reconnection strategy. It can have the following strategies: + // + // - timeout: Reconnect when we have a network timeout. + // - disconnect: Reconnect when we have an unexpected disconnect. + // - online: Reconnect when we're back online. + // + if ('string' === typeof options.strategy) { + options.strategy = options.strategy.split(/\s?\,\s?/g); + } + + if (false === options.strategy) { + // + // Strategies are disabled, but we still need an empty array to join it in + // to nothing. + // + options.strategy = []; + } else if (!options.strategy.length) { + options.strategy.push('disconnect', 'online'); + + // + // Timeout based reconnection should only be enabled conditionally. When + // authorization is enabled it could trigger. + // + if (!this.authorization) options.strategy.push('timeout'); + } + + options.strategy = options.strategy.join(',').toLowerCase(); + + // + // Force the use of WebSockets, even when we've detected some potential + // broken WebSocket implementation. + // + if ('websockets' in options) { + primus.AVOID_WEBSOCKETS = !options.websockets; + } + + // + // Force or disable the use of NETWORK events as leading client side + // disconnection detection. + // + if ('network' in options) { + primus.NETWORK_EVENTS = options.network; + } + + // + // Check if the user wants to manually initialise a connection. If they don't, + // we want to do it after a really small timeout so we give the users enough + // time to listen for `error` events etc. + // + if (!options.manual) primus.timers.setTimeout('open', function open() { + primus.timers.clear('open'); + primus.open(); + }, 0); + + primus.initialise(options); +} + +/** + * Simple require wrapper to make browserify, node and require.js play nice. + * + * @param {String} name The module to require. + * @returns {Object|Undefined} The module that we required. + * @api private + */ +Primus.requires = Primus.require = function requires(name) { + if ('function' !== typeof _dereq_) return undefined; + + return !('function' === typeof define && define.amd) + ? _dereq_(name) + : undefined; +}; + +// +// It's possible that we're running in Node.js or in a Node.js compatible +// environment. In this cases we try to inherit from the Stream base class. +// +try { + Primus.Stream = Primus.requires('stream'); +} catch (e) { } + +if (!Primus.Stream) Primus.Stream = EventEmitter; + +inherits(Primus, Primus.Stream); + +/** + * Primus readyStates, used internally to set the correct ready state. + * + * @type {Number} + * @private + */ +Primus.OPENING = 1; // We're opening the connection. +Primus.CLOSED = 2; // No active connection. +Primus.OPEN = 3; // The connection is open. + +/** + * Are we working with a potentially broken WebSockets implementation? This + * boolean can be used by transformers to remove `WebSockets` from their + * supported transports. + * + * @type {Boolean} + * @private + */ +Primus.prototype.AVOID_WEBSOCKETS = false; + +/** + * Some browsers support registering emitting `online` and `offline` events when + * the connection has been dropped on the client. We're going to detect it in + * a simple `try {} catch (e) {}` statement so we don't have to do complicated + * feature detection. + * + * @type {Boolean} + * @private + */ +Primus.prototype.NETWORK_EVENTS = false; +Primus.prototype.online = true; + +try { + if ( + Primus.prototype.NETWORK_EVENTS = 'onLine' in navigator + && (window.addEventListener || document.body.attachEvent) + ) { + if (!navigator.onLine) { + Primus.prototype.online = false; + } + } +} catch (e) { } + +/** + * The Ark contains all our plugins definitions. It's namespaced by + * name => plugin. + * + * @type {Object} + * @private + */ +Primus.prototype.ark = {}; + +/** + * Simple emit wrapper that returns a function that emits an event once it's + * called. This makes it easier for transports to emit specific events. + * + * @returns {Function} A function that will emit the event when called. + * @api public + */ +Primus.prototype.emits = _dereq_('emits'); + +/** + * Return the given plugin. + * + * @param {String} name The name of the plugin. + * @returns {Object|undefined} The plugin or undefined. + * @api public + */ +Primus.prototype.plugin = function plugin(name) { + context(this, 'plugin'); + + if (name) return this.ark[name]; + + var plugins = {}; + + for (name in this.ark) { + plugins[name] = this.ark[name]; + } + + return plugins; +}; + +/** + * Checks if the given event is an emitted event by Primus. + * + * @param {String} evt The event name. + * @returns {Boolean} Indication of the event is reserved for internal use. + * @api public + */ +Primus.prototype.reserved = function reserved(evt) { + return (/^(incoming|outgoing)::/).test(evt) + || evt in this.reserved.events; +}; + +/** + * The actual events that are used by the client. + * + * @type {Object} + * @public + */ +Primus.prototype.reserved.events = { + 'reconnect scheduled': 1, + 'reconnect timeout': 1, + 'readyStateChange': 1, + 'reconnect failed': 1, + 'reconnected': 1, + 'reconnect': 1, + 'offline': 1, + 'timeout': 1, + 'online': 1, + 'error': 1, + 'close': 1, + 'open': 1, + 'data': 1, + 'end': 1 +}; + +/** + * Initialise the Primus and setup all parsers and internal listeners. + * + * @param {Object} options The original options object. + * @returns {Primus} + * @api private + */ +Primus.prototype.initialise = function initialise(options) { + var primus = this + , start; + + primus.recovery + .on('reconnected', primus.emits('reconnected')) + .on('reconnect failed', primus.emits('reconnect failed', function failed(next) { + primus.emit('end'); + next(); + })) + .on('reconnect timeout', primus.emits('reconnect timeout')) + .on('reconnect scheduled', primus.emits('reconnect scheduled')) + .on('reconnect', primus.emits('reconnect', function reconnect(next) { + primus.emit('outgoing::reconnect'); + next(); + })); + + primus.on('outgoing::open', function opening() { + var readyState = primus.readyState; + + primus.readyState = Primus.OPENING; + if (readyState !== primus.readyState) { + primus.emit('readyStateChange', 'opening'); + } + + start = +new Date(); + }); + + primus.on('incoming::open', function opened() { + var readyState = primus.readyState; + + if (primus.recovery.reconnecting()) { + primus.recovery.reconnected(); + } + + // + // The connection has been opened so we should set our state to + // (writ|read)able so our stream compatibility works as intended. + // + primus.writable = true; + primus.readable = true; + + // + // Make sure we are flagged as `online` as we've successfully opened the + // connection. + // + if (!primus.online) { + primus.online = true; + primus.emit('online'); + } + + primus.readyState = Primus.OPEN; + if (readyState !== primus.readyState) { + primus.emit('readyStateChange', 'open'); + } + + primus.latency = +new Date() - start; + primus.timers.clear('ping', 'pong'); + primus.heartbeat(); + + if (primus.buffer.length) { + var data = primus.buffer.slice() + , length = data.length + , i = 0; + + primus.buffer.length = 0; + + for (; i < length; i++) { + primus._write(data[i]); + } + } + + primus.emit('open'); + }); + + primus.on('incoming::pong', function pong(time) { + primus.online = true; + primus.timers.clear('pong'); + primus.heartbeat(); + + primus.latency = (+new Date()) - time; + }); + + primus.on('incoming::error', function error(e) { + var connect = primus.timers.active('connect') + , err = e; + + // + // When the error is not an Error instance we try to normalize it. + // + if ('string' === typeof e) { + err = new Error(e); + } else if (!(e instanceof Error) && 'object' === typeof e) { + // + // BrowserChannel and SockJS returns an object which contains some + // details of the error. In order to have a proper error we "copy" the + // details in an Error instance. + // + err = new Error(e.message || e.reason); + for (var key in e) { + if (Object.prototype.hasOwnProperty.call(e, key)) + err[key] = e[key]; + } + } + // + // We're still doing a reconnect attempt, it could be that we failed to + // connect because the server was down. Failing connect attempts should + // always emit an `error` event instead of a `open` event. + // + // + if (primus.recovery.reconnecting()) return primus.recovery.reconnected(err); + if (primus.listeners('error').length) primus.emit('error', err); + + // + // We received an error while connecting, this most likely the result of an + // unauthorized access to the server. + // + if (connect) { + if (~primus.options.strategy.indexOf('timeout')) { + primus.recovery.reconnect(); + } else { + primus.end(); + } + } + }); + + primus.on('incoming::data', function message(raw) { + primus.decoder(raw, function decoding(err, data) { + // + // Do a "safe" emit('error') when we fail to parse a message. We don't + // want to throw here as listening to errors should be optional. + // + if (err) return primus.listeners('error').length && primus.emit('error', err); + + // + // Handle all "primus::" prefixed protocol messages. + // + if (primus.protocol(data)) return; + primus.transforms(primus, primus, 'incoming', data, raw); + }); + }); + + primus.on('incoming::end', function end() { + var readyState = primus.readyState; + + // + // This `end` started with the receiving of a primus::server::close packet + // which indicated that the user/developer on the server closed the + // connection and it was not a result of a network disruption. So we should + // kill the connection without doing a reconnect. + // + if (primus.disconnect) { + primus.disconnect = false; + + return primus.end(); + } + + // + // Always set the readyState to closed, and if we're still connecting, close + // the connection so we're sure that everything after this if statement block + // is only executed because our readyState is set to `open`. + // + primus.readyState = Primus.CLOSED; + if (readyState !== primus.readyState) { + primus.emit('readyStateChange', 'end'); + } + + if (primus.timers.active('connect')) primus.end(); + if (readyState !== Primus.OPEN) { + return primus.recovery.reconnecting() + ? primus.recovery.reconnect() + : false; + } + + this.writable = false; + this.readable = false; + + // + // Clear all timers in case we're not going to reconnect. + // + this.timers.clear(); + + // + // Fire the `close` event as an indication of connection disruption. + // This is also fired by `primus#end` so it is emitted in all cases. + // + primus.emit('close'); + + // + // The disconnect was unintentional, probably because the server has + // shutdown, so if the reconnection is enabled start a reconnect procedure. + // + if (~primus.options.strategy.indexOf('disconnect')) { + return primus.recovery.reconnect(); + } + + primus.emit('outgoing::end'); + primus.emit('end'); + }); + + // + // Setup the real-time client. + // + primus.client(); + + // + // Process the potential plugins. + // + for (var plugin in primus.ark) { + primus.ark[plugin].call(primus, primus, options); + } + + // + // NOTE: The following code is only required if we're supporting network + // events as it requires access to browser globals. + // + if (!primus.NETWORK_EVENTS) return primus; + + /** + * Handler for offline notifications. + * + * @api private + */ + primus.offlineHandler = function offline() { + if (!primus.online) return; // Already or still offline, bailout. + + primus.online = false; + primus.emit('offline'); + primus.end(); + + // + // It is certainly possible that we're in a reconnection loop and that the + // user goes offline. In this case we want to kill the existing attempt so + // when the user goes online, it will attempt to reconnect freshly again. + // + primus.recovery.reset(); + }; + + /** + * Handler for online notifications. + * + * @api private + */ + primus.onlineHandler = function online() { + if (primus.online) return; // Already or still online, bailout. + + primus.online = true; + primus.emit('online'); + + if (~primus.options.strategy.indexOf('online')) { + primus.recovery.reconnect(); + } + }; + + if (window.addEventListener) { + window.addEventListener('offline', primus.offlineHandler, false); + window.addEventListener('online', primus.onlineHandler, false); + } else if (document.body.attachEvent){ + document.body.attachEvent('onoffline', primus.offlineHandler); + document.body.attachEvent('ononline', primus.onlineHandler); + } + + return primus; +}; + +/** + * Really dead simple protocol parser. We simply assume that every message that + * is prefixed with `primus::` could be used as some sort of protocol definition + * for Primus. + * + * @param {String} msg The data. + * @returns {Boolean} Is a protocol message. + * @api private + */ +Primus.prototype.protocol = function protocol(msg) { + if ( + 'string' !== typeof msg + || msg.indexOf('primus::') !== 0 + ) return false; + + var last = msg.indexOf(':', 8) + , value = msg.slice(last + 2); + + switch (msg.slice(8, last)) { + case 'pong': + this.emit('incoming::pong', +value); + break; + + case 'server': + // + // The server is closing the connection, forcefully disconnect so we don't + // reconnect again. + // + if ('close' === value) { + this.disconnect = true; + } + break; + + case 'id': + this.emit('incoming::id', value); + break; + + // + // Unknown protocol, somebody is probably sending `primus::` prefixed + // messages. + // + default: + return false; + } + + return true; +}; + +/** + * Execute the set of message transformers from Primus on the incoming or + * outgoing message. + * This function and it's content should be in sync with Spark#transforms in + * spark.js. + * + * @param {Primus} primus Reference to the Primus instance with message transformers. + * @param {Spark|Primus} connection Connection that receives or sends data. + * @param {String} type The type of message, 'incoming' or 'outgoing'. + * @param {Mixed} data The data to send or that has been received. + * @param {String} raw The raw encoded data. + * @returns {Primus} + * @api public + */ +Primus.prototype.transforms = function transforms(primus, connection, type, data, raw) { + var packet = { data: data } + , fns = primus.transformers[type]; + + // + // Iterate in series over the message transformers so we can allow optional + // asynchronous execution of message transformers which could for example + // retrieve additional data from the server, do extra decoding or even + // message validation. + // + (function transform(index, done) { + var transformer = fns[index++]; + + if (!transformer) return done(); + + if (1 === transformer.length) { + if (false === transformer.call(connection, packet)) { + // + // When false is returned by an incoming transformer it means that's + // being handled by the transformer and we should not emit the `data` + // event. + // + return; + } + + return transform(index, done); + } + + transformer.call(connection, packet, function finished(err, arg) { + if (err) return connection.emit('error', err); + if (false === arg) return; + + transform(index, done); + }); + }(0, function done() { + // + // We always emit 2 arguments for the data event, the first argument is the + // parsed data and the second argument is the raw string that we received. + // This allows you, for example, to do some validation on the parsed data + // and then save the raw string in your database without the stringify + // overhead. + // + if ('incoming' === type) return connection.emit('data', packet.data, raw); + + connection._write(packet.data); + })); + + return this; +}; + +/** + * Retrieve the current id from the server. + * + * @param {Function} fn Callback function. + * @returns {Primus} + * @api public + */ +Primus.prototype.id = function id(fn) { + if (this.socket && this.socket.id) return fn(this.socket.id); + + this._write('primus::id::'); + return this.once('incoming::id', fn); +}; + +/** + * Establish a connection with the server. When this function is called we + * assume that we don't have any open connections. If you do call it when you + * have a connection open, it could cause duplicate connections. + * + * @returns {Primus} + * @api public + */ +Primus.prototype.open = function open() { + context(this, 'open'); + + // + // Only start a `connection timeout` procedure if we're not reconnecting as + // that shouldn't count as an initial connection. This should be started + // before the connection is opened to capture failing connections and kill the + // timeout. + // + if (!this.recovery.reconnecting() && this.options.timeout) this.timeout(); + + this.emit('outgoing::open'); + return this; +}; + +/** + * Send a new message. + * + * @param {Mixed} data The data that needs to be written. + * @returns {Boolean} Always returns true as we don't support back pressure. + * @api public + */ +Primus.prototype.write = function write(data) { + context(this, 'write'); + this.transforms(this, this, 'outgoing', data); + + return true; +}; + +/** + * The actual message writer. + * + * @param {Mixed} data The message that needs to be written. + * @returns {Boolean} Successful write to the underlaying transport. + * @api private + */ +Primus.prototype._write = function write(data) { + var primus = this; + + // + // The connection is closed, normally this would already be done in the + // `spark.write` method, but as `_write` is used internally, we should also + // add the same check here to prevent potential crashes by writing to a dead + // socket. + // + if (Primus.OPEN !== primus.readyState) { + // + // If the buffer is at capacity, remove the first item. + // + if (this.buffer.length === this.options.queueSize) { + this.buffer.splice(0, 1); + } + + this.buffer.push(data); + return false; + } + + primus.encoder(data, function encoded(err, packet) { + // + // Do a "safe" emit('error') when we fail to parse a message. We don't + // want to throw here as listening to errors should be optional. + // + if (err) return primus.listeners('error').length && primus.emit('error', err); + + // + // Hack 1: \u2028 and \u2029 are allowed inside a JSON string, but JavaScript + // defines them as newline separators. Unescaped control characters are not + // allowed inside JSON strings, so this causes an error at parse time. We + // work around this issue by escaping these characters. This can cause + // errors with JSONP requests or if the string is just evaluated. + // + if ('string' === typeof packet) { + if (~packet.indexOf('\u2028')) packet = packet.replace(u2028, '\\u2028'); + if (~packet.indexOf('\u2029')) packet = packet.replace(u2029, '\\u2029'); + } + + primus.emit('outgoing::data', packet); + }); + + return true; +}; + +/** + * Send a new heartbeat over the connection to ensure that we're still + * connected and our internet connection didn't drop. We cannot use server side + * heartbeats for this unfortunately. + * + * @returns {Primus} + * @api private + */ +Primus.prototype.heartbeat = function heartbeat() { + var primus = this; + + if (!primus.options.ping) return primus; + + /** + * Exterminate the connection as we've timed out. + * + * @api private + */ + function pong() { + primus.timers.clear('pong'); + + // + // The network events already captured the offline event. + // + if (!primus.online) return; + + primus.online = false; + primus.emit('offline'); + primus.emit('incoming::end'); + } + + /** + * We should send a ping message to the server. + * + * @api private + */ + function ping() { + var value = +new Date(); + + primus.timers.clear('ping'); + primus._write('primus::ping::'+ value); + primus.emit('outgoing::ping', value); + primus.timers.setTimeout('pong', pong, primus.options.pong); + } + + primus.timers.setTimeout('ping', ping, primus.options.ping); + return this; +}; + +/** + * Start a connection timeout. + * + * @returns {Primus} + * @api private + */ +Primus.prototype.timeout = function timeout() { + var primus = this; + + /** + * Remove all references to the timeout listener as we've received an event + * that can be used to determine state. + * + * @api private + */ + function remove() { + primus.removeListener('error', remove) + .removeListener('open', remove) + .removeListener('end', remove) + .timers.clear('connect'); + } + + primus.timers.setTimeout('connect', function expired() { + remove(); // Clean up old references. + + if (primus.readyState === Primus.OPEN || primus.recovery.reconnecting()) { + return; + } + + primus.emit('timeout'); + + // + // We failed to connect to the server. + // + if (~primus.options.strategy.indexOf('timeout')) { + primus.recovery.reconnect(); + } else { + primus.end(); + } + }, primus.options.timeout); + + return primus.on('error', remove) + .on('open', remove) + .on('end', remove); +}; + +/** + * Close the connection completely. + * + * @param {Mixed} data last packet of data. + * @returns {Primus} + * @api public + */ +Primus.prototype.end = function end(data) { + context(this, 'end'); + + if ( + this.readyState === Primus.CLOSED + && !this.timers.active('connect') + && !this.timers.active('open') + ) { + // + // If we are reconnecting stop the reconnection procedure. + // + if (this.recovery.reconnecting()) { + this.recovery.reset(); + this.emit('end'); + } + + return this; + } + + if (data !== undefined) this.write(data); + + this.writable = false; + this.readable = false; + + var readyState = this.readyState; + this.readyState = Primus.CLOSED; + + if (readyState !== this.readyState) { + this.emit('readyStateChange', 'end'); + } + + this.timers.clear(); + this.emit('outgoing::end'); + this.emit('close'); + this.emit('end'); + + return this; +}; + +/** + * Completely demolish the Primus instance and forcefully nuke all references. + * + * @returns {Boolean} + * @api public + */ +Primus.prototype.destroy = destroy('url timers options recovery socket transport transformers', { + before: 'end', + after: ['removeAllListeners', function detach() { + if (!this.NETWORK_EVENTS) return; + + if (window.addEventListener) { + window.removeEventListener('offline', this.offlineHandler); + window.removeEventListener('online', this.onlineHandler); + } else if (document.body.attachEvent){ + document.body.detachEvent('onoffline', this.offlineHandler); + document.body.detachEvent('ononline', this.onlineHandler); + } + }] +}); + +/** + * Create a shallow clone of a given object. + * + * @param {Object} obj The object that needs to be cloned. + * @returns {Object} Copy. + * @api private + */ +Primus.prototype.clone = function clone(obj) { + return this.merge({}, obj); +}; + +/** + * Merge different objects in to one target object. + * + * @param {Object} target The object where everything should be merged in. + * @returns {Object} Original target with all merged objects. + * @api private + */ +Primus.prototype.merge = function merge(target) { + for (var i = 1, key, obj; i < arguments.length; i++) { + obj = arguments[i]; + + for (key in obj) { + if (Object.prototype.hasOwnProperty.call(obj, key)) + target[key] = obj[key]; + } + } + + return target; +}; + +/** + * Parse the connection string. + * + * @type {Function} + * @param {String} url Connection URL. + * @returns {Object} Parsed connection. + * @api private + */ +Primus.prototype.parse = _dereq_('url-parse'); + +/** + * Parse a query string. + * + * @param {String} query The query string that needs to be parsed. + * @returns {Object} Parsed query string. + * @api private + */ +Primus.prototype.querystring = qs.parse; +/** + * Transform a query string object back into string equiv. + * + * @param {Object} obj The query string object. + * @returns {String} + * @api private + */ +Primus.prototype.querystringify = qs.stringify; + +/** + * Generates a connection URI. + * + * @param {String} protocol The protocol that should used to crate the URI. + * @returns {String|options} The URL. + * @api private + */ +Primus.prototype.uri = function uri(options) { + var url = this.url + , server = [] + , qsa = false; + + // + // Query strings are only allowed when we've received clearance for it. + // + if (options.query) qsa = true; + + options = options || {}; + options.protocol = 'protocol' in options + ? options.protocol + : 'http:'; + options.query = url.query && qsa + ? url.query.slice(1) + : false; + options.secure = 'secure' in options + ? options.secure + : url.protocol === 'https:' || url.protocol === 'wss:'; + options.auth = 'auth' in options + ? options.auth + : url.auth; + options.pathname = 'pathname' in options + ? options.pathname + : this.pathname; + options.port = 'port' in options + ? +options.port + : +url.port || (options.secure ? 443 : 80); + + // + // Allow transformation of the options before we construct a full URL from it. + // + this.emit('outgoing::url', options); + + // + // We need to make sure that we create a unique connection URL every time to + // prevent back forward cache from becoming an issue. We're doing this by + // forcing an cache busting query string in to the URL. + // + var querystring = this.querystring(options.query || ''); + querystring._primuscb = yeast(); + options.query = this.querystringify(querystring); + + // + // Automatically suffix the protocol so we can supply `ws:` and `http:` and + // it gets transformed correctly. + // + server.push(options.secure ? options.protocol.replace(':', 's:') : options.protocol, ''); + + server.push(options.auth ? options.auth +'@'+ url.host : url.host); + + // + // Pathnames are optional as some Transformers would just use the pathname + // directly. + // + if (options.pathname) server.push(options.pathname.slice(1)); + + // + // Optionally add a search query. + // + if (qsa) server[server.length - 1] += '?'+ options.query; + else delete options.query; + + if (options.object) return options; + return server.join('/'); +}; + +/** + * Register a new message transformer. This allows you to easily manipulate incoming + * and outgoing data which is particularity handy for plugins that want to send + * meta data together with the messages. + * + * @param {String} type Incoming or outgoing + * @param {Function} fn A new message transformer. + * @returns {Primus} + * @api public + */ +Primus.prototype.transform = function transform(type, fn) { + context(this, 'transform'); + + if (!(type in this.transformers)) { + return this.critical(new Error('Invalid transformer type')); + } + + this.transformers[type].push(fn); + return this; +}; + +/** + * A critical error has occurred, if we have an `error` listener, emit it there. + * If not, throw it, so we get a stack trace + proper error message. + * + * @param {Error} err The critical error. + * @returns {Primus} + * @api private + */ +Primus.prototype.critical = function critical(err) { + if (this.listeners('error').length) { + this.emit('error', err); + return this; + } + + throw err; +}; + +/** + * Syntax sugar, adopt a Socket.IO like API. + * + * @param {String} url The URL we want to connect to. + * @param {Object} options Connection options. + * @returns {Primus} + * @api public + */ +Primus.connect = function connect(url, options) { + return new Primus(url, options); +}; + +// +// Expose the EventEmitter so it can be re-used by wrapping libraries we're also +// exposing the Stream interface. +// +Primus.EventEmitter = EventEmitter; + +// +// These libraries are automatically inserted at the server-side using the +// Primus#library method. +// +Primus.prototype.client = function client() { + var primus = this + , socket; + + // + // Select an available WebSocket factory. + // + var Factory = (function factory() { + if ('undefined' !== typeof WebSocket) return WebSocket; + if ('undefined' !== typeof MozWebSocket) return MozWebSocket; + + try { return Primus.requires('ws'); } + catch (e) {} + + return undefined; + })(); + + if (!Factory) return primus.critical(new Error( + 'Missing required `ws` module. Please run `npm install --save ws`' + )); + + // + // Connect to the given URL. + // + primus.on('outgoing::open', function opening() { + primus.emit('outgoing::end'); + + // + // FireFox will throw an error when we try to establish a connection from + // a secure page to an unsecured WebSocket connection. This is inconsistent + // behaviour between different browsers. This should ideally be solved in + // Primus when we connect. + // + try { + var prot = primus.url.protocol === 'ws+unix:' ? 'ws+unix:' : 'ws:' + , qsa = prot === 'ws:'; + + // + // Only allow primus.transport object in Node.js, it will throw in + // browsers with a TypeError if we supply to much arguments. + // + if (Factory.length === 3) { + primus.socket = socket = new Factory( + primus.uri({ protocol: prot, query: qsa }), // URL + [], // Sub protocols + primus.transport // options. + ); + } else { + primus.socket = socket = new Factory(primus.uri({ + protocol: prot, + query: qsa + })); + + socket.binaryType = 'arraybuffer'; + } + } catch (e) { return primus.emit('error', e); } + + // + // Setup the Event handlers. + // + socket.onopen = primus.emits('incoming::open'); + socket.onerror = primus.emits('incoming::error'); + socket.onclose = primus.emits('incoming::end'); + socket.onmessage = primus.emits('incoming::data', function parse(next, evt) { + next(undefined, evt.data); + }); + }); + + // + // We need to write a new message to the socket. + // + primus.on('outgoing::data', function write(message) { + if (!socket || socket.readyState !== Factory.OPEN) return; + + try { socket.send(message); } + catch (e) { primus.emit('incoming::error', e); } + }); + + // + // Attempt to reconnect the socket. + // + primus.on('outgoing::reconnect', function reconnect() { + primus.emit('outgoing::open'); + }); + + // + // We need to close the socket. + // + primus.on('outgoing::end', function close() { + if (!socket) return; + + socket.onerror = socket.onopen = socket.onclose = socket.onmessage = function () {}; + socket.close(); + socket = null; + }); +}; +Primus.prototype.authorization = false; +Primus.prototype.pathname = "/primus"; +Primus.prototype.encoder = function encoder(data, fn) { + var err; + + try { data = JSON.stringify(data); } + catch (e) { err = e; } + + fn(err, data); +}; +Primus.prototype.decoder = function decoder(data, fn) { + var err; + + if ('string' !== typeof data) return fn(err, data); + + try { data = JSON.parse(data); } + catch (e) { err = e; } + + fn(err, data); +}; +Primus.prototype.version = "6.0.6"; + +if ( + 'undefined' !== typeof document + && 'undefined' !== typeof navigator +) { + // + // Hack 2: If you press ESC in FireFox it will close all active connections. + // Normally this makes sense, when your page is still loading. But versions + // before FireFox 22 will close all connections including WebSocket connections + // after page load. One way to prevent this is to do a `preventDefault()` and + // cancel the operation before it bubbles up to the browsers default handler. + // It needs to be added as `keydown` event, if it's added keyup it will not be + // able to prevent the connection from being closed. + // + if (document.addEventListener) { + document.addEventListener('keydown', function keydown(e) { + if (e.keyCode !== 27 || !e.preventDefault) return; + + e.preventDefault(); + }, false); + } + + // + // Hack 3: This is a Mac/Apple bug only, when you're behind a reverse proxy or + // have you network settings set to `automatic proxy discovery` the safari + // browser will crash when the WebSocket constructor is initialised. There is + // no way to detect the usage of these proxies available in JavaScript so we + // need to do some nasty browser sniffing. This only affects Safari versions + // lower then 5.1.4 + // + var ua = (navigator.userAgent || '').toLowerCase() + , parsed = ua.match(/.+(?:rv|it|ra|ie)[\/: ](\d+)\.(\d+)(?:\.(\d+))?/) || [] + , version = +[parsed[1], parsed[2]].join('.'); + + if ( + !~ua.indexOf('chrome') + && ~ua.indexOf('safari') + && version < 534.54 + ) { + Primus.prototype.AVOID_WEBSOCKETS = true; + } +} + +// +// Expose the library. +// +module.exports = Primus; + +},{"demolish":1,"emits":2,"eventemitter3":3,"inherits":4,"querystringify":7,"recovery":8,"tick-tock":11,"url-parse":12,"yeast":14}]},{},[15])(15); + return Primus; +}, +[ + +]); \ No newline at end of file diff --git a/test/vendor/ember-data.min.js b/test/vendor/ember-data.min.js new file mode 100644 index 0000000..62ba86a --- /dev/null +++ b/test/vendor/ember-data.min.js @@ -0,0 +1,4 @@ +(function(){"use strict";var e=Ember;var r=Ember.get;var t=Ember.Mixin.create({buildURL:function(e,r,t,i,n){switch(i){case"findRecord":return this.urlForFindRecord(r,e,t);case"findAll":return this.urlForFindAll(e);case"query":return this.urlForQuery(n,e);case"queryRecord":return this.urlForQueryRecord(n,e);case"findMany":return this.urlForFindMany(r,e,t);case"findHasMany":return this.urlForFindHasMany(r,e);case"findBelongsTo":return this.urlForFindBelongsTo(r,e);case"createRecord":return this.urlForCreateRecord(e,t);case"updateRecord":return this.urlForUpdateRecord(r,e,t);case"deleteRecord":return this.urlForDeleteRecord(r,e,t);default:return this._buildURL(e,r)}},_buildURL:function(e,t){var i=[];var n=r(this,"host");var a=this.urlPrefix();var o;if(e){o=this.pathForType(e);if(o){i.push(o)}}if(t){i.push(encodeURIComponent(t))}if(a){i.unshift(a)}i=i.join("/");if(!n&&i&&i.charAt(0)!=="/"){i="/"+i}return i},urlForFindRecord:function(e,r,t){return this._buildURL(r,e)},urlForFindAll:function(e){return this._buildURL(e)},urlForQuery:function(e,r){return this._buildURL(r)},urlForQueryRecord:function(e,r){return this._buildURL(r)},urlForFindMany:function(e,r,t){return this._buildURL(r)},urlForFindHasMany:function(e,r){return this._buildURL(r,e)},urlForFindBelongsTo:function(e,r){return this._buildURL(r,e)},urlForCreateRecord:function(e,r){return this._buildURL(e)},urlForUpdateRecord:function(e,r,t){return this._buildURL(r,e)},urlForDeleteRecord:function(e,r,t){return this._buildURL(r,e)},urlPrefix:function(e,t){var i=r(this,"host");var n=r(this,"namespace");var a=[];if(e){if(/^\/\//.test(e)){}else if(e.charAt(0)==="/"){if(i){e=e.slice(1);a.push(i)}}else if(!/^http(s)?:\/\//.test(e)){a.push(t)}}else{if(i){a.push(i)}if(n){a.push(n)}}if(e){a.push(e)}return a.join("/")},pathForType:function(e){var r=Ember.String.camelize(e);return Ember.String.pluralize(r)}});var i=Ember.Error;var n=/^\/?data\/(attributes|relationships)\/(.*)/;function a(e){var r=arguments.length<=1||arguments[1]===undefined?"Adapter operation failed":arguments[1];i.call(this,r);this.errors=e||[{title:"Adapter Error",detail:r}]}a.prototype=Object.create(i.prototype);function o(e){if(!Ember.isArray(e)){e=l(e)}a.call(this,e,"The adapter rejected the commit because it was invalid")}o.prototype=Object.create(a.prototype);function s(){a.call(this,null,"The adapter operation timed out")}s.prototype=Object.create(a.prototype);function u(){a.call(this,null,"The adapter operation was aborted")}u.prototype=Object.create(a.prototype);function l(e){var r=[];if(Ember.isPresent(e)){Object.keys(e).forEach(function(t){var i=Ember.makeArray(e[t]);for(var n=0;n=t){o=0;s.push([])}o+=r;var i=s.length-1;s[i].push(e)});return s}var o=[];t.forEach(function(e,r){var t="&ids%5B%5D=".length;var i=a(e,n,t);i.forEach(function(e){return o.push(e)})});return o},handleResponse:function(e,r,t){if(this.isSuccess(e,r,t)){return t}else if(this.isInvalid(e,r,t)){return new o(t.errors)}var i=this.normalizeErrorResponse(e,r,t);return new a(i)},isSuccess:function(e,r,t){return e>=200&&e<300||e===304},isInvalid:function(e,r,t){return e===422},ajax:function(e,r,t){var i=this;return new Ember.RSVP.Promise(function(n,o){var l=i.ajaxOptions(e,r,t);l.success=function(e,r,t){var s=undefined;if(!(s instanceof a)){s=i.handleResponse(t.status,F(t.getAllResponseHeaders()),s||e)}if(s instanceof a){Ember.run(null,o,s)}else{Ember.run(null,n,s)}};l.error=function(e,r,t){var n=undefined;if(!(n instanceof Error)){if(t instanceof Error){n=t}else if(r==="timeout"){n=new s}else if(r==="abort"){n=new u}else{n=i.handleResponse(e.status,F(e.getAllResponseHeaders()),i.parseErrorResponse(e.responseText)||t)}}Ember.run(null,o,n)};Ember.$.ajax(l)},"DS: RESTAdapter#ajax "+r+" to "+e)},ajaxOptions:function(e,r,t){var i=t||{};i.url=e;i.type=r;i.dataType="json";i.context=this;if(i.data&&r!=="GET"){i.contentType="application/json; charset=utf-8";i.data=JSON.stringify(i.data)}var n=E(this,"headers");if(n!==undefined){i.beforeSend=function(e){Object.keys(n).forEach(function(r){return e.setRequestHeader(r,n[r])})}}return i},parseErrorResponse:function(e){var r=e;try{r=Ember.$.parseJSON(e)}catch(t){}return r},normalizeErrorResponse:function(e,r,t){if(t&&typeof t==="object"&&t.errors){return t.errors}else{return[{status:""+e,title:"The backend responded with an error",detail:""+t}]}}});function F(e){var r=Object.create(null);if(!e){return r}var t=e.split("\r\n");for(var i=0;i0){var o=n.substring(0,a);var s=n.substring(a+2);r[o]=s}}return r}function A(e,r){if(typeof String.prototype.endsWith!=="function"){return e.indexOf(r,e.length-r.length)!==-1}else{return e.endsWith(r)}}var M=_;var z=M.extend({defaultSerializer:"-json-api",ajaxOptions:function(e,r,t){var i=this._super.apply(this,arguments);if(i.contentType){i.contentType="application/vnd.api+json"}var n=i.beforeSend;i.beforeSend=function(e){e.setRequestHeader("Accept","application/vnd.api+json");if(n){n(e)}};return i},findMany:function(e,r,t,i){var n=this.buildURL(r.modelName,t,i,"findMany");return this.ajax(n,"GET",{data:{filter:{id:t.join(",")}}})},pathForType:function(e){var r=Ember.String.dasherize(e);return Ember.String.pluralize(r)},updateRecord:function(e,r,t){var i={};var n=e.serializerFor(r.modelName);n.serializeIntoHash(i,r,t,{includeId:true});var a=t.id;var o=this.buildURL(r.modelName,a,t,"updateRecord");return this.ajax(o,"PATCH",{data:i})}});var k=Ember.Namespace.create({VERSION:"2.0.0"});if(Ember.libraries){Ember.libraries.registerCoreLibrary("Ember Data",k.VERSION)}var S={};Ember.merge(Ember.FEATURES,S);var T=k;var O=C;function C(e){return Ember.String.dasherize(e)}var D=Ember.RSVP.Promise;var w=Ember.get;var P=Ember.ArrayProxy.extend(Ember.PromiseProxyMixin);var x=Ember.ObjectProxy.extend(Ember.PromiseProxyMixin);var N=function(e,r){return x.create({promise:D.resolve(e,r)})};var I=function(e,r){return P.create({promise:D.resolve(e,r)})};function j(e){return function(){var r=w(this,"content");return r[e].apply(r,arguments)}}var L=P.extend({reload:function(){return L.create({promise:w(this,"content").reload()})},createRecord:j("createRecord"),on:j("on"),one:j("one"),trigger:j("trigger"),off:j("off"),has:j("has")});var $=function(e,r){return L.create({promise:D.resolve(e,r)})};var K=Ember.get;function B(e){var r=Array.prototype.slice.call(arguments,1);return function(){return e.apply(undefined,r)}}function H(e,r){var t=e["finally"](function(){if(!r()){t._subscribers.length=0}});return t}function U(e){return!(K(e,"isDestroyed")||K(e,"isDestroying"))}var V=Ember.get;var q=Ember.set;var W=Ember.isEmpty;var Q=Ember.makeArray;var J=Ember.ArrayProxy.extend(Ember.Evented,{registerHandlers:function(e,r,t){this.on("becameInvalid",e,r);this.on("becameValid",e,t)},errorsByAttributeName:Ember.computed(function(){return g.create({defaultValue:function(){return Ember.A()}})}),errorsFor:function(e){return V(this,"errorsByAttributeName").get(e)},messages:Ember.computed.mapBy("content","message"),content:Ember.computed(function(){return Ember.A()}),unknownProperty:function(e){var r=this.errorsFor(e);if(W(r)){return null}return r},isEmpty:Ember.computed.not("length").readOnly(),add:function(e,r){var t=V(this,"isEmpty");r=this._findOrCreateMessages(e,r);this.addObjects(r);V(this,"errorsByAttributeName").get(e).addObjects(r);this.notifyPropertyChange(e);if(t&&!V(this,"isEmpty")){this.trigger("becameInvalid")}},_findOrCreateMessages:function(e,r){var t=this.errorsFor(e);return Q(r).map(function(r){return t.findBy("message",r)||{attribute:e,message:r}})},remove:function(e){if(V(this,"isEmpty")){return}var r=this.rejectBy("attribute",e);q(this,"content",r);V(this,"errorsByAttributeName")["delete"](e);this.notifyPropertyChange(e);if(V(this,"isEmpty")){this.trigger("becameValid")}},clear:function(){if(V(this,"isEmpty")){return}var e=V(this,"errorsByAttributeName");var r=Ember.A();e.forEach(function(e,t){r.push(t)});e.clear();r.forEach(function(e){this.notifyPropertyChange(e)},this);this._super();this.trigger("becameValid")},has:function(e){return!W(this.errorsFor(e))}});var X=Ember.get;var G=Ember.merge;var Y=Ember.copy;function Z(e,r){var t=[];e.forEach(function(e){if(r.indexOf(e)>=0){t.push(e)}});return t}var ee=["currentState","data","store"];var re=Ember.computed("currentState",function(e){return X(this._internalModel.currentState,e)}).readOnly();var te=Ember.Object.extend(Ember.Evented,{_recordArrays:undefined,_relationships:undefined,_internalModel:null,store:null,isEmpty:re,isLoading:re,isLoaded:re,hasDirtyAttributes:Ember.computed("currentState.isDirty",function(){return this.get("currentState.isDirty")}),isSaving:re,isDeleted:re,isNew:re,isValid:re,dirtyType:re,isError:false,isReloading:false,id:null,errors:Ember.computed(function(){var e=J.create();e.registerHandlers(this._internalModel,function(){this.send("becameInvalid")},function(){this.send("becameValid")});return e}).readOnly(),adapterError:null,serialize:function(e){return this.store.serialize(this,e)},toJSON:function(e){var r=this.store.serializerFor("-default");var t=this._internalModel.createSnapshot();return r.serialize(t,e)},ready:Ember.K,didLoad:Ember.K,didUpdate:Ember.K,didCreate:Ember.K,didDelete:Ember.K,becameInvalid:Ember.K,becameError:Ember.K,rolledBack:Ember.K,data:Ember.computed.readOnly("_internalModel._data"),send:function(e,r){return this._internalModel.send(e,r)},transitionTo:function(e){return this._internalModel.transitionTo(e)},deleteRecord:function(){this._internalModel.deleteRecord()},destroyRecord:function(e){this.deleteRecord();return this.save(e)},unloadRecord:function(){if(this.isDestroyed){return}this._internalModel.unloadRecord()},_notifyProperties:function(e){Ember.beginPropertyChanges();var r;for(var t=0,i=e.length;t0;if(!i){e.send("rolledBack")}},pushedData:Ember.K,becomeDirty:Ember.K,willCommit:function(e){e.transitionTo("inFlight")},reloadRecord:function(e,r){r(e.store.reloadRecord(e))},rolledBack:function(e){e.transitionTo("loaded.saved")},becameInvalid:function(e){e.transitionTo("invalid")},rollback:function(e){e.rollbackAttributes();e.triggerLater("ready")}},inFlight:{isSaving:true,didSetProperty:qe,becomeDirty:Ember.K,pushedData:Ember.K,unloadRecord:Ze,willCommit:Ember.K,didCommit:function(e){var r=Ve(this,"dirtyType");e.transitionTo("saved");e.send("invokeLifecycleCallbacks",r)},becameInvalid:function(e){e.transitionTo("invalid");e.send("invokeLifecycleCallbacks")},becameError:function(e){e.transitionTo("uncommitted");e.triggerLater("becameError",e)}},invalid:{isValid:false,deleteRecord:function(e){e.transitionTo("deleted.uncommitted")},didSetProperty:function(e,r){e.removeErrorMessageFromAttribute(r.name);qe(e,r)},becomeDirty:Ember.K,pushedData:Ember.K,willCommit:function(e){e.clearErrorMessages();e.transitionTo("inFlight")},rolledBack:function(e){e.clearErrorMessages();e.transitionTo("loaded.saved");e.triggerLater("ready")},becameValid:function(e){e.transitionTo("uncommitted")},invokeLifecycleCallbacks:function(e){e.triggerLater("becameInvalid",e)},exit:function(e){e._inFlightAttributes=Object.create(null)}}};function Qe(e){var r={};var t;for(var i in e){t=e[i];if(t&&typeof t==="object"){r[i]=Qe(t)}else{r[i]=t}}return r}function Je(e,r){for(var t in r){e[t]=r[t]}return e}function Xe(e){var r=Qe(We);return Je(r,e)}var Ge=Xe({dirtyType:"created",isNew:true});Ge.invalid.rolledBack=function(e){e.transitionTo("deleted.saved")};Ge.uncommitted.rolledBack=function(e){e.transitionTo("deleted.saved")};var Ye=Xe({dirtyType:"updated"});Ge.uncommitted.deleteRecord=function(e){ +e.transitionTo("deleted.saved");e.send("invokeLifecycleCallbacks")};Ge.uncommitted.rollback=function(e){We.uncommitted.rollback.apply(this,arguments);e.transitionTo("deleted.saved")};Ge.uncommitted.pushedData=function(e){e.transitionTo("loaded.updated.uncommitted");e.triggerLater("didLoad")};Ge.uncommitted.propertyWasReset=Ember.K;function Ze(e){}Ye.inFlight.unloadRecord=Ze;Ye.uncommitted.deleteRecord=function(e){e.transitionTo("deleted.uncommitted")};var er={isEmpty:false,isLoading:false,isLoaded:false,isDirty:false,isSaving:false,isDeleted:false,isNew:false,isValid:true,rolledBack:Ember.K,unloadRecord:function(e){e.clearRelationships();e.transitionTo("deleted.saved")},propertyWasReset:Ember.K,empty:{isEmpty:true,loadingData:function(e,r){e._loadingPromise=r;e.transitionTo("loading")},loadedData:function(e){e.transitionTo("loaded.created.uncommitted");e.triggerLater("ready")},pushedData:function(e){e.transitionTo("loaded.saved");e.triggerLater("didLoad");e.triggerLater("ready")}},loading:{isLoading:true,exit:function(e){e._loadingPromise=null},pushedData:function(e){e.transitionTo("loaded.saved");e.triggerLater("didLoad");e.triggerLater("ready");e.didCleanError()},becameError:function(e){e.triggerLater("becameError",e)},notFound:function(e){e.transitionTo("empty")}},loaded:{initialState:"saved",isLoaded:true,loadingData:Ember.K,saved:{setup:function(e){var r=e._attributes;var t=Object.keys(r).length>0;if(t){e.adapterDidDirty()}},didSetProperty:qe,pushedData:Ember.K,becomeDirty:function(e){e.transitionTo("updated.uncommitted")},willCommit:function(e){e.transitionTo("updated.inFlight")},reloadRecord:function(e,r){r(e.store.reloadRecord(e))},deleteRecord:function(e){e.transitionTo("deleted.uncommitted")},unloadRecord:function(e){e.clearRelationships();e.transitionTo("deleted.saved")},didCommit:function(e){e.send("invokeLifecycleCallbacks",Ve(e,"lastDirtyType"))},notFound:Ember.K},created:Ge,updated:Ye},deleted:{initialState:"uncommitted",dirtyType:"deleted",isDeleted:true,isLoaded:true,isDirty:true,setup:function(e){e.updateRecordArrays()},uncommitted:{willCommit:function(e){e.transitionTo("inFlight")},rollback:function(e){e.rollbackAttributes();e.triggerLater("ready")},pushedData:Ember.K,becomeDirty:Ember.K,deleteRecord:Ember.K,rolledBack:function(e){e.transitionTo("loaded.saved");e.triggerLater("ready")}},inFlight:{isSaving:true,unloadRecord:Ze,willCommit:Ember.K,didCommit:function(e){e.transitionTo("saved");e.send("invokeLifecycleCallbacks")},becameError:function(e){e.transitionTo("uncommitted");e.triggerLater("becameError",e)},becameInvalid:function(e){e.transitionTo("invalid");e.triggerLater("becameInvalid",e)}},saved:{isDirty:false,setup:function(e){e.clearRelationships();var r=e.store;r._dematerializeRecord(e)},invokeLifecycleCallbacks:function(e){e.triggerLater("didDelete",e);e.triggerLater("didCommit",e)},willCommit:Ember.K,didCommit:Ember.K},invalid:{isValid:false,didSetProperty:function(e,r){e.removeErrorMessageFromAttribute(r.name);qe(e,r)},deleteRecord:Ember.K,becomeDirty:Ember.K,willCommit:Ember.K,rolledBack:function(e){e.clearErrorMessages();e.transitionTo("loaded.saved");e.triggerLater("ready")},becameValid:function(e){e.transitionTo("uncommitted")}}},invokeLifecycleCallbacks:function(e,r){if(r==="created"){e.triggerLater("didCreate",e)}else{e.triggerLater("didUpdate",e)}e.triggerLater("didCommit",e)}};function rr(e,r,t){e=Je(r?Object.create(r):{},e);e.parentState=r;e.stateName=t;for(var i in e){if(!e.hasOwnProperty(i)||i==="parentState"||i==="stateName"){continue}if(typeof e[i]==="object"){e[i]=rr(e[i],e,t+"."+i)}}return e}er=rr(er,null,"root");var tr=er;var ir=nr;function nr(e,r,t,i){var n=i.options.async;this.members=new we;this.canonicalMembers=new we;this.store=e;this.key=i.key;this.inverseKey=t;this.record=r;this.isAsync=typeof n==="undefined"?true:n;this.relationshipMeta=i;this.inverseKeyForImplicit=this.record.constructor.modelName+this.key;this.linkPromise=null;this.meta=null;this.hasData=false}nr.prototype={constructor:nr,destroy:Ember.K,updateMeta:function(e){this.meta=e},clear:function(){var e=this.members.list;var r;while(e.length>0){r=e[0];this.removeRecord(r)}},removeRecords:function(e){var r=this;e.forEach(function(e){return r.removeRecord(e)})},addRecords:function(e,r){var t=this;e.forEach(function(e){t.addRecord(e,r);if(r!==undefined){r++}})},addCanonicalRecords:function(e,r){for(var t=0;t0){i=this.currentState.slice(e,e+r);this.get("relationship").removeRecords(i)}if(t){this.get("relationship").addRecords(t.map(function(e){return e._internalModel}),e)}},promise:null,loadingRecordsCount:function(e){this.loadingRecordsCount=e},loadedRecord:function(){this.loadingRecordsCount--;if(this.loadingRecordsCount===0){or(this,"isLoaded",true);this.trigger("didLoad")}},reload:function(){return this.relationship.reload()},save:function(){var e=this;var r="DS: ManyArray#save "+ar(this,"type");var t=Ember.RSVP.all(this.invoke("save"),r).then(function(r){return e},null,"DS: ManyArray#save return ManyArray");return P.create({promise:t})},createRecord:function(e){var r=ar(this,"store");var t=ar(this,"type");var i;i=r.createRecord(t.modelName,e);this.pushObject(i);return i}});var ur=function(r,t,i){var n=i.type.modelName;var a=r.type.modelName;var o=t.key;var s=r.store.modelFor(t.type);var u="You cannot add a record of type '"+n+"' to the '"+a+"."+o+"' relationship (only '"+s.modelName+"' allowed)";e.assert(u,lr(s,i))};function lr(r,t){if(r.__isMixin){return r.__mixin.detect(t.type.PrototypeMixin)}if(e.MODEL_FACTORY_INJECTIONS){r=r.superclass}return r.detect(t.type)}var dr=cr;function cr(e,r,t,i){this._super$constructor(e,r,t,i);this.belongsToType=i.type;this.canonicalState=[];this.manyArray=sr.create({canonicalState:this.canonicalState,store:this.store,relationship:this,type:this.store.modelFor(this.belongsToType),record:r});this.isPolymorphic=i.options.polymorphic;this.manyArray.isPolymorphic=this.isPolymorphic}cr.prototype=Object.create(ir.prototype);cr.prototype.constructor=cr;cr.prototype._super$constructor=ir;cr.prototype.destroy=function(){this.manyArray.destroy()};cr.prototype._super$updateMeta=ir.prototype.updateMeta;cr.prototype.updateMeta=function(e){this._super$updateMeta(e);this.manyArray.set("meta",e)};cr.prototype._super$addCanonicalRecord=ir.prototype.addCanonicalRecord;cr.prototype.addCanonicalRecord=function(e,r){if(this.canonicalMembers.has(e)){return}if(r!==undefined){this.canonicalState.splice(r,0,e)}else{this.canonicalState.push(e)}this._super$addCanonicalRecord(e,r)};cr.prototype._super$addRecord=ir.prototype.addRecord;cr.prototype.addRecord=function(e,r){if(this.members.has(e)){return}this._super$addRecord(e,r);this.manyArray.internalAddRecords([e],r)};cr.prototype._super$removeCanonicalRecordFromOwn=ir.prototype.removeCanonicalRecordFromOwn;cr.prototype.removeCanonicalRecordFromOwn=function(e,r){var t=r;if(!this.canonicalMembers.has(e)){return}if(t===undefined){t=this.canonicalState.indexOf(e)}if(t>-1){this.canonicalState.splice(t,1)}this._super$removeCanonicalRecordFromOwn(e,r)};cr.prototype._super$flushCanonical=ir.prototype.flushCanonical;cr.prototype.flushCanonical=function(){this.manyArray.flushCanonical();this._super$flushCanonical()};cr.prototype._super$removeRecordFromOwn=ir.prototype.removeRecordFromOwn;cr.prototype.removeRecordFromOwn=function(e,r){if(!this.members.has(e)){return}this._super$removeRecordFromOwn(e,r);if(r!==undefined){this.manyArray.currentState.removeAt(r)}else{this.manyArray.internalRemoveRecords([e])}};cr.prototype.notifyRecordRelationshipAdded=function(e,r){ur(this.record,this.relationshipMeta,e);this.record.notifyHasManyAdded(this.key,e,r)};cr.prototype.reload=function(){var e=this;if(this.link){return this.fetchLink()}else{return this.store.scheduleFetchMany(this.manyArray.toArray()).then(function(){e.manyArray.set("isLoaded",true);return e.manyArray})}};cr.prototype.computeChanges=function(e){var r=this.canonicalMembers;var t=[];var i;var n;var a;e=hr(e);r.forEach(function(r){if(e.has(r)){return}t.push(r)});this.removeCanonicalRecords(t);e=e.toArray();i=e.length;for(a=0;a"}}};var Dr=Ember._Backburner||Ember.Backburner||Ember.__loader.require("backburner")["default"]||Ember.__loader.require("backburner")["Backburner"];if(!Dr.prototype.join){var wr=function(e){return typeof e==="string"};Dr.prototype.join=function(){var e,r;if(this.currentInstance){var t=arguments.length;if(t===1){e=arguments[0];r=null}else{r=arguments[0];e=arguments[1]}if(wr(e)){e=r[e]}if(t===1){return e()}else if(t===2){return e.call(r)}else{var i=new Array(t-2);for(var n=0,a=t-2;n1){pe(i,t,r,c,d).then(s).then(u(d)).then(null,l(d))}else if(c.length===1){var h=Ember.A(e).findBy("record",a[0]);o(h)}else{}})}else{e.forEach(o)}},peekRecord:function(e,r){if(this.hasRecordForId(e,r)){return this._internalModelForId(e,r).getRecord()}else{return null}},reloadRecord:function(e){var r=e.type.modelName;var t=this.adapterFor(r);var i=e.id;return this.scheduleFetch(e)},hasRecordForId:function(e,r){var t=this.modelFor(e);var i=Re(r);var n=this.typeMapFor(t).idToRecord[i];return!!n&&n.isLoaded()},recordForId:function(e,r){return this._internalModelForId(e,r).getRecord()},_internalModelForId:function(e,r){var t=this.modelFor(e);var i=Re(r);var n=this.typeMapFor(t).idToRecord;var a=n[i];if(!a||!n[i]){a=this.buildInternalModel(t,i)}return a},findMany:function(e){var r=this;return Lr.all(e.map(function(e){return r._findByInternalModel(e)}))},findHasMany:function(e,r,t){var i=this.adapterFor(e.type.modelName);return me(i,this,e,r,t)},findBelongsTo:function(e,r,t){var i=this.adapterFor(e.type.modelName);return ve(i,this,e,r,t)},query:function(e,r){var t=this.modelFor(e);var i=this.recordArrayManager.createAdapterPopulatedRecordArray(t,r);var n=this.adapterFor(e);return I(be(n,this,t,r,i))},queryRecord:function(e,r){var t=this.modelFor(e);var i=this.adapterFor(e);return N(ge(i,this,t,r))},findAll:function(e,r){var t=this.modelFor(e);return this._fetchAll(t,this.peekAll(e),r)},_fetchAll:function(e,r,t){t=t||{};var i=this.adapterFor(e.modelName);var n=this.typeMapFor(e).metadata.since;Nr(r,"isUpdating",true);if(t.reload){return I(ye(i,this,e,n,t))}var a=r.createSnapshot(t);if(i.shouldReloadAll(this,a)){return I(ye(i,this,e,n,t))}if(i.shouldBackgroundReloadAll(this,a)){I(ye(i,this,e,n,t))}return I(Lr.resolve(r))},didUpdateAll:function(e){var r=this.recordArrayManager.liveRecordArrayFor(e);Nr(r,"isUpdating",false)},peekAll:function(e){var r=this.modelFor(e);var t=this.recordArrayManager.liveRecordArrayFor(r);this.recordArrayManager.populateLiveRecordArray(t,r);return t},unloadAll:function(e){if(arguments.length===0){var r=this.typeMaps;var t=Object.keys(r);var i=t.map(l);i.forEach(this.unloadAll,this)}else{var n=this.modelFor(e);var a=this.typeMapFor(n);var o=a.records.slice();var s;for(var u=0;um;p--){i=r[p-1];h=i[0];if(h.test(e)){break}}i=i||[];h=i[0];n=i[1];a=e.replace(h,n);return a}};var ct=lt;function ht(e){return ct.inflector.pluralize(e)}function ft(e){return ct.inflector.singularize(e)}var pt=Ember.String.dasherize;var mt=rt.extend({_normalizeDocumentHelper:function(e){if(Ember.typeOf(e.data)==="object"){e.data=this._normalizeResourceHelper(e.data)}else if(Ember.typeOf(e.data)==="array"){e.data=e.data.map(this._normalizeResourceHelper,this)}if(Ember.typeOf(e.included)==="array"){e.included=e.included.map(this._normalizeResourceHelper,this)}return e},_normalizeRelationshipDataHelper:function(e){var r=this.modelNameFromPayloadKey(e.type);e.type=r;return e},_normalizeResourceHelper:function(e){var r=this.modelNameFromPayloadKey(e.type);var t=this.store.modelFor(r);var i=this.store.serializerFor(r);var n=i.normalize(t,e);var a=n.data;return a},pushPayload:function(e,r){var t=this._normalizeDocumentHelper(r);e.push(t)},_normalizeResponse:function(e,r,t,i,n,a){var o=this._normalizeDocumentHelper(t);return o},extractAttributes:function(e,r){var t=this;var i={};if(r.attributes){e.eachAttribute(function(e){var n=t.keyForAttribute(e,"deserialize");if(r.attributes.hasOwnProperty(n)){i[e]=r.attributes[n]}})}return i},extractRelationship:function(e){if(Ember.typeOf(e.data)==="object"){e.data=this._normalizeRelationshipDataHelper(e.data)}if(Ember.typeOf(e.data)==="array"){e.data=e.data.map(this._normalizeRelationshipDataHelper,this)}return e},extractRelationships:function(e,r){var t=this;var i={};if(r.relationships){e.eachRelationship(function(e,n){var a=t.keyForRelationship(e,n.kind,"deserialize");if(r.relationships.hasOwnProperty(a)){var o=r.relationships[a];i[e]=t.extractRelationship(o)}})}return i},_extractType:function(e,r){return this.modelNameFromPayloadKey(r.type)},modelNameFromPayloadKey:function(e){return ft(O(e))},payloadKeyFromModelName:function(e){return ht(e)},normalize:function(e,r){this.normalizeUsingDeclaredMapping(e,r);var t={id:this.extractId(e,r),type:this._extractType(e,r),attributes:this.extractAttributes(e,r),relationships:this.extractRelationships(e,r)};this.applyTransforms(e,t.attributes);return{data:t}},keyForAttribute:function(e,r){return pt(e)},keyForRelationship:function(e,r,t){return pt(e)},serialize:function(e,r){var t=this._super.apply(this,arguments);t.type=this.payloadKeyFromModelName(e.modelName);return{data:t}},serializeAttribute:function(e,r,t,i){var n=i.type;if(this._canSerialize(t)){r.attributes=r.attributes||{};var a=e.attr(t);if(n){var o=this.transformFor(n);a=o.serialize(a)}var s=this._getMappedKey(t);if(s===t){s=this.keyForAttribute(t,"serialize")}r.attributes[s]=a}},serializeBelongsTo:function(e,r,t){var i=t.key;if(this._canSerialize(i)){var n=e.belongsTo(i);if(n!==undefined){r.relationships=r.relationships||{};var a=this._getMappedKey(i);if(a===i){a=this.keyForRelationship(i,"belongsTo","serialize")}var o=null;if(n){o={type:this.payloadKeyFromModelName(n.modelName),id:n.id}}r.relationships[a]={data:o}}}},serializeHasMany:function(e,r,t){var i=this;var n=t.key;if(this._shouldSerializeHasMany(e,n,t)){var a=e.hasMany(n);if(a!==undefined){r.relationships=r.relationships||{};var o=this._getMappedKey(n);if(o===n&&this.keyForRelationship){o=this.keyForRelationship(n,"hasMany","serialize")}var s=a.map(function(e){return{type:i.payloadKeyFromModelName(e.modelName),id:e.id}});r.relationships[o]={data:s}}}}});var vt=Ember.String.camelize;var yt=rt.extend({normalize:function(e,r,t){if(this.normalizeHash&&this.normalizeHash[t]){this.normalizeHash[t](r)}return this._super(e,r,t)},_normalizeArray:function(e,r,t,i){var n=this;var a={data:[],included:[]};var o=e.modelFor(r);var s=e.serializerFor(r);t.forEach(function(r){var t=n._normalizePolymorphicRecord(e,r,i,o,s);var u=t.data;var l=t.included;a.data.push(u);if(l){var d;(d=a.included).push.apply(d,l)}});return a},_normalizePolymorphicRecord:function(e,r,t,i,n){var a=undefined,o=undefined;if(r.type&&e._hasModelFor(this.modelNameFromPayloadKey(r.type))){a=e.serializerFor(r.type);o=e.modelFor(r.type)}else{a=n;o=i}return a.normalize(o,r,t)},_normalizeResponse:function(e,r,t,i,n,a){var o={data:null,included:[]};var s=this.extractMeta(e,r,t);if(s){o.meta=s}var u=Object.keys(t);for(var l=0,d=u.length;li.attributeLimit){return false}var a=Bt(Ht(n).replace("_"," "));r.push({name:n,desc:a})});return r},getRecords:function(e,r){if(arguments.length<2){var t=e._debugContainerKey;if(t){var i=t.match(/model:(.*)/);if(i){r=i[1]}}}Vt("Cannot find model name. Please upgrade to Ember.js >= 1.13 for Ember Inspector support",!!r);return this.get("store").peekAll(r)},getRecordColumnValues:function(e){var r=this;var t=0;var i={id:Kt(e,"id")};e.eachAttribute(function(n){if(t++>r.attributeLimit){return false}var a=Kt(e,n);i[n]=a});return i},getRecordKeywords:function(e){var r=[];var t=Ember.A(["id"]);e.eachAttribute(function(e){return t.push(e)});t.forEach(function(t){return r.push(Kt(e,t))});return r},getRecordFilterValues:function(e){return{isNew:e.get("isNew"),isModified:e.get("hasDirtyAttributes")&&!e.get("isNew"),isClean:!e.get("hasDirtyAttributes")}},getRecordColor:function(e){var r="black";if(e.get("isNew")){r="green"}else if(e.get("hasDirtyAttributes")){r="blue"}return r},observeRecord:function(e,r){var t=Ember.A();var i=Ember.A(["id","isNew","hasDirtyAttributes"]);e.eachAttribute(function(e){return i.push(e)});var n=this;i.forEach(function(i){var a=function(){r(n.wrapRecord(e))};Ember.addObserver(e,i,a);t.push(function(){Ember.removeObserver(e,i,a)})});var a=function(){t.forEach(function(e){return e()})};return a}});var Wt=Qt;function Qt(e){e.register("data-adapter:main",qt)}var Jt=Xt;function Xt(e){Wt(e);Ot(e);Dt(e);gt(e)}var Gt=Yt;function Yt(e){var r=e.lookup?e:e.container;r.lookup("service:store")}var Zt=Ember.K;Ember.onLoad("Ember.Application",function(e){e.initializer({name:"ember-data",initialize:Jt});e.instanceInitializer({name:"ember-data",initialize:Gt});e.initializer({name:"store",after:"ember-data",initialize:Zt});e.initializer({name:"transforms",before:"store",initialize:Zt});e.initializer({name:"data-adapter",before:"store",initialize:Zt});e.initializer({name:"injectStore",before:"store",initialize:Zt})});Ember.Date=Ember.Date||{};var ei=Date.parse;var ri=[1,4,5,6,7,10,11];Ember.Date.parse=function(e){var r,t;var i=0;if(t=/^(\d{4}|[+\-]\d{6})(?:-(\d{2})(?:-(\d{2}))?)?(?:T(\d{2}):(\d{2})(?::(\d{2})(?:\.(\d{3}))?)?(?:(Z)|([+\-])(\d{2})(?::(\d{2}))?)?)?$/.exec(e)){for(var n=0,a;a=ri[n];++n){t[a]=+t[a]||0}t[2]=(+t[2]||1)-1;t[3]=+t[3]||1;if(t[8]!=="Z"&&t[9]!==undefined){i=t[10]*60+t[11];if(t[9]==="+"){i=0-i}}r=Date.UTC(t[1],t[2],t[3],t[4],t[5]+i,t[6],t[7]); +}else{r=ei?ei(e):NaN}return r};if(Ember.EXTEND_PROTOTYPES===true||Ember.EXTEND_PROTOTYPES.Date){Date.parse=Ember.Date.parse}$t.reopen({_debugInfo:function(){var e=["id"];var r={belongsTo:[],hasMany:[]};var t=[];this.eachAttribute(function(r,t){return e.push(r)});this.eachRelationship(function(e,i){r[i.kind].push(e);t.push(e)});var i=[{name:"Attributes",properties:e,expand:true},{name:"Belongs To",properties:r.belongsTo,expand:true},{name:"Has Many",properties:r.hasMany,expand:true},{name:"Flags",properties:["isLoaded","hasDirtyAttributes","isSaving","isDeleted","isError","isNew","isValid"]}];return{propertyInfo:{includeOtherProperties:true,groups:i,expensiveProperties:t}}}});var ti=$t;var ii=qt;var ni={plurals:[[/$/,"s"],[/s$/i,"s"],[/^(ax|test)is$/i,"$1es"],[/(octop|vir)us$/i,"$1i"],[/(octop|vir)i$/i,"$1i"],[/(alias|status)$/i,"$1es"],[/(bu)s$/i,"$1ses"],[/(buffal|tomat)o$/i,"$1oes"],[/([ti])um$/i,"$1a"],[/([ti])a$/i,"$1a"],[/sis$/i,"ses"],[/(?:([^f])fe|([lr])f)$/i,"$1$2ves"],[/(hive)$/i,"$1s"],[/([^aeiouy]|qu)y$/i,"$1ies"],[/(x|ch|ss|sh)$/i,"$1es"],[/(matr|vert|ind)(?:ix|ex)$/i,"$1ices"],[/^(m|l)ouse$/i,"$1ice"],[/^(m|l)ice$/i,"$1ice"],[/^(ox)$/i,"$1en"],[/^(oxen)$/i,"$1"],[/(quiz)$/i,"$1zes"]],singular:[[/s$/i,""],[/(ss)$/i,"$1"],[/(n)ews$/i,"$1ews"],[/([ti])a$/i,"$1um"],[/((a)naly|(b)a|(d)iagno|(p)arenthe|(p)rogno|(s)ynop|(t)he)(sis|ses)$/i,"$1sis"],[/(^analy)(sis|ses)$/i,"$1sis"],[/([^f])ves$/i,"$1fe"],[/(hive)s$/i,"$1"],[/(tive)s$/i,"$1"],[/([lr])ves$/i,"$1f"],[/([^aeiouy]|qu)ies$/i,"$1y"],[/(s)eries$/i,"$1eries"],[/(m)ovies$/i,"$1ovie"],[/(x|ch|ss|sh)es$/i,"$1"],[/^(m|l)ice$/i,"$1ouse"],[/(bus)(es)?$/i,"$1"],[/(o)es$/i,"$1"],[/(shoe)s$/i,"$1"],[/(cris|test)(is|es)$/i,"$1is"],[/^(a)x[ie]s$/i,"$1xis"],[/(octop|vir)(us|i)$/i,"$1us"],[/(alias|status)(es)?$/i,"$1"],[/^(ox)en/i,"$1"],[/(vert|ind)ices$/i,"$1ex"],[/(matr)ices$/i,"$1ix"],[/(quiz)zes$/i,"$1"],[/(database)s$/i,"$1"]],irregularPairs:[["person","people"],["man","men"],["child","children"],["sex","sexes"],["move","moves"],["cow","kine"],["zombie","zombies"]],uncountable:["equipment","information","rice","money","species","series","fish","sheep","jeans","police"]};ct.inflector=new ct(ni);if(e.EXTEND_PROTOTYPES===true||e.EXTEND_PROTOTYPES.String){String.prototype.pluralize=function(){return ht(this)};String.prototype.singularize=function(){return ft(this)}}ct.defaultRules=ni;e.Inflector=ct;e.String.pluralize=ht;e.String.singularize=ft;var ai=ct;if(typeof define!=="undefined"&&define.amd){define("ember-inflector",["exports"],function(e){e["default"]=ct;return ct})}else if(typeof module!=="undefined"&&module["exports"]){module["exports"]=ct}var oi=Ember.get;var si=Ember.set;var ui=Ember.String.camelize;var li=Ember.Mixin.create({normalize:function(e,r,t){var i=this._super(e,r,t);return this._extractEmbeddedRecords(this,this.store,e,i)},keyForRelationship:function(e,r,t){if(t==="serialize"&&this.hasSerializeRecordsOption(e)||t==="deserialize"&&this.hasDeserializeRecordsOption(e)){return this.keyForAttribute(e,t)}else{return this._super(e,r,t)||e}},serializeBelongsTo:function(e,r,t){var i=t.key;if(this.noSerializeOptionSpecified(i)){this._super(e,r,t);return}var n=this.hasSerializeIdsOption(i);var a=this.hasSerializeRecordsOption(i);var o=e.belongsTo(i);var s;if(n){s=this.keyForRelationship(i,t.kind,"serialize");if(!o){r[s]=null}else{r[s]=o.id}}else if(a){s=this.keyForAttribute(i,"serialize");if(!o){r[s]=null}else{r[s]=o.record.serialize({includeId:true});this.removeEmbeddedForeignKey(e,o,t,r[s])}}},serializeHasMany:function(e,r,t){var i=this;var n=t.key;if(this.noSerializeOptionSpecified(n)){this._super(e,r,t);return}var a=this.hasSerializeIdsOption(n);var o=this.hasSerializeRecordsOption(n);var s,u;if(a){s=this.keyForRelationship(n,t.kind,"serialize");r[s]=e.hasMany(n,{ids:true})}else if(o){s=this.keyForAttribute(n,"serialize");u=e.hasMany(n);r[s]=Ember.A(u).map(function(r){var n=r.record.serialize({includeId:true});i.removeEmbeddedForeignKey(e,r,t,n);return n})}},removeEmbeddedForeignKey:function(e,r,t,i){if(t.kind==="hasMany"){return}else if(t.kind==="belongsTo"){var n=e.type.inverseFor(t.key,this.store);if(n){var a=n.name;var o=this.store.serializerFor(r.modelName);var s=o.keyForRelationship(a,n.kind,"deserialize");if(s){delete i[s]}}}},hasEmbeddedAlwaysOption:function(e){var r=this.attrsOption(e);return r&&r.embedded==="always"},hasSerializeRecordsOption:function(e){var r=this.hasEmbeddedAlwaysOption(e);var t=this.attrsOption(e);return r||t&&t.serialize==="records"},hasSerializeIdsOption:function(e){var r=this.attrsOption(e);return r&&(r.serialize==="ids"||r.serialize==="id")},noSerializeOptionSpecified:function(e){var r=this.attrsOption(e);return!(r&&(r.serialize||r.embedded))},hasDeserializeRecordsOption:function(e){var r=this.hasEmbeddedAlwaysOption(e);var t=this.attrsOption(e);return r||t&&t.deserialize==="records"},attrsOption:function(e){var r=this.get("attrs");return r&&(r[ui(e)]||r[e])},_extractEmbeddedRecords:function(e,r,t,i){var n=this;t.eachRelationship(function(t,a){if(e.hasDeserializeRecordsOption(t)){if(a.kind==="hasMany"){n._extractEmbeddedHasMany(r,t,i,a)}if(a.kind==="belongsTo"){n._extractEmbeddedBelongsTo(r,t,i,a)}}});return i},_extractEmbeddedHasMany:function(e,r,t,i){var n=this;var a=oi(t,"data.relationships."+r+".data");if(!a){return}var o=a.map(function(r){var a=n._normalizeEmbeddedRelationship(e,i,r);var o=a.data;var s=a.included;t.included=t.included||[];t.included.push(o);if(s){var u;(u=t.included).push.apply(u,s)}return{id:o.id,type:o.type}});var s={data:o};si(t,"data.relationships."+r,s)},_extractEmbeddedBelongsTo:function(e,r,t,i){var n=oi(t,"data.relationships."+r+".data");if(!n){return}var a=this._normalizeEmbeddedRelationship(e,i,n);var o=a.data;var s=a.included;t.included=t.included||[];t.included.push(o);if(s){var u;(u=t.included).push.apply(u,s)}var l={id:o.id,type:o.type};var d={data:l};si(t,"data.relationships."+r,d)},_normalizeEmbeddedRelationship:function(e,r,t){var i=r.type;if(r.options.polymorphic){i=t.type}var n=e.modelFor(i);var a=e.serializerFor(i);return a.normalize(n,t,null)}});var di=li;function ci(e,r){var t,i;if(typeof e==="object"){t=e;i=undefined}else{t=r;i=e}if(typeof i==="string"){i=O(i)}t=t||{};var n={type:i,isRelationship:true,options:t,kind:"belongsTo",key:null};return Ember.computed({get:function(e){if(t.hasOwnProperty("serialize")){}if(t.hasOwnProperty("embedded")){}return this._internalModel._relationships.get(e).getRecord()},set:function(e,r){if(r===undefined){r=null}if(r&&r.then){this._internalModel._relationships.get(e).setRecordPromise(r)}else if(r){this._internalModel._relationships.get(e).setRecord(r._internalModel)}else{this._internalModel._relationships.get(e).setRecord(r)}return this._internalModel._relationships.get(e).getRecord()}}).meta(n)}$t.reopen({notifyBelongsToChanged:function(e){this.notifyPropertyChange(e)}});var hi=ci;var fi=pi;function pi(e){if(!e||e.setInterval){return false}if(Array.isArray(e)){return true}if(Ember.Array.detect(e)){return true}var r=Ember.typeOf(e);if("array"===r){return true}if(e.length!==undefined&&"object"===r){return true}return false}function mi(e,r){if(typeof e==="object"){r=e;e=undefined}r=r||{};if(typeof e==="string"){e=O(e)}var t={type:e,isRelationship:true,options:r,kind:"hasMany",key:null};return Ember.computed({get:function(e){var r=this._internalModel._relationships.get(e);return r.getRecords()},set:function(e,r){var t=this._internalModel._relationships.get(e);t.clear();t.addRecords(Ember.A(r).mapBy("_internalModel"));return t.getRecords()}}).meta(t)}$t.reopen({notifyHasManyAdded:function(e){this.notifyPropertyChange(e)}});var vi=mi;function yi(e){var r;r=e.type||e.key;if(e.kind==="hasMany"){r=ft(O(r))}return r}function bi(e){return{key:e.key,kind:e.kind,type:yi(e),options:e.options,parentType:e.parentType,isRelationship:true}}var gi=Ember.get;var Ri=Ember.computed(function(){if(Ember.testing===true&&Ri._cacheable===true){Ri._cacheable=false}var e=new g({defaultValue:function(){return[]}});this.eachComputedProperty(function(r,t){if(t.isRelationship){t.key=r;var i=e.get(yi(t));i.push({name:r,kind:t.kind})}});return e}).readOnly();var Ei=Ember.computed(function(){var e=this;if(Ember.testing===true&&Ei._cacheable===true){Ei._cacheable=false}var r;var t=Ember.A();this.eachComputedProperty(function(e,i){if(i.isRelationship){i.key=e;r=yi(i);if(!t.contains(r)){t.push(r)}}});return t}).readOnly();var _i=Ember.computed(function(){if(Ember.testing===true&&_i._cacheable===true){_i._cacheable=false}var e=b.create();this.eachComputedProperty(function(r,t){if(t.isRelationship){t.key=r;var i=bi(t);i.type=yi(t);e.set(r,i)}});return e}).readOnly();$t.reopen({didDefineProperty:function(e,r,t){if(t instanceof Ember.ComputedProperty){var i=t.meta();i.parentType=e.constructor}}});$t.reopenClass({typeForRelationship:function(e,r){var t=gi(this,"relationshipsByName").get(e);return t&&r.modelFor(t.type)},inverseMap:Ember.computed(function(){return Object.create(null)}),inverseFor:function(e,r){var t=gi(this,"inverseMap");if(t[e]){return t[e]}else{var i=this._findInverseFor(e,r);t[e]=i;return i}},_findInverseFor:function(e,r){var t=this.typeForRelationship(e,r);if(!t){return null}var i=this.metaForProperty(e);var n=i.options;if(n.inverse===null){return null}var a,o,s;if(n.inverse){a=n.inverse;s=Ember.get(t,"relationshipsByName").get(a);o=s.kind}else{if(i.type===i.parentType.modelName){}var u=d(this,t);if(u.length===0){return null}var l=u.filter(function(r){var i=t.metaForProperty(r.name).options;return e===i.inverse});if(l.length===1){u=l}a=u[0].name;o=u[0].kind}function d(r,t,i){var n=i||[];var a=gi(t,"relationships");if(!a){return n}var o=a.get(r.modelName);o=o.filter(function(r){var i=t.metaForProperty(r.name).options;if(!i.inverse){return true}return e===i.inverse});if(o){n.push.apply(n,o)}if(r.superclass){d(r.superclass,t,n)}return n}return{type:t,name:a,kind:o}},relationships:Ri,relationshipNames:Ember.computed(function(){var e={hasMany:[],belongsTo:[]};this.eachComputedProperty(function(r,t){if(t.isRelationship){e[t.kind].push(r)}});return e}),relatedTypes:Ei,relationshipsByName:_i,fields:Ember.computed(function(){var e=b.create();this.eachComputedProperty(function(r,t){if(t.isRelationship){e.set(r,t.kind)}else if(t.isAttribute){e.set(r,"attribute")}});return e}).readOnly(),eachRelationship:function(e,r){gi(this,"relationshipsByName").forEach(function(t,i){e.call(r,i,t)})},eachRelatedType:function(e,r){gi(this,"relatedTypes").forEach(function(t){e.call(r,t)})},determineRelationshipType:function(e,r){var t=e.key;var i=e.kind;var n=this.inverseFor(t,r);var a,o;if(!n){return i==="belongsTo"?"oneToNone":"manyToNone"}a=n.name;o=n.kind;if(o==="belongsTo"){return i==="belongsTo"?"oneToOne":"manyToOne"}else{return i==="belongsTo"?"oneToMany":"manyToMany"}}});$t.reopen({eachRelationship:function(e,r){this.constructor.eachRelationship(e,r)},relationshipFor:function(e){return gi(this.constructor,"relationshipsByName").get(e)},inverseFor:function(e){return this.constructor.inverseFor(e,this.store)}});var Fi=Ai;function Ai(e){this.container=e}Ai.prototype.aliasedFactory=function(e,r){var t=this;return{create:function(){if(r){r()}return t.container.lookup(e)}}};Ai.prototype.registerAlias=function(e,r,t){var i=this.aliasedFactory(r,t);return this.container.register(e,i)};Ai.prototype.registerDeprecation=function(e,r){var t=function(){};return this.registerAlias(e,r,t)};Ai.prototype.registerDeprecations=function(e){var r,t,i,n;for(r=e.length;r>0;r--){t=e[r-1];i=t["deprecated"];n=t["valid"];this.registerDeprecation(i,n)}};if(Ember.VERSION.match(/^1\.[0-7]\./)){throw new Ember.Error("Ember Data requires at least Ember 1.8.0, but you have "+Ember.VERSION+". Please upgrade your version of Ember, then upgrade Ember Data")}if(Ember.VERSION.match(/^1\.12\.0/)){throw new Ember.Error("Ember Data does not work with Ember 1.12.0. Please upgrade to Ember 1.12.1 or higher.")}T.Store=Kr;T.PromiseArray=P;T.PromiseObject=x;T.PromiseManyArray=L;T.Model=$t;T.RootState=tr;T.attr=Pt;T.Errors=J;T.InternalModel=_r;T.Snapshot=gr;T.Adapter=f;T.AdapterError=a;T.InvalidError=o;T.TimeoutError=s;T.AbortError=u;T.errorsHashToArray=l;T.errorsArrayToHash=d;T.Serializer=Xr;T.DebugAdapter=ii;T.RecordArray=ze;T.FilteredRecordArray=Se;T.AdapterPopulatedRecordArray=De;T.ManyArray=sr;T.RecordArrayManager=je;T.RESTAdapter=M;T.BuildURLMixin=t;T.RESTSerializer=bt;T.JSONSerializer=rt;T.JSONAPIAdapter=z;T.JSONAPISerializer=mt;T.Transform=_t;T.DateTransform=zt;T.StringTransform=St;T.NumberTransform=Mt;T.BooleanTransform=Tt;T.EmbeddedRecordsMixin=di;T.belongsTo=hi;T.hasMany=vi;T.Relationship=ir;T.ContainerProxy=Fi;T._setupContainer=Jt;Object.defineProperty(T,"normalizeModelName",{enumerable:true,writable:false,configurable:false,value:O});var Mi=y;Object.defineProperty(T,"FixtureAdapter",{get:function(){if(Mi===y){}return Mi},set:function(e){Mi=e}});Ember.lookup.DS=T;var zi=T;var ki=Ti;var Si=Ember.Error;function Ti(e){Si.call(this,"The backend rejected the commit because it was invalid: "+Ember.inspect(e));this.errors=e}Ti.prototype=Object.create(Si.prototype);var Oi=Ci;function Ci(r){if(e.Helper){return e.Helper.helper(r)}if(e.HTMLBars){return e.HTMLBars.makeBoundHelper(r)}return e.Handlebars.makeBoundHelper(r)}var Di=Oi(function(e){var r,t;if(e.length===1){t=e[0];return ht(t)}else{r=e[0];t=e[1];if((r|0)!==1){t=ht(t)}return r+" "+t}});var wi=Oi(function(e){return ft(e[0])})}).call(this); \ No newline at end of file diff --git a/test/vendor/ember13.min.js b/test/vendor/ember13.min.js new file mode 100644 index 0000000..04b9b4f --- /dev/null +++ b/test/vendor/ember13.min.js @@ -0,0 +1,15 @@ +!function(){var e,t,r,n,i,a=this;!function(){function a(e,t){var r=u[e];if(void 0!==r)return r;if(r=u[e]={},!l[e])throw t?new Error("Could not find module "+e+" required by: "+t):new Error("Could not find module "+e);for(var n=l[e],i=n.deps,s=n.callback,c=[],h=i.length,m=0;h>m;m++)"exports"===i[m]?c.push(r):c.push(a(o(i[m],e),e));return (s.apply(this,c), r)}function o(e,t){if("."!==e.charAt(0))return e;for(var r=e.split("/"),n=t.split("/").slice(0,-1),i=0,a=r.length;a>i;i++){var o=r[i];if(".."===o)n.pop();else{if("."===o)continue;n.push(o)}}return n.join("/")}var s="undefined"!=typeof process&&"[object process]"==={}.toString.call(process);if(s||(i=this.Ember=this.Ember||{}),"undefined"==typeof i&&(i={}),"undefined"==typeof i.__loader){var l={},u={};e=function(e,t,r){var n={};r?(n.deps=t,n.callback=r):(n.deps=[],n.callback=t),l[e]=n},n=r=t=function(e){return a(e,null)},n._eak_seen=l,i.__loader={define:e,require:r,registry:l}}else e=i.__loader.define,n=r=t=i.__loader.require}(),e("backburner",["exports","./backburner/utils","./backburner/platform","./backburner/binary-search","./backburner/deferred-action-queues"],function(e,t,r,n,i){"use strict";function a(e,t){this.queueNames=e,this.options=t||{},this.options.defaultQueue||(this.options.defaultQueue=e[0]),this.instanceStack=[],this._debouncees=[],this._throttlers=[],this._eventCallbacks={end:[],begin:[]},this._timerTimeoutId=void 0,this._timers=[];var r=this;this._boundRunExpiredTimers=function(){r._runExpiredTimers()}}function o(e){return e.onError||e.onErrorTarget&&e.onErrorTarget[e.onErrorMethod]}function s(e){e.begin(),e._autorun=r["default"].setTimeout(function(){e._autorun=null,e.end()})}function l(e,t,r){return c(e,t,r)}function u(e,t,r){return c(e,t,r)}function c(e,t,r){for(var n,i=-1,a=0,o=r.length;o>a;a++)if(n=r[a],n[0]===e&&n[1]===t){i=a;break}return i}function h(e){clearTimeout(e[2])}e["default"]=a;if(a.prototype={begin:function(){var e=this.options,t=e&&e.onBegin,r=this.currentInstance;r&&this.instanceStack.push(r),this.currentInstance=new i["default"](this.queueNames,e),this._trigger("begin",this.currentInstance,r),t&&t(this.currentInstance,r)},end:function(){var e=this.options,t=e&&e.onEnd,r=this.currentInstance,n=null,i=!1;try{r.flush()}finally{i||(i=!0,this.currentInstance=null,this.instanceStack.length&&(n=this.instanceStack.pop(),this.currentInstance=n),this._trigger("end",r,n),t&&t(r,n))}},_trigger:function(e,t,r){var n=this._eventCallbacks[e];if(n)for(var i=0;i2){n=new Array(i-2);for(var a=0,s=i-2;s>a;a++)n[a]=arguments[a+2]}else n=[];var l=o(this.options);this.begin();var u=!1;if(l)try{return e.apply(r,n)}catch(c){l(c)}finally{u||(u=!0,this.end())}else try{return e.apply(r,n)}finally{u||(u=!0,this.end())}},join:function(){if(!this.currentInstance)return this.run.apply(this,arguments);var e,r,n=arguments.length;if(1===n?(e=arguments[0],r=null):(r=arguments[0],e=arguments[1]),t.isString(e)&&(e=r[e]),1===n)return e();if(2===n)return e.call(r);for(var i=new Array(n-2),a=0,o=n-2;o>a;a++)i[a]=arguments[a+2];return e.apply(r,i)},defer:function(e){var r,n,i,a=arguments.length;2===a?(r=arguments[1],n=null):(n=arguments[1],r=arguments[2]),t.isString(r)&&(r=n[r]);var o=this.DEBUG?new Error:void 0;if(a>3){i=new Array(a-3);for(var l=3;a>l;l++)i[l-3]=arguments[l]}else i=void 0;return (this.currentInstance||s(this), this.currentInstance.schedule(e,n,r,i,!1,o))},deferOnce:function(e){var r,n,i,a=arguments.length;2===a?(r=arguments[1],n=null):(n=arguments[1],r=arguments[2]),t.isString(r)&&(r=n[r]);var o=this.DEBUG?new Error:void 0;if(a>3){i=new Array(a-3);for(var l=3;a>l;l++)i[l-3]=arguments[l]}else i=void 0;return (this.currentInstance||s(this), this.currentInstance.schedule(e,n,r,i,!0,o))},setTimeout:function(){function e(){if(f)try{a.apply(l,n)}catch(e){f(e)}else a.apply(l,n)}for(var r=arguments.length,n=new Array(r),i=0;r>i;i++)n[i]=arguments[i];var a,s,l,u,c,h,m=n.length;if(0!==m){if(1===m)a=n.shift(),s=0;else if(2===m)u=n[0],c=n[1],t.isFunction(c)||t.isFunction(u[c])?(l=n.shift(),a=n.shift(),s=0):t.isCoercableNumber(c)?(a=n.shift(),s=n.shift()):(a=n.shift(),s=0);else{var d=n[n.length-1];s=t.isCoercableNumber(d)?n.pop():0,u=n[0],h=n[1],t.isFunction(h)||t.isString(h)&&null!==u&&h in u?(l=n.shift(),a=n.shift()):a=n.shift()}var p=t.now()+parseInt(s,10);t.isString(a)&&(a=l[a]);var f=o(this.options);return this._setTimeout(e,p)}},_setTimeout:function(e,t){if(0===this._timers.length)return (this._timers.push(t,e), this._installTimerTimeout(), e);this._reinstallStalledTimerTimeout();var r=n["default"](t,this._timers);return (this._timers.splice(r,0,t,e), 0===r&&this._reinstallTimerTimeout(), e)},throttle:function(e,n){for(var i=this,a=new Array(arguments.length),o=0;o-1?this._throttlers[c]:(h=r["default"].setTimeout(function(){m||i.run.apply(i,a);var t=u(e,n,i._throttlers);t>-1&&i._throttlers.splice(t,1)},s),m&&this.run.apply(this,a),l=[e,n,h],this._throttlers.push(l),l))},debounce:function(e,n){for(var i=this,a=new Array(arguments.length),o=0;o-1&&(c=this._debouncees[u],this._debouncees.splice(u,1),clearTimeout(c[2])), h=r["default"].setTimeout(function(){m||i.run.apply(i,a);var t=l(e,n,i._debouncees);t>-1&&i._debouncees.splice(t,1)},s), m&&-1===u&&i.run.apply(i,a), c=[e,n,h], i._debouncees.push(c), c)},cancelTimers:function(){t.each(this._throttlers,h),this._throttlers=[],t.each(this._debouncees,h),this._debouncees=[],this._clearTimerTimeout(),this._timers=[],this._autorun&&(clearTimeout(this._autorun),this._autorun=null)},hasTimers:function(){return!!this._timers.length||!!this._debouncees.length||!!this._throttlers.length||this._autorun},cancel:function(e){var t=typeof e;if(e&&"object"===t&&e.queue&&e.method)return e.queue.cancel(e);if("function"!==t)return"[object Array]"===Object.prototype.toString.call(e)?this._cancelItem(u,this._throttlers,e)||this._cancelItem(l,this._debouncees,e):void 0;for(var r=0,n=this._timers.length;n>r;r+=2)if(this._timers[r+1]===e)return (this._timers.splice(r,2), 0===r&&this._reinstallTimerTimeout(), !0)},_cancelItem:function(e,t,r){var n,i;return r.length<3?!1:(i=e(r[0],r[1],t),i>-1&&(n=t[i],n[2]===r[2])?(t.splice(i,1),clearTimeout(r[2]),!0):!1)},_runExpiredTimers:function(){this._timerTimeoutId=void 0,this.run(this,this._scheduleExpiredTimers)},_scheduleExpiredTimers:function(){for(var e=t.now(),r=this._timers,n=0,i=r.length;i>n;n+=2){var a=r[n],o=r[n+1];if(!(e>=a))break;this.schedule(this.options.defaultQueue,null,o)}r.splice(0,n),this._installTimerTimeout()},_reinstallStalledTimerTimeout:function(){if(this._timerTimeoutId){var e=this._timers[0];t.now()-e}},_reinstallTimerTimeout:function(){this._clearTimerTimeout(),this._installTimerTimeout()},_clearTimerTimeout:function(){this._timerTimeoutId&&(clearTimeout(this._timerTimeoutId),this._timerTimeoutId=void 0)},_installTimerTimeout:function(){if(this._timers.length){var e=this._timers[0],r=t.now(),n=Math.max(0,e-r);this._timerTimeoutId=setTimeout(this._boundRunExpiredTimers,n)}}},a.prototype.schedule=a.prototype.defer,a.prototype.scheduleOnce=a.prototype.deferOnce,a.prototype.later=a.prototype.setTimeout,r.needsIETryCatchFix){var m=a.prototype.run;a.prototype.run=t.wrapInTryCatch(m);var d=a.prototype.end;a.prototype.end=t.wrapInTryCatch(d)}}),e("backburner/binary-search",["exports"],function(e){"use strict";function t(e,t){for(var r,n,i=0,a=t.length-2;a>i;)n=(a-i)/2,r=i+n-n%2,e>=t[r]?i=r+2:a=r;return e>=t[i]?i+2:i}e["default"]=t}),e("backburner/deferred-action-queues",["exports","./utils","./queue"],function(e,t,r){"use strict";function n(e,n){var i=this.queues={};this.queueNames=e=e||[],this.options=n,t.each(e,function(e){i[e]=new r["default"](e,n[e],n)})}function i(e){throw new Error("You attempted to schedule an action in a queue ("+e+") that doesn't exist")}function a(e){throw new Error("You attempted to schedule an action in a queue ("+e+") for a method that doesn't exist")}e["default"]=n,n.prototype={schedule:function(e,t,r,n,o,s){var l=this.queues,u=l[e];return (u||i(e), r||a(e), o?u.pushUnique(t,r,n,s):u.push(t,r,n,s))},flush:function(){for(var e,t,r=this.queues,n=this.queueNames,i=0,a=n.length;a>i;){e=n[i],t=r[e];var o=t._queue.length;0===o?i++:(t.flush(!1),i=0)}}}}),e("backburner/platform",["exports"],function(e){"use strict";var t=function(e,t){try{t()}catch(e){}return!!e}();e.needsIETryCatchFix=t;var r;if("object"==typeof self)r=self;else{if("object"!=typeof global)throw new Error("no global: `self` or `global` found");r=global}e["default"]=r}),e("backburner/queue",["exports","./utils"],function(e,t){"use strict";function r(e,t,r){this.name=e,this.globalOptions=r||{},this.options=t,this._queue=[],this.targetQueues={},this._queueBeingFlushed=void 0}e["default"]=r,r.prototype={push:function(e,t,r,n){var i=this._queue;return (i.push(e,t,r,n), {queue:this,target:e,method:t})},pushUniqueWithoutGuid:function(e,t,r,n){for(var i=this._queue,a=0,o=i.length;o>a;a+=4){var s=i[a],l=i[a+1];if(s===e&&l===t)return (i[a+2]=r, void(i[a+3]=n))}i.push(e,t,r,n)},targetQueue:function(e,t,r,n,i){for(var a=this._queue,o=0,s=e.length;s>o;o+=2){var l=e[o],u=e[o+1];if(l===r)return (a[u+2]=n, void(a[u+3]=i))}e.push(r,a.push(t,r,n,i)-4)},pushUniqueWithGuid:function(e,t,r,n,i){var a=this.targetQueues[e];return (a?this.targetQueue(a,t,r,n,i):this.targetQueues[e]=[r,this._queue.push(t,r,n,i)-4], {queue:this,target:t,method:r})},pushUnique:function(e,t,r,n){var i=this.globalOptions.GUID_KEY;if(e&&i){var a=e[i];if(a)return this.pushUniqueWithGuid(a,e,t,r,n)}return (this.pushUniqueWithoutGuid(e,t,r,n), {queue:this,target:e,method:t})},invoke:function(e,t,r,n,i){r&&r.length>0?t.apply(e,r):t.call(e)},invokeWithOnError:function(e,t,r,n,i){try{r&&r.length>0?t.apply(e,r):t.call(e)}catch(a){n(a,i)}},flush:function(e){var r=this._queue,n=r.length;if(0!==n){var i,a,o,s,l=this.globalOptions,u=this.options,c=u&&u.before,h=u&&u.after,m=l.onError||l.onErrorTarget&&l.onErrorTarget[l.onErrorMethod],d=m?this.invokeWithOnError:this.invoke;this.targetQueues=Object.create(null);var p=this._queueBeingFlushed=this._queue.slice();this._queue=[],c&&c();for(var f=0;n>f;f+=4)i=p[f],a=p[f+1],o=p[f+2],s=p[f+3],t.isString(a)&&(a=i[a]),a&&d(i,a,o,m,s);h&&h(),this._queueBeingFlushed=void 0,e!==!1&&this._queue.length>0&&this.flush(!0)}},cancel:function(e){var t,r,n,i,a=this._queue,o=e.target,s=e.method,l=this.globalOptions.GUID_KEY;if(l&&this.targetQueues&&o){var u=this.targetQueues[o[l]];if(u)for(n=0,i=u.length;i>n;n++)u[n]===s&&u.splice(n,1)}for(n=0,i=a.length;i>n;n+=4)if(t=a[n],r=a[n+1],t===o&&r===s)return (a.splice(n,4), !0);if(a=this._queueBeingFlushed)for(n=0,i=a.length;i>n;n+=4)if(t=a[n],r=a[n+1],t===o&&r===s)return (a[n+1]=null, !0)}}}),e("backburner/utils",["exports"],function(e){"use strict";function t(e,t){for(var r=0;r-1){try{if(t.existsSync(o)){var s,l=t.readFileSync(o,{encoding:"utf8"}),u=l.split("/").slice(-1)[0].trim(),c=l.split(" ")[1];if(c){var h=n.join(a,c.trim());s=t.readFileSync(h)}else s=u;i.push(s.slice(0,10))}}catch(m){console.error(m.stack)}return i.join(".")}return e}}),e("container",["exports","container/registry","container/container"],function(e,t,r){"use strict";i.MODEL_FACTORY_INJECTIONS=!1,i.ENV&&"undefined"!=typeof i.ENV.MODEL_FACTORY_INJECTIONS&&(i.MODEL_FACTORY_INJECTIONS=!!i.ENV.MODEL_FACTORY_INJECTIONS),e.Registry=t["default"],e.Container=r["default"]}),e("container/container",["exports","ember-metal/core","ember-metal/keys","ember-metal/dictionary"],function(e,r,n,i){"use strict";function a(e,r){this._registry=e||function(){return (f||(f=t("container/registry")["default"]), new f)}(),this.cache=i["default"](r&&r.cache?r.cache:null),this.factoryCache=i["default"](r&&r.factoryCache?r.factoryCache:null),this.validationCache=i["default"](r&&r.validationCache?r.validationCache:null)}function o(e,t,r){if(r=r||{},e.cache[t]&&r.singleton!==!1)return e.cache[t];var n=h(e,t);return void 0!==n?(e._registry.getOption(t,"singleton")!==!1&&r.singleton!==!1&&(e.cache[t]=n),n):void 0}function s(e){var t={};if(arguments.length>1){for(var r,n=Array.prototype.slice.call(arguments,1),i=[],a=0,s=n.length;s>a;a++)n[a]&&(i=i.concat(n[a]));for(e._registry.validateInjections(i),a=0,s=i.length;s>a;a++)r=i[a],t[r.property]=o(e,r.fullName)}return t}function l(e,t){var n=e.factoryCache;if(n[t])return n[t];var i=e._registry,a=i.resolve(t);if(void 0!==a){var o=t.split(":")[0];if(!a||"function"!=typeof a.extend||!r["default"].MODEL_FACTORY_INJECTIONS&&"model"===o)return (a&&"function"==typeof a._onLookup&&a._onLookup(t), n[t]=a, a);var s=u(e,t),l=c(e,t);l._toString=i.makeToString(a,t);var h=a.extend(s);return (h.reopenClass(l), a&&"function"==typeof a._onLookup&&a._onLookup(t), n[t]=h, h)}}function u(e,t){var r=e._registry,n=t.split(":"),i=n[0],a=s(e,r.getTypeInjections(i),r.getInjections(t));return (a._debugContainerKey=t, a.container=e, a)}function c(e,t){var r=e._registry,n=t.split(":"),i=n[0],a=s(e,r.getFactoryTypeInjections(i),r.getFactoryInjections(t));return (a._debugContainerKey=t, a)}function h(e,t){var r,n,i=l(e,t);if(e._registry.getOption(t,"instantiate")===!1)return i;if(i){if("function"!=typeof i.create)throw new Error("Failed to create an instance of '"+t+"'. Most likely an improperly defined class or an invalid module export.");return (n=e.validationCache, n[t]||"function"!=typeof i._lazyInjections||(r=i._lazyInjections(),r=e._registry.normalizeInjectionsHash(r),e._registry.validateInjections(r)), n[t]=!0, "function"==typeof i.extend?i.create():i.create(u(e,t)))}}function m(e,t){for(var r,i,a=e.cache,o=n["default"](a),s=0,l=o.length;l>s;s++)r=o[s],i=a[r],e._registry.getOption(r,"instantiate")!==!1&&t(i)}function d(e){m(e,function(e){e.destroy&&e.destroy()}),e.cache.dict=i["default"](null)}function p(e,t){var r=e.cache[t];delete e.factoryCache[t],r&&(delete e.cache[t],r.destroy&&r.destroy())}var f;a.prototype={_registry:null,cache:null,factoryCache:null,validationCache:null,lookup:function(e,t){return o(this,this._registry.normalize(e),t)},lookupFactory:function(e){return l(this,this._registry.normalize(e))},destroy:function(){m(this,function(e){e.destroy&&e.destroy()}),this.isDestroyed=!0},reset:function(e){arguments.length>0?p(this,this._registry.normalize(e)):d(this)}},function(){function e(e){a.prototype[e]=function(){return this._registry[e].apply(this._registry,arguments)}}for(var t=["register","unregister","resolve","normalize","typeInjection","injection","factoryInjection","factoryTypeInjection","has","options","optionsForType"],r=0,n=t.length;n>r;r++)e(t[r])}(),e["default"]=a}),e("container/registry",["exports","ember-metal/core","ember-metal/dictionary","ember-metal/keys","ember-metal/merge","./container"],function(e,t,r,n,i,a){"use strict";function o(e){this.fallback=e&&e.fallback?e.fallback:null,this.resolver=e&&e.resolver?e.resolver:function(){},this.registrations=r["default"](e&&e.registrations?e.registrations:null),this._typeInjections=r["default"](null),this._injections=r["default"](null),this._factoryTypeInjections=r["default"](null),this._factoryInjections=r["default"](null),this._normalizeCache=r["default"](null),this._resolveCache=r["default"](null),this._failCache=r["default"](null),this._options=r["default"](null),this._typeOptions=r["default"](null)}function s(e,t){var r=e._resolveCache[t];if(r)return r;if(!e._failCache[t]){var n=e.resolver(t)||e.registrations[t];return (n?e._resolveCache[t]=n:e._failCache[t]=!0, n)}}function l(e,t){return void 0!==e.resolve(t)}var u,c=/^[^:]+.+:[^:]+$/;u=!0,o.prototype={fallback:null,resolver:null,registrations:null,_typeInjections:null,_injections:null,_factoryTypeInjections:null,_factoryInjections:null,_normalizeCache:null,_resolveCache:null,_options:null,_typeOptions:null,_defaultContainer:null,container:function(e){var t=new a["default"](this,e);return (this.registerContainer(t), t)},registerContainer:function(e){this._defaultContainer||(this._defaultContainer=e),this.fallback&&this.fallback.registerContainer(e)},lookup:function(e,t){return this._defaultContainer.lookup(e,t)},lookupFactory:function(e){return this._defaultContainer.lookupFactory(e)},register:function(e,t,r){if(void 0===t)throw new TypeError("Attempting to register an unknown factory: `"+e+"`");var n=this.normalize(e);if(this._resolveCache[n])throw new Error("Cannot re-register: `"+e+"`, as it has already been resolved.");delete this._failCache[n],this.registrations[n]=t,this._options[n]=r||{}},unregister:function(e){var t=this.normalize(e);delete this.registrations[t],delete this._resolveCache[t],delete this._failCache[t],delete this._options[t]},resolve:function(e){var t=s(this,this.normalize(e));return (void 0===t&&this.fallback&&(t=this.fallback.resolve(e)), t)},describe:function(e){return e},normalizeFullName:function(e){return e},normalize:function(e){return this._normalizeCache[e]||(this._normalizeCache[e]=this.normalizeFullName(e))},makeToString:function(e,t){return e.toString()},has:function(e){return l(this,this.normalize(e))},optionsForType:function(e,t){this._typeOptions[e]=t},getOptionsForType:function(e){var t=this._typeOptions[e];return (void 0===t&&this.fallback&&(t=this.fallback.getOptionsForType(e)), t)},options:function(e,t){t=t||{};var r=this.normalize(e);this._options[r]=t},getOptions:function(e){var t=this.normalize(e),r=this._options[t];return (void 0===r&&this.fallback&&(r=this.fallback.getOptions(e)), r)},getOption:function(e,t){var r=this._options[e];if(r&&void 0!==r[t])return r[t];var n=e.split(":")[0];return (r=this._typeOptions[n], r&&void 0!==r[t]?r[t]:this.fallback?this.fallback.getOption(e,t):void 0)},option:function(e,t){return this.getOption(e,t)},typeInjection:function(e,t,r){var n=r.split(":")[0];if(n===e)throw new Error("Cannot inject a `"+r+"` on other "+e+"(s).");var i=this._typeInjections[e]||(this._typeInjections[e]=[]);i.push({property:t,fullName:r})},injection:function(e,t,r){this.validateFullName(r);var n=this.normalize(r);if(-1===e.indexOf(":"))return this.typeInjection(e,t,n);var i=this.normalize(e),a=this._injections[i]||(this._injections[i]=[]);a.push({property:t,fullName:n})},factoryTypeInjection:function(e,t,r){var n=this._factoryTypeInjections[e]||(this._factoryTypeInjections[e]=[]);n.push({property:t,fullName:this.normalize(r)})},factoryInjection:function(e,t,r){var n=this.normalize(e),i=this.normalize(r);if(this.validateFullName(r),-1===e.indexOf(":"))return this.factoryTypeInjection(n,t,i);var a=this._factoryInjections[n]||(this._factoryInjections[n]=[]);a.push({property:t,fullName:i})},knownForType:function(e){for(var t=void 0,a=void 0,o=r["default"](null),s=n["default"](this.registrations),l=0,u=s.length;u>l;l++){var c=s[l],h=c.split(":")[0];h===e&&(o[c]=!0)}return (this.fallback&&(t=this.fallback.knownForType(e)), this.resolver.knownForType&&(a=this.resolver.knownForType(e)), i.assign({},t,o,a))},validateFullName:function(e){if(!c.test(e))throw new TypeError("Invalid Fullname, expected: `type:name` got: "+e);return!0},validateInjections:function(e){if(e)for(var t,r=0,n=e.length;n>r;r++)if(t=e[r].fullName,!this.has(t))throw new Error("Attempting to inject an unknown injection: `"+t+"`")},normalizeInjectionsHash:function(e){var t=[];for(var r in e)e.hasOwnProperty(r)&&t.push({property:r,fullName:e[r]});return t},getInjections:function(e){var t=this._injections[e]||[];return (this.fallback&&(t=t.concat(this.fallback.getInjections(e))), t)},getTypeInjections:function(e){var t=this._typeInjections[e]||[];return (this.fallback&&(t=t.concat(this.fallback.getTypeInjections(e))), t)},getFactoryInjections:function(e){var t=this._factoryInjections[e]||[];return (this.fallback&&(t=t.concat(this.fallback.getFactoryInjections(e))), t)},getFactoryTypeInjections:function(e){var t=this._factoryTypeInjections[e]||[];return (this.fallback&&(t=t.concat(this.fallback.getFactoryTypeInjections(e))), t)}},e["default"]=o}),e("dag-map",["exports"],function(e){"use strict";function t(e,r,n,i){var a,o=e.name,s=e.incoming,l=e.incomingNames,u=l.length;if(n||(n={}),i||(i=[]),!n.hasOwnProperty(o)){for(i.push(o),n[o]=!0,a=0;u>a;a++)t(s[l[a]],r,n,i);r(e,i),i.pop()}}function r(){this.names=[],this.vertices=Object.create(null)}function n(e){this.name=e,this.incoming={},this.incomingNames=[],this.hasOutgoing=!1,this.value=null}r.prototype.add=function(e){if(!e)throw new Error("Can't add Vertex without name");if(void 0!==this.vertices[e])return this.vertices[e];var t=new n(e);return (this.vertices[e]=t, this.names.push(e), t)},r.prototype.map=function(e,t){this.add(e).value=t},r.prototype.addEdge=function(e,r){function n(e,t){if(e.name===r)throw new Error("cycle detected: "+r+" <- "+t.join(" <- "))}if(e&&r&&e!==r){var i=this.add(e),a=this.add(r);a.incoming.hasOwnProperty(e)||(t(i,n),i.hasOutgoing=!0,a.incoming[e]=i,a.incomingNames.push(e))}},r.prototype.topsort=function(e){var r,n,i={},a=this.vertices,o=this.names,s=o.length;for(r=0;s>r;r++)n=a[o[r]],n.hasOutgoing||t(n,e,i)},r.prototype.addEdges=function(e,t,r,n){var i;if(this.map(e,t),r)if("string"==typeof r)this.addEdge(e,r);else for(i=0;i", r.firstChild.childNodes)}function u(e,t,r){this.element=e,this.dom=t,this.namespace=r,this.guid="element"+g++,this.state={},this.isDirty=!0}function c(e){if(this.document=e||document,!this.document)throw new Error("A document object must be passed to the DOMHelper, or available on the global scope");this.canClone=f,this.namespace=null}var h="undefined"==typeof document?!1:document,m=h&&function(e){var t=e.createElement("div");t.appendChild(e.createTextNode(""));var r=t.cloneNode(!0);return 0===r.childNodes.length}(h),d=h&&function(e){var t=e.createElement("input");t.setAttribute("checked","checked");var r=t.cloneNode(!1);return!r.checked}(h),p=h&&(h.createElementNS?function(e){var t=e.createElementNS(n.svgNamespace,"svg");return (t.setAttribute("viewBox","0 0 100 100"), t.removeAttribute("viewBox"), !t.getAttribute("viewBox"))}(h):!0),f=h&&function(e){var t=e.createElement("div");t.appendChild(e.createTextNode(" ")),t.appendChild(e.createTextNode(" "));var r=t.cloneNode(!0);return" "===r.childNodes[0].nodeValue}(h),v=/<([\w:]+)/,g=1;u.prototype.clear=function(){},u.prototype.destroy=function(){this.element=null,this.dom=null};var b=c.prototype;b.constructor=c,b.getElementById=function(e,t){return (t=t||this.document, t.getElementById(e))},b.insertBefore=function(e,t,r){return e.insertBefore(t,r)},b.appendChild=function(e,t){return e.appendChild(t)},b.childAt=function(e,t){for(var r=e,n=0;nn;n++)r=r.nextSibling;return r},b.appendText=function(e,t){return e.appendChild(this.document.createTextNode(t))},b.setAttribute=function(e,t,r){e.setAttribute(t,String(r))},b.getAttribute=function(e,t){return e.getAttribute(t)},b.setAttributeNS=function(e,t,r,n){e.setAttributeNS(t,r,String(n))},b.getAttributeNS=function(e,t,r){return e.getAttributeNS(t,r)},p?b.removeAttribute=function(e,t){e.removeAttribute(t)}:b.removeAttribute=function(e,t){"svg"===e.tagName&&"viewBox"===t?e.setAttribute(t,null):e.removeAttribute(t)},b.setPropertyStrict=function(e,t,r){void 0===r&&(r=null),null!==r||"value"!==t&&"type"!==t&&"src"!==t||(r=""),e[t]=r},b.getPropertyStrict=function(e,t){return e[t]},b.setProperty=function(e,t,r,i){var o=t.toLowerCase();if(e.namespaceURI===n.svgNamespace||"style"===o)a.isAttrRemovalValue(r)?e.removeAttribute(t):i?e.setAttributeNS(i,t,r):e.setAttribute(t,r);else{var s=a.normalizeProperty(e,t),l=s.normalized,u=s.type;"prop"===u?e[l]=r:a.isAttrRemovalValue(r)?e.removeAttribute(t):i&&e.setAttributeNS?e.setAttributeNS(i,t,r):e.setAttribute(t,r)}},h&&h.createElementNS?(b.createElement=function(e,t){var r=this.namespace;return (t&&(r="svg"===e?n.svgNamespace:o(t)), r?this.document.createElementNS(r,e):this.document.createElement(e))},b.setAttributeNS=function(e,t,r,n){e.setAttributeNS(t,r,String(n))}):(b.createElement=function(e){return this.document.createElement(e)},b.setAttributeNS=function(e,t,r,n){e.setAttribute(r,String(n))}),b.addClasses=i.addClasses,b.removeClasses=i.removeClasses,b.setNamespace=function(e){this.namespace=e},b.detectNamespace=function(e){this.namespace=o(e)},b.createDocumentFragment=function(){return this.document.createDocumentFragment()},b.createTextNode=function(e){return this.document.createTextNode(e)},b.createComment=function(e){return this.document.createComment(e)},b.repairClonedNode=function(e,t,r){if(m&&t.length>0)for(var n=0,i=t.length;i>n;n++){var a=this.document.createTextNode(""),o=t[n],s=this.childAtIndex(e,o);s?e.insertBefore(a,s):e.appendChild(a)}d&&r&&e.setAttribute("checked","checked")},b.cloneNode=function(e,t){var r=e.cloneNode(!!t);return r},b.AttrMorphClass=r["default"],b.createAttrMorph=function(e,t,r){return new this.AttrMorphClass(e,t,this,r)},b.ElementMorphClass=u,b.createElementMorph=function(e,t){return new this.ElementMorphClass(e,this,t)},b.createUnsafeAttrMorph=function(e,t,r){var n=this.createAttrMorph(e,t,r);return (n.escaped=!1, n)},b.MorphClass=t["default"],b.createMorph=function(e,t,r,n){if(n&&11===n.nodeType)throw new Error("Cannot pass a fragment as the contextual element to createMorph");!n&&e&&1===e.nodeType&&(n=e);var i=new this.MorphClass(this,n);return (i.firstNode=t, i.lastNode=r, i)},b.createFragmentMorph=function(e){if(e&&11===e.nodeType)throw new Error("Cannot pass a fragment as the contextual element to createMorph");var r=this.createDocumentFragment();return t["default"].create(this,e,r)},b.replaceContentWithMorph=function(e){var r=e.firstChild;if(r){var n=t["default"].attach(this,e,r,e.lastChild);return (n.clear(), n)}var i=this.createComment("");return (this.appendChild(e,i), t["default"].create(this,e,i))},b.createUnsafeMorph=function(e,t,r,n){var i=this.createMorph(e,t,r,n);return (i.parseTextAsHTML=!0, i)},b.createMorphAt=function(e,t,r,n){var i=t===r,a=this.childAtIndex(e,t),o=i?a:this.childAtIndex(e,r);return this.createMorph(e,a,o,n)},b.createUnsafeMorphAt=function(e,t,r,n){var i=this.createMorphAt(e,t,r,n);return (i.parseTextAsHTML=!0, i)},b.insertMorphBefore=function(e,t,r){var n=this.document.createComment("");return (e.insertBefore(n,t), this.createMorph(e,n,n,r))},b.appendMorph=function(e,t){var r=this.document.createComment("");return (e.appendChild(r), this.createMorph(e,r,r,t))},b.insertBoundary=function(e,t){var r=null===t?null:this.childAtIndex(e,t);this.insertBefore(e,this.createTextNode(""),r)},b.setMorphHTML=function(e,t){e.setHTML(t)},b.parseHTML=function(e,t){var r;if(o(t)===n.svgNamespace)r=l(e,this);else{var i=n.buildHTMLDOM(e,t,this);if(s(e,t)){for(var a=i[0];a&&1!==a.nodeType;)a=a.nextSibling;r=a.childNodes}else r=i}var u=this.document.createDocumentFragment();if(r&&r.length>0){var c=r[0];for("SELECT"===t.tagName&&(c=c.nextSibling);c;){var h=c;c=c.nextSibling,u.appendChild(h)}}return u};var y;b.protocolForURL=function(e){return (y||(y=this.document.createElement("a")), y.href=e, y.protocol)},e["default"]=c}),e("dom-helper/build-html-dom",["exports"],function(e){"use strict";function t(e,t){t="­"+t,e.innerHTML=t;for(var r=e.childNodes,n=r[0];1===n.nodeType&&!n.nodeName;)n=n.firstChild;if(3===n.nodeType&&"­"===n.nodeValue.charAt(0)){var i=n.nodeValue.slice(1);i.length?n.nodeValue=n.nodeValue.slice(1):n.parentNode.removeChild(n)}return r}function r(e,r){var i=r.tagName,a=r.outerHTML||(new XMLSerializer).serializeToString(r);if(!a)throw"Can't set innerHTML on "+i+" in this browser";e=n(e,r);for(var o=h[i.toLowerCase()],s=a.match(new RegExp("<"+i+"([^>]*)>","i"))[0],l="",u=[s,e,l],c=o.length,m=1+c;c--;)u.unshift("<"+o[c]+">"),u.push("");var d=document.createElement("div");t(d,u.join(""));for(var p=d;m--;)for(p=p.firstChild;p&&1!==p.nodeType;)p=p.nextSibling;for(;p&&p.tagName!==i;)p=p.nextSibling;return p?p.childNodes:[]}function n(e,t){return("SELECT"===t.tagName&&(e=""+e), e)}var i={foreignObject:1,desc:1,title:1};e.svgHTMLIntegrationPoints=i;var a="http://www.w3.org/2000/svg";e.svgNamespace=a;var o,s="undefined"==typeof document?!1:document,l=s&&function(e){if(void 0!==e.createElementNS){var t=e.createElementNS(a,"title");return (t.innerHTML="
", 0===t.childNodes.length||1!==t.childNodes[0].nodeType)}}(s),u=s&&function(e){var t=e.createElement("div");return (t.innerHTML="
", t.firstChild.innerHTML="", ""===t.firstChild.innerHTML)}(s),c=s&&function(e){var t=e.createElement("div");return (t.innerHTML="Test: Value", "Test:"===t.childNodes[0].nodeValue&&" Value"===t.childNodes[2].nodeValue)}(s),h=s&&function(e){var t,r,n=e.createElement("table");try{n.innerHTML=""}catch(i){}finally{r=0===n.childNodes.length}r&&(t={colgroup:["table"],table:[],tbody:["table"],tfoot:["table"],thead:["table"],tr:["table","tbody"]});var a=e.createElement("select");return (a.innerHTML="", a.childNodes[0]||(t=t||{},t.select=[]), t)}(s);o=u?function(e,r,i){return (e=n(e,r), r=i.cloneNode(r,!1), t(r,e), r.childNodes)}:function(e,t,r){return (e=n(e,t), t=r.cloneNode(t,!1), t.innerHTML=e, t.childNodes)};var m;m=h||c?function(e,t,n){var i=[],a=[];"string"==typeof e&&(e=e.replace(/(\s*)()(\s*)/g,function(e,t,r){return (a.push(r), t)}));var s;s=h[t.tagName.toLowerCase()]?r(e,t):o(e,t,n);var l,u,c,m,d=[];for(l=0;l0&&(f=n.document.createTextNode(v),p.parentNode.insertBefore(f,p)),g=a[l],g&&g.length>0&&(f=n.document.createTextNode(g),p.parentNode.insertBefore(f,p.nextSibling));return s}:o;var d;l?e.buildHTMLDOM=d=function(e,t,r){ +return i[t.tagName]?m(e,document.createElement("div"),r):m(e,t,r)}:e.buildHTMLDOM=d=m,e.buildHTMLDOM=d}),e("dom-helper/classes",["exports"],function(e){"use strict";function t(e){var t=e.getAttribute("class")||"";return""!==t&&" "!==t?t.split(" "):[]}function r(e,t){for(var r=0,n=e.length,i=0,a=t.length,o=new Array(a);n>r;r++)for(i=0;a>i;i++)if(t[i]===e[r]){o[i]=r;break}return o}function n(e,n){for(var i=t(e),a=r(i,n),o=!1,s=0,l=n.length;l>s;s++)void 0===a[s]&&(o=!0,i.push(n[s]));o&&e.setAttribute("class",i.length>0?i.join(" "):"")}function i(e,n){for(var i=t(e),a=r(n,i),o=!1,s=[],l=0,u=i.length;u>l;l++)void 0===a[l]?s.push(i[l]):o=!0;o&&e.setAttribute("class",s.length>0?s.join(" "):"")}var a,o,s="undefined"==typeof document?!1:document,l=s&&function(){var e=document.createElement("div");return e.classList?(e.classList.add("boo"),e.classList.add("boo","baz"),"boo baz"===e.className):!1}();l?(e.addClasses=a=function(e,t){e.classList?1===t.length?e.classList.add(t[0]):2===t.length?e.classList.add(t[0],t[1]):e.classList.add.apply(e.classList,t):n(e,t)},e.removeClasses=o=function(e,t){e.classList?1===t.length?e.classList.remove(t[0]):2===t.length?e.classList.remove(t[0],t[1]):e.classList.remove.apply(e.classList,t):i(e,t)}):(e.addClasses=a=n,e.removeClasses=o=i),e.addClasses=a,e.removeClasses=o}),e("dom-helper/prop",["exports"],function(e){"use strict";function t(e){return null===e||void 0===e}function r(e,t){var r,i;if(t in e)i=t,r="prop";else{var a=t.toLowerCase();a in e?(r="prop",i=a):(r="attr",i=t)}return("prop"===r&&n(e.tagName,i)&&(r="attr"), {normalized:i,type:r})}function n(e,t){var r=i[e.toUpperCase()];return r&&r[t.toLowerCase()]||!1}e.isAttrRemovalValue=t,e.normalizeProperty=r;var i={BUTTON:{type:!0,form:!0},INPUT:{list:!0,type:!0,form:!0},SELECT:{form:!0},OPTION:{form:!0},TEXTAREA:{form:!0},LABEL:{form:!0},FIELDSET:{form:!0},LEGEND:{form:!0},OBJECT:{form:!0}}}),e("ember-application",["exports","ember-metal/core","ember-runtime/system/lazy_load","ember-application/system/resolver","ember-application/system/application","ember-application/ext/controller"],function(e,t,r,n,i,a){"use strict";t["default"].Application=i["default"],t["default"].Resolver=n.Resolver,t["default"].DefaultResolver=n["default"],r.runLoadHooks("Ember.Application",i["default"])}),e("ember-application/ext/controller",["exports","ember-metal/core","ember-metal/property_get","ember-metal/error","ember-metal/utils","ember-metal/computed","ember-runtime/mixins/controller","ember-routing/system/controller_for"],function(e,t,r,n,i,a,o,s){"use strict";function l(e,t,r){var a,o,s,l=[];for(o=0,s=r.length;s>o;o++)a=r[o],-1===a.indexOf(":")&&(a="controller:"+a),t._registry.has(a)||l.push(a);if(l.length)throw new n["default"](i.inspect(e)+" needs [ "+l.join(", ")+" ] but "+(l.length>1?"they":"it")+" could not be found")}var u=a.computed(function(){var e=this;return{needs:r.get(e,"needs"),container:r.get(e,"container"),unknownProperty:function(t){var r,n,a,o=this.needs;for(n=0,a=o.length;a>n;n++)if(r=o[n],r===t)return this.container.lookup("controller:"+t);var s=i.inspect(e)+"#needs does not include `"+t+"`. To access the "+t+" controller from "+i.inspect(e)+", "+i.inspect(e)+" should have a `needs` property that is an array of the controllers it has access to.";throw new ReferenceError(s)},setUnknownProperty:function(t,r){throw new Error("You cannot overwrite the value of `controllers."+t+"` of "+i.inspect(e))}}});o["default"].reopen({concatenatedProperties:["needs"],needs:[],init:function(){var e=r.get(this,"needs"),t=r.get(e,"length");t>0&&(this.container&&l(this,this.container,e),r.get(this,"controllers")),this._super.apply(this,arguments)},controllerFor:function(e){return s["default"](r.get(this,"container"),e)},controllers:u}),e["default"]=o["default"]}),e("ember-application/system/application-instance",["exports","ember-metal/property_get","ember-metal/property_set","ember-runtime/system/object","ember-metal/run_loop","ember-metal/computed","container/registry"],function(e,t,r,n,i,a,o){"use strict";e["default"]=n["default"].extend({container:null,applicationRegistry:null,registry:null,customEvents:null,rootElement:null,init:function(){this._super.apply(this,arguments),this.registry=new o["default"]({fallback:this.applicationRegistry,resolver:this.applicationRegistry.resolver}),this.registry.normalizeFullName=this.applicationRegistry.normalizeFullName,this.registry.makeToString=this.applicationRegistry.makeToString,this.container=this.registry.container(),this.registry.register("-application-instance:main",this,{instantiate:!1})},router:a.computed(function(){return this.container.lookup("router:main")}).readOnly(),overrideRouterLocation:function(e){var n=e&&e.location,i=t.get(this,"router");n&&r.set(i,"location",n)},didCreateRootView:function(e){e.appendTo(this.rootElement)},startRouting:function(){var e=t.get(this,"router"),r=!!this.registry.resolver.moduleBasedResolver;e.startRouting(r),this._didSetupRouter=!0},setupRouter:function(){if(!this._didSetupRouter){this._didSetupRouter=!0;var e=t.get(this,"router"),r=!!this.registry.resolver.moduleBasedResolver;e.setupRouter(r)}},handleURL:function(e){var r=t.get(this,"router");return (this.setupRouter(), r.handleURL(e))},setupEventDispatcher:function(){var e=this.container.lookup("event_dispatcher:main"),r=t.get(this.application,"customEvents");return (e.setup(r,this.rootElement), e)},willDestroy:function(){this._super.apply(this,arguments),i["default"](this.container,"destroy")}})}),e("ember-application/system/application",["exports","dag-map","container/registry","ember-metal","ember-metal/property_get","ember-metal/property_set","ember-runtime/system/lazy_load","ember-runtime/system/namespace","ember-runtime/mixins/deferred","ember-application/system/resolver","ember-metal/platform/create","ember-metal/run_loop","ember-metal/utils","ember-runtime/controllers/controller","ember-metal/enumerable_utils","ember-runtime/controllers/object_controller","ember-runtime/controllers/array_controller","ember-metal-views/renderer","ember-htmlbars/system/dom-helper","ember-views/views/select","ember-routing-views/views/outlet","ember-views/views/view","ember-views/system/event_dispatcher","ember-views/system/jquery","ember-routing/system/route","ember-routing/system/router","ember-routing/location/hash_location","ember-routing/location/history_location","ember-routing/location/auto_location","ember-routing/location/none_location","ember-routing/system/cache","ember-application/system/application-instance","ember-views/views/text_field","ember-views/views/text_area","ember-views/views/checkbox","ember-views/views/legacy_each_view","ember-routing-views/views/link","ember-routing/services/routing","ember-extension-support/container_debug_adapter","ember-metal/environment"],function(e,t,r,n,i,a,o,s,l,u,c,h,m,d,p,f,v,g,b,y,_,w,x,C,k,E,A,N,O,P,S,T,R,M,D,I,V,j,L,F){"use strict";function B(e){var t=[];for(var r in e)t.push(r);return t}function H(e){function t(e){return n.resolve(e)}var r=e.get("resolver")||e.get("Resolver")||u["default"],n=r.create({namespace:e});return (t.describe=function(e){return n.lookupDescription(e)}, t.makeToString=function(e,t){return n.makeToString(e,t)}, t.normalize=function(e){return n.normalize?n.normalize(e):e}, t.knownForType=function(e){return n.knownForType?n.knownForType(e):void 0}, t.moduleBasedResolver=n.moduleBasedResolver, t.__resolver__=n, t)}function z(){W||(W=!0,F["default"].hasDOM&&n["default"].libraries.registerCoreLibrary("jQuery",C["default"]().jquery))}function U(){if(n["default"].LOG_VERSION){n["default"].LOG_VERSION=!1;for(var e=n["default"].libraries._registry,t=p.map(e,function(e){return i.get(e,"name.length")}),r=Math.max.apply(this,t),a=0,o=e.length;o>a;a++){var s=e[a];new Array(r-s.name.length+1).join(" ")}}}function q(e,t){return function(t){if(void 0!==this.superclass[e]&&this.superclass[e]===this[e]){var r={};r[e]=c["default"](this[e]),this.reopenClass(r)}this[e][t.name]=t}}var W=!1,K=s["default"].extend(l["default"],{_suppressDeferredDeprecation:!0,rootElement:"body",eventDispatcher:null,customEvents:null,autoboot:!0,init:function(){this._super.apply(this,arguments),this.$||(this.$=C["default"]),this.buildRegistry(),z(),U(),this._readinessDeferrals=1,this.Router=(this.Router||E["default"]).extend(),this.buildDefaultInstance(),this.waitForDOMReady()},buildRegistry:function(){var e=this.registry=K.buildRegistry(this);return e},buildInstance:function(){return T["default"].create({application:this,rootElement:i.get(this,"rootElement"),applicationRegistry:this.registry})},buildDefaultInstance:function(){var e=this.buildInstance();return (w["default"].views=e.container.lookup("-view-registry:main"), this.__deprecatedInstance__=e, this.__container__=e.container, e)},waitForDOMReady:function(){!this.$||this.$.isReady?h["default"].schedule("actions",this,"domReady"):this.$().ready(h["default"].bind(this,"domReady"))},deferReadiness:function(){this._readinessDeferrals++},advanceReadiness:function(){this._readinessDeferrals--,0===this._readinessDeferrals&&h["default"].once(this,this.didBecomeReady)},register:function(){var e;(e=this.registry).register.apply(e,arguments)},inject:function(){var e;(e=this.registry).injection.apply(e,arguments)},initialize:function(){},domReady:function(){return this.isDestroyed?void 0:(this.boot(),this)},boot:function(){if(this._bootPromise)return this._bootPromise;var e=new n["default"].RSVP.defer;return (this._bootPromise=e.promise, this._bootResolver=e, this.runInitializers(this.registry), o.runLoadHooks("application",this), this.advanceReadiness(), this._bootPromise)},reset:function(){function e(){h["default"](t,"destroy"),h["default"].schedule("actions",this,"domReady",this.buildDefaultInstance())}var t=this.__deprecatedInstance__;this._readinessDeferrals=1,this._bootPromise=null,this._bootResolver=null,h["default"].join(this,e)},runInitializers:function(e){var t=this;this._runInitializer("initializers",function(r,n){n.initialize(e,t)})},runInstanceInitializers:function(e){this._runInitializer("instanceInitializers",function(t,r){r.initialize(e)})},_runInitializer:function(e,r){for(var n,a=i.get(this.constructor,e),o=B(a),s=new t["default"],l=0;l-1&&(i=i.replace(/\.(.)/g,function(e){return e.charAt(1).toUpperCase()})), n.indexOf("_")>-1&&(i=i.replace(/_(.)/g,function(e){return e.charAt(1).toUpperCase()})), r+":"+i)}return e},resolve:function(e){var t,r=this.parseName(e),n=r.resolveMethodName;return (this[n]&&(t=this[n](r)), t=t||this.resolveOther(r), r.root&&r.root.LOG_RESOLVER&&this._logLookup(t,r), t&&u["default"](t,r), t)},parseName:function(e){return this._parseNameCache[e]||(this._parseNameCache[e]=this._parseName(e))},_parseName:function(e){var t=e.split(":"),n=t[0],i=t[1],o=i,l=r.get(this,"namespace"),u=l;if("template"!==n&&-1!==o.indexOf("/")){var c=o.split("/");o=c[c.length-1];var h=a.capitalize(c.slice(0,-1).join("."));u=s["default"].byName(h)}var m="main"===i?"Main":a.classify(n);if(!o||!n)throw new TypeError("Invalid fullName: `"+e+"`, must be of the form `type:name` ");return{fullName:e,type:n,fullNameWithoutType:i,name:o,root:u,resolveMethodName:"resolve"+m}},lookupDescription:function(e){var t,r=this.parseName(e);return"template"===r.type?"template at "+r.fullNameWithoutType.replace(/\./g,"/"):(t=r.root+"."+a.classify(r.name).replace(/\./g,""),"model"!==r.type&&(t+=a.classify(r.type)),t)},makeToString:function(e,t){return e.toString()},useRouterNaming:function(e){e.name=e.name.replace(/\./g,"_"),"basic"===e.name&&(e.name="")},resolveTemplate:function(e){var r=e.fullNameWithoutType.replace(/\./g,"/");return t["default"].TEMPLATES[r]?t["default"].TEMPLATES[r]:(r=a.decamelize(r),t["default"].TEMPLATES[r]?t["default"].TEMPLATES[r]:void 0)},resolveView:function(e){return (this.useRouterNaming(e), this.resolveOther(e))},resolveController:function(e){return (this.useRouterNaming(e), this.resolveOther(e))},resolveRoute:function(e){return (this.useRouterNaming(e), this.resolveOther(e))},resolveModel:function(e){var t=a.classify(e.name),n=r.get(e.root,t);return n?n:void 0},resolveHelper:function(e){return this.resolveOther(e)||l["default"][e.fullNameWithoutType]},resolveOther:function(e){var t=a.classify(e.name)+a.classify(e.type),n=r.get(e.root,t);return n?n:void 0},resolveMain:function(e){var t=a.classify(e.type);return r.get(e.root,t)},_logLookup:function(e,t){var r,i;r=e?"[✓]":"[ ]",i=t.fullName.length>60?".":new Array(60-t.fullName.length).join("."),n["default"].info(r,t.fullName,i,this.lookupDescription(t.fullName))},knownForType:function(e){for(var t=r.get(this,"namespace"),n=a.classify(e),o=new RegExp(n+"$"),s=c["default"](null),l=i["default"](t),u=0,h=l.length;h>u;u++){var m=l[u];if(o.test(m)){var d=this.translateToContainerFullname(e,m);s[d]=!0}}return s},translateToContainerFullname:function(e,t){var r=a.classify(e),n=t.slice(0,-1*r.length),i=a.dasherize(n);return e+":"+i}})}),e("ember-application/utils/validate-type",["exports"],function(e){"use strict";function t(e,t){var n=r[t.type];if(n){n[0],n[1],n[2]}}e["default"]=t;var r={route:["assert","isRouteFactory","Ember.Route"],component:["deprecate","isComponentFactory","Ember.Component"],view:["deprecate","isViewFactory","Ember.View"],service:["deprecate","isServiceFactory","Ember.Service"]}}),e("ember-extension-support",["exports","ember-metal/core","ember-extension-support/data_adapter","ember-extension-support/container_debug_adapter"],function(e,t,r,n){"use strict";t["default"].DataAdapter=r["default"],t["default"].ContainerDebugAdapter=n["default"]}),e("ember-extension-support/container_debug_adapter",["exports","ember-metal/core","ember-runtime/system/native_array","ember-runtime/utils","ember-runtime/system/string","ember-runtime/system/namespace","ember-runtime/system/object"],function(e,t,r,n,i,a,o){"use strict";e["default"]=o["default"].extend({container:null,resolver:null,canCatalogEntriesByType:function(e){return"model"===e||"template"===e?!1:!0},catalogEntriesByType:function(e){var o=r.A(a["default"].NAMESPACES),s=r.A(),l=new RegExp(i.classify(e)+"$");return (o.forEach(function(e){if(e!==t["default"])for(var r in e)if(e.hasOwnProperty(r)&&l.test(r)){var a=e[r];"class"===n.typeOf(a)&&s.push(i.dasherize(r.replace(l,"")))}}), s)}})}),e("ember-extension-support/data_adapter",["exports","ember-metal/property_get","ember-metal/run_loop","ember-runtime/system/string","ember-runtime/system/namespace","ember-runtime/system/object","ember-runtime/system/native_array","ember-application/system/application"],function(e,t,r,n,i,a,o,s){"use strict";e["default"]=a["default"].extend({init:function(){this._super.apply(this,arguments),this.releaseMethods=o.A()},container:null,containerDebugAdapter:void 0,attributeLimit:3,acceptsModelName:!0,releaseMethods:o.A(),getFilters:function(){return o.A()},watchModelTypes:function(e,t){var r,n=this,i=this.getModelTypes(),a=o.A();r=i.map(function(e){var r=e.klass,i=n.wrapModelType(r,e.name);return (a.push(n.observeModelType(e.name,t)), i)}),e(r);var s=function(){a.forEach(function(e){return e()}),n.releaseMethods.removeObject(s)};return (this.releaseMethods.pushObject(s), s)},_nameToClass:function(e){return("string"==typeof e&&(e=this.container.lookupFactory("model:"+e)), e)},watchRecords:function(e,t,r,n){var i,a=this,s=o.A(),l=this._nameToClass(e),u=this.getRecords(l,e),c=function(e){r([e])},h=u.map(function(e){return (s.push(a.observeRecord(e,c)), a.wrapRecord(e))}),m=function(e,r,i,o){for(var l=r;r+o>l;l++){var u=e.objectAt(l),h=a.wrapRecord(u);s.push(a.observeRecord(u,c)),t([h])}i&&n(r,i)},d={didChange:m,willChange:function(){return this}};return (u.addArrayObserver(this,d), i=function(){s.forEach(function(e){e()}),u.removeArrayObserver(a,d),a.releaseMethods.removeObject(i)}, t(h), this.releaseMethods.pushObject(i), i)},willDestroy:function(){this._super.apply(this,arguments),this.releaseMethods.forEach(function(e){e()})},detect:function(e){return!1},columnsForType:function(e){return o.A()},observeModelType:function(e,t){var n=this,i=this._nameToClass(e),a=this.getRecords(i,e),o=function(){t([n.wrapModelType(i,e)])},s={didChange:function(){r["default"].scheduleOnce("actions",this,o)},willChange:function(){return this}};a.addArrayObserver(this,s);var l=function(){a.removeArrayObserver(n,s)};return l},wrapModelType:function(e,r){var n,i=this.getRecords(e,r);return n={name:r,count:t.get(i,"length"),columns:this.columnsForType(e),object:e}},getModelTypes:function(){var e,t=this,r=this.get("containerDebugAdapter");return (e=r.canCatalogEntriesByType("model")?r.catalogEntriesByType("model"):this._getObjectsOnNamespaces(), e=o.A(e).map(function(e){return{klass:t._nameToClass(e),name:e}}), e=o.A(e).filter(function(e){return t.detect(e.klass)}), o.A(e))},_getObjectsOnNamespaces:function(){var e=this,t=o.A(i["default"].NAMESPACES),r=o.A();return (t.forEach(function(t){for(var i in t)if(t.hasOwnProperty(i)&&e.detect(t[i])){var a=n.dasherize(i);t instanceof s["default"]||!t.toString()||(a=t+"/"+a),r.push(a)}}), r)},getRecords:function(e){return o.A()},wrapRecord:function(e){var t={object:e};return (t.columnValues=this.getRecordColumnValues(e), t.searchKeywords=this.getRecordKeywords(e), t.filterValues=this.getRecordFilterValues(e), t.color=this.getRecordColor(e), t)},getRecordColumnValues:function(e){return{}},getRecordKeywords:function(e){return o.A()},getRecordFilterValues:function(e){return{}},getRecordColor:function(e){return null},observeRecord:function(e,t){return function(){}}})}),e("ember-htmlbars",["exports","ember-metal/core","ember-template-compiler","ember-htmlbars/system/make-view-helper","ember-htmlbars/system/make_bound_helper","ember-htmlbars/helpers","ember-htmlbars/helpers/if_unless","ember-htmlbars/helpers/with","ember-htmlbars/helpers/loc","ember-htmlbars/helpers/log","ember-htmlbars/helpers/each","ember-htmlbars/helpers/-bind-attr-class","ember-htmlbars/helpers/-normalize-class","ember-htmlbars/helpers/-concat","ember-htmlbars/helpers/-join-classes","ember-htmlbars/helpers/-legacy-each-with-controller","ember-htmlbars/helpers/-legacy-each-with-keyword","ember-htmlbars/helpers/-html-safe","ember-htmlbars/system/dom-helper","ember-htmlbars/helper","ember-htmlbars/system/bootstrap","ember-htmlbars/compat"],function(e,t,r,n,i,a,o,s,l,u,c,h,m,d,p,f,v,g,b,y,_,w){"use strict";a.registerHelper("if",o.ifHelper),a.registerHelper("unless",o.unlessHelper),a.registerHelper("with",s["default"]),a.registerHelper("loc",l["default"]),a.registerHelper("log",u["default"]),a.registerHelper("each",c["default"]),a.registerHelper("-bind-attr-class",h["default"]),a.registerHelper("-normalize-class",m["default"]),a.registerHelper("concat",d["default"]),a.registerHelper("-join-classes",p["default"]),a.registerHelper("-legacy-each-with-controller",f["default"]),a.registerHelper("-legacy-each-with-keyword",v["default"]),a.registerHelper("-html-safe",g["default"]),t["default"].HTMLBars={_registerHelper:a.deprecatedRegisterHelper,template:r.template,compile:r.compile,precompile:r.precompile,makeViewHelper:n["default"],makeBoundHelper:i["default"],registerPlugin:r.registerPlugin,DOMHelper:b["default"]},y["default"].helper=y.helper,t["default"].Helper=y["default"]}),e("ember-htmlbars/compat",["exports","ember-metal/core","ember-htmlbars/helpers","ember-htmlbars/compat/helper","ember-htmlbars/compat/handlebars-get","ember-htmlbars/compat/make-bound-helper","ember-htmlbars/compat/register-bound-helper","ember-htmlbars/system/make-view-helper","ember-htmlbars/utils/string"],function(e,t,r,n,i,a,o,s,l){"use strict";var u=t["default"].Handlebars=t["default"].Handlebars||{};u.helpers=r["default"],u.helper=n.handlebarsHelper,u.registerHelper=n.registerHandlebarsCompatibleHelper,u.registerBoundHelper=o["default"],u.makeBoundHelper=a["default"],u.get=i["default"],u.makeViewHelper=s["default"],u.SafeString=l.SafeString,u.Utils={escapeExpression:l.escapeExpression},e["default"]=u}),e("ember-htmlbars/compat/handlebars-get",["exports"],function(e){"use strict";function t(e,t,r){return r.legacyGetPath(t)}e["default"]=t}),e("ember-htmlbars/compat/helper",["exports","ember-htmlbars/helpers","ember-views/views/view","ember-views/views/component","ember-htmlbars/system/make-view-helper","ember-htmlbars/compat/make-bound-helper","ember-metal/streams/utils","ember-htmlbars/keywords"],function(e,t,r,n,i,a,o,s){"use strict";function l(e){if(o.isStream(e))return"ID";var t=typeof e;return t.toUpperCase()}function u(e){return o.isStream(e)?e.source&&e.source.dependee&&"self"===e.source.dependee.label?e.path.slice(5):e.path:e}function c(e){this.helperFunction=function(t,r,n,i,a){var o,s,c=n.template&&n.template["yield"],h={hash:{},types:new Array(t.length),hashTypes:{}};h.hash={},c&&(h.fn=function(){n.template["yield"]()},n.inverse["yield"]&&(h.inverse=function(){n.inverse["yield"]()}));for(var m in r)o=r[m],h.hashTypes[m]=l(o),h.hash[m]=u(o);for(var p=new Array(t.length),f=0,v=t.length;v>f;f++)o=t[f],h.types[f]=l(o),p[f]=u(o);if(h.legacyGetPath=function(e){return i.hooks.get(i,a,e).value()},h.data={view:a.view},p.push(h),s=e.apply(this,p),n.element)d(i.dom,n.element,s);else if(!n.template["yield"])return s},this.isHTMLBars=!0}function h(e,r){if(r&&r.isLegacyViewHelper)return void s.registerKeyword(e,function(e,t,n,i,a,o,s,l){return (t.hooks.keyword("view",e,t,n,[r.viewClass],a,o,s,l), !0)});var n;n=r&&r.isHTMLBars?r:new c(r),t["default"][e]=n}function m(e,n){if(r["default"].detect(n))t["default"][e]=i["default"](n);else{var o=p.call(arguments,1),s=a["default"].apply(this,o);t["default"][e]=s}}function d(e,t,r){for(var n="<"+t.tagName+" "+r+">",i=e.parseHTML(n,e.createElement(t.tagName)),a=i.firstChild.attributes,o=0,s=a.length;s>o;o++)t.setAttributeNode(a[o].cloneNode())}e.registerHandlebarsCompatibleHelper=h,e.handlebarsHelper=m;var p=[].slice;c.prototype={preprocessArguments:function(){}},e["default"]=c}),e("ember-htmlbars/compat/make-bound-helper",["exports","ember-metal/streams/utils"],function(e,t){"use strict";function r(e){for(var r=arguments.length,n=Array(r>1?r-1:0),i=1;r>i;i++)n[i-1]=arguments[i];return{_dependentKeys:n,isHandlebarsCompat:!0,isHTMLBars:!0,helperFunction:function(r,n,i){for(var a=t.readArray(r),o=new Array(r.length),s=0,l=r.length;l>s;s++){var u=r[s];t.isStream(u)?o[s]=u.label:o[s]=u}return (a.push({hash:t.readHash(n),templates:i,data:{properties:o}}), e.apply(void 0,a))}}}function n(e){for(var t=arguments.length,n=Array(t>1?t-1:0),i=1;t>i;i++)n[i-1]=arguments[i];return r.apply(void 0,arguments)}e.makeBoundHelper=r,e["default"]=n}),e("ember-htmlbars/compat/register-bound-helper",["exports","ember-metal/core","ember-htmlbars/helpers","ember-htmlbars/compat/make-bound-helper"],function(e,t,r,n){"use strict";function i(e,t){var i=o.call(arguments,1),a=n.makeBoundHelper.apply(this,i);r["default"][e]=a}function a(){return i.apply(void 0,arguments)}e.registerBoundHelper=i,e["default"]=a;var o=[].slice}),e("ember-htmlbars/env",["exports","ember-metal/environment","htmlbars-runtime","ember-metal/merge","ember-htmlbars/hooks/subexpr","ember-htmlbars/hooks/concat","ember-htmlbars/hooks/link-render-node","ember-htmlbars/hooks/create-fresh-scope","ember-htmlbars/hooks/bind-shadow-scope","ember-htmlbars/hooks/bind-self","ember-htmlbars/hooks/bind-scope","ember-htmlbars/hooks/bind-local","ember-htmlbars/hooks/update-self","ember-htmlbars/hooks/get-root","ember-htmlbars/hooks/get-child","ember-htmlbars/hooks/get-value","ember-htmlbars/hooks/get-cell-or-value","ember-htmlbars/hooks/cleanup-render-node","ember-htmlbars/hooks/destroy-render-node","ember-htmlbars/hooks/did-render-node","ember-htmlbars/hooks/will-cleanup-tree","ember-htmlbars/hooks/did-cleanup-tree","ember-htmlbars/hooks/classify","ember-htmlbars/hooks/component","ember-htmlbars/hooks/lookup-helper","ember-htmlbars/hooks/has-helper","ember-htmlbars/hooks/invoke-helper","ember-htmlbars/hooks/element","ember-htmlbars/helpers","ember-htmlbars/keywords","ember-htmlbars/system/dom-helper","ember-htmlbars/keywords/debugger","ember-htmlbars/keywords/with","ember-htmlbars/keywords/outlet","ember-htmlbars/keywords/real_outlet","ember-htmlbars/keywords/customized_outlet","ember-htmlbars/keywords/unbound","ember-htmlbars/keywords/view","ember-htmlbars/keywords/component","ember-htmlbars/keywords/partial","ember-htmlbars/keywords/input","ember-htmlbars/keywords/textarea","ember-htmlbars/keywords/collection","ember-htmlbars/keywords/template","ember-htmlbars/keywords/legacy-yield","ember-htmlbars/keywords/mut","ember-htmlbars/keywords/each","ember-htmlbars/keywords/readonly"],function(e,t,r,n,i,a,o,s,l,u,c,h,m,d,p,f,v,g,b,y,_,w,x,C,k,E,A,N,O,P,S,T,R,M,D,I,V,j,L,F,B,H,z,U,q,W,K,G){"use strict";var Q=n["default"]({},r.hooks);Q.keywords=P["default"],n["default"](Q,{linkRenderNode:o["default"],createFreshScope:s["default"],bindShadowScope:l["default"],bindSelf:u["default"],bindScope:c["default"],bindLocal:h["default"],updateSelf:m["default"],getRoot:d["default"],getChild:p["default"],getValue:f["default"],getCellOrValue:v["default"],subexpr:i["default"],concat:a["default"],cleanupRenderNode:g["default"],destroyRenderNode:b["default"],willCleanupTree:_["default"],didCleanupTree:w["default"],didRenderNode:y["default"],classify:x["default"],component:C["default"],lookupHelper:k["default"],hasHelper:E["default"],invokeHelper:A["default"],element:N["default"]}),P.registerKeyword("debugger",T["default"]),P.registerKeyword("with",R["default"]),P.registerKeyword("outlet",M["default"]),P.registerKeyword("@real_outlet",D["default"]),P.registerKeyword("@customized_outlet",I["default"]),P.registerKeyword("unbound",V["default"]),P.registerKeyword("view",j["default"]),P.registerKeyword("component",L["default"]),P.registerKeyword("partial",F["default"]),P.registerKeyword("template",U["default"]),P.registerKeyword("input",B["default"]),P.registerKeyword("textarea",H["default"]),P.registerKeyword("collection",z["default"]),P.registerKeyword("legacy-yield",q["default"]),P.registerKeyword("mut",W["default"]),P.registerKeyword("@mut",W.privateMut),P.registerKeyword("each",K["default"]),P.registerKeyword("readonly",G["default"]),e["default"]={hooks:Q,helpers:O["default"],useFragmentCache:!0};var Y=t["default"].hasDOM?new S["default"]:null;e.domHelper=Y}),e("ember-htmlbars/helper",["exports","ember-runtime/system/object"],function(e,t){"use strict";function r(e){return{isHelperInstance:!0,compute:e}}e.helper=r;var n=t["default"].extend({isHelper:!0,recompute:function(){this._stream.notify()}});n.reopenClass({isHelperFactory:!0}),e["default"]=n}),e("ember-htmlbars/helpers",["exports","ember-metal/platform/create","ember-metal/core"],function(e,t,r){"use strict";function n(e,t){i[e]=t}e.registerHelper=n;var i=t["default"](null),a=r["default"].deprecateFunc("Using Ember.HTMLBars._registerHelper is deprecated. Helpers (even dashless ones) are automatically resolved.",{id:"ember-htmlbars.register-helper",until:"2.0.0"},n);e.deprecatedRegisterHelper=a,e["default"]=i}),e("ember-htmlbars/helpers/-bind-attr-class",["exports","ember-metal/property_get","ember-metal/utils"],function(e,t,r){"use strict";function n(e){var n=e[0];return (r.isArray(n)&&(n=0!==t.get(n,"length")), n===!0?e[1]:n===!1||void 0===n||null===n?"":n)}e["default"]=n}),e("ember-htmlbars/helpers/-concat",["exports"],function(e){"use strict";function t(e){return e.join("")}e["default"]=t}),e("ember-htmlbars/helpers/-html-safe",["exports","htmlbars-util/safe-string"],function(e,t){"use strict";function r(e){var r=e[0];return new t["default"](r)}e["default"]=r}),e("ember-htmlbars/helpers/-join-classes",["exports"],function(e){"use strict";function t(e){for(var t=[],r=0,n=e.length;n>r;r++){var i=e[r];i&&t.push(i)}return t.join(" ")}e["default"]=t}),e("ember-htmlbars/helpers/-legacy-each-with-controller",["exports","ember-metal/property_get","ember-metal/enumerable_utils","ember-htmlbars/utils/normalize-self","ember-htmlbars/utils/decode-each-key"],function(e,t,r,n,i){ +"use strict";function a(e,a,s){var l=e[0],u=a.key;return l&&0!==t.get(l,"length")?void r.forEach(l,function(e,t){var r;0===s.template.arity&&(r=n["default"](e),r=o(r,!0));var a=i["default"](e,u,t);s.template.yieldItem(a,[e,t],r)}):void(s.inverse["yield"]&&s.inverse["yield"]())}function o(e,t){return{controller:e,hasBoundController:!0,self:e?e:void 0}}e["default"]=a;var s="Using the context switching form of {{each}} is deprecated. Please use the keyword form (`{{#each items as |item|}}`) instead.";e.deprecation=s}),e("ember-htmlbars/helpers/-legacy-each-with-keyword",["exports","ember-metal/enumerable_utils","ember-views/streams/should_display","ember-htmlbars/utils/decode-each-key"],function(e,t,r,n){"use strict";function i(e,i,o){var s=e[0],l=i.key,u=i["-legacy-keyword"];r["default"](s)?t.forEach(s,function(e,t){var r;u&&(r=a(r,u,e));var i=n["default"](e,l,t);o.template.yieldItem(i,[e,t],r)}):o.inverse["yield"]&&o.inverse["yield"]()}function a(e,t,r){var n;return (n={self:e}, n[t]=r, n)}e["default"]=i;var o="Using the context switching form of {{each}} is deprecated. Please use the keyword form (`{{#each items as |item|}}`) instead.";e.deprecation=o}),e("ember-htmlbars/helpers/-normalize-class",["exports","ember-runtime/system/string","ember-metal/path_cache"],function(e,t,r){"use strict";function n(e,n){var i=e[0],a=e[1],o=n.activeClass,s=n.inactiveClass;if(o||s)return a?o:s;if(a===!0){if(i&&r.isPath(i)){var l=i.split(".");i=l[l.length-1]}return t.dasherize(i)}return a!==!1&&null!=a?a:null}e["default"]=n}),e("ember-htmlbars/helpers/bind-attr",["exports"],function(e){"use strict"}),e("ember-htmlbars/helpers/each",["exports","ember-metal/enumerable_utils","ember-htmlbars/utils/normalize-self","ember-views/streams/should_display","ember-htmlbars/utils/decode-each-key"],function(e,t,r,n,i){"use strict";function a(e,a,o){var s=e[0],l=a.key;0===o.template.arity,n["default"](s)?t.forEach(s,function(e,t){var n;0===o.template.arity&&(n=r["default"](e));var a=i["default"](e,l,t);o.template.yieldItem(a,[e,t],n)}):o.inverse["yield"]&&o.inverse["yield"]()}e["default"]=a;var o="Using the context switching form of {{each}} is deprecated. Please use the keyword form (`{{#each items as |item|}}`) instead.";e.deprecation=o}),e("ember-htmlbars/helpers/if_unless",["exports","ember-metal/core","ember-views/streams/should_display"],function(e,t,r){"use strict";function n(e,t,n){return a(e,t,n,r["default"](e[0]))}function i(e,t,n){return a(e,t,n,!r["default"](e[0]))}function a(e,t,r,n){if(n){if(!r.template["yield"])return e[1];r.template["yield"]()}else{if(!r.inverse["yield"])return e[2];r.inverse["yield"]()}}e.ifHelper=n,e.unlessHelper=i}),e("ember-htmlbars/helpers/loc",["exports","ember-runtime/system/string"],function(e,t){"use strict";function r(e){return t.loc.apply(null,e)}e["default"]=r}),e("ember-htmlbars/helpers/log",["exports","ember-metal/logger"],function(e,t){"use strict";function r(e){t["default"].log.apply(null,e)}e["default"]=r}),e("ember-htmlbars/helpers/with",["exports","ember-htmlbars/utils/normalize-self","ember-views/streams/should_display"],function(e,t,r){"use strict";function n(e,n,i){if(r["default"](e[0])){var a=!1;if(0!==i.template.arity&&(a=!0),a)this["yield"]([e[0]]);else{var o=t["default"](e[0]);n.controller&&(o={hasBoundController:!0,controller:n.controller,self:o}),this["yield"]([],o)}}else i.inverse&&i.inverse["yield"]&&i.inverse["yield"]([])}e["default"]=n}),e("ember-htmlbars/hooks/bind-local",["exports","ember-metal/streams/stream","ember-metal/streams/proxy-stream"],function(e,t,r){"use strict";function n(e,n,i,a){var o=n.locals.hasOwnProperty(i);if(o){var s=n.locals[i];s!==a&&s.setSource(a)}else{var l=t["default"].wrap(a,r["default"],i);n.locals[i]=l}}e["default"]=n}),e("ember-htmlbars/hooks/bind-scope",["exports"],function(e){"use strict";function t(e,t){}e["default"]=t}),e("ember-htmlbars/hooks/bind-self",["exports","ember-metal/streams/proxy-stream","ember-htmlbars/utils/subscribe"],function(e,t,r){"use strict";function n(e,t,r){var n=r;if(n&&n.hasBoundController){var a=n,o=a.controller;n=n.self,i(t.locals,"controller",o||n)}return n&&n.isView?(i(t.locals,"view",n,null),i(t.locals,"controller",t.locals.view.getKey("controller")),void i(t,"self",t.locals.view.getKey("context"),null,!0)):(i(t,"self",n,null,!0),void(t.locals.controller||(t.locals.controller=t.self)))}function i(e,n,i,a,o){var s=new t["default"](i,o?"":n);a&&r["default"](a,e,s),e[n]=s}e["default"]=n}),e("ember-htmlbars/hooks/bind-shadow-scope",["exports","ember-views/views/component","ember-metal/streams/proxy-stream","ember-htmlbars/utils/subscribe"],function(e,t,r,n){"use strict";function i(e,r,n,i){if(i){var o=!1;r&&r.overrideController&&(o=!0,n.locals.controller=r.locals.controller);var s=i.view;return(!s||s instanceof t["default"]||(a(n.locals,"view",s,null),o||a(n.locals,"controller",n.locals.view.getKey("controller")),s.isView&&a(n,"self",n.locals.view.getKey("context"),null,!0)), n.view=s, s&&i.attrs&&(n.component=s), "attrs"in i&&(n.attrs=i.attrs), n)}}function a(e,t,i,a,o){var s=new r["default"](i,o?"":t);a&&n["default"](a,e,s),e[t]=s}e["default"]=i}),e("ember-htmlbars/hooks/classify",["exports","ember-htmlbars/utils/is-component"],function(e,t){"use strict";function r(e,r,n){return t["default"](e,r,n)?"component":null}e["default"]=r}),e("ember-htmlbars/hooks/cleanup-render-node",["exports"],function(e){"use strict";function t(e){e.cleanup&&e.cleanup()}e["default"]=t}),e("ember-htmlbars/hooks/component",["exports","ember-htmlbars/node-managers/component-node-manager"],function(e,t){"use strict";function r(e,r,n,i,a,o,s,l){var u=e.state;if(u.manager)return void u.manager.rerender(r,o,l);var c=i,h=!1;"<"===c.charAt(0)&&(c=c.slice(1,-1),h=!0);var m=r.view,d=t["default"].create(e,r,{tagName:c,params:a,attrs:o,parentView:m,templates:s,isAngleBracket:h,parentScope:n});u.manager=d,d.render(r,l)}e["default"]=r}),e("ember-htmlbars/hooks/concat",["exports","ember-metal/streams/utils"],function(e,t){"use strict";function r(e,r){return t.concat(r,"")}e["default"]=r}),e("ember-htmlbars/hooks/create-fresh-scope",["exports"],function(e){"use strict";function t(){return{self:null,blocks:{},component:null,attrs:null,locals:{},localPresent:{}}}e["default"]=t}),e("ember-htmlbars/hooks/destroy-render-node",["exports"],function(e){"use strict";function t(e){e.emberView&&e.emberView.destroy();var t=e.streamUnsubscribers;if(t)for(var r=0,n=t.length;n>r;r++)t[r]()}e["default"]=t}),e("ember-htmlbars/hooks/did-cleanup-tree",["exports"],function(e){"use strict";function t(e){e.view.ownerView._destroyingSubtreeForView=null}e["default"]=t}),e("ember-htmlbars/hooks/did-render-node",["exports"],function(e){"use strict";function t(e,t){t.renderedNodes[e.guid]=!0}e["default"]=t}),e("ember-htmlbars/hooks/element",["exports","ember-htmlbars/system/lookup-helper","htmlbars-runtime/hooks","ember-htmlbars/system/invoke-helper"],function(e,t,r,n){"use strict";function i(e,t){o||(o=document.createElement("div")),o.innerHTML="<"+e.tagName+" "+t+">";for(var r=o.firstChild.attributes,n=0,i=r.length;i>n;n++){var a=r[n];a.specified&&e.setAttribute(a.name,a.value)}}function a(e,a,o,s,l,u,c){if(!r.handleRedirect(e,a,o,s,l,u,null,null,c)){var h,m=t.findHelper(s,o.self,a);if(m){var d=n.buildHelperStream(m,l,u,{element:e.element},a,o);h=d.value()}else h=a.hooks.get(a,o,s);var p=a.hooks.getValue(h);p&&i(e.element,p)}}e["default"]=a;var o}),e("ember-htmlbars/hooks/get-cell-or-value",["exports","ember-metal/streams/utils","ember-htmlbars/keywords/mut"],function(e,t,r){"use strict";function n(e){return e&&e[r.MUTABLE_REFERENCE]?e.cell():t.read(e)}e["default"]=n}),e("ember-htmlbars/hooks/get-child",["exports","ember-metal/streams/utils"],function(e,t){"use strict";function r(e,r){return t.isStream(e)?e.getKey(r):e[r]}e["default"]=r}),e("ember-htmlbars/hooks/get-root",["exports","ember-metal/core","ember-metal/path_cache","ember-metal/streams/proxy-stream"],function(e,t,r,n){"use strict";function i(e,n){return"this"===n?[e.self]:"hasBlock"===n?[!!e.blocks["default"]]:"hasBlockParams"===n?[!(!e.blocks["default"]||!e.blocks["default"].arity)]:r.isGlobal(n)&&t["default"].lookup[n]?[o(n)]:n in e.locals?[e.locals[n]]:[a(e,n)]}function a(e,t){if("attrs"===t&&e.attrs)return e.attrs;var r=e.self||e.locals.view;return r?r.getKey(t):e.attrs&&t in e.attrs?e.attrs[t]:void 0}function o(e){return new n["default"](t["default"].lookup[e],e)}e["default"]=i}),e("ember-htmlbars/hooks/get-value",["exports","ember-metal/streams/utils","ember-views/compat/attrs-proxy"],function(e,t,r){"use strict";function n(e){var n=t.read(e);return n&&n[r.MUTABLE_CELL]?n.value:n}e["default"]=n}),e("ember-htmlbars/hooks/has-helper",["exports","ember-htmlbars/system/lookup-helper"],function(e,t){"use strict";function r(e,r,n){if(e.helpers[n])return!0;var i=e.container;if(t.validateLazyHelperName(n,i,e.hooks.keywords,e.knownHelpers)){var a="helper:"+n;if(i._registry.has(a))return!0}return!1}e["default"]=r}),e("ember-htmlbars/hooks/invoke-helper",["exports","ember-metal/core","ember-htmlbars/system/invoke-helper","ember-htmlbars/utils/subscribe"],function(e,t,r,n){"use strict";function i(e,t,i,a,o,s,l,u,c){if(l.isLegacyViewHelper)return (t.hooks.keyword("view",e,t,i,[l.viewClass],s,u.template.raw,null,a), {handled:!0});var h=r.buildHelperStream(l,o,s,u,t,i,c);if(h.linkable){if(e){for(var m=!1,d=0,p=o.length;p>d;d++)m=!0,h.addDependency(o[d]);for(var f in s)m=!0,h.addDependency(s[f]);m&&n["default"](e,t,i,h)}return{link:!0,value:h}}return{value:h.value()}}e["default"]=i}),e("ember-htmlbars/hooks/link-render-node",["exports","ember-htmlbars/utils/subscribe","ember-runtime/utils","ember-metal/streams/utils","ember-htmlbars/system/lookup-helper"],function(e,t,r,n,i){"use strict";function a(e,r,n,a,l,c){if(e.streamUnsubscribers)return!0;var h,m=r.hooks.keywords[a];if(m&&m.link)m.link(e.state,l,c);else switch(a){case"unbound":return!0;case"unless":case"if":l[0]=s(l[0]);break;case"each":l[0]=o(l[0]);break;case"@content-helper":break;default:h=i.findHelper(a,r.view,r),h&&h.isHandlebarsCompat&&l[0]&&(l[0]=u(l[0],h._dependentKeys))}if(l&&l.length)for(var d=0;d0:"boolean"==typeof s?s:!!a},"ShouldDisplay");return (n.addDependency(a,t), n.addDependency(a,i), a)}function l(e,t){return n.isStream(e)?e.getKey(t):e&&e[t]}function u(e,t){if(!n.isStream(e)||0===t.length)return e;for(var r=[],i=n.chain(e,function(){return (n.readArray(r), n.read(e))},"HandlebarsCompatHelper"),a=0,o=t.length;o>a;a++){var s=e.get(t[a]);r.push(s),i.addDependency(s)}return i}e["default"]=a}),e("ember-htmlbars/hooks/lookup-helper",["exports","ember-htmlbars/system/lookup-helper"],function(e,t){"use strict";function r(e,r,n){return t["default"](n,r.self,e)}e["default"]=r}),e("ember-htmlbars/hooks/subexpr",["exports","ember-htmlbars/system/lookup-helper","ember-htmlbars/system/invoke-helper","ember-metal/streams/utils"],function(e,t,r,n){"use strict";function i(e,n,i,o,s){var l=e.hooks.keywords[i];if(l)return l(null,e,n,o,s,null,null);for(var u=a(o,s,i),c=t["default"](i,n.self,e),h=r.buildHelperStream(c,o,s,{template:{},inverse:{}},e,n,u),m=0,d=o.length;d>m;m++)h.addDependency(o[m]);for(var p in s)h.addDependency(s[p]);return h}function a(e,t,r){return function(){var n=o(e),i=s(t),a="("+r;return (n&&(a+=" "+n), i&&(a+=" "+i), a+")")}}function o(e){return n.labelsFor(e).join(" ")}function s(e){var t=[];for(var r in e)t.push(r+"="+n.labelFor(e[r]));return t.join(" ")}e["default"]=i}),e("ember-htmlbars/hooks/update-self",["exports","ember-metal/property_get","ember-htmlbars/utils/update-scope"],function(e,t,r){"use strict";function n(e,n,i){var a=i;if(a&&a.hasBoundController){var o=a,s=o.controller;a=a.self,r["default"](n.locals,"controller",s||a)}return a&&a.isView?(r["default"](n.locals,"view",a,null),void r["default"](n,"self",t.get(a,"context"),null,!0)):void r["default"](n,"self",a,null)}e["default"]=n}),e("ember-htmlbars/hooks/will-cleanup-tree",["exports"],function(e){"use strict";function t(e){var t=e.view;t.ownerView._destroyingSubtreeForView=t}e["default"]=t}),e("ember-htmlbars/keywords",["exports","htmlbars-runtime","ember-metal/platform/create"],function(e,t,r){"use strict";function n(e,t){i[e]=t}e.registerKeyword=n;var i=r["default"](t.hooks.keywords);e["default"]=i}),e("ember-htmlbars/keywords/collection",["exports","ember-views/streams/utils","ember-views/views/collection_view","ember-htmlbars/node-managers/view-node-manager","ember-metal/keys","ember-metal/merge"],function(e,t,r,n,i,a){"use strict";function o(e,n){var i;return i=e?t.readViewFactory(e,n):r["default"]}e["default"]={setupState:function(e,t,r,n,i){var s=t.hooks.getValue;return a.assign({},e,{parentView:t.view,viewClassOrInstance:o(s(n[0]),t.container)})},rerender:function(e,t,r,n,a,o,s,l){return i["default"](a).length?e.state.manager.rerender(t,a,l,!0):void 0},render:function(e,t,r,i,a,o,s,l){var u=e.state,c=u.parentView,h={component:e.state.viewClassOrInstance,layout:null};o&&(h.createOptions={_itemViewTemplate:o&&{raw:o},_itemViewInverse:s&&{raw:s}}),a.itemView&&(a.itemViewClass=a.itemView),a.emptyView&&(a.emptyViewClass=a.emptyView);var m=n["default"].create(e,t,a,h,c,null,r,o);u.manager=m,m.render(t,a,l)}}}),e("ember-htmlbars/keywords/component",["exports","ember-metal/merge"],function(e,t){"use strict";function r(e,t,r,n,i,a,o,s){var l=e.state.componentPath;void 0!==l&&null!==l&&t.hooks.component(e,t,r,l,n,i,{"default":a,inverse:o},s)}e["default"]={setupState:function(e,r,n,i,a){var o=r.hooks.getValue(i[0]);return t.assign({},e,{componentPath:o,isComponentHelper:!0})},render:function(e){e.state.manager&&e.state.manager.destroy(),e.state.manager=null;for(var t=arguments.length,n=Array(t>1?t-1:0),i=1;t>i;i++)n[i-1]=arguments[i];r.apply(void 0,[e].concat(n))},rerender:r}}),e("ember-htmlbars/keywords/customized_outlet",["exports","ember-htmlbars/node-managers/view-node-manager","ember-views/streams/utils","ember-metal/streams/utils"],function(e,t,r,n){"use strict";e["default"]={setupState:function(e,t,n,i,a){var o=t.hooks.getValue,s=o(a.viewClass)||r.readViewFactory(o(a.view),t.container);return{viewClass:s}},render:function(e,r,n,i,a,o,s,l){var u=e.state,c=r.view,h={component:u.viewClass},m=t["default"].create(e,r,a,h,c,null,null,null);u.manager=m,m.render(r,a,l)}}}),e("ember-htmlbars/keywords/debugger",["exports","ember-metal/logger"],function(e,t){"use strict";function r(e,r,n){r.hooks.getValue(n.locals.view),r.hooks.getValue(n.self);return (t["default"].info("Use `view`, `context`, and `get()` to debug this template."), !0)}e["default"]=r}),e("ember-htmlbars/keywords/each",["exports","ember-runtime/controllers/array_controller"],function(e,t){"use strict";function r(e,r,n,i,a,o,s,l){var u=r.hooks.getValue,c=i[0]&&u(i[0]),h=a["-legacy-keyword"]&&u(a["-legacy-keyword"]);return c&&c instanceof t["default"]?(r.hooks.block(e,r,n,"-legacy-each-with-controller",i,a,o,s,l),!0):h?(r.hooks.block(e,r,n,"-legacy-each-with-keyword",i,a,o,s,l),!0):!1}e["default"]=r}),e("ember-htmlbars/keywords/input",["exports","ember-metal/core","ember-metal/merge"],function(e,t,r){"use strict";e["default"]={setupState:function(e,t,a,o,s){var l=t.hooks.getValue(s.type),u=i[l]||n;return r.assign({},e,{componentName:u})},render:function(e,t,r,n,i,a,o,s){t.hooks.component(e,t,r,e.state.componentName,n,i,{"default":a,inverse:o},s)},rerender:function(){this.render.apply(this,arguments)}};var n="-text-field",i={checkbox:"-checkbox"}}),e("ember-htmlbars/keywords/legacy-yield",["exports","ember-metal/streams/proxy-stream"],function(e,t){"use strict";function r(e,r,n,i,a,o,s,l){var u=n;return (0===u.blocks["default"].arity?(a.controller&&(u=r.hooks.createChildScope(u),u.locals.controller=new t["default"](a.controller,"controller"),u.overrideController=!0),u.blocks["default"](r,[],i[0],e,u,l)):u.blocks["default"](r,i,void 0,e,u,l), !0)}e["default"]=r}),e("ember-htmlbars/keywords/mut",["exports","ember-metal/core","ember-metal/platform/create","ember-metal/merge","ember-metal/utils","ember-metal/streams/proxy-stream","ember-metal/streams/utils","ember-metal/streams/stream","ember-views/compat/attrs-proxy","ember-routing-htmlbars/keywords/closure-action"],function(e,t,r,n,i,a,o,s,l,u){"use strict";function c(e,t,r,n,i,a,o){if(null===e){var s=n[0];return m(t.hooks.getValue,s)}return!0}function h(e,t,r,n,i,a,o){if(null===e){var s=n[0];return m(t.hooks.getValue,s,!0)}return!0}function m(e,t,r){return (r&&(o.isStream(t)||!function(){var e=t;t=new s["default"](function(){return e},"(literal "+e+")"),t.setValue=function(r){e=r,t.notify()}}()), t[f]?t:new d(t))}function d(e){this.init("(mut "+e.label+")"),this.path=e.path,this.sourceDep=this.addMutableDependency(e),this[f]=!0}var p;e["default"]=c,e.privateMut=h;var f=i.symbol("MUTABLE_REFERENCE");e.MUTABLE_REFERENCE=f,d.prototype=r["default"](a["default"].prototype),n["default"](d.prototype,(p={cell:function(){var e=this,t=e.value();if(t&&t[u.ACTION])return t;var r={value:t,update:function(t){e.setValue(t)}};return (r[l.MUTABLE_CELL]=!0, r)}},p[u.INVOKE]=function(e){this.setValue(e)},p))}),e("ember-htmlbars/keywords/outlet",["exports","htmlbars-runtime/hooks"],function(e,t){"use strict";e["default"]=function(e,r,n,i,a,o,s,l){return (a.hasOwnProperty("view")||a.hasOwnProperty("viewClass")?t.keyword("@customized_outlet",e,r,n,i,a,o,s,l):t.keyword("@real_outlet",e,r,n,i,a,o,s,l), !0)}}),e("ember-htmlbars/keywords/partial",["exports","ember-views/system/lookup_partial","htmlbars-runtime"],function(e,t,r){"use strict";e["default"]={setupState:function(e,t,r,n,i){return{partialName:t.hooks.getValue(n[0])}},render:function(e,n,i,a,o,s,l,u){var c=e.state;if(!c.partialName)return!0;var h=t["default"](n,c.partialName);return h?void r.internal.hostBlock(e,n,i,h.raw,null,null,u,function(e){e.templates.template["yield"]()}):!0}}}),e("ember-htmlbars/keywords/readonly",["exports","ember-htmlbars/keywords/mut"],function(e,t){"use strict";function r(e,r,n,i,a,o,s){if(null===e){var l=i[0];return l&&l[t.MUTABLE_REFERENCE]?l.sourceDep.dependee:l}return!0}e["default"]=r}),e("ember-htmlbars/keywords/real_outlet",["exports","ember-metal/property_get","ember-htmlbars/node-managers/view-node-manager","ember-htmlbars/templates/top-level-view"],function(e,t,r,n){"use strict";function i(e){return!e||!e.render.ViewClass&&!e.render.template}function a(e,t){if(!e&&!t)return!0;if(!e||!t)return!1;e=e.render,t=t.render;for(var r in e)if(e.hasOwnProperty(r)&&e[r]!==t[r]&&"name"!==r)return!1;return!0}n["default"].meta.revision="Ember@1.13.12",e["default"]={willRender:function(e,t){t.view.ownerView._outlets.push(e)},setupState:function(e,t,r,i,a){var o=t.outletState,s=t.hooks.getValue,l=s(i[0])||"main",u=o[l],c=u&&u.render;return(!c||c.template||c.ViewClass||(c.template=n["default"]), {outletState:u,hasParentOutlet:t.hasParentOutlet,manager:e.manager})},childEnv:function(e,t){return t.childWithOutletState(e.outletState&&e.outletState.outlets,!0)},isStable:function(e,t){return a(e.outletState,t.outletState)},isEmpty:function(e){return i(e.outletState)},render:function(e,n,i,a,o,s,l,u){var c=e.state,h=n.view,m=c.outletState,d=m.render,p=n.container.lookup("application:main"),f=(t.get(p,"LOG_VIEW_LOOKUPS"),m.render.ViewClass);c.hasParentOutlet||f||(f=n.container.lookupFactory("view:toplevel"));var v={component:f,self:d.controller,createOptions:{controller:d.controller}};s=s||d.template&&d.template.raw,c.manager&&(c.manager.destroy(),c.manager=null),c.manager&&(c.manager.destroy(),c.manager=null);var g=r["default"].create(e,n,{},v,h,null,null,s);c.manager=g,g.render(n,o,u)}}}),e("ember-htmlbars/keywords/template",["exports","ember-metal/core"],function(e,t){"use strict";function r(e,t,r,n,i,a,o,s){return (t.hooks.keyword("partial",e,t,r,n,i,a,o,s), !0)}e["default"]=r;var n="The `template` helper has been deprecated in favor of the `partial` helper.";e.deprecation=n}),e("ember-htmlbars/keywords/textarea",["exports"],function(e){"use strict";function t(e,t,r,n,i,a,o,s){return (t.hooks.component(e,t,r,"-text-area",n,i,{"default":a,inverse:o},s), !0)}e["default"]=t}),e("ember-htmlbars/keywords/unbound",["exports","ember-metal/merge","ember-metal/platform/create","ember-metal/streams/stream","ember-metal/streams/utils"],function(e,t,r,n,i){"use strict";function a(e,t,r,n,i,a,s){var l=n.slice(),u=l.shift();return null===e?(n.length>1&&(u=t.hooks.subexpr(t,r,u.key,l,i)),new o(u)):(0===l.length?t.hooks.range(e,t,r,null,u):null===a?t.hooks.inline(e,t,r,u.key,l,i):t.hooks.block(e,t,r,u.key,l,i,a,s),!0)}function o(e){this.init("(volatile "+e.label+")"),this.source=e,this.addDependency(e)}e["default"]=a,o.prototype=r["default"](n["default"].prototype),t["default"](o.prototype,{value:function(){return i.read(this.source)},notify:function(){}})}),e("ember-htmlbars/keywords/view",["exports","ember-views/streams/utils","ember-views/views/view","ember-htmlbars/node-managers/view-node-manager","ember-metal/keys"],function(e,t,r,n,i){"use strict";function a(e,n){var i;return i=e?t.readViewFactory(e,n):n?n.lookupFactory("view:toplevel"):r["default"]}function o(e,t,r){var n={};for(var i in e)i===t?n[r]=e[i]:n[i]=e[i];return n}e["default"]={setupState:function(e,t,r,n,i){var o=t.hooks.getValue,s=o(r.self),l=e.viewClassOrInstance;l||(l=a(o(n[0]),t.container));var u=r.locals.view?null:o(r.self);return{manager:e.manager,parentView:t.view,controller:u,targetObject:s,viewClassOrInstance:l}},rerender:function(e,t,r,n,a,o,s,l){return i["default"](a).length?e.state.manager.rerender(t,a,l,!0):void 0},render:function(e,t,r,i,a,s,l,u){a.tag&&(a=o(a,"tag","tagName")),a.classNameBindings&&(a.classNameBindings=a.classNameBindings.split(" "));var c=e.state,h=c.parentView,m={component:e.state.viewClassOrInstance,layout:null};m.createOptions={},e.state.controller&&(m.createOptions._controller=e.state.controller),e.state.targetObject&&(m.createOptions._targetObject=e.state.targetObject),c.manager&&(c.manager.destroy(),c.manager=null);var d=n["default"].create(e,t,a,m,h,null,r,s);c.manager=d,d.render(t,a,u)}}}),e("ember-htmlbars/keywords/with",["exports","ember-metal/core","ember-metal/property_get","htmlbars-runtime","ember-metal/streams/utils"],function(e,t,r,n,i){"use strict";e["default"]={setupState:function(e,t,n,a,o){var s=o.controller;if(s){if(!e.controller){var l=a[0],u=t.container.lookupFactory("controller:"+s),c=null;n.locals.controller?c=i.read(n.locals.controller):n.locals.view&&(c=r.get(i.read(n.locals.view),"context"));var h=u.create({model:t.hooks.getValue(l),parentController:c,target:c});return (a[0]=h, {controller:h})}return e}return{controller:null}},isStable:function(){return!0},isEmpty:function(e){return!1},render:function(e,t,r,i,a,o,s,l){e.state.controller&&(e.addDestruction(e.state.controller),a.controller=e.state.controller),o&&0===o.arity,n.internal.continueBlock(e,t,r,"with",i,a,o,s,l)},rerender:function(e,t,r,i,a,o,s,l){n.internal.continueBlock(e,t,r,"with",i,a,o,s,l)}}}),e("ember-htmlbars/morphs/attr-morph",["exports","ember-metal/core","dom-helper","ember-metal/platform/create"],function(e,t,r,n){"use strict";function i(e,t,r,n){a.call(this,e,t,r,n),this.streamUnsubscribers=null}var a=r["default"].prototype.AttrMorphClass,o="Binding style attributes may introduce cross-site scripting vulnerabilities; please ensure that values being bound are properly escaped. For more information, including how to disable this warning, see http://emberjs.com/deprecations/v1.x/#toc_binding-style-attributes.";e.styleWarning=o;var s=i.prototype=n["default"](a.prototype);s.HTMLBarsAttrMorph$setContent=a.prototype.setContent,s._deprecateEscapedStyle=function(e){},s.setContent=function(e){this._deprecateEscapedStyle(e),this.HTMLBarsAttrMorph$setContent(e)},e["default"]=i}),e("ember-htmlbars/morphs/morph",["exports","dom-helper","ember-metal/platform/create"],function(e,t,r){"use strict";function n(e,t){this.HTMLBarsMorph$constructor(e,t),this.emberView=null,this.emberToDestroy=null,this.streamUnsubscribers=null,this.guid=a++,this.shouldReceiveAttrs=!1}var i=t["default"].prototype.MorphClass,a=1,o=n.prototype=r["default"](i.prototype);o.HTMLBarsMorph$constructor=i,o.HTMLBarsMorph$clear=i.prototype.clear,o.addDestruction=function(e){this.emberToDestroy=this.emberToDestroy||[],this.emberToDestroy.push(e)},o.cleanup=function(){var e=this.emberView;if(e){var t=e.parentView;t&&e.ownerView._destroyingSubtreeForView===t&&t.removeChild(e)}var r=this.emberToDestroy;if(r){for(var n=0,i=r.length;i>n;n++)r[n].destroy();this.emberToDestroy=null}},o.didRender=function(e,t){e.renderedNodes[this.guid]=!0},e["default"]=n}),e("ember-htmlbars/node-managers/component-node-manager",["exports","ember-metal/core","ember-metal/merge","ember-views/system/build-component-template","ember-htmlbars/utils/lookup-component","ember-htmlbars/hooks/get-cell-or-value","ember-metal/property_get","ember-metal/property_set","ember-metal/set_properties","ember-views/compat/attrs-proxy","htmlbars-util/safe-string","ember-htmlbars/system/instrumentation-support","ember-views/views/component","ember-metal/streams/stream","ember-metal/streams/utils","ember-htmlbars/hooks/get-value"],function(e,t,r,n,i,a,o,s,l,u,c,h,m,d,p,f){"use strict";function v(e,t,r,n,i,a,o){this.component=e,this.isAngleBracket=t,this.scope=r,this.renderNode=n,this.attrs=i,this.block=a,this.expectElement=o}function g(e,t,r,n){var i=t.positionalParams,a=void 0;return (i||(a=t.proto(),i=a.positionalParams), i&&b(e,i,r,n), a)}function b(e,t,r,n){var i=e.state.isComponentHelper?1:0,a="string"==typeof t,o=void 0;if(a&&(o=new d["default"](function(){return p.readArray(r.slice(i))},"params"),n[t]=o),a)for(var s=i;sn;n++)r.push(t["default"](e[n]));return r}function n(e){var r={};for(var n in e)r[n]=t["default"](e[n]);return r}e.getArrayValues=r,e.getHashValues=n}),e("ember-htmlbars/system/append-templated-view",["exports","ember-metal/core","ember-metal/property_get","ember-views/views/view"],function(e,t,r,n){"use strict";function i(e,t,i,a){var o;o=n["default"].detectInstance(i)?i:i.proto();var s=!o.controller;return (o.controller&&o.controller.isDescriptor&&(s=!0), !s||o.controllerBinding||a.controller||a.controllerBinding||(a._context=r.get(e,"context")), a._morph=t, e.appendChild(i,a))}e["default"]=i}),e("ember-htmlbars/system/bootstrap",["exports","ember-metal/core","ember-views/component_lookup","ember-views/system/jquery","ember-metal/error","ember-runtime/system/lazy_load","ember-template-compiler/system/compile","ember-metal/environment"],function(e,t,r,n,i,a,o,s){"use strict";function l(e){var r='script[type="text/x-handlebars"], script[type="text/x-raw-handlebars"]';n["default"](r,e).each(function(){var e,r,a=n["default"](this),s=a.attr("data-template-name")||a.attr("id")||"application";if("text/x-raw-handlebars"===a.attr("type")?(r=n["default"].proxy(Handlebars.compile,Handlebars),e=r(a.html())):e=o["default"](a.html(),{moduleName:s}),void 0!==t["default"].TEMPLATES[s])throw new i["default"]('Template named "'+s+'" already exists.');t["default"].TEMPLATES[s]=e,a.remove()})}function u(){l(n["default"](document))}function c(e){e.registry.register("component-lookup:main",r["default"])}a.onLoad("Ember.Application",function(e){e.initializer({name:"domTemplates",initialize:s["default"].hasDOM?u:function(){}}),e.instanceInitializer({name:"registerComponentLookup",initialize:c})}),e["default"]=l}),e("ember-htmlbars/system/discover-known-helpers",["exports","ember-metal/core","ember-metal/dictionary","ember-metal/keys"],function(e,t,r,n){"use strict";function i(e){var t=e&&e._registry,i=r["default"](null);if(!t)return i;for(var a=t.knownForType("helper"),o=n["default"](a),s=0,l=o.length;l>s;s++){var u=o[s],c=u.slice(7);i[c]=!0}return i}e["default"]=i}),e("ember-htmlbars/system/dom-helper",["exports","dom-helper","ember-htmlbars/morphs/morph","ember-htmlbars/morphs/attr-morph","ember-metal/platform/create"],function(e,t,r,n,i){"use strict";function a(e){t["default"].call(this,e)}var o=a.prototype=i["default"](t["default"].prototype);o.MorphClass=r["default"],o.AttrMorphClass=n["default"],e["default"]=a}),e("ember-htmlbars/system/helper",["exports"],function(e){"use strict";function t(e){this.helperFunction=e,this.isHelper=!0,this.isHTMLBars=!0}e["default"]=t}),e("ember-htmlbars/system/instrumentation-support",["exports","ember-metal/instrumentation"],function(e,t){"use strict";function r(e,r,n){var i,a,o,s;return t.subscribers.length?(i=e?e.instrumentName:"node",o={},e&&e.instrumentDetails(o),s=t._instrumentStart("render."+i,function(){return o}),a=r.call(n),s&&s(),a):r.call(n)}e.instrument=r}),e("ember-htmlbars/system/invoke-helper",["exports","ember-htmlbars/streams/helper-instance","ember-htmlbars/streams/helper-factory","ember-htmlbars/streams/built-in-helper","ember-htmlbars/streams/compat-helper"],function(e,t,r,n,i){"use strict";function a(e,a,o,s,l,u,c,h){return e.isHelperFactory?new r["default"](e,a,o,h):e.isHelperInstance?new t["default"](e,a,o,h):e.helperFunction?new i["default"](e,a,o,s,l,u,h):new n["default"](e,a,o,s,l,u,c,h)}e.buildHelperStream=a}),e("ember-htmlbars/system/lookup-helper",["exports","ember-metal/core","ember-metal/cache","ember-htmlbars/compat/helper"],function(e,t,r,n){"use strict";function i(e,t,r,n){return!t||e in r?!1:n[e]||l.get(e)?!0:void 0}function a(e){return e&&!e.isHelperFactory&&!e.isHelperInstance&&!e.isHTMLBars}function o(e,t,r){var o=r.helpers[e];if(!o){var s=r.container;if(i(e,s,r.hooks.keywords,r.knownHelpers)){var l="helper:"+e;s._registry.has(l)&&(o=s.lookupFactory(l),a(o)&&(o=new n["default"](o)))}}return o}function s(e,t,r){var n=o(e,t,r);return n}e.validateLazyHelperName=i,e.findHelper=o,e["default"]=s;var l=new r["default"](1e3,function(e){return-1!==e.indexOf("-")});e.CONTAINS_DASH_CACHE=l}),e("ember-htmlbars/system/make-view-helper",["exports","ember-metal/core"],function(e,t){"use strict";function r(e){return{isLegacyViewHelper:!0,isHTMLBars:!0,viewClass:e}}e["default"]=r}),e("ember-htmlbars/system/make_bound_helper",["exports","ember-metal/core","ember-htmlbars/helper"],function(e,t,r){"use strict";function n(e){return r.helper(e)}e["default"]=n}),e("ember-htmlbars/system/render-env",["exports","ember-htmlbars/env","ember-htmlbars/system/discover-known-helpers"],function(e,t,r){"use strict";function n(e){this.lifecycleHooks=e.lifecycleHooks||[],this.renderedViews=e.renderedViews||[],this.renderedNodes=e.renderedNodes||{},this.hasParentOutlet=e.hasParentOutlet||!1,this.view=e.view,this.outletState=e.outletState,this.container=e.container,this.renderer=e.renderer,this.dom=e.dom,this.knownHelpers=e.knownHelpers||r["default"](e.container),this.hooks=t["default"].hooks,this.helpers=t["default"].helpers,this.useFragmentCache=t["default"].useFragmentCache}e["default"]=n,n.build=function(e){return new n({view:e,outletState:e.outletState,container:e.container,renderer:e.renderer,dom:e.renderer._dom})},n.prototype.childWithView=function(e){return new n({view:e,outletState:this.outletState,container:this.container,renderer:this.renderer,dom:this.dom,lifecycleHooks:this.lifecycleHooks,renderedViews:this.renderedViews,renderedNodes:this.renderedNodes,hasParentOutlet:this.hasParentOutlet,knownHelpers:this.knownHelpers})},n.prototype.childWithOutletState=function(e){var t=arguments.length<=1||void 0===arguments[1]?this.hasParentOutlet:arguments[1];return new n({view:this.view,outletState:e,container:this.container,renderer:this.renderer,dom:this.dom,lifecycleHooks:this.lifecycleHooks,renderedViews:this.renderedViews,renderedNodes:this.renderedNodes,hasParentOutlet:t,knownHelpers:this.knownHelpers})}}),e("ember-htmlbars/system/render-view",["exports","ember-htmlbars/node-managers/view-node-manager","ember-htmlbars/system/render-env"],function(e,t,r){"use strict";function n(e,n,i){var a=r["default"].build(e);e.env=a,t.createOrUpdateComponent(e,{},null,i,a);var o=new t["default"](e,null,i,n,""!==e.tagName);o.render(a,{})}e.renderHTMLBarsBlock=n}),e("ember-htmlbars/templates/component",["exports","ember-template-compiler/system/template"],function(e,t){"use strict";e["default"]=t["default"](function(){return{meta:{},arity:0,cachedFragment:null,hasRendered:!1,buildFragment:function(e){var t=e.createDocumentFragment(),r=e.createComment("");return (e.appendChild(t,r), t)},buildRenderNodes:function(e,t,r){var n=new Array(1);return (n[0]=e.createMorphAt(t,0,0,r), e.insertBoundary(t,0), e.insertBoundary(t,null), n)},statements:[["content","yield",["loc",[null,[1,0],[1,9]]]]],locals:[],templates:[]}}())}),e("ember-htmlbars/templates/container-view",["exports","ember-template-compiler/system/template"],function(e,t){"use strict";e["default"]=t["default"](function(){var e=function(){return{meta:{},arity:1,cachedFragment:null,hasRendered:!1,buildFragment:function(e){var t=e.createDocumentFragment(),r=e.createComment("");return (e.appendChild(t,r), t)},buildRenderNodes:function(e,t,r){var n=new Array(1);return (n[0]=e.createMorphAt(t,0,0,r), e.insertBoundary(t,0), e.insertBoundary(t,null), n)},statements:[["inline","view",[["get","childView",["loc",[null,[1,63],[1,72]]]]],[],["loc",[null,[1,56],[1,74]]]]],locals:["childView"],templates:[]}}(),t=function(){var e=function(){return{meta:{},arity:0,cachedFragment:null,hasRendered:!1,buildFragment:function(e){var t=e.createDocumentFragment(),r=e.createComment("");return (e.appendChild(t,r), t)},buildRenderNodes:function(e,t,r){var n=new Array(1);return (n[0]=e.createMorphAt(t,0,0,r), e.insertBoundary(t,0), e.insertBoundary(t,null), n)},statements:[["inline","view",[["get","view._emptyView",["loc",[null,[1,108],[1,123]]]]],["_defaultTagName",["get","view._emptyViewTagName",["loc",[null,[1,140],[1,162]]]]],["loc",[null,[1,101],[1,164]]]]],locals:[],templates:[]}}();return{meta:{},arity:0,cachedFragment:null,hasRendered:!1,buildFragment:function(e){var t=e.createDocumentFragment(),r=e.createComment("");return (e.appendChild(t,r), t)},buildRenderNodes:function(e,t,r){var n=new Array(1);return (n[0]=e.createMorphAt(t,0,0,r), e.insertBoundary(t,0), e.insertBoundary(t,null), n)},statements:[["block","if",[["get","view._emptyView",["loc",[null,[1,84],[1,99]]]]],[],0,null,["loc",[null,[1,74],[1,164]]]]],locals:[],templates:[e]}}();return{meta:{},arity:0,cachedFragment:null,hasRendered:!1,buildFragment:function(e){var t=e.createDocumentFragment(),r=e.createComment("");return (e.appendChild(t,r), t)},buildRenderNodes:function(e,t,r){var n=new Array(1);return (n[0]=e.createMorphAt(t,0,0,r), e.insertBoundary(t,0), e.insertBoundary(t,null), n)},statements:[["block","each",[["get","view.childViews",["loc",[null,[1,8],[1,23]]]]],["key","elementId"],0,1,["loc",[null,[1,0],[1,173]]]]],locals:[],templates:[e,t]}}())}),e("ember-htmlbars/templates/empty",["exports","ember-template-compiler/system/template"],function(e,t){"use strict";e["default"]=t["default"](function(){return{meta:{},arity:0,cachedFragment:null,hasRendered:!1,buildFragment:function(e){var t=e.createDocumentFragment();return t},buildRenderNodes:function(){return[]},statements:[],locals:[],templates:[]}}())}),e("ember-htmlbars/templates/legacy-each",["exports","ember-template-compiler/system/template"],function(e,t){"use strict";e["default"]=t["default"](function(){var e=function(){var e=function(){var e=function(){var e=function(){return{meta:{},arity:0,cachedFragment:null,hasRendered:!1,buildFragment:function(e){var t=e.createDocumentFragment(),r=e.createComment("");return (e.appendChild(t,r), t)},buildRenderNodes:function(e,t,r){var n=new Array(1);return (n[0]=e.createMorphAt(t,0,0,r), e.insertBoundary(t,0), e.insertBoundary(t,null), n)},statements:[["inline","legacy-yield",[["get","item",["loc",[null,[5,24],[5,28]]]]],[],["loc",[null,[5,8],[5,31]]]]],locals:[],templates:[]}}();return{meta:{},arity:0,cachedFragment:null,hasRendered:!1,buildFragment:function(e){var t=e.createDocumentFragment(),r=e.createComment("");return (e.appendChild(t,r), t)},buildRenderNodes:function(e,t,r){var n=new Array(1);return (n[0]=e.createMorphAt(t,0,0,r), e.insertBoundary(t,0), e.insertBoundary(t,null), n)},statements:[["block","view",[["get","attrs.itemViewClass",["loc",[null,[4,15],[4,34]]]]],["_defaultTagName",["get","view._itemTagName",["loc",[null,[4,51],[4,68]]]]],0,null,["loc",[null,[4,6],[6,17]]]]],locals:[],templates:[e]}}(),t=function(){return{meta:{},arity:0,cachedFragment:null,hasRendered:!1,buildFragment:function(e){var t=e.createDocumentFragment(),r=e.createComment("");return (e.appendChild(t,r), t)},buildRenderNodes:function(e,t,r){var n=new Array(1);return (n[0]=e.createMorphAt(t,0,0,r), e.insertBoundary(t,0), e.insertBoundary(t,null), n)},statements:[["inline","legacy-yield",[["get","item",["loc",[null,[8,22],[8,26]]]]],[],["loc",[null,[8,6],[8,29]]]]],locals:[],templates:[]}}();return{meta:{},arity:0,cachedFragment:null,hasRendered:!1,buildFragment:function(e){var t=e.createDocumentFragment(),r=e.createComment("");return (e.appendChild(t,r), t)},buildRenderNodes:function(e,t,r){var n=new Array(1);return (n[0]=e.createMorphAt(t,0,0,r), e.insertBoundary(t,0), e.insertBoundary(t,null), n)},statements:[["block","if",[["get","attrs.itemViewClass",["loc",[null,[3,11],[3,30]]]]],[],0,1,["loc",[null,[3,4],[9,13]]]]],locals:[],templates:[e,t]}}(),t=function(){var e=function(){var e=function(){return{meta:{},arity:0,cachedFragment:null,hasRendered:!1,buildFragment:function(e){var t=e.createDocumentFragment(),r=e.createComment("");return (e.appendChild(t,r), t)},buildRenderNodes:function(e,t,r){var n=new Array(1);return (n[0]=e.createMorphAt(t,0,0,r), e.insertBoundary(t,0), e.insertBoundary(t,null), n)},statements:[["inline","legacy-yield",[["get","item",["loc",[null,[13,24],[13,28]]]]],[],["loc",[null,[13,8],[13,31]]]]],locals:[],templates:[]}}();return{meta:{},arity:0,cachedFragment:null,hasRendered:!1,buildFragment:function(e){var t=e.createDocumentFragment(),r=e.createComment("");return (e.appendChild(t,r), t)},buildRenderNodes:function(e,t,r){var n=new Array(1);return (n[0]=e.createMorphAt(t,0,0,r), e.insertBoundary(t,0), e.insertBoundary(t,null), n)},statements:[["block","view",[["get","attrs.itemViewClass",["loc",[null,[12,15],[12,34]]]]],["controller",["get","item",["loc",[null,[12,46],[12,50]]]],"_defaultTagName",["get","view._itemTagName",["loc",[null,[12,67],[12,84]]]]],0,null,["loc",[null,[12,6],[14,17]]]]],locals:[],templates:[e]}}(),t=function(){return{meta:{},arity:0,cachedFragment:null,hasRendered:!1,buildFragment:function(e){var t=e.createDocumentFragment(),r=e.createComment("");return (e.appendChild(t,r), t)},buildRenderNodes:function(e,t,r){var n=new Array(1);return (n[0]=e.createMorphAt(t,0,0,r), e.insertBoundary(t,0), e.insertBoundary(t,null), n)},statements:[["inline","legacy-yield",[["get","item",["loc",[null,[16,22],[16,26]]]]],["controller",["get","item",["loc",[null,[16,38],[16,42]]]]],["loc",[null,[16,6],[16,45]]]]],locals:[],templates:[]}}();return{meta:{},arity:0,cachedFragment:null,hasRendered:!1,buildFragment:function(e){var t=e.createDocumentFragment(),r=e.createComment("");return (e.appendChild(t,r), t)},buildRenderNodes:function(e,t,r){var n=new Array(1);return (n[0]=e.createMorphAt(t,0,0,r), e.insertBoundary(t,0), e.insertBoundary(t,null), n)},statements:[["block","if",[["get","attrs.itemViewClass",["loc",[null,[11,11],[11,30]]]]],[],0,1,["loc",[null,[11,4],[17,13]]]]],locals:[],templates:[e,t]}}();return{meta:{},arity:1,cachedFragment:null,hasRendered:!1,buildFragment:function(e){var t=e.createDocumentFragment(),r=e.createComment("");return (e.appendChild(t,r), t)},buildRenderNodes:function(e,t,r){var n=new Array(1);return (n[0]=e.createMorphAt(t,0,0,r), e.insertBoundary(t,0), e.insertBoundary(t,null), n)},statements:[["block","if",[["get","view.keyword",["loc",[null,[2,9],[2,21]]]]],[],0,1,["loc",[null,[2,2],[18,11]]]]],locals:["item"],templates:[e,t]}}(),t=function(){var e=function(){return{meta:{},arity:0,cachedFragment:null,hasRendered:!1,buildFragment:function(e){var t=e.createDocumentFragment(),r=e.createComment("");return (e.appendChild(t,r), t)},buildRenderNodes:function(e,t,r){var n=new Array(1);return (n[0]=e.createMorphAt(t,0,0,r), e.insertBoundary(t,0), e.insertBoundary(t,null), n)},statements:[["inline","view",[["get","view._emptyView",["loc",[null,[20,10],[20,25]]]]],["_defaultTagName",["get","view._itemTagName",["loc",[null,[20,42],[20,59]]]]],["loc",[null,[20,2],[20,62]]]]],locals:[],templates:[]}}();return{meta:{},arity:0,cachedFragment:null,hasRendered:!1,buildFragment:function(e){var t=e.createDocumentFragment(),r=e.createComment("");return (e.appendChild(t,r), t)},buildRenderNodes:function(e,t,r){var n=new Array(1);return (n[0]=e.createMorphAt(t,0,0,r), e.insertBoundary(t,0), e.insertBoundary(t,null), n)},statements:[["block","if",[["get","view._emptyView",["loc",[null,[19,11],[19,26]]]]],[],0,null,["loc",[null,[19,0],[21,0]]]]],locals:[],templates:[e]}}();return{meta:{},arity:0,cachedFragment:null,hasRendered:!1,buildFragment:function(e){var t=e.createDocumentFragment(),r=e.createComment("");return (e.appendChild(t,r), t)},buildRenderNodes:function(e,t,r){var n=new Array(1);return (n[0]=e.createMorphAt(t,0,0,r), e.insertBoundary(t,0), e.insertBoundary(t,null), n)},statements:[["block","each",[["get","view._arrangedContent",["loc",[null,[1,9],[1,30]]]]],["-legacy-keyword",["get","view.keyword",["loc",[null,[1,47],[1,59]]]]],0,1,["loc",[null,[1,0],[21,11]]]]],locals:[],templates:[e,t]}}())}),e("ember-htmlbars/templates/link-to-escaped",["exports","ember-template-compiler/system/template"],function(e,t){"use strict";e["default"]=t["default"](function(){return{meta:{},arity:0,cachedFragment:null,hasRendered:!1,buildFragment:function(e){var t=e.createDocumentFragment(),r=e.createComment("");return (e.appendChild(t,r), t)},buildRenderNodes:function(e,t,r){var n=new Array(1);return (n[0]=e.createMorphAt(t,0,0,r), e.insertBoundary(t,0), e.insertBoundary(t,null), n)},statements:[["content","linkTitle",["loc",[null,[1,0],[1,13]]]]],locals:[],templates:[]}}())}),e("ember-htmlbars/templates/link-to-unescaped",["exports","ember-template-compiler/system/template"],function(e,t){"use strict";e["default"]=t["default"](function(){return{meta:{},arity:0,cachedFragment:null,hasRendered:!1,buildFragment:function(e){var t=e.createDocumentFragment(),r=e.createComment("");return (e.appendChild(t,r), t)},buildRenderNodes:function(e,t,r){var n=new Array(1);return (n[0]=e.createUnsafeMorphAt(t,0,0,r), e.insertBoundary(t,0), e.insertBoundary(t,null), n)},statements:[["content","linkTitle",["loc",[null,[1,0],[1,15]]]]],locals:[],templates:[]}}())}),e("ember-htmlbars/templates/link-to",["exports","ember-template-compiler/system/template"],function(e,t){"use strict";e["default"]=t["default"](function(){var e=function(){var e=function(){return{meta:{},arity:0,cachedFragment:null,hasRendered:!1,buildFragment:function(e){var t=e.createDocumentFragment(),r=e.createComment("");return (e.appendChild(t,r), t)},buildRenderNodes:function(e,t,r){var n=new Array(1);return (n[0]=e.createMorphAt(t,0,0,r), e.insertBoundary(t,0), e.insertBoundary(t,null), n)},statements:[["content","linkTitle",["loc",[null,[1,38],[1,51]]]]],locals:[],templates:[]}}(),t=function(){return{meta:{},arity:0,cachedFragment:null,hasRendered:!1,buildFragment:function(e){var t=e.createDocumentFragment(),r=e.createComment("");return (e.appendChild(t,r), t)},buildRenderNodes:function(e,t,r){var n=new Array(1);return (n[0]=e.createUnsafeMorphAt(t,0,0,r), e.insertBoundary(t,0), e.insertBoundary(t,null), n)},statements:[["content","linkTitle",["loc",[null,[1,59],[1,74]]]]],locals:[],templates:[]}}();return{meta:{},arity:0,cachedFragment:null,hasRendered:!1,buildFragment:function(e){var t=e.createDocumentFragment(),r=e.createComment("");return (e.appendChild(t,r), t)},buildRenderNodes:function(e,t,r){var n=new Array(1);return (n[0]=e.createMorphAt(t,0,0,r), e.insertBoundary(t,0), e.insertBoundary(t,null), n)},statements:[["block","if",[["get","attrs.escaped",["loc",[null,[1,23],[1,36]]]]],[],0,1,["loc",[null,[1,17],[1,81]]]]],locals:[],templates:[e,t]}}(),t=function(){return{meta:{},arity:0,cachedFragment:null,hasRendered:!1,buildFragment:function(e){var t=e.createDocumentFragment(),r=e.createComment("");return (e.appendChild(t,r), t)},buildRenderNodes:function(e,t,r){var n=new Array(1);return (n[0]=e.createMorphAt(t,0,0,r), e.insertBoundary(t,0), e.insertBoundary(t,null), n)},statements:[["content","yield",["loc",[null,[1,89],[1,98]]]]],locals:[],templates:[]}}();return{meta:{},arity:0,cachedFragment:null,hasRendered:!1,buildFragment:function(e){var t=e.createDocumentFragment(),r=e.createComment("");return (e.appendChild(t,r), t)},buildRenderNodes:function(e,t,r){var n=new Array(1);return (n[0]=e.createMorphAt(t,0,0,r), e.insertBoundary(t,0), e.insertBoundary(t,null), n)},statements:[["block","if",[["get","linkTitle",["loc",[null,[1,6],[1,15]]]]],[],0,1,["loc",[null,[1,0],[1,105]]]]],locals:[],templates:[e,t]}}())}),e("ember-htmlbars/templates/select-optgroup",["exports","ember-template-compiler/system/template"],function(e,t){"use strict";e["default"]=t["default"](function(){var e=function(){return{meta:{},arity:1,cachedFragment:null,hasRendered:!1,buildFragment:function(e){var t=e.createDocumentFragment(),r=e.createComment("");return (e.appendChild(t,r), t)},buildRenderNodes:function(e,t,r){var n=new Array(1);return (n[0]=e.createMorphAt(t,0,0,r), e.insertBoundary(t,0), e.insertBoundary(t,null), n)},statements:[["inline","view",[["get","attrs.optionView",["loc",[null,[1,40],[1,56]]]]],["content",["get","item",["loc",[null,[1,65],[1,69]]]],"selection",["get","attrs.selection",["loc",[null,[1,80],[1,95]]]],"parentValue",["get","attrs.value",["loc",[null,[1,108],[1,119]]]],"multiple",["get","attrs.multiple",["loc",[null,[1,129],[1,143]]]],"optionLabelPath",["get","attrs.optionLabelPath",["loc",[null,[1,160],[1,181]]]],"optionValuePath",["get","attrs.optionValuePath",["loc",[null,[1,198],[1,219]]]]],["loc",[null,[1,33],[1,221]]]]],locals:["item"],templates:[]}}();return{meta:{},arity:0,cachedFragment:null,hasRendered:!1,buildFragment:function(e){var t=e.createDocumentFragment(),r=e.createComment("");return (e.appendChild(t,r), t)},buildRenderNodes:function(e,t,r){var n=new Array(1);return (n[0]=e.createMorphAt(t,0,0,r), e.insertBoundary(t,0), e.insertBoundary(t,null), n)},statements:[["block","each",[["get","attrs.content",["loc",[null,[1,8],[1,21]]]]],[],0,null,["loc",[null,[1,0],[1,230]]]]],locals:[],templates:[e]}}())}),e("ember-htmlbars/templates/select-option",["exports","ember-template-compiler/system/template"],function(e,t){"use strict";e["default"]=t["default"](function(){return{meta:{},arity:0,cachedFragment:null,hasRendered:!1,buildFragment:function(e){var t=e.createDocumentFragment(),r=e.createComment("");return (e.appendChild(t,r), t)},buildRenderNodes:function(e,t,r){var n=new Array(1);return (n[0]=e.createMorphAt(t,0,0,r), e.insertBoundary(t,0), e.insertBoundary(t,null), n)},statements:[["content","view.label",["loc",[null,[1,0],[1,16]]]]],locals:[],templates:[]}}())}),e("ember-htmlbars/templates/select",["exports","ember-template-compiler/system/template"],function(e,t){"use strict";e["default"]=t["default"](function(){var e=function(){return{meta:{},arity:0,cachedFragment:null,hasRendered:!1,buildFragment:function(e){var t=e.createDocumentFragment(),r=e.createElement("option");e.setAttribute(r,"value","");var n=e.createComment("");return (e.appendChild(r,n), e.appendChild(t,r), t)},buildRenderNodes:function(e,t,r){var n=new Array(1);return (n[0]=e.createMorphAt(e.childAt(t,[0]),0,0), n)},statements:[["content","view.prompt",["loc",[null,[1,36],[1,51]]]]],locals:[],templates:[]}}(),t=function(){var e=function(){return{meta:{},arity:1,cachedFragment:null,hasRendered:!1,buildFragment:function(e){var t=e.createDocumentFragment(),r=e.createComment("");return (e.appendChild(t,r), t)},buildRenderNodes:function(e,t,r){var n=new Array(1);return (n[0]=e.createMorphAt(t,0,0,r), e.insertBoundary(t,0), e.insertBoundary(t,null), n)},statements:[["inline","view",[["get","view.groupView",["loc",[null,[1,142],[1,156]]]]],["content",["get","group.content",["loc",[null,[1,165],[1,178]]]],"label",["get","group.label",["loc",[null,[1,185],[1,196]]]],"selection",["get","view.selection",["loc",[null,[1,207],[1,221]]]],"value",["get","view.value",["loc",[null,[1,228],[1,238]]]],"multiple",["get","view.multiple",["loc",[null,[1,248],[1,261]]]],"optionLabelPath",["get","view.optionLabelPath",["loc",[null,[1,278],[1,298]]]],"optionValuePath",["get","view.optionValuePath",["loc",[null,[1,315],[1,335]]]],"optionView",["get","view.optionView",["loc",[null,[1,347],[1,362]]]]],["loc",[null,[1,135],[1,364]]]]],locals:["group"],templates:[]}}();return{meta:{},arity:0,cachedFragment:null,hasRendered:!1,buildFragment:function(e){var t=e.createDocumentFragment(),r=e.createComment("");return (e.appendChild(t,r), t)},buildRenderNodes:function(e,t,r){var n=new Array(1);return (n[0]=e.createMorphAt(t,0,0,r), e.insertBoundary(t,0), e.insertBoundary(t,null), n)},statements:[["block","each",[["get","view.groupedContent",["loc",[null,[1,103],[1,122]]]]],[],0,null,["loc",[null,[1,95],[1,373]]]]],locals:[],templates:[e]}}(),r=function(){var e=function(){return{meta:{},arity:1,cachedFragment:null,hasRendered:!1,buildFragment:function(e){var t=e.createDocumentFragment(),r=e.createComment("");return (e.appendChild(t,r), t)},buildRenderNodes:function(e,t,r){var n=new Array(1);return (n[0]=e.createMorphAt(t,0,0,r), e.insertBoundary(t,0), e.insertBoundary(t,null), n)},statements:[["inline","view",[["get","view.optionView",["loc",[null,[1,420],[1,435]]]]],["content",["get","item",["loc",[null,[1,444],[1,448]]]],"selection",["get","view.selection",["loc",[null,[1,459],[1,473]]]],"parentValue",["get","view.value",["loc",[null,[1,486],[1,496]]]],"multiple",["get","view.multiple",["loc",[null,[1,506],[1,519]]]],"optionLabelPath",["get","view.optionLabelPath",["loc",[null,[1,536],[1,556]]]],"optionValuePath",["get","view.optionValuePath",["loc",[null,[1,573],[1,593]]]]],["loc",[null,[1,413],[1,595]]]]],locals:["item"],templates:[]}}();return{meta:{},arity:0,cachedFragment:null,hasRendered:!1,buildFragment:function(e){var t=e.createDocumentFragment(),r=e.createComment("");return (e.appendChild(t,r), t)},buildRenderNodes:function(e,t,r){var n=new Array(1);return (n[0]=e.createMorphAt(t,0,0,r), e.insertBoundary(t,0), e.insertBoundary(t,null), n)},statements:[["block","each",[["get","view.content",["loc",[null,[1,389],[1,401]]]]],[],0,null,["loc",[null,[1,381],[1,604]]]]],locals:[],templates:[e]}}();return{meta:{},arity:0,cachedFragment:null,hasRendered:!1,buildFragment:function(e){var t=e.createDocumentFragment(),r=e.createComment("");e.appendChild(t,r);var r=e.createComment("");e.appendChild(t,r);var r=e.createTextNode("\n");return (e.appendChild(t,r), t)},buildRenderNodes:function(e,t,r){var n=new Array(2);return (n[0]=e.createMorphAt(t,0,0,r), n[1]=e.createMorphAt(t,1,1,r), e.insertBoundary(t,0), n)},statements:[["block","if",[["get","view.prompt",["loc",[null,[1,6],[1,17]]]]],[],0,null,["loc",[null,[1,0],[1,67]]]],["block","if",[["get","view.optionGroupPath",["loc",[null,[1,73],[1,93]]]]],[],1,2,["loc",[null,[1,67],[1,611]]]]],locals:[],templates:[e,t,r]}}())}),e("ember-htmlbars/templates/top-level-view",["exports","ember-template-compiler/system/template"],function(e,t){"use strict";e["default"]=t["default"](function(){return{meta:{},arity:0,cachedFragment:null,hasRendered:!1,buildFragment:function(e){var t=e.createDocumentFragment(),r=e.createComment("");return (e.appendChild(t,r), t)},buildRenderNodes:function(e,t,r){var n=new Array(1);return (n[0]=e.createMorphAt(t,0,0,r), e.insertBoundary(t,0), e.insertBoundary(t,null), n)},statements:[["content","outlet",["loc",[null,[1,0],[1,10]]]]],locals:[],templates:[]}}())}),e("ember-htmlbars/utils/decode-each-key",["exports","ember-metal/core","ember-metal/property_get","ember-metal/utils"],function(e,t,r,n){"use strict";function i(e){var t=void 0,r=typeof e;return t="string"===r||"number"===r?e:n.guidFor(e)}function a(e,t,a){var o,s;switch(t){case"@index":o=a;break;case"@guid":s="@guid",o=n.guidFor(e);break;case"@item":s="@item",o=e;break;case"@identity":o=i(e);break;default:o=t?r.get(e,t):i(e)}return("number"==typeof o&&(o=String(o)), o)}e["default"]=a}),e("ember-htmlbars/utils/is-component",["exports","ember-htmlbars/system/lookup-helper"],function(e,t){"use strict";function r(e,r,n){var i=e.container;return i&&t.CONTAINS_DASH_CACHE.get(n)?i._registry.has("component:"+n)||i._registry.has("template:components/"+n):!1}e["default"]=r}),e("ember-htmlbars/utils/lookup-component",["exports"],function(e){"use strict";function t(e,t){var r=e.lookup("component-lookup:main");return{component:r.componentFor(t,e),layout:r.layoutFor(t,e)}}e["default"]=t}),e("ember-htmlbars/utils/normalize-self",["exports"],function(e){"use strict";function t(e){return void 0===e?null:e}e["default"]=t}),e("ember-htmlbars/utils/string",["exports","htmlbars-util","ember-runtime/system/string"],function(e,t,r){"use strict";function n(e){return null===e||void 0===e?"":("string"!=typeof e&&(e=""+e),new t.SafeString(e))}r["default"].htmlSafe=n,(i.EXTEND_PROTOTYPES===!0||i.EXTEND_PROTOTYPES.String)&&(String.prototype.htmlSafe=function(){return n(this)}),e.SafeString=t.SafeString,e.htmlSafe=n,e.escapeExpression=t.escapeExpression}),e("ember-htmlbars/utils/subscribe",["exports","ember-metal/streams/utils"],function(e,t){"use strict";function r(e,r,n,i){if(t.isStream(i)){var a=n.component,o=e.streamUnsubscribers=e.streamUnsubscribers||[];o.push(i.subscribe(function(){e.isDirty=!0,a&&a._renderNode&&(a._renderNode.isDirty=!0),e.state.manager&&(e.shouldReceiveAttrs=!0),e.ownerNode.emberView.scheduleRevalidate(e,t.labelFor(i))}))}}e["default"]=r}),e("ember-htmlbars/utils/update-scope",["exports","ember-metal/streams/proxy-stream","ember-htmlbars/utils/subscribe"],function(e,t,r){"use strict";function n(e,n,i,a,o){var s=e[n];if(s)s.setSource(i);else{var l=new t["default"](i,o?null:n);a&&r["default"](a,e,l),e[n]=l}}e["default"]=n}),e("ember-metal-views",["exports","ember-metal-views/renderer"],function(e,t){"use strict";e.Renderer=t["default"]}),e("ember-metal-views/renderer",["exports","ember-metal/run_loop","ember-metal/property_get","ember-metal/property_set","ember-metal/merge","ember-metal/set_properties","ember-views/system/build-component-template","ember-metal/enumerable_utils"],function(e,t,r,n,i,a,o,s){"use strict";function l(e){this._dom=e}l.prototype.prerenderTopLevelView=function(e,t){ +if("inDOM"===e._state)throw new Error("You cannot insert a View that has already been rendered");e.ownerView=t.emberView=e,e._renderNode=t;var n=r.get(e,"layout"),i=e.isComponent?r.get(e,"_template"):r.get(e,"template"),a={component:e,layout:n},s=o["default"](a,{},{self:e,templates:i?{"default":i.raw}:void 0}).block;e.renderBlock(s,t),e.lastResult=t.lastResult,this.clearRenderedViews(e.env)},l.prototype.renderTopLevelView=function(e,t){e._willInsert&&(e._willInsert=!1,this.prerenderTopLevelView(e,t),this.dispatchLifecycleHooks(e.env))},l.prototype.revalidateTopLevelView=function(e){e._renderNode.lastResult&&(e._renderNode.lastResult.revalidate(e.env),"inDOM"===e._state&&this.dispatchLifecycleHooks(e.env),this.clearRenderedViews(e.env))},l.prototype.dispatchLifecycleHooks=function(e){var t,r,n=e.view,i=e.lifecycleHooks;for(t=0;t-1},n=function(e,t){return r(e)?e:t},a=n(t.map,function(e){if(void 0===this||null===this||"function"!=typeof e)throw new TypeError;for(var t=Object(this),r=t.length>>>0,n=new Array(r),i=0;r>i;i++)i in t&&(n[i]=e.call(arguments[1],t[i],i,t));return n}),o=n(t.forEach,function(e){if(void 0===this||null===this||"function"!=typeof e)throw new TypeError;for(var t=Object(this),r=t.length>>>0,n=0;r>n;n++)n in t&&e.call(arguments[1],t[n],n,t)}),s=n(t.indexOf,function(e,t){null===t||void 0===t?t=0:0>t&&(t=Math.max(0,this.length+t));for(var r=t,n=this.length;n>r;r++)if(this[r]===e)return r;return-1}),l=n(t.lastIndexOf,function(e,t){var r,n=this.length;for(t=void 0===t?n-1:0>t?Math.ceil(t):Math.floor(t),0>t&&(t+=n),r=t;r>=0;r--)if(this[r]===e)return r;return-1}),u=n(t.filter,function(e,t){var r,n,i=[],a=this.length;for(r=0;a>r;r++)Object.prototype.hasOwnProperty.call(this,r)&&(n=this[r],e.call(t,n,r,this)&&i.push(n));return i});i.SHIM_ES5&&(t.map=t.map||a,t.forEach=t.forEach||o,t.filter=t.filter||u,t.indexOf=t.indexOf||s,t.lastIndexOf=t.lastIndexOf||l),e.map=a,e.forEach=o,e.filter=u,e.indexOf=s,e.lastIndexOf=l}),e("ember-metal/binding",["exports","ember-metal/core","ember-metal/property_get","ember-metal/property_set","ember-metal/utils","ember-metal/observer","ember-metal/run_loop","ember-metal/path_cache"],function(e,t,r,n,i,a,o,s){"use strict";function l(e,n){return r.get(s.isGlobal(n)?t["default"].lookup:e,n)}function u(e,t){this._direction=void 0,this._from=t,this._to=e,this._readyToSync=void 0,this._oneWay=void 0}function c(e,t){for(var r in t)t.hasOwnProperty(r)&&(e[r]=t[r])}function h(e,t,r){return new u(t,r).connect(e)}function m(e,t,r){return new u(t,r).oneWay().connect(e)}e.bind=h,e.oneWay=m,t["default"].LOG_BINDINGS=!!t["default"].ENV.LOG_BINDINGS,u.prototype={copy:function(){var e=new u(this._to,this._from);return (this._oneWay&&(e._oneWay=!0), e)},from:function(e){return (this._from=e, this)},to:function(e){return (this._to=e, this)},oneWay:function(){return (this._oneWay=!0, this)},toString:function(){var e=this._oneWay?"[oneWay]":"";return"Ember.Binding<"+i.guidFor(this)+">("+this._from+" -> "+this._to+")"+e},connect:function(e){var t=this._from,r=this._to;return (n.trySet(e,r,l(e,t)), a.addObserver(e,t,this,this.fromDidChange), this._oneWay||a.addObserver(e,r,this,this.toDidChange), this._readyToSync=!0, this)},disconnect:function(e){var t=!this._oneWay;return (a.removeObserver(e,this._from,this,this.fromDidChange), t&&a.removeObserver(e,this._to,this,this.toDidChange), this._readyToSync=!1, this)},fromDidChange:function(e){this._scheduleSync(e,"fwd")},toDidChange:function(e){this._scheduleSync(e,"back")},_scheduleSync:function(e,t){var r=this._direction;void 0===r&&(o["default"].schedule("sync",this,this._sync,e),this._direction=t),"back"===r&&"fwd"===t&&(this._direction="fwd")},_sync:function(e){var i=t["default"].LOG_BINDINGS;if(!e.isDestroyed&&this._readyToSync){var o=this._direction,u=this._from,c=this._to;if(this._direction=void 0,"fwd"===o){var h=l(e,this._from);i&&t["default"].Logger.log(" ",this.toString(),"->",h,e),this._oneWay?n.trySet(e,c,h):a._suspendObserver(e,c,this,this.toDidChange,function(){n.trySet(e,c,h)})}else if("back"===o){var m=r.get(e,this._to);i&&t["default"].Logger.log(" ",this.toString(),"<-",m,e),a._suspendObserver(e,u,this,this.fromDidChange,function(){n.trySet(s.isGlobal(u)?t["default"].lookup:e,u,m)})}}}},c(u,{from:function(e){var t=this;return new t(void 0,e)},to:function(e){var t=this;return new t(e,void 0)},oneWay:function(e,t){var r=this;return new r(void 0,e).oneWay(t)}}),e.Binding=u,e.isGlobalPath=s.isGlobal}),e("ember-metal/cache",["exports","ember-metal/dictionary"],function(e,t){"use strict";function r(e,r){this.store=t["default"](null),this.size=0,this.misses=0,this.hits=0,this.limit=e,this.func=r}e["default"]=r;var n=function(){};r.prototype={set:function(e,t){return (this.limit>this.size&&(this.size++,void 0===t?this.store[e]=n:this.store[e]=t), t)},get:function(e){var t=this.store[e];return (void 0===t?(this.misses++,t=this.set(e,this.func(e))):t===n?(this.hits++,t=void 0):this.hits++, t)},purge:function(){this.store=t["default"](null),this.size=0,this.hits=0,this.misses=0}}}),e("ember-metal/chains",["exports","ember-metal/core","ember-metal/property_get","ember-metal/utils","ember-metal/array","ember-metal/watch_key"],function(e,t,r,n,i,a){"use strict";function o(e){return e.match(f)[0]}function s(e){return e&&"object"==typeof e}function l(){if(0!==v.length){var e=v;v=[],i.forEach.call(e,function(e){e[0].add(e[1])}),p("Watching an undefined global, Ember expects watched globals to be setup by the time the run loop is flushed, check for typos",0===v.length)}}function u(e,t,r){if(s(e)){var i=n.meta(e),o=i.chainWatchers;i.hasOwnProperty("chainWatchers")||(o=i.chainWatchers={}),o[t]||(o[t]=[]),o[t].push(r),a.watchKey(e,t,i)}}function c(e,t,r){if(s(e)){var n=e.__ember_meta__;if(!n||n.hasOwnProperty("chainWatchers")){var i=n&&n.chainWatchers;if(i&&i[t]){i=i[t];for(var o=0,l=i.length;l>o;o++)if(i[o]===r){i.splice(o,1);break}}a.unwatchKey(e,t,n)}}}function h(e,t,r){this._parent=e,this._key=t,this._watching=void 0===r,this._value=r,this._paths={},this._watching&&(this._object=e.value(),this._object&&u(this._object,this._key,this)),this._parent&&"@each"===this._parent._key&&this.value()}function m(e,t){if(e){var n=e.__ember_meta__;if(!n||n.proto!==e){if("@each"===t)return r.get(e,t);var i=e[t],a=null!==i&&"object"==typeof i&&i.isDescriptor?i:void 0;return a&&a._cacheable?n.cache&&t in n.cache?n.cache[t]:void 0:r.get(e,t)}}}function d(e){var t,r,i,a=e.__ember_meta__;if(a){if(r=a.chainWatchers)for(var o in r)if(r.hasOwnProperty(o)&&(i=r[o]))for(var s=0,l=i.length;l>s;s++){var u=i[s];u&&u.didChange(null)}t=a.chains,t&&t.value()!==e&&(n.meta(e).chains=t=t.copy(e))}}e.flushPendingChains=l,e.finishChains=d;var p=t["default"].warn,f=/^([^\.]+)/,v=[];h.prototype={value:function(){if(void 0===this._value&&this._watching){var e=this._parent.value();this._value=m(e,this._key)}return this._value},destroy:function(){if(this._watching){var e=this._object;e&&c(e,this._key,this),this._watching=!1}},copy:function(e){var t,r=new h(null,null,e),n=this._paths;for(t in n)n[t]<=0||r.add(t);return r},add:function(e){var t,n,i,a,s;if(s=this._paths,s[e]=(s[e]||0)+1,t=this.value(),n=r.normalizeTuple(t,e),n[0]&&n[0]===t)e=n[1],i=o(e),e=e.slice(i.length+1);else{if(!n[0])return (v.push([this,e]), void(n.length=0));a=n[0],i=e.slice(0,0-(n[1].length+1)),e=n[1]}n.length=0,this.chain(i,e,a)},remove:function(e){var t,n,i,a,s;s=this._paths,s[e]>0&&s[e]--,t=this.value(),n=r.normalizeTuple(t,e),n[0]===t?(e=n[1],i=o(e),e=e.slice(i.length+1)):(a=n[0],i=e.slice(0,0-(n[1].length+1)),e=n[1]),n.length=0,this.unchain(i,e)},count:0,chain:function(e,t,r){var n,i=this._chains;i||(i=this._chains={}),n=i[e],n||(n=i[e]=new h(this,e,r)),n.count++,t&&(e=o(t),t=t.slice(e.length+1),n.chain(e,t))},unchain:function(e,t){var r=this._chains,n=r[e];if(t&&t.length>1){var i=o(t),a=t.slice(i.length+1);n.unchain(i,a)}n.count--,n.count<=0&&(delete r[n._key],n.destroy())},willChange:function(e){var t,r=this._chains;if(r)for(var n in r)t=r[n],void 0!==t&&t.willChange(e);this._parent&&this._parent.chainWillChange(this,this._key,1,e)},chainWillChange:function(e,t,r,n){this._key&&(t=this._key+"."+t),this._parent?this._parent.chainWillChange(this,t,r+1,n):(r>1&&n.push(this.value(),t),t="this."+t,this._paths[t]>0&&n.push(this.value(),t))},chainDidChange:function(e,t,r,n){this._key&&(t=this._key+"."+t),this._parent?this._parent.chainDidChange(this,t,r+1,n):(r>1&&n.push(this.value(),t),t="this."+t,this._paths[t]>0&&n.push(this.value(),t))},didChange:function(e){if(this._watching){var t=this._parent.value();t!==this._object&&(c(this._object,this._key,this),this._object=t,u(t,this._key,this)),this._value=void 0,this._parent&&"@each"===this._parent._key&&this.value()}var r=this._chains;if(r)for(var n in r)r.hasOwnProperty(n)&&r[n].didChange(e);null!==e&&this._parent&&this._parent.chainDidChange(this,this._key,1,e)}},e.removeChainWatcher=c,e.ChainNode=h}),e("ember-metal/computed",["exports","ember-metal/core","ember-metal/property_set","ember-metal/utils","ember-metal/expand_properties","ember-metal/error","ember-metal/properties","ember-metal/property_events","ember-metal/dependent_keys"],function(e,t,r,n,i,a,o,s,l){"use strict";function u(){}function c(e,t){this.isDescriptor=!0,"function"==typeof e?(e.__ember_arity=e.length,this._getter=e,e.__ember_arity>1&&(this._setter=e)):(this._getter=e.get,this._setter=e.set,this._setter&&void 0===this._setter.__ember_arity&&(this._setter.__ember_arity=this._setter.length)),this._dependentKeys=void 0,this._suspended=void 0,this._meta=void 0,this._cacheable=t&&void 0!==t.cacheable?t.cacheable:!0,this._dependentKeys=t&&t.dependentKeys,this._readOnly=t&&(void 0!==t.readOnly||!!t.readOnly)||!1}function h(e){for(var t=0,r=e.length;r>t;t++)e[t].didChange(null)}function m(e){var t;arguments.length>1&&(t=[].slice.call(arguments),e=t.pop());var r=new c(e);return (t&&r.property.apply(r,t), r)}function d(e,t){var r=e.__ember_meta__,n=r&&r.cache,i=n&&n[t];return i!==u?i:void 0}var p=n.meta;c.prototype=new o.Descriptor;var f=c.prototype;f.cacheable=function(e){return (this._cacheable=e!==!1, this)},f["volatile"]=function(){return (this._cacheable=!1, this)},f.readOnly=function(e){return (this._readOnly=void 0===e||!!e, this)},f.property=function(){var e,t=function(t){e.push(t)};e=[];for(var r=0,n=arguments.length;n>r;r++)i["default"](arguments[r],t);return (this._dependentKeys=e, this)},f.meta=function(e){return 0===arguments.length?this._meta||{}:(this._meta=e,this)},f.didChange=function(e,t){if(this._cacheable&&this._suspended!==e){var r=p(e);r.cache&&void 0!==r.cache[t]&&(r.cache[t]=void 0,l.removeDependentKeys(this,e,t,r))}},f.get=function(e,t){var r,n,i,a;if(this._cacheable){i=p(e),n=i.cache;var o=n&&n[t];if(o===u)return;if(void 0!==o)return o;r=this._getter.call(e,t),n=i.cache,n||(n=i.cache={}),void 0===r?n[t]=u:n[t]=r,a=i.chainWatchers&&i.chainWatchers[t],a&&h(a),l.addDependentKeys(this,e,t,i)}else r=this._getter.call(e,t);return r},f.set=function(e,t,r){var n=this._suspended;this._suspended=e;try{this._set(e,t,r)}finally{this._suspended=n}},f._set=function(e,t,i){var c,h,m=this._cacheable,d=this._setter,f=p(e,m),v=f.cache,g=!1;if(this._readOnly)throw new a["default"]('Cannot set read-only property "'+t+'" on object: '+n.inspect(e));if(m&&v&&void 0!==v[t]&&(v[t]!==u&&(c=v[t]),g=!0),!d)return (o.defineProperty(e,t,null,c), void r.set(e,t,i));if(h=2===d.__ember_arity?d.call(e,t,i):d.call(e,t,i,c),!g||c!==h){var b=f.watching[t];return (b&&s.propertyWillChange(e,t), g&&(v[t]=void 0), m&&(g||l.addDependentKeys(this,e,t,f),v||(v=f.cache={}),void 0===h?v[t]=u:v[t]=h), b&&s.propertyDidChange(e,t), h)}},f.teardown=function(e,t){var r=p(e);return (r.cache&&(t in r.cache&&l.removeDependentKeys(this,e,t,r),this._cacheable&&delete r.cache[t]), null)},d.set=function(e,t,r){void 0===r?e[t]=u:e[t]=r},d.get=function(e,t){var r=e[t];if(r!==u)return r},d.remove=function(e,t){e[t]=void 0},e.ComputedProperty=c,e.computed=m,e.cacheFor=d}),e("ember-metal/computed_macros",["exports","ember-metal/core","ember-metal/property_get","ember-metal/property_set","ember-metal/computed","ember-metal/is_empty","ember-metal/is_none","ember-metal/alias"],function(e,t,r,n,i,a,o,s){"use strict";function l(e,t){for(var n={},i=0;in;n++)r[n]=arguments[n];var a=i.computed(function(){return e.apply(this,[l(this,r)])});return a.property.apply(a,r)}}function c(e){return i.computed(e+".length",function(){return a["default"](r.get(this,e))})}function h(e){return i.computed(e+".length",function(){return!a["default"](r.get(this,e))})}function m(e){return i.computed(e,function(){return o["default"](r.get(this,e))})}function d(e){return i.computed(e,function(){return!r.get(this,e)})}function p(e){return i.computed(e,function(){return!!r.get(this,e)})}function f(e,t){return i.computed(e,function(){var n=r.get(this,e);return"string"==typeof n?t.test(n):!1})}function v(e,t){return i.computed(e,function(){return r.get(this,e)===t})}function g(e,t){return i.computed(e,function(){return r.get(this,e)>t})}function b(e,t){return i.computed(e,function(){return r.get(this,e)>=t})}function y(e,t){return i.computed(e,function(){return r.get(this,e)r;r++)t[r]=arguments[r];return t[t.length-1]}),e["default"]=i}),e("ember-metal/dependent_keys",["exports","ember-metal/platform/create","ember-metal/watching"],function(e,t,r){function n(e,r){var n=e[r];return (n?e.hasOwnProperty(r)||(n=e[r]=t["default"](n)):n=e[r]={}, n)}function i(e){return n(e,"deps")}function a(e,t,a,o){var s,l,u,c,h,m=e._dependentKeys;if(m)for(s=i(o),l=0,u=m.length;u>l;l++)c=m[l],h=n(s,c),h[a]=(h[a]||0)+1,r.watch(t,c,o)}function o(e,t,a,o){var s,l,u,c,h,m=e._dependentKeys;if(m)for(s=i(o),l=0,u=m.length;u>l;l++)c=m[l],h=n(s,c),h[a]=(h[a]||0)-1,r.unwatch(t,c,o)}e.addDependentKeys=a,e.removeDependentKeys=o}),e("ember-metal/deprecate_property",["exports","ember-metal/core","ember-metal/platform/define_property","ember-metal/properties","ember-metal/property_get","ember-metal/property_set"],function(e,t,r,n,i,a){"use strict";function o(e,t,o){function s(){}r.hasPropertyAccessors&&n.defineProperty(e,t,{configurable:!0,enumerable:!1,set:function(e){s(),a.set(this,o,e)},get:function(){return (s(), i.get(this,o))}})}e.deprecateProperty=o}),e("ember-metal/dictionary",["exports","ember-metal/platform/create"],function(e,t){"use strict";function r(e){var r=t["default"](e);return (r._dict=null, delete r._dict, r)}e["default"]=r}),e("ember-metal/empty_object",["exports","ember-metal/platform/create"],function(e,t){"use strict";function r(){}var n=t["default"](null,{constructor:{value:void 0,enumerable:!1,writable:!0}});r.prototype=n,e["default"]=r}),e("ember-metal/enumerable_utils",["exports","ember-metal/core","ember-metal/array"],function(e,t,r){"use strict";function n(e,t,n){return e.map?e.map(t,n):r.map.call(e,t,n)}function i(e,t,n){return e.forEach?e.forEach(t,n):r.forEach.call(e,t,n)}function a(e,t,n){return e.filter?e.filter(t,n):r.filter.call(e,t,n)}function o(e,t,n){return e.indexOf?e.indexOf(t,n):r.indexOf.call(e,t,n)}function s(e,t){return void 0===t?[]:n(t,function(t){return o(e,t)})}function l(e,t){var r=o(e,t);-1===r&&e.push(t)}function u(e,t){var r=o(e,t);-1!==r&&e.splice(r,1)}function c(e,t,r,n){for(var i,a,o=[].concat(n),s=[],l=6e4,u=t,c=r;o.length;)i=c>l?l:c,0>=i&&(i=0),a=o.splice(0,l),a=[u,i].concat(a),u+=l,c-=i,s=s.concat(d.apply(e,a));return s}function h(e,t,r,n){return e.replace?e.replace(t,r,n):c(e,t,r,n)}function m(e,t){var r=[];return (i(e,function(e){o(t,e)>=0&&r.push(e)}), r)}e.map=n,e.forEach=i,e.filter=a,e.indexOf=o,e.indexesOf=s,e.addObject=l,e.removeObject=u,e._replace=c,e.replace=h,e.intersection=m;var d=Array.prototype.splice,p=t["default"].deprecateFunc("Ember.EnumberableUtils.map is deprecated, please refactor to use Array.prototype.map.",n),f=t["default"].deprecateFunc("Ember.EnumberableUtils.forEach is deprecated, please refactor to use Array.prototype.forEach.",i),v=t["default"].deprecateFunc("Ember.EnumberableUtils.filter is deprecated, please refactor to use Array.prototype.filter.",a),g=t["default"].deprecateFunc("Ember.EnumberableUtils.indexOf is deprecated, please refactor to use Array.prototype.indexOf.",o),b=t["default"].deprecateFunc("Ember.EnumerableUtils.indexesOf is deprecated.",s),y=t["default"].deprecateFunc("Ember.EnumerableUtils.addObject is deprecated.",l),_=t["default"].deprecateFunc("Ember.EnumerableUtils.removeObject is deprecated.",u),w=t["default"].deprecateFunc("Ember.EnumerableUtils.replace is deprecated.",h),x=t["default"].deprecateFunc("Ember.EnumerableUtils.intersection is deprecated.",m);e["default"]={_replace:c,addObject:y,filter:v,forEach:f,indexOf:g,indexesOf:b,intersection:x,map:p,removeObject:_,replace:w}}),e("ember-metal/environment",["exports","ember-metal/core"],function(e,t){"use strict";var r,n="undefined"!=typeof window&&"undefined"!=typeof document&&"undefined"!=typeof document.createElement&&!t["default"].ENV.disableBrowserEnvironment;r=n?{hasDOM:!0,isChrome:!!window.chrome&&!window.opera,isFirefox:"undefined"!=typeof InstallTrigger,location:window.location,history:window.history,userAgent:window.navigator.userAgent,global:window}:{hasDOM:!1,isChrome:!1,isFirefox:!1, +location:null,history:null,userAgent:"Lynx (textmode)",global:null},e["default"]=r}),e("ember-metal/error",["exports","ember-metal/platform/create"],function(e,t){"use strict";function r(){var e=Error.apply(this,arguments);Error.captureStackTrace&&Error.captureStackTrace(this,i.Error);for(var t=0;t=0;i-=3)if(t===e[i]&&r===e[i+1]){n=i;break}return n}function a(e,t){var i,a=r.meta(e,!0),o=a.listeners;return (o?o.__source__!==e&&(o=a.listeners=n["default"](o),o.__source__=e):(o=a.listeners=n["default"](null),o.__source__=e), i=o[t], i&&i.__source__!==e?(i=o[t]=o[t].slice(),i.__source__=e):i||(i=o[t]=[],i.__source__=e), i)}function o(e,t,r){var n=e.__ember_meta__,a=n&&n.listeners&&n.listeners[t];if(a){for(var o=[],s=a.length-3;s>=0;s-=3){var l=a[s],u=a[s+1],c=a[s+2],h=i(r,l,u);-1===h&&(r.push(l,u,c),o.push(l,u,c))}return o}}function s(e,t,r,n,o){n||"function"!=typeof r||(n=r,r=null);var s=a(e,t),l=i(s,r,n),u=0;o&&(u|=v),-1===l&&(s.push(r,n,u),"function"==typeof e.didAddListener&&e.didAddListener(t,r,n))}function l(e,t,r,n){function o(r,n){var o=a(e,t),s=i(o,r,n);-1!==s&&(o.splice(s,3),"function"==typeof e.didRemoveListener&&e.didRemoveListener(t,r,n))}if(n||"function"!=typeof r||(n=r,r=null),n)o(r,n);else{var s=e.__ember_meta__,l=s&&s.listeners&&s.listeners[t];if(!l)return;for(var u=l.length-3;u>=0;u-=3)o(l[u],l[u+1])}}function u(e,t,n,o,s){function l(){return s.call(n)}function u(){-1!==h&&(c[h+2]&=~g)}o||"function"!=typeof n||(o=n,n=null);var c=a(e,t),h=i(c,n,o);return(-1!==h&&(c[h+2]|=g), r.tryFinally(l,u))}function c(e,t,n,o,s){function l(){return s.call(n)}function u(){for(var e=0,t=p.length;t>e;e++){var r=p[e];f[e][r+2]&=~g}}o||"function"!=typeof n||(o=n,n=null);var c,h,m,d,p=[],f=[];for(m=0,d=t.length;d>m;m++){c=t[m],h=a(e,c);var v=i(h,n,o);-1!==v&&(h[v+2]|=g,p.push(v),f.push(h))}return r.tryFinally(l,u)}function h(e){var t=e.__ember_meta__.listeners,r=[];if(t)for(var n in t)"__source__"!==n&&t[n]&&r.push(n);return r}function m(e,n,i,a){if(e!==t["default"]&&"function"==typeof e.sendEvent&&e.sendEvent(n,i),!a){var o=e.__ember_meta__;a=o&&o.listeners&&o.listeners[n]}if(a){for(var s=a.length-3;s>=0;s-=3){var u=a[s],c=a[s+1],h=a[s+2];c&&(h&g||(h&v&&l(e,n,u,c),u||(u=e),"string"==typeof c?i?r.applyStr(u,c,i):u[c]():i?r.apply(u,c,i):c.call(u)))}return!0}}function d(e,t){var r=e.__ember_meta__,n=r&&r.listeners&&r.listeners[t];return!(!n||!n.length)}function p(e,t){var r=[],n=e.__ember_meta__,i=n&&n.listeners&&n.listeners[t];if(!i)return r;for(var a=0,o=i.length;o>a;a+=3){var s=i[a],l=i[a+1];r.push([s,l])}return r}function f(){for(var e=arguments.length,t=Array(e),r=0;e>r;r++)t[r]=arguments[r];var n=t.pop(),i=t;return (n.__ember_listens__=i, n)}e.accumulateListeners=o,e.addListener=s,e.suspendListener=u,e.suspendListeners=c,e.watchedEvents=h,e.sendEvent=m,e.hasListeners=d,e.listenersFor=p,e.on=f;var v=1,g=2;e.removeListener=l}),e("ember-metal/expand_properties",["exports","ember-metal/error","ember-metal/array"],function(e,t,r){"use strict";function n(e,n){if(e.indexOf(" ")>-1)throw new t["default"]("Brace expanded properties cannot contain spaces, e.g. 'user.{firstName, lastName}' should be 'user.{firstName,lastName}'");if("string"==typeof e){var o=e.split(a),s=[o];r.forEach.call(o,function(e,t){e.indexOf(",")>=0&&(s=i(s,e.split(","),t))}),r.forEach.call(s,function(e){n(e.join(""))})}else n(e)}function i(e,t,n){var i=[];return (r.forEach.call(e,function(e){r.forEach.call(t,function(t){var r=e.slice(0);r[n]=t,i.push(r)})}), i)}e["default"]=n;var a=/\{|\}/}),e("ember-metal/get_properties",["exports","ember-metal/property_get","ember-metal/utils"],function(e,t,r){"use strict";function n(e){var n={},i=arguments,a=1;2===arguments.length&&r.isArray(arguments[1])&&(a=0,i=arguments[1]);for(var o=i.length;o>a;a++)n[i[a]]=t.get(e,i[a]);return n}e["default"]=n}),e("ember-metal/injected_property",["exports","ember-metal/core","ember-metal/computed","ember-metal/alias","ember-metal/properties","ember-metal/platform/create"],function(e,t,r,n,i,a){"use strict";function o(e,t){this.type=e,this.name=t,this._super$Constructor(s),c.oneWay.call(this)}function s(e){var t=this[e],r=null!==t&&"object"==typeof t&&t.isDescriptor?t:void 0;return this.container.lookup(r.type+":"+(r.name||e))}o.prototype=a["default"](i.Descriptor.prototype);var l=o.prototype,u=r.ComputedProperty.prototype,c=n.AliasedProperty.prototype;l._super$Constructor=r.ComputedProperty,l.get=u.get,l.readOnly=u.readOnly,l.teardown=u.teardown,e["default"]=o}),e("ember-metal/instrumentation",["exports","ember-metal/core","ember-metal/utils"],function(e,t,r){"use strict";function n(e,t,n,a){if(arguments.length<=3&&"function"==typeof t&&(a=n,n=t,t=void 0),0===l.length)return n.call(a);var o=t||{},s=i(e,function(){return o});if(s){var u=function(){return n.call(a)},c=function(e){o.exception=e};return r.tryCatchFinally(u,c,s)}return n.call(a)}function i(e,r){var n=u[e];if(n||(n=c(e)),0!==n.length){var i,a=r(),o=t["default"].STRUCTURED_PROFILE;o&&(i=e+": "+a.object,console.time(i));var s,l,m=n.length,d=new Array(m),p=h();for(s=0;m>s;s++)l=n[s],d[s]=l.before(e,p,a);return function(){var t,r,s,l=h();for(t=0,r=n.length;r>t;t++)s=n[t],s.after(e,l,a,d[t]);o&&console.timeEnd(i)}}}function a(e,t){for(var r,n=e.split("."),i=[],a=0,o=n.length;o>a;a++)r=n[a],"*"===r?i.push("[^\\.]*"):i.push(r);i=i.join("\\."),i+="(\\..*)?";var s={pattern:e,regex:new RegExp("^"+i+"$"),object:t};return (l.push(s), u={}, s)}function o(e){for(var t,r=0,n=l.length;n>r;r++)l[r]===e&&(t=r);l.splice(t,1),u={}}function s(){l.length=0,u={}}e.instrument=n,e._instrumentStart=i,e.subscribe=a,e.unsubscribe=o,e.reset=s;var l=[];e.subscribers=l;var u={},c=function(e){for(var t,r=[],n=0,i=l.length;i>n;n++)t=l[n],t.regex.test(e)&&r.push(t.object);return (u[e]=r, r)},h=function(){var e="undefined"!=typeof window?window.performance||{}:{},t=e.now||e.mozNow||e.webkitNow||e.msNow||e.oNow;return t?t.bind(e):function(){return+new Date}}()}),e("ember-metal/is_blank",["exports","ember-metal/is_empty"],function(e,t){"use strict";function r(e){return t["default"](e)||"string"==typeof e&&null===e.match(/\S/)}e["default"]=r}),e("ember-metal/is_empty",["exports","ember-metal/property_get","ember-metal/is_none"],function(e,t,r){"use strict";function n(e){var n=r["default"](e);if(n)return n;if("number"==typeof e.size)return!e.size;var i=typeof e;if("object"===i){var a=t.get(e,"size");if("number"==typeof a)return!a}if("number"==typeof e.length&&"function"!==i)return!e.length;if("object"===i){var o=t.get(e,"length");if("number"==typeof o)return!o}return!1}e["default"]=n}),e("ember-metal/is_none",["exports"],function(e){"use strict";function t(e){return null===e||void 0===e}e["default"]=t}),e("ember-metal/is_present",["exports","ember-metal/is_blank"],function(e,t){"use strict";function r(e){return!t["default"](e)}e["default"]=r}),e("ember-metal/keys",["exports","ember-metal/platform/define_property"],function(e,t){"use strict";var r=Object.keys;r&&t.canDefineNonEnumerableProperties||(r=function(){var e=Object.prototype.hasOwnProperty,t=!{toString:null}.propertyIsEnumerable("toString"),r=["toString","toLocaleString","valueOf","hasOwnProperty","isPrototypeOf","propertyIsEnumerable","constructor"],n=r.length;return function(i){if("object"!=typeof i&&("function"!=typeof i||null===i))throw new TypeError("Object.keys called on non-object");var a,o,s=[];for(a in i)"_super"!==a&&0!==a.lastIndexOf("__",0)&&e.call(i,a)&&s.push(a);if(t)for(o=0;n>o;o++)e.call(i,r[o])&&s.push(r[o]);return s}}()),e["default"]=r}),e("ember-metal/libraries",["exports","ember-metal/core","ember-metal/enumerable_utils"],function(e,t,r){"use strict";function n(){this._registry=[],this._coreLibIndex=0}n.prototype={constructor:n,_getLibraryByName:function(e){for(var t=this._registry,r=t.length,n=0;r>n;n++)if(t[n].name===e)return t[n]},register:function(e,t,r){var n=this._registry.length;this._getLibraryByName(e)||(r&&(n=this._coreLibIndex++),this._registry.splice(n,0,{name:e,version:t}))},registerCoreLibrary:function(e,t){this.register(e,t,!0)},deRegister:function(e){var t,n=this._getLibraryByName(e);n&&(t=r.indexOf(this._registry,n),this._registry.splice(t,1))},each:function(e){r.forEach(this._registry,function(t){e(t.name,t.version)})}},e["default"]=n}),e("ember-metal/logger",["exports","ember-metal/core","ember-metal/error"],function(e,t,r){"use strict";function n(){return this}function i(e){var r,n;t["default"].imports.console?r=t["default"].imports.console:"undefined"!=typeof console&&(r=console);var i="object"==typeof r?r[e]:null;return i?"function"==typeof i.bind?(n=i.bind(r),n.displayName="console."+e,n):"function"==typeof i.apply?(n=function(){i.apply(r,arguments)},n.displayName="console."+e,n):function(){var e=Array.prototype.join.call(arguments,", ");i(e)}:void 0}function a(e,t){if(!e)try{throw new r["default"]("assertion failed: "+t)}catch(n){setTimeout(function(){throw n},0)}}e["default"]={log:i("log")||n,warn:i("warn")||n,error:i("error")||n,info:i("info")||n,debug:i("debug")||i("info")||n,assert:i("assert")||a}}),e("ember-metal/map",["exports","ember-metal/utils","ember-metal/array","ember-metal/platform/create","ember-metal/deprecate_property"],function(e,t,r,n,a){"use strict";function o(e){throw new TypeError(Object.prototype.toString.call(e)+" is not a function")}function s(e){throw new TypeError("Constructor "+e+" requires 'new'")}function l(e){var t=n["default"](null);for(var r in e)t[r]=e[r];return t}function u(e,t){var r=e._keys.copy(),n=l(e._values);return (t._keys=r, t._values=n, t.size=e.size, t)}function c(){this instanceof c?(this.clear(),this._silenceRemoveDeprecation=!1):s("OrderedSet")}function h(){this instanceof this.constructor?(this._keys=c.create(),this._keys._silenceRemoveDeprecation=!0,this._values=n["default"](null),this.size=0):s("OrderedSet")}function m(e){this._super$constructor(),this.defaultValue=e.defaultValue}c.create=function(){var e=this;return new e},c.prototype={constructor:c,clear:function(){this.presenceSet=n["default"](null),this.list=[],this.size=0},add:function(e,r){var n=r||t.guidFor(e),i=this.presenceSet,a=this.list;return (i[n]!==!0&&(i[n]=!0,this.size=a.push(e)), this)},remove:function(e,t){return this["delete"](e,t)},"delete":function(e,n){var i=n||t.guidFor(e),a=this.presenceSet,o=this.list;if(a[i]===!0){delete a[i];var s=r.indexOf.call(o,e);return (s>-1&&o.splice(s,1), this.size=o.length, !0)}return!1},isEmpty:function(){return 0===this.size},has:function(e){if(0===this.size)return!1;var r=t.guidFor(e),n=this.presenceSet;return n[r]===!0},forEach:function(e){if("function"!=typeof e&&o(e),0!==this.size){var t,r=this.list,n=arguments.length;if(2===n)for(t=0;to;o++)n=i[o],e[n]=r[n];return e}function n(e){for(var r=arguments.length,n=Array(r>1?r-1:0),i=1;r>i;i++)n[i-1]=arguments[i];for(var a=0,o=n.length;o>a;a++){var s=n[a];if(s)for(var l=t["default"](s),u=0,c=l.length;c>u;u++){var h=l[u];e[h]=s[h]}}return e}e["default"]=r,e.assign=n}),e("ember-metal/mixin",["exports","ember-metal/core","ember-metal/merge","ember-metal/array","ember-metal/platform/create","ember-metal/property_get","ember-metal/property_set","ember-metal/utils","ember-metal/expand_properties","ember-metal/properties","ember-metal/computed","ember-metal/binding","ember-metal/observer","ember-metal/events","ember-metal/streams/utils"],function(e,t,r,n,i,a,o,s,l,u,c,h,m,d,p){function f(){var e,t=this.__nextSuper;if(t){var r=arguments.length;return (this.__nextSuper=null, e=0===r?t.call(this):1===r?t.call(this,arguments[0]):2===r?t.call(this,arguments[0],arguments[1]):t.apply(this,arguments), this.__nextSuper=t, e)}}function v(e){var t=s.meta(e,!0),r=t.mixins;return (r?t.hasOwnProperty("mixins")||(r=t.mixins=i["default"](r)):r=t.mixins={}, r)}function g(e){return"function"==typeof e&&e.isMethod!==!1&&e!==Boolean&&e!==Object&&e!==Number&&e!==Array&&e!==Date&&e!==String}function b(e,t){var r;return t instanceof I?(r=s.guidFor(t),e[r]?G:(e[r]=t,t.properties)):t}function y(e,t,r,n){var i;return (i=r[e]||n[e], t[e]&&(i=i?i.concat(t[e]):t[e]), i)}function _(e,t,r,n,a,o){var l;if(void 0===n[t]&&(l=a[t]),!l){var u=o[t],h=null!==u&&"object"==typeof u&&u.isDescriptor?u:void 0;l=h}return void 0!==l&&l instanceof c.ComputedProperty?(r=i["default"](r),r._getter=s.wrap(r._getter,l._getter),l._setter&&(r._setter?r._setter=s.wrap(r._setter,l._setter):r._setter=l._setter),r):r}function w(e,t,r,n,i){var a;if(void 0===i[t]&&(a=n[t]),a=a||e[t],void 0===a||"function"!=typeof a)return r;var o;return (Q&&(o=r.__hasSuper,void 0===o&&(o=r.toString().indexOf("_super")>-1,r.__hasSuper=o)), Q===!1||o?s.wrap(r,a):r)}function x(e,t,r,n){var i=n[t]||e[t];return i?"function"==typeof i.concat?null===r||void 0===r?i:i.concat(r):s.makeArray(i).concat(r):s.makeArray(r)}function C(e,t,n,i){var a=i[t]||e[t];if(!a)return n;var o=r["default"]({},a),s=!1;for(var l in n)if(n.hasOwnProperty(l)){var u=n[l];g(u)?(s=!0,o[l]=w(e,l,u,a,{})):o[l]=u}return (s&&(o._super=f), o)}function k(e,t,r,i,a,o,s,l){if(r instanceof u.Descriptor){if(r===q&&a[t])return G;r._getter&&(r=_(i,t,r,o,a,e)),a[t]=r,o[t]=void 0}else s&&n.indexOf.call(s,t)>=0||"concatenatedProperties"===t||"mergedProperties"===t?r=x(e,t,r,o):l&&n.indexOf.call(l,t)>=0?r=C(e,t,r,o):g(r)&&(r=w(e,t,r,o,a)),a[t]=void 0,o[t]=r}function E(e,t,r,i,a,o){function l(e){delete r[e],delete i[e]}for(var u,c,h,m,d,p,f=0,v=e.length;v>f;f++)if(u=e[f],c=b(t,u),c!==G)if(c){p=s.meta(a),a.willMergeMixin&&a.willMergeMixin(c),m=y("concatenatedProperties",c,i,a),d=y("mergedProperties",c,i,a);for(h in c)c.hasOwnProperty(h)&&(o.push(h),k(a,h,c[h],p,r,i,m,d));c.hasOwnProperty("toString")&&(a.toString=c.toString)}else u.mixins&&(E(u.mixins,t,r,i,a,o),u._without&&n.forEach.call(u._without,l))}function A(e,t,r,n){if(Y.test(t)){var a=n.bindings;a?n.hasOwnProperty("bindings")||(a=n.bindings=i["default"](n.bindings)):a=n.bindings={},a[t]=r}}function N(e,t,r){var n=function(r){m._suspendObserver(e,t,null,s,function(){o.trySet(e,t,r.value())})},s=function(){r.setValue(a.get(e,t),n)};o.set(e,t,r.value()),m.addObserver(e,t,null,s),r.subscribe(n),void 0===e._streamBindingSubscriptions&&(e._streamBindingSubscriptions=i["default"](null)),e._streamBindingSubscriptions[t]=n}function O(e,t){var r,n,i,a=t.bindings;if(a){for(r in a)if(n=a[r]){if(i=r.slice(0,-7),p.isStream(n)){N(e,i,n);continue}n instanceof h.Binding?(n=n.copy(),n.to(i)):n=new h.Binding(i,n),n.connect(e),e[r]=n}t.bindings={}}}function P(e,t){return (O(e,t||s.meta(e)), e)}function S(e,t,r,n,i){var a,o,s=t.methodName;return (n[s]||i[s]?(a=i[s],t=n[s]):(o=e[s])&&null!==o&&"object"==typeof o&&o.isDescriptor?(t=o,a=void 0):(t=void 0,a=e[s]), {desc:t,value:a})}function T(e,t,r,n,i){var a=r[n];if(a)for(var o=0,s=a.length;s>o;o++)i(e,a[o],null,t)}function R(e,t,r){var n=e[t];"function"==typeof n&&(T(e,t,n,"__ember_observesBefore__",m._removeBeforeObserver),T(e,t,n,"__ember_observes__",m.removeObserver),T(e,t,n,"__ember_listens__",d.removeListener)),"function"==typeof r&&(T(e,t,r,"__ember_observesBefore__",m._addBeforeObserver),T(e,t,r,"__ember_observes__",m.addObserver),T(e,t,r,"__ember_listens__",d.addListener))}function M(e,t,r){var n,i,a,o={},l={},c=s.meta(e),h=[];e._super=f,E(t,v(e),o,l,e,h);for(var m=0,d=h.length;d>m;m++)if(n=h[m],"constructor"!==n&&l.hasOwnProperty(n)&&(a=o[n],i=l[n],a!==q)){for(;a&&a instanceof F;){var p=S(e,a,c,o,l);a=p.desc,i=p.value}(void 0!==a||void 0!==i)&&(R(e,n,i),A(e,n,i,c),u.defineProperty(e,n,a,i,c))}return (r||P(e,c), e)}function D(e){for(var t=arguments.length,r=Array(t>1?t-1:0),n=1;t>n;n++)r[n-1]=arguments[n];return (M(e,r,!1), e)}function I(e,t){this.properties=t;var r=e&&e.length;if(r>0){for(var n=new Array(r),i=0;r>i;i++){var a=e[i];a instanceof I?n[i]=a:n[i]=new I(void 0,a)}this.mixins=n}else this.mixins=void 0;this.ownerConstructor=void 0}function V(e,t,r){var n=s.guidFor(e);if(r[n])return!1;if(r[n]=!0,e===t)return!0;for(var i=e.mixins,a=i?i.length:0;--a>=0;)if(V(i[a],t,r))return!0;return!1}function j(e,t,r){if(!r[s.guidFor(t)])if(r[s.guidFor(t)]=!0,t.properties){var i=t.properties;for(var a in i)i.hasOwnProperty(a)&&(e[a]=!0)}else t.mixins&&n.forEach.call(t.mixins,function(t){j(e,t,r)})}function L(){return q}function F(e){this.isDescriptor=!0,this.methodName=e}function B(e){return new F(e)}function H(){for(var e=arguments.length,r=Array(e),n=0;e>n;n++)r[n]=arguments[n];var i,a=r.slice(-1)[0],o=function(e){i.push(e)},s=r.slice(0,-1);"function"!=typeof a&&(a=r[0],s=r.slice(1)),i=[];for(var u=0;ue;e++){arguments[e]}return H.apply(this,arguments)}function U(){for(var e=arguments.length,r=Array(e),n=0;e>n;n++)r[n]=arguments[n];var i,a=r.slice(-1)[0],o=function(e){i.push(e)},s=r.slice(0,-1);"function"!=typeof a&&(a=r[0],s=r.slice(1)),i=[];for(var u=0;u-1,Y=/^.+Binding$/;e["default"]=I,I._apply=M,I.applyPartial=function(e){var t=W.call(arguments,1);return M(e,t,!0)},I.finishPartial=P,t["default"].anyUnprocessedMixins=!1,I.create=function(){t["default"].anyUnprocessedMixins=!0;for(var e=this,r=arguments.length,n=Array(r),i=0;r>i;i++)n[i]=arguments[i];return new e(n,void 0)};var $=I.prototype;$.reopen=function(){var e;this.properties?(e=new I(void 0,this.properties),this.properties=void 0,this.mixins=[e]):this.mixins||(this.mixins=[]);var t,r=arguments.length,n=this.mixins;for(t=0;r>t;t++)e=arguments[t],e instanceof I?n.push(e):n.push(new I(void 0,e));return this},$.apply=function(e){return M(e,[this],!1)},$.applyPartial=function(e){return M(e,[this],!0)},$.detect=function(e){if(!e)return!1;if(e instanceof I)return V(e,this,{});var t=e.__ember_meta__,r=t&&t.mixins;return r?!!r[s.guidFor(this)]:!1},$.without=function(){for(var e=new I([this]),t=arguments.length,r=Array(t),n=0;t>n;n++)r[n]=arguments[n];return (e._without=r, e)},$.keys=function(){var e={},t={},r=[];j(e,this,t);for(var n in e)e.hasOwnProperty(n)&&r.push(n);return r},I.mixins=function(e){var t=e.__ember_meta__,r=t&&t.mixins,n=[];if(!r)return n;for(var i in r){var a=r[i];a.properties||n.push(a)}return n},e.REQUIRED=q=new u.Descriptor,q.toString=function(){return"(Required Property)"},F.prototype=new u.Descriptor,e.IS_BINDING=Y,e.Mixin=I,e.required=L,e.REQUIRED=q}),e("ember-metal/observer",["exports","ember-metal/watching","ember-metal/array","ember-metal/events"],function(e,t,r,n){"use strict";function i(e){return e+v}function a(e){return e+g}function o(e,r,a,o){return (n.addListener(e,i(r),a,o), t.watch(e,r), this)}function s(e,t){return n.listenersFor(e,i(t))}function l(e,r,a,o){return (t.unwatch(e,r), n.removeListener(e,i(r),a,o), this)}function u(e,r,i,o){return (n.addListener(e,a(r),i,o), t.watch(e,r), this)}function c(e,t,r,i,o){return n.suspendListener(e,a(t),r,i,o)}function h(e,t,r,a,o){return n.suspendListener(e,i(t),r,a,o)}function m(e,t,i,o,s){var l=r.map.call(t,a);return n.suspendListeners(e,l,i,o,s)}function d(e,t,a,o,s){var l=r.map.call(t,i);return n.suspendListeners(e,l,a,o,s)}function p(e,t){return n.listenersFor(e,a(t))}function f(e,r,i,o){return (t.unwatch(e,r), n.removeListener(e,a(r),i,o), this)}e.addObserver=o,e.observersFor=s,e.removeObserver=l,e._addBeforeObserver=u,e._suspendBeforeObserver=c,e._suspendObserver=h,e._suspendBeforeObservers=m,e._suspendObservers=d,e._beforeObserversFor=p,e._removeBeforeObserver=f;var v=":change",g=":before"}),e("ember-metal/observer_set",["exports","ember-metal/utils","ember-metal/events"],function(e,t,r){"use strict";function n(){this.clear()}e["default"]=n,n.prototype.add=function(e,r,n){var i,a=this.observerSet,o=this.observers,s=t.guidFor(e),l=a[s];return (l||(a[s]=l={}), i=l[r], void 0===i&&(i=o.push({sender:e,keyName:r,eventName:n,listeners:[]})-1,l[r]=i), o[i].listeners)},n.prototype.flush=function(){var e,t,n,i,a=this.observers;for(this.clear(),e=0,t=a.length;t>e;++e)n=a[e],i=n.sender,i.isDestroying||i.isDestroyed||r.sendEvent(i,n.eventName,[i,n.keyName],n.listeners)},n.prototype.clear=function(){this.observerSet={},this.observers=[]}}),e("ember-metal/path_cache",["exports","ember-metal/cache"],function(e,t){"use strict";function r(e){return h.get(e)}function n(e){return m.get(e)}function i(e){return d.get(e)}function a(e){return-1!==p.get(e)}function o(e){return f.get(e)}function s(e){return v.get(e)}e.isGlobal=r,e.isGlobalPath=n,e.hasThis=i,e.isPath=a,e.getFirstKey=o,e.getTailPath=s;var l=/^[A-Z$]/,u=/^[A-Z$].*[\.]/,c="this.",h=new t["default"](1e3,function(e){return l.test(e)}),m=new t["default"](1e3,function(e){return u.test(e)}),d=new t["default"](1e3,function(e){return 0===e.lastIndexOf(c,0)}),p=new t["default"](1e3,function(e){return e.indexOf(".")}),f=new t["default"](1e3,function(e){var t=p.get(e);return-1===t?e:e.slice(0,t)}),v=new t["default"](1e3,function(e){var t=p.get(e);return-1!==t?e.slice(t+1):void 0}),g={isGlobalCache:h,isGlobalPathCache:m,hasThisCache:d,firstDotIndexCache:p,firstKeyCache:f,tailPathCache:v};e.caches=g}),e("ember-metal/platform/create",["exports","ember-metal/platform/define_properties"],function(e,t){"REMOVE_USE_STRICT: true";var r;if(!Object.create||Object.create(null).hasOwnProperty){var n,i=!({__proto__:null}instanceof Object);n=i||"undefined"==typeof document?function(){return{__proto__:null}}:function(){function e(){}var t=document.createElement("iframe"),r=document.body||document.documentElement;t.style.display="none",r.appendChild(t),t.src="javascript:";var i=t.contentWindow.Object.prototype;return (r.removeChild(t), t=null, delete i.constructor, delete i.hasOwnProperty, delete i.propertyIsEnumerable, delete i.isPrototypeOf, delete i.toLocaleString, delete i.toString, delete i.valueOf, e.prototype=i, n=function(){return new e}, new e)},r=Object.create=function(e,r){function i(){}var a;if(null===e)a=n();else{if("object"!=typeof e&&"function"!=typeof e)throw new TypeError("Object prototype may only be an Object or null");i.prototype=e,a=new i}return (void 0!==r&&t["default"](a,r), a)}}else r=Object.create;e["default"]=r}),e("ember-metal/platform/define_properties",["exports","ember-metal/platform/define_property"],function(e,t){"use strict";var r=Object.defineProperties;r||(r=function(e,r){for(var n in r)r.hasOwnProperty(n)&&"__proto__"!==n&&t.defineProperty(e,n,r[n]);return e},Object.defineProperties=r),e["default"]=r}),e("ember-metal/platform/define_property",["exports"],function(e){"use strict";var t=function(e){if(e)try{var t=5,r={};if(e(r,"a",{configurable:!0,enumerable:!0,get:function(){return t},set:function(e){t=e}}),5!==r.a)return;if(r.a=10,10!==t)return;e(r,"a",{configurable:!0,enumerable:!1,writable:!0,value:!0});for(var n in r)if("a"===n)return;if(r.a!==!0)return;if(e(r,"a",{enumerable:!1}),r.a!==!0)return;return e}catch(i){return}}(Object.defineProperty),r=!!t;if(r&&"undefined"!=typeof document){var n=function(){try{return (t(document.createElement("div"),"definePropertyOnDOM",{}), !0)}catch(e){}return!1}();n||(e.defineProperty=t=function(e,t,r){var n;return (n="object"==typeof Node?e instanceof Node:"object"==typeof e&&"number"==typeof e.nodeType&&"string"==typeof e.nodeName, n?e[t]=r.value:Object.defineProperty(e,t,r))})}r||(e.defineProperty=t=function(e,t,r){r.get||(e[t]=r.value)});var i=r,a=r;e.hasES5CompliantDefineProperty=r,e.defineProperty=t,e.hasPropertyAccessors=i,e.canDefineNonEnumerableProperties=a}),e("ember-metal/properties",["exports","ember-metal/core","ember-metal/utils","ember-metal/platform/define_property","ember-metal/property_events"],function(e,t,r,n,i){"use strict";function a(){this.isDescriptor=!0}function o(e){return function(e){}}function s(e){return function(){var t=this.__ember_meta__;return t&&t.values[e]}}function l(e,t,o,s,l){var u,c,h,m;l||(l=r.meta(e));var d=l.watching[t];return (u=e[t], c=null!==u&&"object"==typeof u&&u.isDescriptor?u:void 0, h=void 0!==d&&d>0, c&&c.teardown(e,t), o instanceof a?(m=o,e[t]=m,o.setup&&o.setup(e,t)):null==o?(m=s,e[t]=s):(m=o,n.defineProperty(e,t,o)), h&&i.overrideChains(e,t,l), e.didDefineProperty&&e.didDefineProperty(e,t,m), this)}e.Descriptor=a,e.MANDATORY_SETTER_FUNCTION=o,e.DEFAULT_GETTER_FUNCTION=s,e.defineProperty=l}),e("ember-metal/property_events",["exports","ember-metal/utils","ember-metal/events","ember-metal/observer_set"],function(e,t,r,n){"use strict";function i(e,t){var r=e.__ember_meta__,n=r&&r.watching[t]>0||"length"===t,i=r&&r.proto,a=e[t],s=null!==a&&"object"==typeof a&&a.isDescriptor?a:void 0;n&&i!==e&&(s&&s.willChange&&s.willChange(e,t),o(e,t,r),c(e,t,r),v(e,t))}function a(e,t){var r=e.__ember_meta__,n=r&&r.watching[t]>0||"length"===t,i=r&&r.proto,a=e[t],o=null!==a&&"object"==typeof a&&a.isDescriptor?a:void 0;i!==e&&(o&&o.didChange&&o.didChange(e,t),e[b]&&e[b](t),(n||"length"===t)&&(r&&r.deps&&r.deps[t]&&s(e,t,r),h(e,t,r,!1),g(e,t)))}function o(e,t,r){if(!e.isDestroying){var n;if(r&&r.deps&&(n=r.deps[t])){var a=y,o=!a;o&&(a=y={}),u(i,e,n,t,a,r),o&&(y=null)}}}function s(e,t,r){if(!e.isDestroying){var n;if(r&&r.deps&&(n=r.deps[t])){var i=_,o=!i;o&&(i=_={}),u(a,e,n,t,i,r),o&&(_=null)}}}function l(e){var t=[];for(var r in e)t.push(r);return t}function u(e,r,n,i,a,o){var s,u,c,h,m,d=t.guidFor(r),p=a[d];if(p||(p=a[d]={}),!p[i]&&(p[i]=!0,n))for(s=l(n),c=0;cn;n++)o[n].willChange(s);for(n=0,a=s.length;a>n;n+=2)i(s[n],s[n+1])}}function h(e,t,r,n){if(r&&r.hasOwnProperty("chainWatchers")&&r.chainWatchers[t]){var i,o,s=r.chainWatchers[t],l=n?null:[];for(i=0,o=s.length;o>i;i++)s[i].didChange(l);if(!n)for(i=0,o=l.length;o>i;i+=2)a(l[i],l[i+1])}}function m(e,t,r){h(e,t,r,!0)}function d(){C++}function p(){C--,0>=C&&(w.clear(),x.flush())}function f(e,r){d(),t.tryFinally(e,p,r)}function v(e,t){if(!e.isDestroying){var n,i,a=t+":before";C?(n=w.add(e,t,a),i=r.accumulateListeners(e,a,n),r.sendEvent(e,a,[e,t],i)):r.sendEvent(e,a,[e,t])}}function g(e,t){if(!e.isDestroying){var n,i=t+":change";C?(n=x.add(e,t,i),r.accumulateListeners(e,i,n)):r.sendEvent(e,i,[e,t])}}var b=t.symbol("PROPERTY_DID_CHANGE");e.PROPERTY_DID_CHANGE=b;var y,_,w=new n["default"],x=new n["default"],C=0;e.propertyWillChange=i,e.propertyDidChange=a,e.overrideChains=m,e.beginPropertyChanges=d,e.endPropertyChanges=p,e.changeProperties=f}),e("ember-metal/property_get",["exports","ember-metal/core","ember-metal/error","ember-metal/path_cache","ember-metal/platform/define_property","ember-metal/is_none"],function(e,t,r,n,i,a){"use strict";function o(e,r){if(""===r)return e;if(r||"string"!=typeof e||(r=e,e=t["default"].lookup),a["default"](e))return u(e,r);var i,o=(e.__ember_meta__,e[r]),s=null!==o&&"object"==typeof o&&o.isDescriptor?o:void 0;return void 0===s&&n.isPath(r)?u(e,r):s?s.get(e,r):(i=e[r],void 0!==i||"object"!=typeof e||r in e||"function"!=typeof e.unknownProperty?i:e.unknownProperty(r))}function s(e,r){var i,a=n.hasThis(r),s=!a&&n.isGlobal(r);return e||s?(a&&(r=r.slice(5)),(!e||s)&&(e=t["default"].lookup),s&&n.isPath(r)&&(i=r.match(h)[0],e=o(e,i),r=r.slice(i.length+1)),l(r),[e,r]):[void 0,""]}function l(e){if(!e||0===e.length)throw new r["default"]("Object in path "+e+" could not be found or was destroyed.")}function u(e,t){var r,i,a,l,u;for(r=n.hasThis(t),(!e||r)&&(a=s(e,t),e=a[0],t=a[1],a.length=0),i=t.split("."),u=i.length,l=0;null!=e&&u>l;l++)if(e=o(e,i[l]),e&&e.isDestroyed)return;return e}function c(e,t,r){var n=o(e,t);return void 0===n?r:n}e.get=o,e.normalizeTuple=s,e._getPath=u,e.getWithDefault=c;var h=/^([^\.]+)/;e["default"]=o}),e("ember-metal/property_set",["exports","ember-metal/core","ember-metal/property_get","ember-metal/property_events","ember-metal/properties","ember-metal/error","ember-metal/path_cache","ember-metal/platform/define_property"],function(e,t,r,n,i,a,o,s){"use strict";function l(e,r,i,a){if("string"==typeof e&&(i=r,r=e,e=t["default"].lookup),e===t["default"].lookup)return u(e,r,i,a);var s,l,c;e&&(s=e.__ember_meta__,l=e[r],c=null!==l&&"object"==typeof l&&l.isDescriptor?l:void 0);var h,m;if((!e||void 0===c)&&o.isPath(r))return u(e,r,i,a);if(c)c.set(e,r,i);else{if(null!==e&&void 0!==i&&"object"==typeof e&&e[r]===i)return i;h="object"==typeof e&&!(r in e),h&&"function"==typeof e.setUnknownProperty?e.setUnknownProperty(r,i):s&&s.watching[r]>0?(s.proto!==e&&(m=e[r]),i!==m&&(n.propertyWillChange(e,r),e[r]=i,n.propertyDidChange(e,r))):(e[r]=i,e[n.PROPERTY_DID_CHANGE]&&e[n.PROPERTY_DID_CHANGE](r))}return i}function u(e,t,n,i){var o;if(o=t.slice(t.lastIndexOf(".")+1),t=t===o?o:t.slice(0,t.length-(o.length+1)),"this"!==t&&(e=r._getPath(e,t)),!o||0===o.length)throw new a["default"]("Property set failed: You passed an empty path");if(!e){if(i)return;throw new a["default"]('Property set failed: object in path "'+t+'" could not be found or was destroyed.')}return l(e,o,n)}function c(e,t,r){return l(e,t,r,!0)}e.set=l,e.trySet=c}),e("ember-metal/run_loop",["exports","ember-metal/core","ember-metal/utils","ember-metal/array","ember-metal/property_events","backburner"],function(e,t,r,n,i,a){"use strict";function o(e){l.currentRunLoop=e}function s(e,t){l.currentRunLoop=t}function l(){return c.run.apply(c,arguments)}function u(){!l.currentRunLoop}var c=new a["default"](["sync","actions","destroy"],{GUID_KEY:r.GUID_KEY,sync:{before:i.beginPropertyChanges, +after:i.endPropertyChanges},defaultQueue:"actions",onBegin:o,onEnd:s,onErrorTarget:t["default"],onErrorMethod:"onerror"});e["default"]=l,l.join=function(){return c.join.apply(c,arguments)},l.bind=function(){for(var e=arguments.length,t=Array(e),r=0;e>r;r++)t[r]=arguments[r];return function(){for(var e=arguments.length,r=Array(e),n=0;e>n;n++)r[n]=arguments[n];return l.join.apply(l,t.concat(r))}},l.backburner=c,l.currentRunLoop=null,l.queues=c.queueNames,l.begin=function(){c.begin()},l.end=function(){c.end()},l.schedule=function(){u(),c.schedule.apply(c,arguments)},l.hasScheduledTimers=function(){return c.hasTimers()},l.cancelTimers=function(){c.cancelTimers()},l.sync=function(){c.currentInstance&&c.currentInstance.queues.sync.flush()},l.later=function(){return c.later.apply(c,arguments)},l.once=function(){u();for(var e=arguments.length,t=Array(e),r=0;e>r;r++)t[r]=arguments[r];return (t.unshift("actions"), c.scheduleOnce.apply(c,t))},l.scheduleOnce=function(){return (u(), c.scheduleOnce.apply(c,arguments))},l.next=function(){for(var e=arguments.length,t=Array(e),r=0;e>r;r++)t[r]=arguments[r];return (t.push(1), c.later.apply(c,t))},l.cancel=function(e){return c.cancel(e)},l.debounce=function(){return c.debounce.apply(c,arguments)},l.throttle=function(){return c.throttle.apply(c,arguments)},l._addQueue=function(e,t){-1===n.indexOf.call(l.queues,e)&&l.queues.splice(n.indexOf.call(l.queues,t)+1,0,e)}}),e("ember-metal/set_properties",["exports","ember-metal/property_events","ember-metal/property_set","ember-metal/keys"],function(e,t,r,n){"use strict";function i(e,i){return i&&"object"==typeof i?(t.changeProperties(function(){for(var t,a=n["default"](i),o=0,s=a.length;s>o;o++)t=a[o],r.set(e,t,i[t])}),e):e}e["default"]=i}),e("ember-metal/streams/conditional",["exports","ember-metal/streams/stream","ember-metal/streams/utils","ember-metal/platform/create"],function(e,t,r,n){"use strict";function i(e,t,n){return r.isStream(e)?new a(e,t,n):e?t:n}function a(e,t,r){this.init(),this.oldTestResult=void 0,this.test=e,this.consequent=t,this.alternate=r}e["default"]=i,a.prototype=n["default"](t["default"].prototype),a.prototype.compute=function(){var e=this.oldTestResult,t=!!r.read(this.test);if(t!==e){switch(e){case!0:r.unsubscribe(this.consequent,this.notify,this);break;case!1:r.unsubscribe(this.alternate,this.notify,this);break;case void 0:r.subscribe(this.test,this.notify,this)}switch(t){case!0:r.subscribe(this.consequent,this.notify,this);break;case!1:r.subscribe(this.alternate,this.notify,this)}this.oldTestResult=t}return t?r.read(this.consequent):r.read(this.alternate)}}),e("ember-metal/streams/dependency",["exports","ember-metal/core","ember-metal/merge","ember-metal/streams/utils"],function(e,t,r,n){"use strict";function i(e,t){this.next=null,this.prev=null,this.depender=e,this.dependee=t,this.unsubscription=null}r["default"](i.prototype,{subscribe:function(){this.unsubscription=n.subscribe(this.dependee,this.depender.notify,this.depender)},unsubscribe:function(){this.unsubscription&&(this.unsubscription(),this.unsubscription=null)},replace:function(e){this.dependee!==e&&(this.dependee=e,this.unsubscription&&(this.unsubscribe(),this.subscribe()))},getValue:function(){return n.read(this.dependee)},setValue:function(e){return n.setValue(this.dependee,e)}}),e["default"]=i}),e("ember-metal/streams/key-stream",["exports","ember-metal/core","ember-metal/merge","ember-metal/platform/create","ember-metal/property_get","ember-metal/property_set","ember-metal/observer","ember-metal/streams/stream","ember-metal/streams/utils"],function(e,t,r,n,i,a,o,s,l){"use strict";function u(e,t){var r=c(e,t);this.init(r),this.path=r,this.sourceDep=this.addMutableDependency(e),this.observedObject=null,this.key=t}function c(e,t){return e.label?e.label+"."+t:t}u.prototype=n["default"](s["default"].prototype),r["default"](u.prototype,{compute:function(){var e=this.sourceDep.getValue();return e?i.get(e,this.key):void 0},setValue:function(e){var t=this.sourceDep.getValue();t&&a.set(t,this.key,e)},setSource:function(e){this.sourceDep.replace(e),this.notify()},_super$revalidate:s["default"].prototype.revalidate,revalidate:function(e){this._super$revalidate(e);var t=this.sourceDep.getValue();t!==this.observedObject&&(this._clearObservedObject(),t&&"object"==typeof t&&(o.addObserver(t,this.key,this,this.notify),this.observedObject=t))},_super$deactivate:s["default"].prototype.deactivate,_clearObservedObject:function(){this.observedObject&&(o.removeObserver(this.observedObject,this.key,this,this.notify),this.observedObject=null)},deactivate:function(){this._super$deactivate(),this._clearObservedObject()}}),e["default"]=u}),e("ember-metal/streams/proxy-stream",["exports","ember-metal/merge","ember-metal/streams/stream","ember-metal/platform/create"],function(e,t,r,n){"use strict";function i(e,t){this.init(t),this.sourceDep=this.addMutableDependency(e)}i.prototype=n["default"](r["default"].prototype),t["default"](i.prototype,{compute:function(){return this.sourceDep.getValue()},setValue:function(e){this.sourceDep.setValue(e)},setSource:function(e){this.sourceDep.replace(e),this.notify()}}),e["default"]=i}),e("ember-metal/streams/stream",["exports","ember-metal/core","ember-metal/platform/create","ember-metal/path_cache","ember-metal/observer","ember-metal/streams/utils","ember-metal/streams/subscriber","ember-metal/streams/dependency"],function(e,t,r,n,i,a,o,s){"use strict";function l(e,t){this.init(t),this.compute=e}function u(e){return void 0===e?"(no label)":e}var c,h;l.prototype={isStream:!0,init:function(e){this.label=u(e),this.isActive=!1,this.isDirty=!0,this.isDestroyed=!1,this.cache=void 0,this.children=void 0,this.subscriberHead=null,this.subscriberTail=null,this.dependencyHead=null,this.dependencyTail=null,this.observedProxy=null},_makeChildStream:function(e){return new(c=c||t["default"].__loader.require("ember-metal/streams/key-stream")["default"])(this,e)},removeChild:function(e){delete this.children[e]},getKey:function(e){void 0===this.children&&(this.children=r["default"](null));var t=this.children[e];return (void 0===t&&(t=this._makeChildStream(e),this.children[e]=t), t)},get:function(e){var t=n.getFirstKey(e),i=n.getTailPath(e);void 0===this.children&&(this.children=r["default"](null));var a=this.children[t];return (void 0===a&&(a=this._makeChildStream(t,e),this.children[t]=a), void 0===i?a:a.get(i))},value:function(){this.isActive||(this.isDirty=!0);var e=!1;return(!this.isActive&&this.subscriberHead&&(this.activate(),e=!0), this.isDirty&&(this.isActive&&(e=!0),this.cache=this.compute(),this.isDirty=!1), e&&this.revalidate(this.cache), this.cache)},addMutableDependency:function(e){var t=new s["default"](this,e);if(this.isActive&&t.subscribe(),null===this.dependencyHead)this.dependencyHead=this.dependencyTail=t;else{var r=this.dependencyTail;r.next=t,t.prev=r,this.dependencyTail=t}return t},addDependency:function(e){a.isStream(e)&&this.addMutableDependency(e)},subscribeDependencies:function(){for(var e=this.dependencyHead;e;){var t=e.next;e.subscribe(),e=t}},unsubscribeDependencies:function(){for(var e=this.dependencyHead;e;){var t=e.next;e.unsubscribe(),e=t}},maybeDeactivate:function(){!this.subscriberHead&&this.isActive&&(this.isActive=!1,this.unsubscribeDependencies(),this.deactivate())},activate:function(){this.isActive=!0,this.subscribeDependencies()},revalidate:function(e){e!==this.observedProxy&&(this._clearObservedProxy(),h=h||t["default"].__loader.require("ember-runtime/mixins/-proxy")["default"],h.detect(e)&&(i.addObserver(e,"content",this,this.notify),this.observedProxy=e))},_clearObservedProxy:function(){this.observedProxy&&(i.removeObserver(this.observedProxy,"content",this,this.notify),this.observedProxy=null)},deactivate:function(){this._clearObservedProxy()},compute:function(){throw new Error("Stream error: compute not implemented")},setValue:function(){throw new Error("Stream error: setValue not implemented")},notify:function(){this.notifyExcept()},notifyExcept:function(e,t){this.isDirty||(this.isDirty=!0,this.notifySubscribers(e,t))},subscribe:function(e,t){var r=new o["default"](e,t,this);if(null===this.subscriberHead)this.subscriberHead=this.subscriberTail=r;else{var n=this.subscriberTail;n.next=r,r.prev=n,this.subscriberTail=r}var i=this;return function(e){r.removeFrom(i),e&&i.prune()}},prune:function(){null===this.subscriberHead&&this.destroy(!0)},unsubscribe:function(e,t){for(var r=this.subscriberHead;r;){var n=r.next;r.callback===e&&r.context===t&&r.removeFrom(this),r=n}},notifySubscribers:function(e,t){for(var r=this.subscriberHead;r;){var n=r.next,i=r.callback,a=r.context;r=n,(i!==e||a!==t)&&(void 0===a?i(this):i.call(a,this))}},destroy:function(e){if(!this.isDestroyed){this.isDestroyed=!0,this.subscriberHead=this.subscriberTail=null,this.maybeDeactivate();var t=this.dependencies;if(t)for(var r=0,n=t.length;n>r;r++)t[r](e);return (this.dependencies=null, !0)}}},l.wrap=function(e,t,r){return a.isStream(e)?e:new t(e,r)},e["default"]=l}),e("ember-metal/streams/subscriber",["exports","ember-metal/merge"],function(e,t){"use strict";function r(e,t){this.next=null,this.prev=null,this.callback=e,this.context=t}t["default"](r.prototype,{removeFrom:function(e){var t=this.next,r=this.prev;r?r.next=t:e.subscriberHead=t,t?t.prev=r:e.subscriberTail=r,e.maybeDeactivate()}}),e["default"]=r}),e("ember-metal/streams/utils",["exports","./stream"],function(e,t){"use strict";function r(e){return e&&e.isStream}function n(e,t,r){return e&&e.isStream?e.subscribe(t,r):void 0}function i(e,t,r){e&&e.isStream&&e.unsubscribe(t,r)}function a(e){return e&&e.isStream?e.value():e}function o(e){for(var t=e.length,r=new Array(t),n=0;t>n;n++)r[n]=a(e[n]);return r}function s(e){var t={};for(var r in e)t[r]=a(e[r]);return t}function l(e){for(var t=e.length,n=!1,i=0;t>i;i++)if(r(e[i])){n=!0;break}return n}function u(e){var t=!1;for(var n in e)if(r(e[n])){t=!0;break}return t}function c(e,r){var n=l(e);if(n){var i,a,s=new t["default"](function(){return c(o(e),r)},function(){var t=h(e);return"concat(["+t.join(", ")+"]; separator="+p(r)+")"});for(i=0,a=e.length;a>i;i++)s.addDependency(e[i]);return (s.isConcat=!0, s)}return e.join(r)}function h(e){for(var t=[],r=0,n=e.length;n>r;r++){var i=e[r];t.push(d(i))}return t}function m(e){var t=[];for(var r in e)t.push(r+": "+p(e[r]));return t.length?"{ "+t.join(", ")+" }":"{}"}function d(e){if(r(e)){var t=e;return"function"==typeof t.label?t.label():t.label}return p(e)}function p(e){switch(typeof e){case"string":return'"'+e+'"';case"object":return"{ ... }";case"function":return"function() { ... }";default:return String(e)}}function f(e,r){var n=new t["default"](function(){return e.value()||r.value()},function(){return d(e)+" || "+d(r)});return (n.addDependency(e), n.addDependency(r), n)}function v(e,t){r(e)&&e.addDependency(t)}function g(e,r,n){for(var i=new t["default"](function(){var t=o(e);return r?r(t):t},function(){return n+"("+h(e)+")"}),a=0,s=e.length;s>a;a++)i.addDependency(e[a]);return i}function b(e,r,n){var i=new t["default"](function(){var t=s(e);return r?r(t):t},function(){return n+"("+m(e)+")"});for(var a in e)i.addDependency(e[a]);return i}function y(e,n,i){if(r(e)){var a=new t["default"](n,function(){return i+"("+d(e)+")"});return (a.addDependency(e), a)}return n()}function _(e,t){e&&e.isStream&&e.setValue(t)}e.isStream=r,e.subscribe=n,e.unsubscribe=i,e.read=a,e.readArray=o,e.readHash=s,e.scanArray=l,e.scanHash=u,e.concat=c,e.labelsFor=h,e.labelsForObject=m,e.labelFor=d,e.or=f,e.addDependency=v,e.zip=g,e.zipHash=b,e.chain=y,e.setValue=_}),e("ember-metal/symbol",["exports"],function(e){"use strict"}),e("ember-metal/utils",["exports","ember-metal/core","ember-metal/platform/create","ember-metal/platform/define_property"],function(e,t,r,n){function i(){return++w}function a(e){var t={};t[e]=1;for(var r in t)if(r===e)return r;return e}function o(e){return a(e+" [id="+E+Math.floor(Math.random()*new Date)+"]")}function s(e,t){t||(t=x);var r=t+i();return (e&&(null===e[E]?e[E]=r:(A.value=r,e.__defineNonEnumerable?e.__defineNonEnumerable(T):n.defineProperty(e,E,A))), r)}function l(e){if(e&&e[E])return e[E];if(void 0===e)return"(undefined)";if(null===e)return"(null)";var t,r=typeof e;switch(r){case"number":return (t=C[e], t||(t=C[e]="nu"+e), t);case"string":return (t=k[e], t||(t=k[e]="st"+i()), t);case"boolean":return e?"(true)":"(false)";default:return e===Object?"(Object)":e===Array?"(Array)":(t=x+i(),null===e[E]?e[E]=t:(A.value=t,e.__defineNonEnumerable?e.__defineNonEnumerable(T):n.defineProperty(e,E,A)),t)}}function u(e){this.watching={},this.cache=void 0,this.cacheMeta=void 0,this.source=e,this.deps=void 0,this.listeners=void 0,this.mixins=void 0,this.bindings=void 0,this.chains=void 0,this.values=void 0,this.proto=void 0}function c(e,t){var i=e.__ember_meta__;return t===!1?i||D:(i?i.source!==e&&(e.__defineNonEnumerable?e.__defineNonEnumerable(S):n.defineProperty(e,"__ember_meta__",P),i=r["default"](i),i.watching=r["default"](i.watching),i.cache=void 0,i.cacheMeta=void 0,i.source=e,e.__ember_meta__=i):(n.canDefineNonEnumerableProperties&&(e.__defineNonEnumerable?e.__defineNonEnumerable(S):n.defineProperty(e,"__ember_meta__",P)),i=new u(e),e.__ember_meta__=i),i)}function h(e,t){var r=c(e,!1);return r[t]}function m(e,t,r){var n=c(e,!0);return (n[t]=r, r)}function d(e,t,n){for(var i,a,o=c(e,n),s=0,l=t.length;l>s;s++){if(i=t[s],a=o[i]){if(a.__ember_source__!==e){if(!n)return;a=o[i]=r["default"](a),a.__ember_source__=e}}else{if(!n)return;a=o[i]={__ember_source__:e}}o=a}return a}function p(e,t){function r(){var r,n=this&&this.__nextSuper,i=arguments.length;if(this&&(this.__nextSuper=t),0===i)r=e.call(this);else if(1===i)r=e.call(this,arguments[0]);else if(2===i)r=e.call(this,arguments[0],arguments[1]);else{for(var a=new Array(i),o=0;i>o;o++)a[o]=arguments[o];r=y(this,e,a)}return (this&&(this.__nextSuper=n), r)}return (r.wrappedFunction=e, r.__ember_observes__=e.__ember_observes__, r.__ember_observesBefore__=e.__ember_observesBefore__, r.__ember_listens__=e.__ember_listens__, r)}function f(e,t){return!(!e||"function"!=typeof e[t])}function v(e,t,r){return f(e,t)?r?_(e,t,r):_(e,t):void 0}function g(e){return null===e||void 0===e?[]:B(e)?e:[e]}function b(e){if(null===e)return"null";if(void 0===e)return"undefined";if(B(e))return"["+e+"]";if("object"!=typeof e)return""+e;if("function"==typeof e.toString&&e.toString!==F)return e.toString();var t,r=[];for(var n in e)if(e.hasOwnProperty(n)){if(t=e[n],"toString"===t)continue;"function"==typeof t&&(t="function() { ... }"),t&&"function"!=typeof t.toString?r.push(n+": "+F.call(t)):r.push(n+": "+t)}return"{"+r.join(", ")+"}"}function y(e,t,r){var n=r&&r.length;if(!r||!n)return t.call(e);switch(n){case 1:return t.call(e,r[0]);case 2:return t.call(e,r[0],r[1]);case 3:return t.call(e,r[0],r[1],r[2]);case 4:return t.call(e,r[0],r[1],r[2],r[3]);case 5:return t.call(e,r[0],r[1],r[2],r[3],r[4]);default:return t.apply(e,r)}}function _(e,t,r){var n=r&&r.length;if(!r||!n)return e[t]();switch(n){case 1:return e[t](r[0]);case 2:return e[t](r[0],r[1]);case 3:return e[t](r[0],r[1],r[2]);case 4:return e[t](r[0],r[1],r[2],r[3]);case 5:return e[t](r[0],r[1],r[2],r[3],r[4]);default:return e[t].apply(e,r)}}e.uuid=i,e.symbol=o,e.generateGuid=s,e.guidFor=l,e.getMeta=h,e.setMeta=m,e.metaPath=d,e.wrap=p,e.tryInvoke=v,e.makeArray=g,e.inspect=b,e.apply=y,e.applyStr=_;var w=0,x="ember",C=[],k={},E=a("__ember"+ +new Date),A={writable:!0,configurable:!0,enumerable:!1,value:null};e.GUID_DESC=A;var N={configurable:!0,writable:!0,enumerable:!1,value:void 0},O={configurable:!0,writable:!0,enumerable:!1,value:null},P={writable:!0,configurable:!0,enumerable:!1,value:null},S={name:"__ember_meta__",descriptor:P};e.EMBER_META_PROPERTY=S;var T={name:E,descriptor:O};e.GUID_KEY_PROPERTY=T;var R={name:"__nextSuper",descriptor:N};e.NEXT_SUPER_PROPERTY=R,u.prototype={chainWatchers:null},n.canDefineNonEnumerableProperties||(u.prototype.__preventPlainObject__=!0,u.prototype.toJSON=function(){});var M,D=new u(null),I=function(){var e=0;try{try{}finally{throw (e++, new Error("needsFinallyFixTest"))}}catch(t){}return 1!==e}();I?e.tryFinally=M=function(e,t,r){var n,i,a;r=r||this;try{n=e.call(r)}finally{try{i=t.call(r)}catch(o){a=o}}if(a)throw a;return void 0===i?n:i}:e.tryFinally=M=function(e,t,r){var n,i;r=r||this;try{n=e.call(r)}finally{i=t.call(r)}return void 0===i?n:i};var V,j=function(){return M.apply(this,arguments)};I?e.tryCatchFinally=V=function(e,t,r,n){var i,a,o;n=n||this;try{i=e.call(n)}catch(s){i=t.call(n,s)}finally{try{a=r.call(n)}catch(l){o=l}}if(o)throw o;return void 0===a?i:a}:e.tryCatchFinally=V=function(e,t,r,n){var i,a;n=n||this;try{i=e.call(n)}catch(o){i=t.call(n,o)}finally{a=r.call(n)}return void 0===a?i:a};var L=function(){return V.apply(this,arguments)},F=Object.prototype.toString,B=Array.isArray||function(e){return null!==e&&void 0!==e&&"object"==typeof e&&"number"==typeof e.length&&"[object Array]"===F.call(e)};e.GUID_KEY=E,e.META_DESC=P,e.EMPTY_META=D,e.meta=c,e.isArray=B,e.makeArray=g,e.tryCatchFinally=V,e.deprecatedTryCatchFinally=L,e.canInvoke=f,e.tryFinally=M,e.deprecatedTryFinally=j}),e("ember-metal/watch_key",["exports","ember-metal/core","ember-metal/utils","ember-metal/platform/define_property","ember-metal/properties"],function(e,t,r,n,i){"use strict";function a(e,t,n){if("length"!==t||!r.isArray(e)){var i=n||r.meta(e),a=i.watching;if(a[t])a[t]=(a[t]||0)+1;else{a[t]=1;var o=e[t],s=null!==o&&"object"==typeof o&&o.isDescriptor?o:void 0;s&&s.willWatch&&s.willWatch(e,t),"function"==typeof e.willWatchProperty&&e.willWatchProperty(t)}}}function o(e,t,n){var i=n||r.meta(e),a=i.watching;if(1===a[t]){a[t]=0;var o=e[t],s=null!==o&&"object"==typeof o&&o.isDescriptor?o:void 0;s&&s.didUnwatch&&s.didUnwatch(e,t),"function"==typeof e.didUnwatchProperty&&e.didUnwatchProperty(t)}else a[t]>1&&a[t]--}e.watchKey=a,e.unwatchKey=o}),e("ember-metal/watch_path",["exports","ember-metal/utils","ember-metal/chains"],function(e,t,r){"use strict";function n(e,n){var i=n||t.meta(e),a=i.chains;return (a?a.value()!==e&&(a=i.chains=a.copy(e)):a=i.chains=new r.ChainNode(null,null,e), a)}function i(e,r,i){if("length"!==r||!t.isArray(e)){var a=i||t.meta(e),o=a.watching;o[r]?o[r]=(o[r]||0)+1:(o[r]=1,n(e,a).add(r))}}function a(e,r,i){var a=i||t.meta(e),o=a.watching;1===o[r]?(o[r]=0,n(e,a).remove(r)):o[r]>1&&o[r]--}e.watchPath=i,e.unwatchPath=a}),e("ember-metal/watching",["exports","ember-metal/utils","ember-metal/chains","ember-metal/watch_key","ember-metal/watch_path","ember-metal/path_cache"],function(e,t,r,n,i,a){"use strict";function o(e,r,o){"length"===r&&t.isArray(e)||(a.isPath(r)?i.watchPath(e,r,o):n.watchKey(e,r,o))}function s(e,t){var r=e.__ember_meta__;return(r&&r.watching[t])>0}function l(e,r,o){"length"===r&&t.isArray(e)||(a.isPath(r)?i.unwatchPath(e,r,o):n.unwatchKey(e,r,o))}function u(e){var t,n,i,a,o=e.__ember_meta__;if(o&&(e.__ember_meta__=null,t=o.chains))for(c.push(t);c.length>0;){if(t=c.pop(),n=t._chains)for(i in n)n.hasOwnProperty(i)&&c.push(n[i]);t._watching&&(a=t._object,a&&r.removeChainWatcher(a,t._key,t))}}e.isWatching=s,e.unwatch=l,e.destroy=u,e.watch=o,o.flushPending=r.flushPendingChains;var c=[]}),e("ember-routing-htmlbars",["exports","ember-metal/core","ember-metal/merge","ember-htmlbars/helpers","ember-htmlbars/keywords","ember-routing-htmlbars/helpers/query-params","ember-routing-htmlbars/keywords/action","ember-routing-htmlbars/keywords/element-action","ember-routing-htmlbars/keywords/link-to","ember-routing-htmlbars/keywords/render"],function(e,t,r,n,i,a,o,s,l,u){"use strict";n.registerHelper("query-params",a.queryParamsHelper),i.registerKeyword("action",o["default"]),i.registerKeyword("@element_action",s["default"]),i.registerKeyword("link-to",l["default"]),i.registerKeyword("render",u["default"]);var c=r["default"]({},l["default"]);r["default"](c,{link:function(e,t,r){l["default"].link.call(this,e,t,r)}}),i.registerKeyword("linkTo",c),e["default"]=t["default"]}),e("ember-routing-htmlbars/helpers/query-params",["exports","ember-metal/core","ember-routing/system/query_params"],function(e,t,r){"use strict";function n(e,t){return r["default"].create({values:t})}e.queryParamsHelper=n}),e("ember-routing-htmlbars/keywords/action",["exports","htmlbars-runtime/hooks","ember-routing-htmlbars/keywords/closure-action"],function(e,t,r){"use strict";e["default"]=function(e,n,i,a,o,s,l,u){return e?(t.keyword("@element_action",e,n,i,a,o,s,l,u),!0):r["default"](e,n,i,a,o,s,l,u)}}),e("ember-routing-htmlbars/keywords/closure-action",["exports","ember-metal/streams/stream","ember-metal/array","ember-metal/streams/utils","ember-metal/keys","ember-metal/utils","ember-metal/property_get","ember-metal/error"],function(e,t,r,n,i,a,o,s){"use strict";function l(e,a,o,l,h,m,d,p){return new t["default"](function(){var e=this;r.map.call(l,this.addDependency,this),r.map.call(i["default"](h),function(t){e.addDependency(t)});var t,a,m,d=l[0],p=n.readArray(l.slice(1,l.length));if(d[c])t=d,a=d[c];else if(t=n.read(o.self),a=n.read(d),"string"==typeof a){var f=a;if(a=null,h.target&&(t=n.read(h.target)),t.actions?a=t.actions[f]:t._actions&&(a=t._actions[f]),!a)throw new s["default"]("An action named '"+f+"' was not found in "+t+".")}return (h.value&&(m=n.read(h.value)), u(t,a,m,p))})}function u(e,t,r,n){var i;return (i=n.length>0?function(){var i=n;if(arguments.length>0){var a=Array.prototype.slice.apply(arguments);i=n.concat(a)}return (r&&i.length>0&&(i[0]=o.get(i[0],r)), t.apply(e,i))}:function(){var n=arguments;return (r&&n.length>0&&(n=Array.prototype.slice.apply(n),n[0]=o.get(n[0],r)), t.apply(e,n))}, i[h]=!0, i)}e["default"]=l;var c=a.symbol("INVOKE");e.INVOKE=c;var h=a.symbol("ACTION");e.ACTION=h}),e("ember-routing-htmlbars/keywords/element-action",["exports","ember-metal/core","ember-metal/utils","ember-metal/run_loop","ember-views/streams/utils","ember-views/system/utils","ember-views/system/action_manager"],function(e,t,r,n,i,a,o){"use strict";function s(e,t){}function l(e,t){if("undefined"==typeof t){if(h.test(e.type))return a.isSimpleClick(e);t=""}if(t.indexOf("any")>=0)return!0;for(var r=0,n=c.length;n>r;r++)if(e[c[r]+"Key"]&&-1===t.indexOf(c[r]))return!1;return!0}e["default"]={setupState:function(e,t,r,n,a){var o=t.hooks.get,l=t.hooks.getValue,u=l(n[0]);s("You specified a quoteless path to the {{action}} helper which did not resolve to an action name (a string). Perhaps you meant to use a quoted actionName? (e.g. {{action 'save'}}).","string"==typeof u||"function"==typeof u);for(var c=[],h=1,m=n.length;m>h;h++)c.push(i.readUnwrappedModel(n[h]));var d;return (d=a.target?l("string"==typeof a.target?o(t,r,a.target):a.target):l(r.locals.controller)||l(r.self), {actionName:u,actionArgs:c,target:d})},isStable:function(e,t,r,n,i){return!0},render:function(e,t,n,i,a,o,s,l){var c=t.dom.getAttribute(e.element,"data-ember-action")||r.uuid();u.registerAction({actionId:c,node:e,eventName:a.on||"click",bubbles:a.bubbles,preventDefault:a.preventDefault,withKeyCode:a.withKeyCode,allowedKeys:a.allowedKeys}),e.cleanup=function(){u.unregisterAction(c)},t.dom.setAttribute(e.element,"data-ember-action",c)}};var u={};e.ActionHelper=u,u.registeredActions=o["default"].registeredActions,u.registerAction=function(e){var t=e.actionId,r=e.node,i=e.eventName,a=e.preventDefault,s=e.bubbles,u=e.allowedKeys,c=o["default"].registeredActions[t];return (c||(c=o["default"].registeredActions[t]=[]), c.push({eventName:i,handler:function(e){if(!l(e,u))return!0;a!==!1&&e.preventDefault(),s===!1&&e.stopPropagation();var t=r.state,i=t.target,o=t.actionName,c=t.actionArgs;n["default"](function(){return"function"==typeof o?void o.apply(i,c):void(i.send?i.send.apply(i,[o].concat(c)):i[o].apply(i,c))})}}), t)},u.unregisterAction=function(e){delete o["default"].registeredActions[e]};var c=["alt","shift","meta","ctrl"],h=/^click|mouse|touch/}),e("ember-routing-htmlbars/keywords/link-to",["exports","ember-metal/streams/utils","ember-metal/core","ember-metal/merge"],function(e,t,r,n){"use strict";e["default"]={link:function(e,t,r){},render:function(e,r,i,a,o,s,l,u){var c=n["default"]({},o);c.params=t.readArray(a),c.view=r.view,c.hasBlock=!!s,c.escaped=!e.parseTextAsHTML,r.hooks.component(e,r,i,"-link-to",a,c,{"default":s},u)},rerender:function(e,t,r,n,i,a,o,s){this.render(e,t,r,n,i,a,o,s)}}}),e("ember-routing-htmlbars/keywords/render",["exports","ember-metal/core","ember-metal/property_get","ember-metal/error","ember-metal/platform/create","ember-metal/streams/utils","ember-runtime/system/string","ember-routing/system/generate_controller","ember-htmlbars/node-managers/view-node-manager"],function(e,t,r,n,i,a,o,s,l){"use strict";function u(e,t){var r=t.view.ownerView;if(r&&r.outletState){var n=r.outletState;if(n.main){var a=n.main.outlets.__ember_orphans__;if(a){var o=a.outlets[e];if(o){var s=i["default"](null);return (s[o.render.outlet]=o, o.wasUsed=!0, s)}}}}}function c(e,t){if(!e&&!t)return!0;if(!e||!t)return!1;for(var r in e)if(!h(e[r],t[r]))return!1;return!0}function h(e,t){if(!e&&!t)return!0;if(!e||!t)return!1;e=e.render,t=t.render;for(var r in e)if(e.hasOwnProperty(r)&&e[r]!==t[r]&&"name"!==r)return!1;return!0}e["default"]={willRender:function(e,t){t.view.ownerView._outlets&&t.view.ownerView._outlets.push(e)},setupState:function(e,t,r,n,i){var a=n[0];return{parentView:t.view,manager:e.manager,controller:e.controller,childOutletState:u(a,t)}},childEnv:function(e,t){return t.childWithOutletState(e.childOutletState)},isStable:function(e,t){return c(e.childOutletState,t.childOutletState)},isEmpty:function(e){return!1},render:function(e,t,i,u,c,h,m,d){var p=e.state,f=u[0],v=u[1],g=t.container,b=g.lookup("router:main");if(1===u.length);else if(2!==u.length)throw new n["default"]("You must pass a templateName to render");f=f.replace(/\//g,".");var y="template:"+f,_=g.lookup("view:"+f);_||(_=g.lookup("view:default"));var w=_&&!!r.get(_,"template");h||w||(h=g.lookup(y)),_&&(_.ownerView=t.view.ownerView);var x,C;c.controller?(x=c.controller,C="controller:"+x,delete c.controller):(x=f,C="controller:"+x);var k,E=a.read(i.locals.controller);if(u.length>1){var A=g.lookupFactory(C)||s.generateControllerFactory(g,x);k=A.create({model:a.read(v),parentController:E,target:E}),e.addDestruction(k)}else k=g.lookup(C)||s["default"](g,x),k.setProperties({target:E,parentController:E});_&&_.set("controller",k),p.controller=k,c.viewName=o.camelize(f),h&&h.raw&&(h=h.raw);var N={layout:null,self:k};_&&(N.component=_);var O=l["default"].create(e,t,c,N,p.parentView,null,null,h);p.manager=O,b&&1===u.length&&b._connectActiveComponentNode(f,O),O.render(t,c,d)},rerender:function(e,t,r,n,i,o,s,l){var u=a.read(n[1]);e.state.controller.set("model",u)}}}),e("ember-routing-views",["exports","ember-metal/core","ember-routing-views/views/link","ember-routing-views/views/outlet"],function(e,t,r,n){"use strict";t["default"].LinkView=r.DeprecatedLinkView,t["default"].LinkComponent=r["default"],t["default"].OutletView=n.OutletView,e["default"]=t["default"]}),e("ember-routing-views/views/link",["exports","ember-metal/core","ember-metal/property_get","ember-metal/computed","ember-views/system/utils","ember-views/views/component","ember-runtime/inject","ember-runtime/mixins/controller","ember-htmlbars/hooks/get-value","ember-htmlbars/templates/link-to"],function(e,t,r,n,i,a,o,s,l,u){"use strict";function c(e,t){if(r.get(e,"loading"))return!1;var n=r.get(e,"currentWhen"),i=!!n;n=n||r.get(e,"targetRouteName"),n=n.split(" ");for(var a=0,o=n.length;o>a;a++)if(m(e,n[a],i,t))return r.get(e,"activeClass");return!1}function h(e){for(var t=0,r=e.length;r>t;t++)if(null==e[t])return!1;return!0}function m(e,t,n,i){var a=r.get(e,"_routing");return a.isActiveForRoute(r.get(e,"models"),r.get(e,"resolvedQueryParams"),t,i,n)}function d(e,t){var r={};if(!e)return r;var n=e.values;for(var i in n)n.hasOwnProperty(i)&&(r[i]=n[i]);return r}u["default"].meta.revision="Ember@1.13.12";var p=["active","loading","disabled"];p=["active","loading","disabled","transitioningIn","transitioningOut"];var f=a["default"].extend({defaultLayout:u["default"],tagName:"a",currentWhen:null,"current-when":null,title:null,rel:null,tabindex:null,target:null,activeClass:"active",loadingClass:"loading",disabledClass:"disabled",_isDisabled:!1,replace:!1,attributeBindings:["href","title","rel","tabindex","target"],classNameBindings:p,eventName:"click",init:function(){this._super.apply(this,arguments);var e=r.get(this,"eventName");this.on(e,this,this._invoke)},_routing:o["default"].service("-routing"),disabled:n.computed({get:function(e,t){return!1},set:function(e,t){return (void 0!==t&&this.set("_isDisabled",t), t?r.get(this,"disabledClass"):!1)}}),active:n.computed("attrs.params","_routing.currentState",function(){var e=r.get(this,"_routing.currentState");return e?c(this,e):!1}),willBeActive:n.computed("_routing.targetState",function(){var e=r.get(this,"_routing"),t=r.get(e,"targetState");return r.get(e,"currentState")!==t?!!c(this,t):void 0}),transitioningIn:n.computed("active","willBeActive",function(){var e=r.get(this,"willBeActive");return"undefined"==typeof e?!1:!r.get(this,"active")&&e&&"ember-transitioning-in"}),transitioningOut:n.computed("active","willBeActive",function(){var e=r.get(this,"willBeActive");return"undefined"==typeof e?!1:r.get(this,"active")&&!e&&"ember-transitioning-out"}),_invoke:function(e){if(!i.isSimpleClick(e))return!0;if(this.attrs.preventDefault!==!1){var n=this.attrs.target;n&&"_self"!==n||e.preventDefault()}if(this.attrs.bubbles===!1&&e.stopPropagation(),r.get(this,"_isDisabled"))return!1;if(r.get(this,"loading"))return (t["default"].Logger.warn("This link-to is in an inactive loading state because at least one of its parameters presently has a null/undefined value, or the provided route name is invalid."), !1);var a=this.attrs.target;if(a&&"_self"!==a)return!1;var o=r.get(this,"_routing"),s=this._handleOnlyQueryParamsSupplied(r.get(this,"targetRouteName")),l=r.get(this,"models"),u=r.get(this,"queryParams.values"),c=r.get(this,"attrs.replace");o.transitionTo(s,l,u,c)},queryParams:null,href:n.computed("models","targetRouteName","_routing.currentState",function(){if("a"===r.get(this,"tagName")){var e=r.get(this,"targetRouteName"),t=r.get(this,"models");if(r.get(this,"loading"))return r.get(this,"loadingHref");e=this._handleOnlyQueryParamsSupplied(e);var n=r.get(this,"_routing");return n.generateURL(e,t,r.get(this,"queryParams.values"))}}),loading:n.computed("models","targetRouteName",function(){var e=r.get(this,"targetRouteName"),t=r.get(this,"models");return h(t)&&null!=e?void 0:r.get(this,"loadingClass")}),_handleOnlyQueryParamsSupplied:function(e){var t=this.attrs.params.slice(),n=t[t.length-1];n&&n.isQueryParams&&t.pop();var i=this.attrs.hasBlock?0===t.length:1===t.length;if(i){var a=this.container.lookup("controller:application");if(a)return r.get(a,"currentRouteName")}return e},loadingHref:"#",willRender:function(){var e,t=this.attrs,r=t.params.slice(),n=r[r.length-1];e=n&&n.isQueryParams?r.pop():{},t.disabledWhen&&this.set("disabled",l["default"](t.disabledWhen));var i=l["default"](t["current-when"]);t.currentWhen&&(i=t.currentWhen),i&&this.set("currentWhen",i),t.hasBlock||this.set("linkTitle",r.shift());for(var a=0;ai;i++){var o=r.slice(0,i+1).join(".");if(0!==t.indexOf(o))break;n=o}return n}s["default"].reopen({concatenatedProperties:["queryParams"],init:function(){this._super.apply(this,arguments),u(this)},queryParams:null,_qpDelegate:null,_normalizedQueryParams:i.computed(function(){var e=a.meta(this);if(e.proto!==this)return r.get(e.proto,"_normalizedQueryParams");var t=r.get(this,"queryParams");if(t._qpMap)return t._qpMap;for(var n=t._qpMap={},i=0,o=t.length;o>i;++i)l(t[i],n);return n}),_cacheMeta:i.computed(function(){var e=a.meta(this);if(e.proto!==this)return r.get(e.proto,"_cacheMeta");var t={},n=r.get(this,"_normalizedQueryParams");for(var i in n)if(n.hasOwnProperty(i)){var o,s=n[i],l=s.scope;"controller"===l&&(o=[]),t[i]={parts:o,values:null,scope:l,prefix:"",def:r.get(this,i)}}return t}),_updateCacheParams:function(e){var t=r.get(this,"_cacheMeta");for(var i in t)if(t.hasOwnProperty(i)){var a=t[i];a.values=e;var o=this._calculateCacheKey(a.prefix,a.parts,a.values),s=this._bucketCache;if(s){var l=s.lookup(o,i,a.def);n.set(this,i,l)}}},_qpChanged:function(e,t){var n=t.substr(0,t.length-3),i=r.get(e,"_cacheMeta"),a=i[n],o=e._calculateCacheKey(a.prefix||"",a.parts,a.values),s=r.get(e,n),l=this._bucketCache;l&&e._bucketCache.stash(o,n,s);var u=e._qpDelegate;u&&u(e,n)},_calculateCacheKey:function(e,t,n){for(var i=t||[],a="",o=0,s=i.length;s>o;++o){var l,u=i[o],m=c(e,u);if(n)if(m&&m in n){var d=0===u.indexOf(m)?u.substr(m.length+1):u;l=r.get(n[m],d)}else l=r.get(n,u);a+="::"+u+":"+l}return e+a.replace(h,"-")},transitionToRoute:function(){var e=r.get(this,"target"),t=e.transitionToRoute||e.transitionTo;return t.apply(e,arguments)},transitionTo:function(){return this.transitionToRoute.apply(this,arguments)},replaceRoute:function(){var e=r.get(this,"target"),t=e.replaceRoute||e.replaceWith;return t.apply(e,arguments)},replaceWith:function(){return this.replaceRoute.apply(this,arguments)}});var h=/\./g;e["default"]=s["default"]}),e("ember-routing/ext/run_loop",["exports","ember-metal/run_loop"],function(e,t){"use strict";t["default"]._addQueue("routerTransitions","actions")}),e("ember-routing/initializers/routing-service",["exports","ember-runtime/system/lazy_load","ember-routing/services/routing"],function(e,t,r){"use strict";t.onLoad("Ember.Application",function(e){e.initializer({name:"routing-service",initialize:function(e){e.register("service:-routing",r["default"]),e.injection("service:-routing","router","router:main")}})})}),e("ember-routing/location/api",["exports","ember-metal/core","ember-metal/environment","ember-routing/location/util"],function(e,t,r,n){"use strict";e["default"]={create:function(e){var t=e&&e.implementation,r=this.implementations[t];return r.create.apply(r,arguments)},registerImplementation:function(e,t){this.implementations[e]=t},implementations:{},_location:r["default"].location,_getHash:function(){return n.getHash(this.location)}}}),e("ember-routing/location/auto_location",["exports","ember-metal/core","ember-metal/property_get","ember-metal/property_set","ember-metal/utils","ember-runtime/system/object","ember-metal/environment","ember-routing/location/util"],function(e,t,r,n,i,a,o,s){"use strict";function l(e){return function(){for(var t=r.get(this,"concreteImplementation"),n=arguments.length,a=Array(n),o=0;n>o;o++)a[o]=arguments[o];return i.tryInvoke(t,e,a)}}function u(e){var t=e.location,r=e.userAgent,n=e.history,i=e.documentMode,a=e.global,o=e.rootURL,l="none",u=!1,m=s.getFullPath(t);if(s.supportsHistory(r,n)){var d=c(o,t);if(m===d)return"history";"/#"===m.substr(0,2)?(n.replaceState({path:d},null,d),l="history"):(u=!0,s.replacePath(t,d))}else if(s.supportsHashChange(i,a)){var p=h(o,t);m===p||"/"===m&&"/#/"===p?l="hash":(u=!0,s.replacePath(t,p))}return u?!1:l}function c(e,t){var r,n,i=s.getPath(t),a=s.getHash(t),o=s.getQuery(t);i.indexOf(e);return("#/"===a.substr(0,2)?(n=a.substr(1).split("#"),r=n.shift(),"/"===i.slice(-1)&&(r=r.substr(1)),i=i+r+o,n.length&&(i+="#"+n.join("#"))):i=i+o+a, i)}function h(e,t){var r=e,n=c(e,t),i=n.substr(e.length);return(""!==i&&("/"!==i.charAt(0)&&(i="/"+i),r+="#"+i), r)}e.getHistoryPath=c,e.getHashPath=h,e["default"]=a["default"].extend({location:o["default"].location,history:o["default"].history,global:o["default"].global,userAgent:o["default"].userAgent,cancelRouterSetup:!1,rootURL:"/",detect:function(){var e=this.rootURL,t=u({location:this.location,history:this.history,userAgent:this.userAgent,rootURL:e,documentMode:this.documentMode,global:this.global});t===!1&&(n.set(this,"cancelRouterSetup",!0),t="none");var r=this.container.lookup("location:"+t);n.set(r,"rootURL",e),n.set(this,"concreteImplementation",r)},initState:l("initState"),getURL:l("getURL"),setURL:l("setURL"),replaceURL:l("replaceURL"),onUpdateURL:l("onUpdateURL"),formatURL:l("formatURL"),willDestroy:function(){var e=r.get(this,"concreteImplementation");e&&e.destroy()}})}),e("ember-routing/location/hash_location",["exports","ember-metal/core","ember-metal/property_get","ember-metal/property_set","ember-metal/run_loop","ember-metal/utils","ember-runtime/system/object","ember-routing/location/api"],function(e,t,r,n,i,a,o,s){"use strict";e["default"]=o["default"].extend({implementation:"hash",init:function(){n.set(this,"location",r.get(this,"_location")||window.location)},getHash:s["default"]._getHash,getURL:function(){var e=this.getHash().substr(1),t=e;return("/"!==t.charAt(0)&&(t="/",e&&(t+="#"+e)), t)},setURL:function(e){r.get(this,"location").hash=e,n.set(this,"lastSetURL",e)},replaceURL:function(e){r.get(this,"location").replace("#"+e),n.set(this,"lastSetURL",e)},onUpdateURL:function(e){var o=this,s=a.guidFor(this);t["default"].$(window).on("hashchange.ember-location-"+s,function(){i["default"](function(){var t=o.getURL();r.get(o,"lastSetURL")!==t&&(n.set(o,"lastSetURL",null),e(t))})})},formatURL:function(e){return"#"+e},willDestroy:function(){var e=a.guidFor(this);t["default"].$(window).off("hashchange.ember-location-"+e)}})}),e("ember-routing/location/history_location",["exports","ember-metal/property_get","ember-metal/property_set","ember-metal/utils","ember-runtime/system/object","ember-routing/location/api","ember-views/system/jquery"],function(e,t,r,n,i,a,o){"use strict";var s=!1;e["default"]=i["default"].extend({implementation:"history",init:function(){r.set(this,"location",t.get(this,"location")||window.location),r.set(this,"baseURL",o["default"]("base").attr("href")||"")},initState:function(){var e=t.get(this,"history")||window.history;r.set(this,"history",e),e&&"state"in e&&(this.supportsHistory=!0),this.replaceState(this.formatURL(this.getURL()))},rootURL:"/",getURL:function(){var e=t.get(this,"rootURL"),r=t.get(this,"location"),n=r.pathname,i=t.get(this,"baseURL");e=e.replace(/\/$/,""),i=i.replace(/\/$/,"");var a=n.replace(i,"").replace(e,""),o=r.search||"";return (a+=o, a+=this.getHash())},setURL:function(e){var t=this.getState();e=this.formatURL(e),t&&t.path===e||this.pushState(e)},replaceURL:function(e){var t=this.getState();e=this.formatURL(e),t&&t.path===e||this.replaceState(e)},getState:function(){return this.supportsHistory?t.get(this,"history").state:this._historyState},pushState:function(e){var r={path:e};t.get(this,"history").pushState(r,null,e),this._historyState=r,this._previousURL=this.getURL()},replaceState:function(e){var r={path:e};t.get(this,"history").replaceState(r,null,e),this._historyState=r,this._previousURL=this.getURL()},onUpdateURL:function(e){var t=this,r=n.guidFor(this);o["default"](window).on("popstate.ember-location-"+r,function(r){(s||(s=!0,t.getURL()!==t._previousURL))&&e(t.getURL())})},formatURL:function(e){var r=t.get(this,"rootURL"),n=t.get(this,"baseURL");return(""!==e?(r=r.replace(/\/$/,""),n=n.replace(/\/$/,"")):n.match(/^\//)&&r.match(/^\//)&&(n=n.replace(/\/$/,"")), n+r+e)},willDestroy:function(){var e=n.guidFor(this);o["default"](window).off("popstate.ember-location-"+e)},getHash:a["default"]._getHash})}),e("ember-routing/location/none_location",["exports","ember-metal/property_get","ember-metal/property_set","ember-runtime/system/object"],function(e,t,r,n){"use strict";e["default"]=n["default"].extend({implementation:"none",path:"",getURL:function(){return t.get(this,"path")},setURL:function(e){r.set(this,"path",e)},onUpdateURL:function(e){this.updateCallback=e},handleURL:function(e){r.set(this,"path",e),this.updateCallback(e)},formatURL:function(e){return e}})}),e("ember-routing/location/util",["exports"],function(e){"use strict";function t(e){var t=e.pathname;return("/"!==t.charAt(0)&&(t="/"+t), t)}function r(e){return e.search}function n(e){var t=e.href,r=t.indexOf("#");return-1===r?"":t.substr(r)}function i(e){return t(e)+r(e)+n(e)}function a(e){var t=e.origin;return (t||(t=e.protocol+"//"+e.hostname,e.port&&(t+=":"+e.port)), t)}function o(e,t){return"onhashchange"in t&&(void 0===e||e>7)}function s(e,t){return-1===e.indexOf("Android 2.")&&-1===e.indexOf("Android 4.0")||-1===e.indexOf("Mobile Safari")||-1!==e.indexOf("Chrome")||-1!==e.indexOf("Windows Phone")?!!(t&&"pushState"in t):!1}function l(e,t){e.replace(a(e)+t)}e.getPath=t,e.getQuery=r,e.getHash=n,e.getFullPath=i,e.getOrigin=a,e.supportsHashChange=o,e.supportsHistory=s,e.replacePath=l}),e("ember-routing/services/routing",["exports","ember-runtime/system/service","ember-metal/property_get","ember-metal/computed_macros","ember-routing/utils","ember-metal/keys","ember-metal/merge"],function(e,t,r,n,i,a,o){"use strict";var s=t["default"].extend({router:null,targetState:n.readOnly("router.targetState"),currentState:n.readOnly("router.currentState"),currentRouteName:n.readOnly("router.currentRouteName"),availableRoutes:function(){return a["default"](r.get(this,"router").router.recognizer.names)},hasRoute:function(e){return r.get(this,"router").hasRoute(e)},transitionTo:function(e,t,n,i){var a=r.get(this,"router"),o=a._doTransition(e,t,n);i&&o.method("replace")},normalizeQueryParams:function(e,t,n){r.get(this,"router")._prepareQueryParams(e,t,n)},generateURL:function(e,t,n){var a=r.get(this,"router");if(a.router){var s={};o["default"](s,n),this.normalizeQueryParams(e,t,s);var l=i.routeArgs(e,t,s);return a.generate.apply(a,l)}},isActiveForRoute:function(e,t,n,i,a){var o=r.get(this,"router"),s=o.router.recognizer.handlersFor(n),u=s[s.length-1].handler,c=l(n,s);return (e.length>c&&(n=u), i.isActiveIntent(n,e,t,!a))}}),l=function(e,t){for(var r=0,n=0,i=t.length;i>n&&(r+=t[n].names.length,t[n].handler!==e);n++);return r};e["default"]=s}),e("ember-routing/system/cache",["exports","ember-runtime/system/object"],function(e,t){"use strict";e["default"]=t["default"].extend({init:function(){this.cache={}},has:function(e){return e in this.cache},stash:function(e,t,r){var n=this.cache[e];n||(n=this.cache[e]={}),n[t]=r},lookup:function(e,t,r){var n=this.cache;if(!(e in n))return r;var i=n[e];return t in i?i[t]:r},cache:null})}),e("ember-routing/system/controller_for",["exports"],function(e){"use strict";function t(e,t,r){return e.lookup("controller:"+t,r)}e["default"]=t}),e("ember-routing/system/dsl",["exports","ember-metal/core","ember-metal/array"],function(e,t,r){"use strict";function n(e,t){this.parent=e,this.enableLoadingSubstates=t&&t.enableLoadingSubstates,this.matches=[]}function i(e){return e.parent&&"application"!==e.parent}function a(e,t,r){return i(e)&&r!==!0?e.parent+"."+t:t}function o(e,t,r,n){r=r||{};var i=a(e,t,r.resetNamespace);"string"!=typeof r.path&&(r.path="/"+t),e.push(r.path,i,n)}e["default"]=n,n.prototype={route:function(e,t,r){var i="/_unused_dummy_error_path_route_"+e+"/:error";2===arguments.length&&"function"==typeof t&&(r=t,t={}),1===arguments.length&&(t={});t.resetNamespace===!0?"resource":"route";if(this.enableLoadingSubstates&&(o(this,e+"_loading",{resetNamespace:t.resetNamespace}),o(this,e+"_error",{path:i})),r){var s=a(this,e,t.resetNamespace),l=new n(s,{enableLoadingSubstates:this.enableLoadingSubstates});o(l,"loading"),o(l,"error",{path:i}),r.call(l),o(this,e,t,l.generate())}else o(this,e,t)},push:function(e,t,r){var n=t.split(".");(""===e||"/"===e||"index"===n[n.length-1])&&(this.explicitIndex=!0),this.matches.push([e,t,r])},resource:function(e,t,r){2===arguments.length&&"function"==typeof t&&(r=t,t={}),1===arguments.length&&(t={}),t.resetNamespace=!0,this.route(e,t,r)},generate:function(){var e=this.matches;return (this.explicitIndex||this.route("index",{path:"/"}), function(t){for(var r=0,n=e.length;n>r;r++){var i=e[r];t(i[0]).to(i[1],i[2])}})}},n.map=function(e){var t=new n;return (e.call(t), t)}}),e("ember-routing/system/generate_controller",["exports","ember-metal/core","ember-metal/property_get","ember-runtime/utils"],function(e,t,r,n){"use strict";function i(e,t,r){var i,a,o,s;return (s=r&&n.isArray(r)?"array":r?"object":"basic", o="controller:"+s, i=e.lookupFactory(o).extend({isGenerated:!0,toString:function(){return"(generated "+t+" controller)"}}), a="controller:"+t, e._registry.register(a,i), i)}function a(e,n,a){i(e,n,a);var o="controller:"+n,s=e.lookup(o);return (r.get(s,"namespace.LOG_ACTIVE_GENERATION")&&t["default"].Logger.info("generated -> "+o,{fullName:o}), s)}e.generateControllerFactory=i,e["default"]=a}),e("ember-routing/system/query_params",["exports","ember-runtime/system/object"],function(e,t){"use strict";e["default"]=t["default"].extend({isQueryParams:!0,values:null})}),e("ember-routing/system/route",["exports","ember-metal/core","ember-metal/error","ember-metal/property_get","ember-metal/property_set","ember-metal/get_properties","ember-metal/enumerable_utils","ember-metal/is_none","ember-metal/computed","ember-metal/merge","ember-runtime/utils","ember-metal/run_loop","ember-metal/keys","ember-runtime/copy","ember-runtime/system/string","ember-runtime/system/object","ember-runtime/mixins/evented","ember-runtime/mixins/action_handler","ember-routing/system/generate_controller","ember-routing/utils"],function(e,t,r,n,i,a,o,s,l,u,c,h,m,d,p,f,v,g,b,y){"use strict";function _(){return this}function w(e){var t=x(e,e.router.router.state.handlerInfos,-1);return t&&t.handler}function x(e,t,r){if(t)for(var n,i=r||0,a=0,o=t.length;o>a;a++)if(n=t[a].handler,n===e)return t[a+i]}function C(e,i,a,o,s){var l,u,c,h,m=s&&s.controller,d=n.get(e.router,"namespace.LOG_VIEW_LOOKUPS"),p=s&&s.into&&s.into.replace(/\//g,"."),f=s&&s.outlet||"main";if(o?(o=o.replace(/\//g,"."),l=o):(o=e.routeName,l=e.templateName||o),m||(m=i?e.container.lookup("controller:"+o)||e.controllerName||e.routeName:e.controllerName||e.container.lookup("controller:"+o)),"string"==typeof m){var v=m;if(m=e.container.lookup("controller:"+v),!m)throw new r["default"]("You passed `controller: '"+v+"'` into the `render` method, but no such controller could be found.")}if(s&&s.model&&m.set("model",s.model),u=s&&s.view||i&&o||e.viewName||o,c=e.container.lookupFactory("view:"+u),h=e.container.lookup("template:"+l),!c&&!h&&d){var g="template:"+o;t["default"].Logger.info('Could not find "'+o+'" template or view. Nothing will be rendered',{fullName:g})}var b;p&&(b=w(e))&&p===w(e).routeName&&(p=void 0);var y={into:p,outlet:f,name:o,controller:m,ViewClass:c,template:h};return y}function k(e,t){if(t.fullQueryParams)return t.fullQueryParams;t.fullQueryParams={},u["default"](t.fullQueryParams,t.queryParams);var r=t.handlerInfos[t.handlerInfos.length-1].name;return (e._deserializeQueryParams(r,t.fullQueryParams), t.fullQueryParams)}function E(e,t){t.queryParamsFor=t.queryParamsFor||{};var r=e.routeName;if(t.queryParamsFor[r])return t.queryParamsFor[r];for(var i=k(e.router,t),a=t.queryParamsFor[r]={},o=n.get(e,"_qp"),s=o.qps,l=0,u=s.length;u>l;++l){var c=s[l],h=c.prop in i;a[c.prop]=h?i[c.prop]:A(c.def)}return a}function A(e){return c.isArray(e)?t["default"].A(e.slice()):e}var N=Array.prototype.slice,O=f["default"].extend(g["default"],v["default"],{queryParams:{},_qp:l.computed(function(){var e=this,r=this.controllerName||this.routeName,i=this.container.lookupFactory("controller:"+r);if(!i)return P;var a=i.proto(),o=n.get(a,"_normalizedQueryParams"),s=n.get(a,"_cacheMeta"),l=[],u={};for(var h in o)if(o.hasOwnProperty(h)){var m=o[h],d=m.as||this.serializeQueryParamKey(h),p=n.get(a,h);c.isArray(p)&&(p=t["default"].A(p.slice()));var f=c.typeOf(p),v=this.serializeQueryParam(p,d,f),g=r+":"+h,b={def:p,sdef:v,type:f,urlKey:d,prop:h,fprop:g,ctrl:r,cProto:a,svalue:v,cacheType:m.scope,route:this,cacheMeta:s[h]};u[h]=u[d]=u[g]=b,l.push(b)}return{qps:l,map:u,states:{active:function(t,r){return e._activeQPChanged(t,u[r])},allowOverrides:function(t,r){return e._updatingQPChanged(t,u[r])}}}}),_names:null,_stashNames:function(e,t){var r=e;if(!this._names){var i=this._names=r._names;i.length||(r=t,i=r&&r._names||[]);for(var a=n.get(this,"_qp.qps"),o=a.length,s=new Array(i.length),l=0,u=i.length;u>l;++l)s[l]=r.name+"."+i[l];for(var c=0;o>c;++c){var h=a[c],m=h.cacheMeta;"model"===m.scope&&(m.parts=s),m.prefix=h.ctrl}}},_updateSerializedQPValue:function(e,t){var r=n.get(e,t.prop);t.svalue=this.serializeQueryParam(r,t.urlKey,t.type)},_activeQPChanged:function(e,t){var r=n.get(e,t.prop);this.router._queuedQPChanges[t.fprop]=r,h["default"].once(this,this._fireQueryParamTransition)},_updatingQPChanged:function(e,t){var r=this.router;r._qpUpdates||(r._qpUpdates={}),r._qpUpdates[t.urlKey]=!0},mergedProperties:["events","queryParams"],paramsFor:function(e){var t=this.container.lookup("route:"+e);if(!t)return{};var r=this.router.router.activeTransition,n=r?r.state:this.router.router.state,i={};return (u["default"](i,n.params[e]), u["default"](i,E(t,n)), i)},serializeQueryParamKey:function(e){return e},serializeQueryParam:function(e,t,r){return"array"===r?JSON.stringify(e):""+e},deserializeQueryParam:function(e,r,n){return"boolean"===n?"true"===e?!0:!1:"number"===n?Number(e).valueOf():"array"===n?t["default"].A(JSON.parse(e)):e},_fireQueryParamTransition:function(){this.transitionTo({queryParams:this.router._queuedQPChanges}),this.router._queuedQPChanges={}},_optionsForQueryParam:function(e){return n.get(this,"queryParams."+e.urlKey)||n.get(this,"queryParams."+e.prop)||{}},resetController:_,exit:function(){this.deactivate(),this.trigger("deactivate"),this.teardownViews()},_reset:function(e,t){var r=this.controller;r._qpDelegate=null,this.resetController(r,e,t)},enter:function(){this.connections=[],this.activate(),this.trigger("activate")},viewName:null,templateName:null,controllerName:null,_actions:{queryParamsDidChange:function(e,t,r){for(var i=n.get(this,"_qp").map,a=m["default"](e).concat(m["default"](r)),o=0,s=a.length;s>o;++o){var l=i[a[o]];l&&n.get(this._optionsForQueryParam(l),"refreshModel")&&this.refresh()}return!0},finalizeQueryParamChange:function(e,t,r){if("application"!==this.routeName)return!0;if(r){var a,s=r.state.handlerInfos,l=this.router,u=l._queryParamsFor(s[s.length-1].name),c=l._qpUpdates;y.stashParamNames(l,s);for(var h=0,m=u.qps.length;m>h;++h){var d,p,f=u.qps[h],v=f.route,g=v.controller,b=f.urlKey in e&&f.urlKey;c&&f.urlKey in c?(d=n.get(g,f.prop),p=v.serializeQueryParam(d,f.urlKey,f.type)):b?(p=e[b],d=v.deserializeQueryParam(p,f.urlKey,f.type)):(p=f.sdef,d=A(f.def)),g._qpDelegate=null;var _=p!==f.svalue;if(_){if(r.queryParamsOnly&&a!==!1){var w=v._optionsForQueryParam(f),x=n.get(w,"replace");x?a=!0:x===!1&&(a=!1)}i.set(g,f.prop,d)}f.svalue=p;var C=f.sdef===p;C||t.push({value:p,visible:!0,key:b||f.urlKey})}a&&r.method("replace"),o.forEach(u.qps,function(e){var t=n.get(e.route,"_qp"),r=e.route.controller;r._qpDelegate=n.get(t,"states.active")}),l._qpUpdates=null}}},events:null,deactivate:_,activate:_,transitionTo:function(e,t){var r=this.router;return r.transitionTo.apply(r,arguments)},intermediateTransitionTo:function(){var e=this.router;e.intermediateTransitionTo.apply(e,arguments)},refresh:function(){return this.router.router.refresh(this)},replaceWith:function(){var e=this.router;return e.replaceWith.apply(e,arguments)},send:function(){for(var e=arguments.length,r=Array(e),n=0;e>n;n++)r[n]=arguments[n];if(this.router&&this.router.router||!t["default"].testing){var i;(i=this.router).send.apply(i,r)}else{var a=r[0];r=N.call(r,1);var o=this._actions[a];if(o)return this._actions[a].apply(this,r)}},setup:function(e,t){var r=this.controllerName||this.routeName,i=this.controllerFor(r,!0);if(i||(i=this.generateController(r,e)),this.controller=i,this.setupControllers)this.setupControllers(i,e);else{var a=n.get(this,"_qp.states");if(t&&(y.stashParamNames(this.router,t.state.handlerInfos),i._updateCacheParams(t.params)),i._qpDelegate=a.allowOverrides,t){var o=E(this,t.state);i.setProperties(o)}this.setupController(i,e,t)}this.renderTemplates?this.renderTemplates(e):this.renderTemplate(i,e)},beforeModel:_,afterModel:_,redirect:_,contextDidChange:function(){this.currentModel=this.context},model:function(e,t){var r,i,a,o,s=n.get(this,"_qp.map");for(var l in e)"queryParams"===l||s&&l in s||((r=l.match(/^(.*)_id$/))&&(i=r[1],o=e[l]),a=!0);if(!i&&a)return d["default"](e);if(!i){if(t.resolveIndex<1)return;var u=t.state.handlerInfos[t.resolveIndex-1].context;return u}return this.findModel(i,o)},deserialize:function(e,t){return this.model(this.paramsFor(this.routeName),t)},findModel:function(){var e=n.get(this,"store");return e.find.apply(e,arguments)},store:l.computed(function(){var e=this.container;this.routeName,n.get(this,"router.namespace");return{find:function(t,r){var n=e.lookupFactory("model:"+t);if(n)return n.find(r)}}}),serialize:function(e,t){if(!(t.length<1)&&e){var r=t[0],i={};return (1===t.length?r in e?i[r]=n.get(e,r):/_id$/.test(r)&&(i[r]=n.get(e,"id")):i=a["default"](e,t), i)}},setupController:function(e,t,r){e&&void 0!==t&&i.set(e,"model",t)},controllerFor:function(e,t){var r,n=this.container,i=n.lookup("route:"+e);return (i&&i.controllerName&&(e=i.controllerName), r=n.lookup("controller:"+e))},generateController:function(e,t){var r=this.container;return (t=t||this.modelFor(e), b["default"](r,e,t))},modelFor:function(e){var t=this.container.lookup("route:"+e),r=this.router?this.router.router.activeTransition:null;if(r){var n=t&&t.routeName||e;if(r.resolvedModels.hasOwnProperty(n))return r.resolvedModels[n]}return t&&t.currentModel},renderTemplate:function(e,t){this.render()},render:function(e,r){var n,i="string"==typeof e&&!!e,a=0===arguments.length||t["default"].isEmpty(arguments[0]);"object"!=typeof e||r?n=e:(n=this.routeName,r=e);var o=C(this,i,a,n,r);this.connections.push(o),h["default"].once(this.router,"_setOutlets")},disconnectOutlet:function(e){var t,r;e&&"string"!=typeof e?(t=e.outlet,r=e.parentView):t=e,r=r&&r.replace(/\//g,"."),t=t||"main",this._disconnectOutlet(t,r);for(var n=0;n0&&(this.connections=[],h["default"].once(this.router,"_setOutlets"))}});O.reopenClass({isRouteFactory:!0});var P={qps:[],map:{},states:{}};e["default"]=O}),e("ember-routing/system/router",["exports","ember-metal/core","ember-metal/error","ember-metal/property_get","ember-metal/property_set","ember-metal/properties","ember-metal/computed","ember-metal/merge","ember-metal/run_loop","ember-runtime/system/string","ember-runtime/system/object","ember-runtime/mixins/evented","ember-routing/system/dsl","ember-routing/location/api","ember-routing/utils","ember-metal/platform/create","./router_state","router","router/transition"],function(e,t,r,n,i,a,o,s,l,u,c,h,m,d,p,f,v,g,b){"use strict";function y(){return this}function _(e,t,r){for(var n,i,a=t.state.handlerInfos,o=!1,s=a.length-1;s>=0;--s)if(n=a[s],i=n.handler,o){if(r(i,a[s+1].handler)!==!0)return!1}else e===i&&(o=!0);return!0}function w(e,r){var n,i=[];n=e&&"object"==typeof e&&"object"==typeof e.errorThrown?e.errorThrown:e,r&&i.push(r),n&&(n.message&&i.push(n.message),n.stack&&i.push(n.stack),"string"==typeof n&&i.push(n)),t["default"].Logger.error.apply(this,i)}function x(e,t,r){var n,i=e.router,a=t.routeName.split(".").pop(),o="application"===e.routeName?"":e.routeName+".";return (n=o+a+"_"+r, C(i,n)?n:(n=o+r,C(i,n)?n:void 0))}function C(e,t){var r=e.container;return e.hasRoute(t)&&(r._registry.has("template:"+t)||r._registry.has("route:"+t))}function k(e,t,n){var i=n.shift();if(!e){if(t)return;throw new r["default"]("Can't trigger action '"+i+"' because your app hasn't finished transitioning into its first route. To trigger an action on destination routes during a transition, you can call `.send()` on the `Transition` object passed to the `model/beforeModel/afterModel` hooks.")}for(var a,o,s=!1,l=e.length-1;l>=0;l--)if(a=e[l],o=a.handler,o._actions&&o._actions[i]){if(o._actions[i].apply(o,n)!==!0)return;s=!0}if(V[i])return void V[i].apply(null,n);if(!s&&!t)throw new r["default"]("Nothing handled the action '"+i+"'. If you did handle the action, this error can be caused by returning true from an action handler in a controller, causing the action to bubble.")}function E(e,t,r){for(var n=e.router,i=n.applyIntent(t,r),a=i.handlerInfos,o=i.params,s=0,l=a.length;l>s;++s){var u=a[s];u.isResolved||(u=u.becomeResolved(null,u.context)),o[u.name]=u.params}return i}function A(e){var t=e.container.lookup("controller:application");if(t){var r=e.router.currentHandlerInfos,n=I._routePath(r);"currentPath"in t||a.defineProperty(t,"currentPath"),i.set(t,"currentPath",n),i.set(e,"currentPath",n),"currentRouteName"in t||a.defineProperty(t,"currentRouteName"),i.set(t,"currentRouteName",r[r.length-1].name),i.set(e,"currentRouteName",r[r.length-1].name)}}function N(e,t){var r=v["default"].create({emberRouter:t,routerJs:t.router,routerJsState:e.state});t.currentState||t.set("currentState",r),t.set("targetState",r),e.then(null,function(e){return e&&e.name?e:void 0},"Ember: Process errors from Router")}function O(e){return"string"==typeof e&&(""===e||"/"===e.charAt(0))}function P(e,t,r,n){var i=e._queryParamsFor(t);for(var a in r)if(r.hasOwnProperty(a)){var o=r[a],s=i.map[a];s&&n(a,o,s)}}function S(e,t){if(e)for(var r=[e];r.length>0;){var n=r.shift();if(n.render.name===t)return n;var i=n.outlets;for(var a in i)r.push(i[a])}}function T(e,t,r){var n,a={render:r,outlets:f["default"](null)};return (n=r.into?S(e,r.into):t, n?i.set(n.outlets,r.outlet,a):r.into?R(e,r.into,a):e=a, {liveRoutes:e,ownState:a})}function R(e,r,n){e.outlets.__ember_orphans__||(e.outlets.__ember_orphans__={render:{name:"__ember_orphans__"},outlets:f["default"](null)}),e.outlets.__ember_orphans__.outlets[r]=n,t["default"].run.schedule("afterRender",function(){})}function M(e,t,r){var n=S(e,r.routeName);return n?n:(t.outlets.main={render:{name:r.routeName,outlet:"main"},outlets:{}},t)}var D=[].slice,I=c["default"].extend(h["default"],{location:"hash",rootURL:"/",_initRouterJs:function(e){function r(){this.resource("application",{path:"/",overrideNameAssertion:!0},function(){for(var e=0;en;n++)r[n]=arguments[n];if(O(r[0]))return this._doURLTransition("transitionTo",r[0]);var i=r[r.length-1];e=i&&i.hasOwnProperty("queryParams")?r.pop().queryParams:{};var a=r.shift();return this._doTransition(a,r,e)},intermediateTransitionTo:function(){var e;(e=this.router).intermediateTransitionTo.apply(e,arguments),A(this);var r=this.router.currentHandlerInfos;n.get(this,"namespace").LOG_TRANSITIONS&&t["default"].Logger.log("Intermediate-transitioned into '"+I._routePath(r)+"'")},replaceWith:function(){return this.transitionTo.apply(this,arguments).method("replace")},generate:function(){var e,t=(e=this.router).generate.apply(e,arguments); +return this.location.formatURL(t)},isActive:function(e){var t=this.router;return t.isActive.apply(t,arguments)},isActiveIntent:function(e,t,r){return this.currentState.isActiveIntent(e,t,r)},send:function(e,t){var r;(r=this.router).trigger.apply(r,arguments)},hasRoute:function(e){return this.router.hasRoute(e)},reset:function(){this.router&&this.router.reset()},willDestroy:function(){this._toplevelView&&(this._toplevelView.destroy(),this._toplevelView=null),this._super.apply(this,arguments),this.reset()},_lookupActiveComponentNode:function(e){return this._activeViews[e]},_connectActiveComponentNode:function(e,t){function r(){delete n[e]}var n=this._activeViews;this._activeViews[e]=t,t.renderNode.addDestruction({destroy:r})},_setupLocation:function(){var e=n.get(this,"location"),t=n.get(this,"rootURL");if("string"==typeof e&&this.container){var r=this.container.lookup("location:"+e);if("undefined"!=typeof r)e=i.set(this,"location",r);else{var a={implementation:e};e=i.set(this,"location",d["default"].create(a))}}null!==e&&"object"==typeof e&&(t&&i.set(e,"rootURL",t),"function"==typeof e.detect&&e.detect(),"function"==typeof e.initState&&e.initState())},_getHandlerFunction:function(){var e=this,r=f["default"](null),i=this.container,a=i.lookupFactory("route:basic");return function(o){var s="route:"+o,l=i.lookup(s);return r[o]?l:(r[o]=!0,l||(i._registry.register(s,a.extend()),l=i.lookup(s),n.get(e,"namespace.LOG_ACTIVE_GENERATION")&&t["default"].Logger.info("generated -> "+s,{fullName:s})),l.routeName=o,l)}},_setupRouter:function(e,t){var r,n=this;e.getHandler=this._getHandlerFunction();var i=function(){t.setURL(r)};if(e.updateURL=function(e){r=e,l["default"].once(i)},t.replaceURL){var a=function(){t.replaceURL(r)};e.replaceURL=function(e){r=e,l["default"].once(a)}}e.didTransition=function(e){n.didTransition(e)},e.willTransition=function(e,t,r){n.willTransition(e,t,r)}},_serializeQueryParams:function(e,t){var r={};P(this,e,t,function(e,n,i){var a=i.urlKey;r[a]||(r[a]=[]),r[a].push({qp:i,value:n}),delete t[e]});for(var n in r){var i=r[n],a=i[0].qp;t[a.urlKey]=a.route.serializeQueryParam(i[0].value,a.urlKey,a.type)}},_deserializeQueryParams:function(e,t){P(this,e,t,function(e,r,n){delete t[e],t[n.prop]=n.route.deserializeQueryParam(r,n.urlKey,n.type)})},_pruneDefaultQueryParamValues:function(e,t){var r=this._queryParamsFor(e);for(var n in t){var i=r.map[n];i&&i.sdef===t[n]&&delete t[n]}},_doTransition:function(e,t,r){var n=e||p.getActiveTargetName(this.router),i={};s["default"](i,r),this._prepareQueryParams(n,t,i);var a=p.routeArgs(n,t,i),o=this.router.transitionTo.apply(this.router,a);return (N(o,this), o)},_prepareQueryParams:function(e,t,r){this._hydrateUnsuppliedQueryParams(e,t,r),this._serializeQueryParams(e,r),this._pruneDefaultQueryParamValues(e,r)},_queryParamsFor:function(e){if(this._qpCache[e])return this._qpCache[e];var t={},r=[];this._qpCache[e]={map:t,qps:r};for(var i=this.router,a=i.recognizer.handlersFor(e),o=0,l=a.length;l>o;++o){var u=a[o],c=i.getHandler(u.handler),h=n.get(c,"_qp");h&&(s["default"](t,h.map),r.push.apply(r,h.qps))}return{qps:r,map:t}},_hydrateUnsuppliedQueryParams:function(e,t,r){var i=E(this,e,t),a=i.handlerInfos,o=this._bucketCache;p.stashParamNames(this,a);for(var s=0,l=a.length;l>s;++s)for(var u=a[s].handler,c=n.get(u,"_qp"),h=0,m=c.qps.length;m>h;++h){var d=c.qps[h],f=d.prop in r&&d.prop||d.fprop in r&&d.fprop;if(f)f!==d.fprop&&(r[d.fprop]=r[f],delete r[f]);else{var v=d.cProto,g=n.get(v,"_cacheMeta"),b=v._calculateCacheKey(d.ctrl,g[d.prop].parts,i.params);r[d.fprop]=o.lookup(b,d.prop,d.def)}}},_scheduleLoadingEvent:function(e,t){this._cancelSlowTransitionTimer(),this._slowTransitionTimer=l["default"].scheduleOnce("routerTransitions",this,"_handleSlowTransition",e,t)},currentState:null,targetState:null,_handleSlowTransition:function(e,t){this.router.activeTransition&&(this.set("targetState",v["default"].create({emberRouter:this,routerJs:this.router,routerJsState:this.router.activeTransition.state})),e.trigger(!0,"loading",e,t))},_cancelSlowTransitionTimer:function(){this._slowTransitionTimer&&l["default"].cancel(this._slowTransitionTimer),this._slowTransitionTimer=null}}),V={willResolveModel:function(e,t){t.router._scheduleLoadingEvent(e,t)},error:function(e,t,r){var n=r.router,i=_(r,t,function(t,r){var i=x(t,r,"error");return i?void n.intermediateTransitionTo(i,e):!0});return i&&C(r.router,"application_error")?void n.intermediateTransitionTo("application_error",e):void w(e,"Error while processing route: "+t.targetName)},loading:function(e,t){var r=t.router,n=_(t,e,function(t,n){var i=x(t,n,"loading");return i?void r.intermediateTransitionTo(i):e.pivotHandler!==t?!0:void 0});return n&&C(t.router,"application_loading")?void r.intermediateTransitionTo("application_loading"):void 0}};I.reopenClass({router:null,map:function(e){return (this.dslCallbacks||(this.dslCallbacks=[],this.reopenClass({dslCallbacks:this.dslCallbacks})), this.dslCallbacks.push(e), this)},_routePath:function(e){function t(e,t){for(var r=0,n=e.length;n>r;++r)if(e[r]!==t[r])return!1;return!0}for(var r,n,i,a=[],o=1,s=e.length;s>o;o++){for(r=e[o].name,n=r.split("."),i=D.call(a);i.length&&!t(i,n);)i.shift();a.push.apply(a,n.slice(i.length))}return a.join(".")}}),e["default"]=I}),e("ember-routing/system/router_state",["exports","ember-metal/is_empty","ember-metal/keys","ember-runtime/system/object","ember-metal/merge"],function(e,t,r,n,i){"use strict";function a(e,t){var r;for(r in e)if(e.hasOwnProperty(r)&&e[r]!==t[r])return!1;for(r in t)if(t.hasOwnProperty(r)&&e[r]!==t[r])return!1;return!0}var o=n["default"].extend({emberRouter:null,routerJs:null,routerJsState:null,isActiveIntent:function(e,n,o,s){var l=this.routerJsState;if(!this.routerJs.isActiveIntent(e,n,null,l))return!1;var u=t["default"](r["default"](o));if(s&&!u){var c={};return (i["default"](c,o), this.emberRouter._prepareQueryParams(e,n,c), a(c,l.queryParams))}return!0}});e["default"]=o}),e("ember-routing/utils",["exports"],function(e){"use strict";function t(e,t,r){var n=[];return("string"==typeof e&&n.push(""+e), n.push.apply(n,t), n.push({queryParams:r}), n)}function r(e){var t=e.activeTransition?e.activeTransition.state.handlerInfos:e.state.handlerInfos;return t[t.length-1].name}function n(e,t){if(!t._namesStashed){for(var r=t[t.length-1].name,n=e.router.recognizer.handlersFor(r),i=null,a=0,o=t.length;o>a;++a){var s=t[a],l=n[a].names;l.length&&(i=s),s._names=l;var u=s.handler;u._stashNames(s,i)}t._namesStashed=!0}}e.routeArgs=t,e.getActiveTargetName=r,e.stashParamNames=n}),e("ember-runtime",["exports","ember-metal","ember-runtime/core","ember-runtime/compare","ember-runtime/copy","ember-runtime/inject","ember-runtime/system/namespace","ember-runtime/system/object","ember-runtime/system/tracked_array","ember-runtime/system/subarray","ember-runtime/system/container","ember-runtime/system/array_proxy","ember-runtime/system/object_proxy","ember-runtime/system/core_object","ember-runtime/system/native_array","ember-runtime/system/set","ember-runtime/system/string","ember-runtime/system/deferred","ember-runtime/system/lazy_load","ember-runtime/mixins/array","ember-runtime/mixins/comparable","ember-runtime/mixins/copyable","ember-runtime/mixins/enumerable","ember-runtime/mixins/freezable","ember-runtime/mixins/-proxy","ember-runtime/mixins/observable","ember-runtime/mixins/action_handler","ember-runtime/mixins/deferred","ember-runtime/mixins/mutable_enumerable","ember-runtime/mixins/mutable_array","ember-runtime/mixins/target_action_support","ember-runtime/mixins/evented","ember-runtime/mixins/promise_proxy","ember-runtime/mixins/sortable","ember-runtime/computed/array_computed","ember-runtime/computed/reduce_computed","ember-runtime/computed/reduce_computed_macros","ember-runtime/controllers/array_controller","ember-runtime/controllers/object_controller","ember-runtime/controllers/controller","ember-runtime/mixins/controller","ember-runtime/system/service","ember-runtime/ext/rsvp","ember-runtime/ext/string","ember-runtime/ext/function","ember-runtime/utils"],function(e,t,r,n,i,a,o,s,l,u,c,h,m,d,p,f,v,g,b,y,_,w,x,C,k,E,A,N,O,P,S,T,R,M,D,I,V,j,L,F,B,H,z,U,q,W){"use strict";t["default"].compare=n["default"],t["default"].copy=i["default"],t["default"].isEqual=r.isEqual,t["default"].inject=a["default"],t["default"].Array=y["default"],t["default"].Comparable=_["default"],t["default"].Copyable=w["default"],t["default"].SortableMixin=M["default"],t["default"].Freezable=C.Freezable,t["default"].FROZEN_ERROR=C.FROZEN_ERROR,t["default"].DeferredMixin=N["default"],t["default"].MutableEnumerable=O["default"],t["default"].MutableArray=P["default"],t["default"].TargetActionSupport=S["default"],t["default"].Evented=T["default"],t["default"].PromiseProxyMixin=R["default"],t["default"].Observable=E["default"],t["default"].arrayComputed=D.arrayComputed,t["default"].ArrayComputedProperty=D.ArrayComputedProperty,t["default"].reduceComputed=I.reduceComputed,t["default"].ReduceComputedProperty=I.ReduceComputedProperty,t["default"].typeOf=W.typeOf,t["default"].isArray=W.isArray;var K=t["default"].computed;K.sum=V.sum,K.min=V.min,K.max=V.max,K.map=V.map,K.sort=V.sort,K.setDiff=V.setDiff,K.mapBy=V.mapBy,K.mapProperty=V.mapProperty,K.filter=V.filter,K.filterBy=V.filterBy,K.filterProperty=V.filterProperty,K.uniq=V.uniq,K.union=V.union,K.intersect=V.intersect,t["default"].String=v["default"],t["default"].Object=s["default"],t["default"].TrackedArray=l["default"],t["default"].SubArray=u["default"],t["default"].Container=c.Container,t["default"].Registry=c.Registry,t["default"].Namespace=o["default"],t["default"].Enumerable=x["default"],t["default"].ArrayProxy=h["default"],t["default"].ObjectProxy=m["default"],t["default"].ActionHandler=A["default"],t["default"].CoreObject=d["default"],t["default"].NativeArray=p["default"],t["default"].Set=f["default"],t["default"].Deferred=g["default"],t["default"].onLoad=b.onLoad,t["default"].runLoadHooks=b.runLoadHooks,t["default"].ArrayController=j["default"],t["default"].ObjectController=L["default"],t["default"].Controller=F["default"],t["default"].ControllerMixin=B["default"],t["default"].Service=H["default"],t["default"]._ProxyMixin=k["default"],t["default"].RSVP=z["default"],e["default"]=t["default"]}),e("ember-runtime/compare",["exports","ember-runtime/utils","ember-runtime/mixins/comparable"],function(e,t,r){"use strict";function n(e,t){var r=e-t;return(r>0)-(0>r)}function i(e,o){if(e===o)return 0;var s=t.typeOf(e),l=t.typeOf(o);if(r["default"]){if("instance"===s&&r["default"].detect(e)&&e.constructor.compare)return e.constructor.compare(e,o);if("instance"===l&&r["default"].detect(o)&&o.constructor.compare)return-1*o.constructor.compare(o,e)}var u=n(a[s],a[l]);if(0!==u)return u;switch(s){case"boolean":case"number":return n(e,o);case"string":return n(e.localeCompare(o),0);case"array":for(var c=e.length,h=o.length,m=Math.min(c,h),d=0;m>d;d++){var p=i(e[d],o[d]);if(0!==p)return p}return n(c,h);case"instance":return r["default"]&&r["default"].detect(e)?e.compare(e,o):0;case"date":return n(e.getTime(),o.getTime());default:return 0}}e["default"]=i;var a={undefined:0,"null":1,"boolean":2,number:3,string:4,array:5,object:6,instance:7,"function":8,"class":9,date:10}}),e("ember-runtime/computed/array_computed",["exports","ember-metal/core","ember-runtime/computed/reduce_computed","ember-metal/enumerable_utils","ember-metal/platform/create","ember-metal/observer","ember-metal/error"],function(e,t,r,n,i,a,o){"use strict";function s(){var e=this;return (this._isArrayComputed=!0, r.ReduceComputedProperty.apply(this,arguments), this._getter=function(t){return function(r){return (e._hasInstanceMeta(this,r)||n.forEach(e._dependentKeys,function(t){a.addObserver(this,t,function(){e.recomputeOnce.call(this,r)})},this), t.apply(this,arguments))}}(this._getter), this)}function l(e){var t;if(arguments.length>1&&(t=u.call(arguments,0,-1),e=u.call(arguments,-1)[0]),"object"!=typeof e)throw new o["default"]("Array Computed Property declared without an options hash");var r=new s(e);return (t&&r.property.apply(r,t), r)}var u=[].slice;s.prototype=i["default"](r.ReduceComputedProperty.prototype),s.prototype.initialValue=function(){return t["default"].A()},s.prototype.resetValue=function(e){return (e.clear(), e)},s.prototype.didChange=function(e,t){},e.arrayComputed=l,e.ArrayComputedProperty=s}),e("ember-runtime/computed/reduce_computed",["exports","ember-metal/core","ember-metal/property_get","ember-metal/utils","ember-metal/error","ember-metal/property_events","ember-metal/expand_properties","ember-metal/observer","ember-metal/computed","ember-metal/platform/create","ember-metal/enumerable_utils","ember-runtime/system/tracked_array","ember-runtime/mixins/array","ember-metal/run_loop"],function(e,t,r,n,i,a,o,s,l,u,c,h,m,d){"use strict";function p(e,t){return"@this"===t?e:r.get(e,t)}function f(e,t,r,n,i,a){this.callbacks=e,this.cp=t,this.instanceMeta=r,this.dependentKeysByGuid={},this.trackedArraysByGuid={},this.suspended=!1,this.changedItems={},this.changedItemCount=0}function v(e,t,r){this.dependentArray=e,this.index=t,this.item=e.objectAt(t),this.trackedArray=r,this.beforeObserver=null,this.observer=null,this.destroyed=!1}function g(e,t,r){return 0>e?Math.max(0,t+e):t>e?e:Math.min(t-r,e)}function b(e,t,r){return Math.min(r,t-e)}function y(e,t,r,n,i,a,o){this.arrayChanged=e,this.index=r,this.item=t,this.propertyName=n,this.property=i,this.changedCount=a,o&&(this.previousValues=o)}function _(e,t,r,n,i){c.forEach(e,function(a,o){i.setValue(t.addedItem.call(this,i.getValue(),a,new y(e,a,o,n,r,e.length),i.sugarMeta))},this),t.flushedChanges.call(this,i.getValue(),i.sugarMeta)}function w(e,t){var r=e._hasInstanceMeta(this,t),n=e._instanceMeta(this,t);r&&n.setValue(e.resetValue(n.getValue())),e.options.initialize&&e.options.initialize.call(this,n.getValue(),{property:e,propertyName:t},n.sugarMeta)}function x(e,t){if(M.test(t))return!1;var r=p(e,t);return m["default"].detect(r)}function C(e,t,r){this.context=e,this.propertyName=t;var i=n.meta(e),a=i.cache;a||(a=i.cache={}),this.cache=a,this.dependentArrays={},this.sugarMeta={},this.initialValue=r}function k(e){var t=this;this._isArrayComputed,this.options=e,this._dependentKeys=null,this._cacheable=!0,this._itemPropertyKeys={},this._previousItemPropertyKeys={},this.readOnly(),this.recomputeOnce=function(e){d["default"].once(this,r,e)};var r=function(e){var r=t._instanceMeta(this,e),n=t._callbacks();w.call(this,t,e),r.dependentArraysObserver.suspendArrayObservers(function(){c.forEach(t._dependentKeys,function(e){if(x(this,e)){var n=p(this,e),i=r.dependentArrays[e];n===i?t._previousItemPropertyKeys[e]&&(r.dependentArraysObserver.teardownPropertyObservers(e,t._previousItemPropertyKeys[e]),delete t._previousItemPropertyKeys[e],r.dependentArraysObserver.setupPropertyObservers(e,t._itemPropertyKeys[e])):(r.dependentArrays[e]=n,i&&r.dependentArraysObserver.teardownObservers(i,e),n&&r.dependentArraysObserver.setupObservers(n,e))}},this)},this),c.forEach(t._dependentKeys,function(i){if(x(this,i)){var a=p(this,i);a&&_.call(this,a,n,t,e,r)}},this)};this._getter=function(e){return (r.call(this,e), t._instanceMeta(this,e).getValue())}}function E(e){return e}function A(e){var t;if(arguments.length>1&&(t=S.call(arguments,0,-1),e=S.call(arguments,-1)[0]),"object"!=typeof e)throw new i["default"]("Reduce Computed Property declared without an options hash");if(!("initialValue"in e))throw new i["default"]("Reduce Computed Property declared without an initial value");var r=new k(e);return (t&&r.property.apply(r,t), r)}e.reduceComputed=A;var N=l.cacheFor.set,O=l.cacheFor.get,P=l.cacheFor.remove,S=[].slice,T=/^(.*)\.@each\.(.*)/,R=/(.*\.@each){2,}/,M=/\.\[\]$/;f.prototype={setValue:function(e){this.instanceMeta.setValue(e,!0)},getValue:function(){return this.instanceMeta.getValue()},setupObservers:function(e,t){this.dependentKeysByGuid[n.guidFor(e)]=t,e.addArrayObserver(this,{willChange:"dependentArrayWillChange",didChange:"dependentArrayDidChange"}),this.cp._itemPropertyKeys[t]&&this.setupPropertyObservers(t,this.cp._itemPropertyKeys[t])},teardownObservers:function(e,t){var r=this.cp._itemPropertyKeys[t]||[];delete this.dependentKeysByGuid[n.guidFor(e)],this.teardownPropertyObservers(t,r),e.removeArrayObserver(this,{willChange:"dependentArrayWillChange",didChange:"dependentArrayDidChange"})},suspendArrayObservers:function(e,t){var r=this.suspended;this.suspended=!0,e.call(t),this.suspended=r},setupPropertyObservers:function(e,t){var r=p(this.instanceMeta.context,e),n=p(r,"length"),i=new Array(n);this.resetTransformations(e,i),c.forEach(r,function(n,a){var o=this.createPropertyObserverContext(r,a,this.trackedArraysByGuid[e]);i[a]=o,c.forEach(t,function(e){s._addBeforeObserver(n,e,this,o.beforeObserver),s.addObserver(n,e,this,o.observer)},this)},this)},teardownPropertyObservers:function(e,t){var r,n,i,a=this,o=this.trackedArraysByGuid[e];o&&o.apply(function(e,o,l){l!==h["default"].DELETE&&c.forEach(e,function(e){e.destroyed=!0,r=e.beforeObserver,n=e.observer,i=e.item,c.forEach(t,function(e){s._removeBeforeObserver(i,e,a,r),s.removeObserver(i,e,a,n)})})})},createPropertyObserverContext:function(e,t,r){var n=new v(e,t,r);return (this.createPropertyObserver(n), n)},createPropertyObserver:function(e){var t=this;e.beforeObserver=function(r,n){return t.itemPropertyWillChange(r,n,e.dependentArray,e)},e.observer=function(r,n){return t.itemPropertyDidChange(r,n,e.dependentArray,e)}},resetTransformations:function(e,t){this.trackedArraysByGuid[e]=new h["default"](t,!0)},trackAdd:function(e,t,r){var n=this.trackedArraysByGuid[e];n&&n.addItems(t,r)},trackRemove:function(e,t,r){var n=this.trackedArraysByGuid[e];return n?n.removeItems(t,r):[]},updateIndexes:function(e,t){var r=p(t,"length");e.apply(function(e,t,n,i){n!==h["default"].DELETE&&(0!==i||n!==h["default"].RETAIN||e.length!==r||0!==t)&&c.forEach(e,function(e,r){e.index=r+t})})},dependentArrayWillChange:function(e,t,r,i){function a(e){m[h].destroyed=!0,s._removeBeforeObserver(l,e,this,m[h].beforeObserver),s.removeObserver(l,e,this,m[h].observer)}if(!this.suspended){var o,l,u,h,m,d=this.callbacks.removedItem,f=n.guidFor(e),v=this.dependentKeysByGuid[f],_=this.cp._itemPropertyKeys[v]||[],w=p(e,"length"),x=g(t,w,0),C=b(x,w,r);for(m=this.trackRemove(v,x,C),h=C-1;h>=0&&(u=x+h,!(u>=w));--h)l=e.objectAt(u),c.forEach(_,a,this),o=new y(e,l,u,this.instanceMeta.propertyName,this.cp,C),this.setValue(d.call(this.instanceMeta.context,this.getValue(),l,o,this.instanceMeta.sugarMeta));this.callbacks.flushedChanges.call(this.instanceMeta.context,this.getValue(),this.instanceMeta.sugarMeta)}},dependentArrayDidChange:function(e,t,r,i){if(!this.suspended){var a,o,l=this.callbacks.addedItem,u=n.guidFor(e),h=this.dependentKeysByGuid[u],m=new Array(i),d=this.cp._itemPropertyKeys[h],f=p(e,"length"),v=g(t,f,i),b=v+i;c.forEach(e.slice(v,b),function(t,r){d&&(o=this.createPropertyObserverContext(e,v+r,this.trackedArraysByGuid[h]),m[r]=o,c.forEach(d,function(e){s._addBeforeObserver(t,e,this,o.beforeObserver),s.addObserver(t,e,this,o.observer)},this)),a=new y(e,t,v+r,this.instanceMeta.propertyName,this.cp,i),this.setValue(l.call(this.instanceMeta.context,this.getValue(),t,a,this.instanceMeta.sugarMeta))},this),this.callbacks.flushedChanges.call(this.instanceMeta.context,this.getValue(),this.instanceMeta.sugarMeta),this.trackAdd(h,v,m)}},itemPropertyWillChange:function(e,t,r,i){var a=n.guidFor(e);this.changedItems[a]||(this.changedItems[a]={array:r,observerContext:i,obj:e,previousValues:{}}),++this.changedItemCount,this.changedItems[a].previousValues[t]=p(e,t)},itemPropertyDidChange:function(e,t,r,n){0===--this.changedItemCount&&this.flushChanges()},flushChanges:function(){var e,t,r,n=this.changedItems;for(e in n)t=n[e],t.observerContext.destroyed||(this.updateIndexes(t.observerContext.trackedArray,t.observerContext.dependentArray),r=new y(t.array,t.obj,t.observerContext.index,this.instanceMeta.propertyName,this.cp,n.length,t.previousValues),this.setValue(this.callbacks.removedItem.call(this.instanceMeta.context,this.getValue(),t.obj,r,this.instanceMeta.sugarMeta)),this.setValue(this.callbacks.addedItem.call(this.instanceMeta.context,this.getValue(),t.obj,r,this.instanceMeta.sugarMeta)));this.changedItems={},this.callbacks.flushedChanges.call(this.instanceMeta.context,this.getValue(),this.instanceMeta.sugarMeta)}},C.prototype={getValue:function(){var e=O(this.cache,this.propertyName);return void 0!==e?e:this.initialValue},setValue:function(e,t){e!==O(this.cache,this.propertyName)&&(t&&a.propertyWillChange(this.context,this.propertyName),void 0===e?P(this.cache,this.propertyName):N(this.cache,this.propertyName,e),t&&a.propertyDidChange(this.context,this.propertyName))}},e.ReduceComputedProperty=k,k.prototype=u["default"](l.ComputedProperty.prototype),k.prototype._callbacks=function(){if(!this.callbacks){var e=this.options;this.callbacks={removedItem:e.removedItem||E,addedItem:e.addedItem||E,flushedChanges:e.flushedChanges||E}}return this.callbacks},k.prototype._hasInstanceMeta=function(e,t){var r=e.__ember_meta__,n=r&&r.cacheMeta;return!(!n||!n[t])},k.prototype._instanceMeta=function(e,t){var r=e.__ember_meta__,n=r.cacheMeta,i=n&&n[t];return (n||(n=r.cacheMeta={}), i||(i=n[t]=new C(e,t,this.initialValue()),i.dependentArraysObserver=new f(this._callbacks(),this,i,e,t,i.sugarMeta)), i)},k.prototype.initialValue=function(){return"function"==typeof this.options.initialValue?this.options.initialValue():this.options.initialValue},k.prototype.resetValue=function(e){return this.initialValue()},k.prototype.itemPropertyKey=function(e,t){this._itemPropertyKeys[e]=this._itemPropertyKeys[e]||[],this._itemPropertyKeys[e].push(t)},k.prototype.clearItemPropertyKeys=function(e){this._itemPropertyKeys[e]&&(this._previousItemPropertyKeys[e]=this._itemPropertyKeys[e],this._itemPropertyKeys[e]=[])},k.prototype.property=function(){var e,t,r=this,a=S.call(arguments),s={};c.forEach(a,function(a){if(R.test(a))throw new i["default"]("Nested @each properties not supported: "+a);if(e=T.exec(a)){t=e[1];var l=e[2],u=function(e){r.itemPropertyKey(t,e)};o["default"](l,u),s[n.guidFor(t)]=t}else s[n.guidFor(a)]=a});var u=[];for(var h in s)u.push(s[h]);return l.ComputedProperty.prototype.property.apply(this,u)}}),e("ember-runtime/computed/reduce_computed_macros",["exports","ember-metal/core","ember-metal/property_get","ember-metal/utils","ember-metal/error","ember-metal/enumerable_utils","ember-metal/run_loop","ember-metal/observer","ember-runtime/computed/array_computed","ember-runtime/computed/reduce_computed","ember-runtime/system/subarray","ember-metal/keys","ember-runtime/compare"],function(e,t,r,n,i,a,o,s,l,u,c,h,m){"use strict";function d(e){return u.reduceComputed(e,{_suppressDeprecation:!0,initialValue:0,addedItem:function(e,t,r,n){return e+t},removedItem:function(e,t,r,n){return e-t}})}function p(e){return u.reduceComputed(e,{_suppressDeprecation:!0,initialValue:-(1/0),addedItem:function(e,t,r,n){return Math.max(e,t)},removedItem:function(e,t,r,n){return e>t?e:void 0}})}function f(e){return u.reduceComputed(e,{_suppressDeprecation:!0,initialValue:1/0,addedItem:function(e,t,r,n){return Math.min(e,t)},removedItem:function(e,t,r,n){return t>e?e:void 0}})}function v(e,t){var r={_suppressDeprecation:!0,addedItem:function(e,r,n,i){var a=t.call(this,r,n.index);return (e.insertAt(n.index,a), e)},removedItem:function(e,t,r,n){return (e.removeAt(r.index,1), e)}};return l.arrayComputed(e,r)}function g(e,t){var n=function(e){return r.get(e,t)};return v(e+".@each."+t,n)}function b(e,t){var r={_suppressDeprecation:!0,initialize:function(e,t,r){r.filteredArrayIndexes=new c["default"](void 0,!0)},addedItem:function(e,r,n,i){var a=!!t.call(this,r,n.index,n.arrayChanged),o=i.filteredArrayIndexes.addItem(n.index,a);return (a&&e.insertAt(o,r), e)},removedItem:function(e,t,r,n){var i=n.filteredArrayIndexes.removeItem(r.index);return (i>-1&&e.removeAt(i), e)}};return l.arrayComputed(e,r)}function y(e,t,n){var i;return (i=2===arguments.length?function(e){return r.get(e,t)}:function(e){return r.get(e,t)===n}, b(e+".@each."+t,i))}function _(){var e=O.call(arguments);return (e.push({_suppressDeprecation:!0,initialize:function(e,t,r){r.itemCounts={}},addedItem:function(e,t,r,i){var a=n.guidFor(t);return (i.itemCounts[a]?++i.itemCounts[a]:(i.itemCounts[a]=1,e.pushObject(t)), e)},removedItem:function(e,t,r,i){var a=n.guidFor(t),o=i.itemCounts;return (0===--o[a]&&e.removeObject(t), e)}}), l.arrayComputed.apply(null,e))}function w(){var e=O.call(arguments);return (e.push({_suppressDeprecation:!0,initialize:function(e,t,r){r.itemCounts={}},addedItem:function(e,t,r,i){var a=n.guidFor(t),o=n.guidFor(r.arrayChanged),s=r.property._dependentKeys.length,l=i.itemCounts;return (l[a]||(l[a]={}), void 0===l[a][o]&&(l[a][o]=0), 1===++l[a][o]&&s===h["default"](l[a]).length&&e.addObject(t), e)},removedItem:function(e,t,r,i){var a,o=n.guidFor(t),s=n.guidFor(r.arrayChanged),l=i.itemCounts;return (void 0===l[o][s]&&(l[o][s]=0), 0===--l[o][s]&&(delete l[o][s],a=h["default"](l[o]).length,0===a&&delete l[o],e.removeObject(t)), e)}}), l.arrayComputed.apply(null,e))}function x(e,t){if(2!==arguments.length)throw new i["default"]("setDiff requires exactly two dependent arrays.");return l.arrayComputed(e,t,{_suppressDeprecation:!0,addedItem:function(n,i,a,o){var s=r.get(this,e),l=r.get(this,t);return (a.arrayChanged===s?l.contains(i)||n.addObject(i):n.removeObject(i), n)},removedItem:function(n,i,a,o){var s=r.get(this,e),l=r.get(this,t);return (a.arrayChanged===l?s.contains(i)&&n.addObject(i):n.removeObject(i), n)}})}function C(e,t,i,a){var o,s,l,u,c;return (arguments.length<4&&(a=r.get(e,"length")), arguments.length<3&&(i=0), i===a?i:(o=i+Math.floor((a-i)/2),s=e.objectAt(o),u=n.guidFor(s),c=n.guidFor(t),u===c?o:(l=this.order(s,t),0===l&&(l=c>u?-1:1),0>l?this.binarySearch(e,t,o+1,a):l>0?this.binarySearch(e,t,i,o):o)))}function k(e,t){return"function"==typeof t?E(e,t):A(e,t)}function E(e,t){return l.arrayComputed(e,{_suppressDeprecation:!0,initialize:function(e,r,n){n.order=t,n.binarySearch=C,n.waitingInsertions=[],n.insertWaiting=function(){var t,r,i=n.waitingInsertions;n.waitingInsertions=[];for(var a=0;a=0&&n>e&&(t=this.lookupItemController(a))?this.controllerAt(e,a,t):a},arrangedContentDidChange:function(){this._super.apply(this,arguments),this._resetSubControllers()},arrayContentDidChange:function(e,t,r){var i=this._subControllers;if(i.length){var a=i.slice(e,e+t);n.forEach(a,function(e){e&&e.destroy()}),n.replace(i,e,t,new Array(r))}this._super(e,t,r)},init:function(){this._super.apply(this,arguments),this._subControllers=[]},model:s.computed({get:function(e){return t["default"].A()},set:function(e,t){return t}}),_isVirtual:!1,controllerAt:function(e,t,n){var i,a,o,s=r.get(this,"container"),u=this._subControllers;if(u.length>e&&(a=u[e]))return a;if(o=this._isVirtual?r.get(this,"parentController"):this,i="controller:"+n,!s._registry.has(i))throw new l["default"]('Could not resolve itemController: "'+n+'"');return (a=s.lookupFactory(i).create({target:o,parentController:o,model:t}), u[e]=a, a)},_subControllers:null,_resetSubControllers:function(){var e,t=this._subControllers;if(t.length){for(var r=0,n=t.length;n>r;r++)e=t[r],e&&e.destroy();t.length=0}},willDestroy:function(){this._resetSubControllers(),this._super.apply(this,arguments)}})}),e("ember-runtime/controllers/controller",["exports","ember-metal/core","ember-runtime/system/object","ember-runtime/mixins/controller","ember-runtime/inject"],function(e,t,r,n,i){"use strict";function a(e){}var o=r["default"].extend(n["default"]);i.createInjectionHelper("controller",a),e["default"]=o}),e("ember-runtime/controllers/object_controller",["exports","ember-metal/core","ember-runtime/mixins/controller","ember-runtime/system/object_proxy"],function(e,t,r,n){"use strict";var i="Ember.ObjectController is deprecated, please use Ember.Controller and use `model.propertyName`.";e.objectControllerDeprecation=i,e["default"]=n["default"].extend(r["default"],{init:function(){this._super()}})}),e("ember-runtime/copy",["exports","ember-metal/enumerable_utils","ember-metal/utils","ember-runtime/system/object","ember-runtime/mixins/copyable"],function(e,t,r,n,i){"use strict";function a(e,n,o,s){var l,u,c;if("object"!=typeof e||null===e)return e;if(n&&(u=t.indexOf(o,e))>=0)return s[u];if(r.isArray(e)){if(l=e.slice(),n)for(u=l.length;--u>=0;)l[u]=a(l[u],n,o,s)}else if(i["default"]&&i["default"].detect(e))l=e.copy(n,o,s);else if(e instanceof Date)l=new Date(e.getTime());else{l={};for(c in e)Object.prototype.hasOwnProperty.call(e,c)&&"__"!==c.substring(0,2)&&(l[c]=n?a(e[c],n,o,s):e[c])}return (n&&(o.push(e),s.push(l)), l)}function o(e,t){return"object"!=typeof e||null===e?e:i["default"]&&i["default"].detect(e)?e.copy(t):a(e,t,t?[]:null,t?[]:null)}e["default"]=o}),e("ember-runtime/core",["exports"],function(e){"use strict";function t(e,t){return e&&"function"==typeof e.isEqual?e.isEqual(t):e instanceof Date&&t instanceof Date?e.getTime()===t.getTime():e===t}e.isEqual=t}),e("ember-runtime/ext/function",["exports","ember-metal/core","ember-metal/expand_properties","ember-metal/computed","ember-metal/mixin"],function(e,t,r,n,i){"use strict";var a=Array.prototype.slice,o=Function.prototype;(t["default"].EXTEND_PROTOTYPES===!0||t["default"].EXTEND_PROTOTYPES.Function)&&(o.property=function(){var e=n.computed(this);return e.property.apply(e,arguments)},o.observes=function(){for(var e=arguments.length,t=Array(e),r=0;e>r;r++)t[r]=arguments[r];return (t.push(this), i.observer.apply(this,t))},o._observesImmediately=function(){return this.observes.apply(this,arguments)},o.observesImmediately=t["default"].deprecateFunc("Function#observesImmediately is deprecated. Use Function#observes instead",o._observesImmediately),o._observesBefore=function(){for(var e=[],t=function(t){e.push(t)},n=0,i=arguments.length;i>n;++n)r["default"](arguments[n],t);return (this.__ember_observesBefore__=e, this)},o.observesBefore=t["default"].deprecateFunc("Function#observesBefore is deprecated and will be removed in the near future.",{url:"http://emberjs.com/deprecations/v1.x/#toc_beforeobserver"},o._observesBefore),o.on=function(){var e=a.call(arguments);return (this.__ember_listens__=e, this)})}),e("ember-runtime/ext/rsvp",["exports","ember-metal/core","ember-metal/logger","ember-metal/run_loop","rsvp"],function(e,r,n,i,a){"use strict";function o(e){var i;if(e&&e.errorThrown?(i=e.errorThrown,"string"==typeof i&&(i=new Error(i)),i.__reason_with_error_thrown__=e):i=e,i&&"TransitionAborted"!==i.name)if(r["default"].testing){if(!s&&r["default"].__loader.registry[l]&&(s=t(l)["default"]),!s||!s.adapter)throw i;s.adapter.exception(i),n["default"].error(i.stack)}else r["default"].onerror?r["default"].onerror(i):n["default"].error(i.stack)}e.onerrorDefault=o;var s,l="ember-testing/test",u=function(){r["default"].Test&&r["default"].Test.adapter&&r["default"].Test.adapter.asyncStart()},c=function(){r["default"].Test&&r["default"].Test.adapter&&r["default"].Test.adapter.asyncEnd()};a.configure("async",function(e,t){var n=!i["default"].currentRunLoop;r["default"].testing&&n&&u(),i["default"].backburner.schedule("actions",function(){r["default"].testing&&n&&c(),e(t)})}),a.Promise.prototype.fail=function(e,t){return this["catch"](e,t)},a.on("error",o),e["default"]=a}),e("ember-runtime/ext/string",["exports","ember-metal/core","ember-runtime/system/string"],function(e,t,r){"use strict";var n=String.prototype;(t["default"].EXTEND_PROTOTYPES===!0||t["default"].EXTEND_PROTOTYPES.String)&&(n.fmt=function(){return r.fmt(this,arguments)},n.w=function(){return r.w(this)},n.loc=function(){return r.loc(this,arguments)},n.camelize=function(){return r.camelize(this)},n.decamelize=function(){return r.decamelize(this)},n.dasherize=function(){return r.dasherize(this)},n.underscore=function(){return r.underscore(this)},n.classify=function(){return r.classify(this)},n.capitalize=function(){return r.capitalize(this)})}),e("ember-runtime/inject",["exports","ember-metal/core","ember-metal/enumerable_utils","ember-metal/injected_property","ember-metal/keys"],function(e,t,r,n,i){"use strict";function a(){}function o(e,t){l[e]=t,a[e]=function(t){return new n["default"](e,t)}}function s(e){var t,i,a,o,s,u=e.proto(),c=[];for(t in u)i=u[t],i instanceof n["default"]&&-1===r.indexOf(c,i.type)&&c.push(i.type);if(c.length)for(o=0,s=c.length;s>o;o++)a=l[c[o]],"function"==typeof a&&a(e);return!0}e.createInjectionHelper=o,e.validatePropertyInjections=s;var l={};e["default"]=a}),e("ember-runtime/mixins/-proxy",["exports","ember-metal/core","ember-metal/property_get","ember-metal/property_set","ember-metal/utils","ember-metal/observer","ember-metal/property_events","ember-metal/computed","ember-metal/properties","ember-metal/mixin","ember-runtime/system/string"],function(e,t,r,n,i,a,o,s,l,u,c){"use strict";function h(e,t){var r=t.slice(8);r in this||o.propertyWillChange(this,r)}function m(e,t){var r=t.slice(8);r in this||o.propertyDidChange(this,r)}e["default"]=u.Mixin.create({content:null,_contentDidChange:u.observer("content",function(){}),isTruthy:s.computed.bool("content"),_debugContainerKey:null,willWatchProperty:function(e){var t="content."+e;a._addBeforeObserver(this,t,null,h),a.addObserver(this,t,null,m)},didUnwatchProperty:function(e){var t="content."+e;a._removeBeforeObserver(this,t,null,h),a.removeObserver(this,t,null,m)},unknownProperty:function(e){var t=r.get(this,"content");return t?r.get(t,e):void 0},setUnknownProperty:function(e,t){var a=i.meta(this);if(a.proto===this)return (l.defineProperty(this,e,null,t), t);var o=r.get(this,"content");return n.set(o,e,t)}})}),e("ember-runtime/mixins/action_handler",["exports","ember-metal/merge","ember-metal/mixin","ember-metal/property_get"],function(e,t,r,n){"use strict";var i=r.Mixin.create({mergedProperties:["_actions"],willMergeMixin:function(e){var r;e._actions||(e.actions&&"object"==typeof e.actions?r="actions":e.events&&"object"==typeof e.events&&(r="events"),r&&(e._actions=t["default"](e._actions||{},e[r])),delete e[r])},send:function(e){for(var t=arguments.length,r=Array(t>1?t-1:0),i=1;t>i;i++)r[i-1]=arguments[i];var a;if(this._actions&&this._actions[e]){var o=this._actions[e].apply(this,r)===!0;if(!o)return}if(a=n.get(this,"target")){var s;(s=a).send.apply(s,arguments)}}});e["default"]=i}),e("ember-runtime/mixins/array",["exports","ember-metal/core","ember-metal/property_get","ember-metal/computed","ember-metal/is_none","ember-runtime/mixins/enumerable","ember-metal/enumerable_utils","ember-metal/mixin","ember-metal/property_events","ember-metal/events","ember-metal/watching"],function(e,r,n,i,a,o,s,l,u,c,h){"use strict";function m(e,t,r,i,a){var o=r&&r.willChange||"arrayWillChange",s=r&&r.didChange||"arrayDidChange",l=n.get(e,"hasArrayObservers");return (l===a&&u.propertyWillChange(e,"hasArrayObservers"), i(e,"@array:before",t,o), i(e,"@array:change",t,s), l===a&&u.propertyDidChange(e,"hasArrayObservers"), e)}e["default"]=l.Mixin.create(o["default"],{length:null,objectAt:function(e){return 0>e||e>=n.get(this,"length")?void 0:n.get(this,e)},objectsAt:function(e){var t=this;return s.map(e,function(e){return t.objectAt(e)})},nextObject:function(e){return this.objectAt(e)},"[]":i.computed({get:function(e){return this},set:function(e,t){return (this.replace(0,n.get(this,"length"),t), this)}}),firstObject:i.computed(function(){return this.objectAt(0)}),lastObject:i.computed(function(){return this.objectAt(n.get(this,"length")-1)}),contains:function(e){return this.indexOf(e)>=0},slice:function(e,t){var i=r["default"].A(),o=n.get(this,"length");for(a["default"](e)&&(e=0),(a["default"](t)||t>o)&&(t=o),0>e&&(e=o+e),0>t&&(t=o+t);t>e;)i[i.length]=this.objectAt(e++);return i},indexOf:function(e,t){var r,i=n.get(this,"length");for(void 0===t&&(t=0),0>t&&(t+=i),r=t;i>r;r++)if(this.objectAt(r)===e)return r;return-1},lastIndexOf:function(e,t){var r,i=n.get(this,"length");for((void 0===t||t>=i)&&(t=i-1),0>t&&(t+=i),r=t;r>=0;r--)if(this.objectAt(r)===e)return r;return-1},addArrayObserver:function(e,t){return m(this,e,t,c.addListener,!1)},removeArrayObserver:function(e,t){return m(this,e,t,c.removeListener,!0)},hasArrayObservers:i.computed(function(){return c.hasListeners(this,"@array:change")||c.hasListeners(this,"@array:before")}),arrayContentWillChange:function(e,t,r){var i,a;if(void 0===e?(e=0,t=r=-1):(void 0===t&&(t=-1),void 0===r&&(r=-1)),h.isWatching(this,"@each")&&n.get(this,"@each"),c.sendEvent(this,"@array:before",[this,e,t,r]),e>=0&&t>=0&&n.get(this,"hasEnumerableObservers")){i=[],a=e+t;for(var o=e;a>o;o++)i.push(this.objectAt(o))}else i=t;return (this.enumerableContentWillChange(i,r), this)},arrayContentDidChange:function(e,t,r){var a,o;if(void 0===e?(e=0,t=r=-1):(void 0===t&&(t=-1),void 0===r&&(r=-1)),e>=0&&r>=0&&n.get(this,"hasEnumerableObservers")){a=[],o=e+r;for(var s=e;o>s;s++)a.push(this.objectAt(s))}else a=r;this.enumerableContentDidChange(t,a),c.sendEvent(this,"@array:change",[this,e,t,r]);var l=n.get(this,"length"),h=i.cacheFor(this,"firstObject"),m=i.cacheFor(this,"lastObject");return (this.objectAt(0)!==h&&(u.propertyWillChange(this,"firstObject"),u.propertyDidChange(this,"firstObject")), this.objectAt(l-1)!==m&&(u.propertyWillChange(this,"lastObject"),u.propertyDidChange(this,"lastObject")), this)},"@each":i.computed(function(){if(!this.__each){var e=t("ember-runtime/system/each_proxy").EachProxy;this.__each=new e(this)}return this.__each})})}),e("ember-runtime/mixins/comparable",["exports","ember-metal/mixin"],function(e,t){"use strict";e["default"]=t.Mixin.create({compare:null})}),e("ember-runtime/mixins/controller",["exports","ember-metal/mixin","ember-metal/alias","ember-runtime/mixins/action_handler","ember-runtime/mixins/controller_content_model_alias_deprecation"],function(e,t,r,n,i){"use strict";e["default"]=t.Mixin.create(n["default"],i["default"],{isController:!0,target:null,container:null,parentController:null,store:null,model:null,content:r["default"]("model")})}),e("ember-runtime/mixins/controller_content_model_alias_deprecation",["exports","ember-metal/core","ember-metal/mixin"],function(e,t,r){"use strict";e["default"]=r.Mixin.create({willMergeMixin:function(e){this._super.apply(this,arguments);var t=!!e.model;e.content&&!t&&(e.model=e.content,delete e.content)}})}),e("ember-runtime/mixins/copyable",["exports","ember-metal/core","ember-metal/property_get","ember-metal/mixin","ember-runtime/mixins/freezable","ember-runtime/system/string","ember-metal/error"],function(e,t,r,n,i,a,o){"use strict";e["default"]=n.Mixin.create({copy:null,frozenCopy:function(){if(i.Freezable&&i.Freezable.detect(this))return r.get(this,"isFrozen")?this:this.copy().freeze();throw new o["default"](a.fmt("%@ does not support freezing",[this]))}})}),e("ember-runtime/mixins/deferred",["exports","ember-metal/core","ember-metal/property_get","ember-metal/mixin","ember-metal/computed","ember-runtime/ext/rsvp"],function(e,t,r,n,i,a){"use strict";e["default"]=n.Mixin.create({then:function(e,t,n){function i(t){return e(t===o?s:t)}var a,o,s;return (s=this, a=r.get(this,"_deferred"), o=a.promise, o.then(e&&i,t,n))},resolve:function(e){var t,n;t=r.get(this,"_deferred"),n=t.promise,e===this?t.resolve(n):t.resolve(e)},reject:function(e){r.get(this,"_deferred").reject(e)},_deferred:i.computed(function(){return a["default"].defer("Ember: DeferredMixin - "+this)})})}),e("ember-runtime/mixins/enumerable",["exports","ember-metal/core","ember-metal/property_get","ember-metal/property_set","ember-metal/mixin","ember-metal/enumerable_utils","ember-metal/computed","ember-metal/property_events","ember-metal/events","ember-runtime/compare"],function(e,t,r,n,i,a,o,s,l,u){"use strict";function c(){return 0===p.length?{}:p.pop()}function h(e){return (p.push(e), null)}function m(e,t){function n(n){var a=r.get(n,e);return i?t===a:!!a}var i=2===arguments.length;return n}function d(e,t){return function(){return this[t].apply(this,arguments)}}var p=[];e["default"]=i.Mixin.create({nextObject:null,firstObject:o.computed("[]",function(){if(0!==r.get(this,"length")){var e=c(),t=this.nextObject(0,null,e);return (h(e), t)}}),lastObject:o.computed("[]",function(){var e=r.get(this,"length");if(0!==e){var t,n=c(),i=0,a=null;do a=t,t=this.nextObject(i++,a,n);while(void 0!==t);return (h(n), a)}}),contains:function(e){var t=this.find(function(t){return t===e});return void 0!==t},forEach:function(e,t){if("function"!=typeof e)throw new TypeError;var n=c(),i=r.get(this,"length"),a=null;void 0===t&&(t=null);for(var o=0;i>o;o++){var s=this.nextObject(o,a,n);e.call(t,s,o,this),a=s}return (a=null, n=h(n), this)},getEach:i.aliasMethod("mapBy"),setEach:function(e,t){return this.forEach(function(r){n.set(r,e,t)})},map:function(e,r){var n=t["default"].A();return (this.forEach(function(t,i,a){n[i]=e.call(r,t,i,a)}), n)},mapBy:function(e){return this.map(function(t){return r.get(t,e)})},mapProperty:d("mapProperty","mapBy"),filter:function(e,r){var n=t["default"].A();return (this.forEach(function(t,i,a){e.call(r,t,i,a)&&n.push(t)}), n)},reject:function(e,t){return this.filter(function(){return!e.apply(t,arguments)})},filterBy:function(e,t){return this.filter(m.apply(this,arguments))},filterProperty:d("filterProperty","filterBy"),rejectBy:function(e,t){var n=function(n){return r.get(n,e)===t},i=function(t){return!!r.get(t,e)},a=2===arguments.length?n:i;return this.reject(a)},rejectProperty:d("rejectProperty","rejectBy"),find:function(e,t){var n=r.get(this,"length");void 0===t&&(t=null);for(var i,a,o=c(),s=!1,l=null,u=0;n>u&&!s;u++)i=this.nextObject(u,l,o),(s=e.call(t,i,u,this))&&(a=i),l=i;return (i=l=null, o=h(o), a)},findBy:function(e,t){return this.find(m.apply(this,arguments))},findProperty:d("findProperty","findBy"),every:function(e,t){return!this.find(function(r,n,i){return!e.call(t,r,n,i)})},everyBy:d("everyBy","isEvery"),everyProperty:d("everyProperty","isEvery"),isEvery:function(e,t){return this.every(m.apply(this,arguments))},any:function(e,t){var n,i,a=r.get(this,"length"),o=c(),s=!1,l=null;for(void 0===t&&(t=null),i=0;a>i&&!s;i++)n=this.nextObject(i,l,o),s=e.call(t,n,i,this),l=n;return (n=l=null, o=h(o), s)},some:d("some","any"),isAny:function(e,t){return this.any(m.apply(this,arguments))},anyBy:d("anyBy","isAny"),someProperty:d("someProperty","isAny"),reduce:function(e,t,r){if("function"!=typeof e)throw new TypeError;var n=t;return (this.forEach(function(t,i){n=e(n,t,i,this,r)},this), n)},invoke:function(e){for(var r=arguments.length,n=Array(r>1?r-1:0),i=1;r>i;i++)n[i-1]=arguments[i];var a=t["default"].A();return (this.forEach(function(t,r){var i=t&&t[e];"function"==typeof i&&(a[r]=n?i.apply(t,n):t[e]())},this), a)},toArray:function(){var e=t["default"].A();return (this.forEach(function(t,r){e[r]=t}), e)},compact:function(){return this.filter(function(e){return null!=e})},without:function(e){if(!this.contains(e))return this;var r=t["default"].A();return (this.forEach(function(t){t!==e&&(r[r.length]=t)}), r)},uniq:function(){var e=t["default"].A();return (this.forEach(function(t){a.indexOf(e,t)<0&&e.push(t)}), e)},"[]":o.computed({get:function(e){return this}}),addEnumerableObserver:function(e,t){var n=t&&t.willChange||"enumerableWillChange",i=t&&t.didChange||"enumerableDidChange",a=r.get(this,"hasEnumerableObservers");return (a||s.propertyWillChange(this,"hasEnumerableObservers"), l.addListener(this,"@enumerable:before",e,n), l.addListener(this,"@enumerable:change",e,i), a||s.propertyDidChange(this,"hasEnumerableObservers"), this)},removeEnumerableObserver:function(e,t){var n=t&&t.willChange||"enumerableWillChange",i=t&&t.didChange||"enumerableDidChange",a=r.get(this,"hasEnumerableObservers");return (a&&s.propertyWillChange(this,"hasEnumerableObservers"), l.removeListener(this,"@enumerable:before",e,n), l.removeListener(this,"@enumerable:change",e,i), a&&s.propertyDidChange(this,"hasEnumerableObservers"), this)},hasEnumerableObservers:o.computed(function(){return l.hasListeners(this,"@enumerable:change")||l.hasListeners(this,"@enumerable:before")}),enumerableContentWillChange:function(e,t){var n,i,a;return (n="number"==typeof e?e:e?r.get(e,"length"):e=-1, i="number"==typeof t?t:t?r.get(t,"length"):t=-1, a=0>i||0>n||i-n!==0, -1===e&&(e=null), -1===t&&(t=null), s.propertyWillChange(this,"[]"), a&&s.propertyWillChange(this,"length"), l.sendEvent(this,"@enumerable:before",[this,e,t]), this)},enumerableContentDidChange:function(e,t){var n,i,a;return (n="number"==typeof e?e:e?r.get(e,"length"):e=-1, i="number"==typeof t?t:t?r.get(t,"length"):t=-1, a=0>i||0>n||i-n!==0, -1===e&&(e=null), -1===t&&(t=null), l.sendEvent(this,"@enumerable:change",[this,e,t]), a&&s.propertyDidChange(this,"length"), s.propertyDidChange(this,"[]"), this)},sortBy:function(){var e=arguments;return this.toArray().sort(function(t,n){for(var i=0;i1?t-1:0),i=1;t>i;i++)n[i-1]=arguments[i];r.sendEvent(this,e,n)},off:function(e,t,n){return (r.removeListener(this,e,t,n), this)},has:function(e){return r.hasListeners(this,e)}})}),e("ember-runtime/mixins/freezable",["exports","ember-metal/core","ember-metal/mixin","ember-metal/property_get","ember-metal/property_set"],function(e,t,r,n,i){"use strict";var a=r.Mixin.create({init:function(){this._super.apply(this,arguments)},isFrozen:!1,freeze:function(){return n.get(this,"isFrozen")?this:(i.set(this,"isFrozen",!0),this)}});e.Freezable=a;var o="Frozen object cannot be modified.";e.FROZEN_ERROR=o}),e("ember-runtime/mixins/mutable_array",["exports","ember-metal/property_get","ember-metal/utils","ember-metal/error","ember-metal/mixin","ember-runtime/mixins/array","ember-runtime/mixins/mutable_enumerable","ember-runtime/mixins/enumerable"],function(e,t,r,n,i,a,o,s){"use strict";var l="Index out of range",u=[];e["default"]=i.Mixin.create(a["default"],o["default"],{replace:null,clear:function(){var e=t.get(this,"length");return 0===e?this:(this.replace(0,e,u),this)},insertAt:function(e,r){if(e>t.get(this,"length"))throw new n["default"](l);return (this.replace(e,0,[r]), this)},removeAt:function(e,r){if("number"==typeof e){if(0>e||e>=t.get(this,"length"))throw new n["default"](l);void 0===r&&(r=1),this.replace(e,r,u)}return this},pushObject:function(e){return (this.insertAt(t.get(this,"length"),e), e)},pushObjects:function(e){if(!s["default"].detect(e)&&!r.isArray(e))throw new TypeError("Must pass Ember.Enumerable to Ember.MutableArray#pushObjects");return (this.replace(t.get(this,"length"),0,e), this)},popObject:function(){var e=t.get(this,"length");if(0===e)return null;var r=this.objectAt(e-1);return (this.removeAt(e-1,1), r)},shiftObject:function(){if(0===t.get(this,"length"))return null;var e=this.objectAt(0);return (this.removeAt(0), e)},unshiftObject:function(e){return (this.insertAt(0,e), e)},unshiftObjects:function(e){return (this.replace(0,0,e), this)},reverseObjects:function(){var e=t.get(this,"length");if(0===e)return this;var r=this.toArray().reverse();return (this.replace(0,e,r), this)},setObjects:function(e){if(0===e.length)return this.clear();var r=t.get(this,"length");return (this.replace(0,r,e), this)},removeObject:function(e){for(var r=t.get(this,"length")||0;--r>=0;){var n=this.objectAt(r);n===e&&this.removeAt(r)}return this},addObject:function(e){return (this.contains(e)||this.pushObject(e), this)}})}),e("ember-runtime/mixins/mutable_enumerable",["exports","ember-metal/enumerable_utils","ember-runtime/mixins/enumerable","ember-metal/mixin","ember-metal/property_events"],function(e,t,r,n,i){"use strict";e["default"]=n.Mixin.create(r["default"],{addObject:null,addObjects:function(e){return (i.beginPropertyChanges(this), t.forEach(e,function(e){this.addObject(e)},this), i.endPropertyChanges(this), this)},removeObject:null,removeObjects:function(e){i.beginPropertyChanges(this);for(var t=e.length-1;t>=0;t--)this.removeObject(e[t]);return (i.endPropertyChanges(this), this)}})}),e("ember-runtime/mixins/observable",["exports","ember-metal/core","ember-metal/property_get","ember-metal/property_set","ember-metal/get_properties","ember-metal/set_properties","ember-metal/mixin","ember-metal/events","ember-metal/property_events","ember-metal/observer","ember-metal/computed","ember-metal/is_none"],function(e,t,r,n,i,a,o,s,l,u,c,h){"use strict";e["default"]=o.Mixin.create({get:function(e){return r.get(this,e)},getProperties:function(){for(var e=arguments.length,t=Array(e),r=0;e>r;r++)t[r]=arguments[r];return i["default"].apply(null,[this].concat(t))},set:function(e,t){return (n.set(this,e,t), this)},setProperties:function(e){return a["default"](this,e)},beginPropertyChanges:function(){return (l.beginPropertyChanges(), this)},endPropertyChanges:function(){return (l.endPropertyChanges(), this)},propertyWillChange:function(e){return (l.propertyWillChange(this,e), this)},propertyDidChange:function(e){return (l.propertyDidChange(this,e), this)},notifyPropertyChange:function(e){return (this.propertyWillChange(e), this.propertyDidChange(e), this)},_addBeforeObserver:function(e,t,r){u._addBeforeObserver(this,e,t,r)},addObserver:function(e,t,r){u.addObserver(this,e,t,r)},removeObserver:function(e,t,r){u.removeObserver(this,e,t,r)},hasObserverFor:function(e){return s.hasListeners(this,e+":change")},getWithDefault:function(e,t){return r.getWithDefault(this,e,t)},incrementProperty:function(e,t){return (h["default"](t)&&(t=1), n.set(this,e,(parseFloat(r.get(this,e))||0)+t), r.get(this,e))},decrementProperty:function(e,t){return (h["default"](t)&&(t=1), n.set(this,e,(r.get(this,e)||0)-t), r.get(this,e))},toggleProperty:function(e){return (n.set(this,e,!r.get(this,e)), r.get(this,e))},cacheFor:function(e){return c.cacheFor(this,e)},observersForKey:function(e){return u.observersFor(this,e)}})}),e("ember-runtime/mixins/promise_proxy",["exports","ember-metal/property_get","ember-metal/set_properties","ember-metal/computed","ember-metal/mixin","ember-metal/error"],function(e,t,r,n,i,a){"use strict";function o(e,t){return (r["default"](e,{isFulfilled:!1,isRejected:!1}), t.then(function(t){return (r["default"](e,{content:t,isFulfilled:!0}), t)},function(t){throw (r["default"](e,{reason:t,isRejected:!0}), t)},"Ember: PromiseProxy"))}function s(e){return function(){var r=t.get(this,"promise");return r[e].apply(r,arguments)}}var l=n.computed.not,u=n.computed.or;e["default"]=i.Mixin.create({reason:null,isPending:l("isSettled").readOnly(),isSettled:u("isRejected","isFulfilled").readOnly(),isRejected:!1,isFulfilled:!1,promise:n.computed({get:function(){throw new a["default"]("PromiseProxy's promise must be set")},set:function(e,t){return o(this,t)}}),then:s("then"),"catch":s("catch"),"finally":s("finally")})}),e("ember-runtime/mixins/sortable",["exports","ember-metal/core","ember-metal/property_get","ember-metal/enumerable_utils","ember-runtime/mixins/mutable_enumerable","ember-runtime/compare","ember-metal/observer","ember-metal/computed","ember-metal/computed_macros","ember-metal/mixin"],function(e,t,r,n,i,a,o,s,l,u){"use strict";e["default"]=u.Mixin.create(i["default"],{sortProperties:null,sortAscending:!0,sortFunction:a["default"],init:function(){this._super.apply(this,arguments)},orderBy:function(e,t){var i=0,a=r.get(this,"sortProperties"),o=r.get(this,"sortAscending"),s=r.get(this,"sortFunction");return (n.forEach(a,function(n){0===i&&(i=s.call(this,r.get(e,n),r.get(t,n)),0===i||o||(i=-1*i))},this), i)},destroy:function(){var e=r.get(this,"content"),t=r.get(this,"sortProperties");return (e&&t&&n.forEach(e,function(e){n.forEach(t,function(t){o.removeObserver(e,t,this,"contentItemSortPropertyDidChange")},this)},this), this._super.apply(this,arguments))},isSorted:l.notEmpty("sortProperties"),arrangedContent:s.computed("content","sortProperties.[]",{get:function(e){var i=r.get(this,"content"),a=r.get(this,"isSorted"),s=r.get(this,"sortProperties"),l=this;return i&&a?(i=i.slice(),i.sort(function(e,t){return l.orderBy(e,t)}),n.forEach(i,function(e){n.forEach(s,function(t){o.addObserver(e,t,this,"contentItemSortPropertyDidChange")},this)},this),t["default"].A(i)):i}}),_contentWillChange:u._beforeObserver("content",function(){var e=r.get(this,"content"),t=r.get(this,"sortProperties");e&&t&&n.forEach(e,function(e){n.forEach(t,function(t){o.removeObserver(e,t,this,"contentItemSortPropertyDidChange")},this)},this),this._super.apply(this,arguments)}),sortPropertiesWillChange:u._beforeObserver("sortProperties",function(){this._lastSortAscending=void 0}),sortPropertiesDidChange:u.observer("sortProperties",function(){this._lastSortAscending=void 0}),sortAscendingWillChange:u._beforeObserver("sortAscending",function(){this._lastSortAscending=r.get(this,"sortAscending")}),sortAscendingDidChange:u.observer("sortAscending",function(){if(void 0!==this._lastSortAscending&&r.get(this,"sortAscending")!==this._lastSortAscending){var e=r.get(this,"arrangedContent");e.reverseObjects()}}),contentArrayWillChange:function(e,t,i,a){var s=r.get(this,"isSorted");if(s){var l=r.get(this,"arrangedContent"),u=e.slice(t,t+i),c=r.get(this,"sortProperties");n.forEach(u,function(e){l.removeObject(e),n.forEach(c,function(t){o.removeObserver(e,t,this,"contentItemSortPropertyDidChange")},this)},this)}return this._super(e,t,i,a)},contentArrayDidChange:function(e,t,i,a){var s=r.get(this,"isSorted"),l=r.get(this,"sortProperties");if(s){var u=e.slice(t,t+a);n.forEach(u,function(e){this.insertItemSorted(e),n.forEach(l,function(t){o.addObserver(e,t,this,"contentItemSortPropertyDidChange")},this)},this)}return this._super(e,t,i,a)},insertItemSorted:function(e){var t=r.get(this,"arrangedContent"),n=r.get(t,"length"),i=this._binarySearch(e,0,n);t.insertAt(i,e)},contentItemSortPropertyDidChange:function(e){var t=r.get(this,"arrangedContent"),n=t.indexOf(e),i=t.objectAt(n-1),a=t.objectAt(n+1),o=i&&this.orderBy(e,i),s=a&&this.orderBy(e,a);(0>o||s>0)&&(t.removeObject(e),this.insertItemSorted(e))},_binarySearch:function(e,t,n){var i,a,o,s;return t===n?t:(s=r.get(this,"arrangedContent"),i=t+Math.floor((n-t)/2),a=s.objectAt(i),o=this.orderBy(a,e),0>o?this._binarySearch(e,i+1,n):o>0?this._binarySearch(e,t,i):i)}})}),e("ember-runtime/mixins/target_action_support",["exports","ember-metal/core","ember-metal/property_get","ember-metal/mixin","ember-metal/computed"],function(e,t,r,n,i){"use strict";var a=n.Mixin.create({target:null,action:null,actionContext:null,targetObject:i.computed("target",function(){if(this._targetObject)return this._targetObject;var e=r.get(this,"target");if("string"==typeof e){var n=r.get(this,e);return (void 0===n&&(n=r.get(t["default"].lookup,e)), n)}return e}),actionContextObject:i.computed(function(){var e=r.get(this,"actionContext");if("string"==typeof e){var n=r.get(this,e);return (void 0===n&&(n=r.get(t["default"].lookup,e)), n)}return e}).property("actionContext"),triggerAction:function(e){function t(e,t){var r=[];return (t&&r.push(t), r.concat(e))}e=e||{};var n=e.action||r.get(this,"action"),i=e.target||r.get(this,"targetObject"),a=e.actionContext;if("undefined"==typeof a&&(a=r.get(this,"actionContextObject")||this),i&&n){var o;return (o=i.send?i.send.apply(i,t(a,n)):i[n].apply(i,t(a)), o!==!1&&(o=!0), o)}return!1}});e["default"]=a}),e("ember-runtime/system/application",["exports","ember-runtime/system/namespace"],function(e,t){"use strict";e["default"]=t["default"].extend()}),e("ember-runtime/system/array_proxy",["exports","ember-metal/core","ember-metal/property_get","ember-runtime/utils","ember-metal/computed","ember-metal/mixin","ember-metal/property_events","ember-metal/error","ember-runtime/system/object","ember-runtime/mixins/mutable_array","ember-runtime/mixins/enumerable","ember-runtime/system/string","ember-metal/alias"],function(e,t,r,n,i,a,o,s,l,u,c,h,m){"use strict";function d(){return this}var p="Index out of range",f=[],v=l["default"].extend(u["default"],{content:null,arrangedContent:m["default"]("content"),objectAtContent:function(e){return r.get(this,"arrangedContent").objectAt(e)},replaceContent:function(e,t,n){r.get(this,"content").replace(e,t,n)},_contentWillChange:a._beforeObserver("content",function(){this._teardownContent()}),_teardownContent:function(){var e=r.get(this,"content");e&&e.removeArrayObserver(this,{willChange:"contentArrayWillChange",didChange:"contentArrayDidChange"})},contentArrayWillChange:d,contentArrayDidChange:d,_contentDidChange:a.observer("content",function(){r.get(this,"content");this._setupContent()}),_setupContent:function(){var e=r.get(this,"content");e&&e.addArrayObserver(this,{willChange:"contentArrayWillChange",didChange:"contentArrayDidChange"})},_arrangedContentWillChange:a._beforeObserver("arrangedContent",function(){var e=r.get(this,"arrangedContent"),t=e?r.get(e,"length"):0;this.arrangedContentArrayWillChange(this,0,t,void 0),this.arrangedContentWillChange(this),this._teardownArrangedContent(e)}),_arrangedContentDidChange:a.observer("arrangedContent",function(){var e=r.get(this,"arrangedContent"),t=e?r.get(e,"length"):0;this._setupArrangedContent(),this.arrangedContentDidChange(this),this.arrangedContentArrayDidChange(this,0,void 0,t)}),_setupArrangedContent:function(){var e=r.get(this,"arrangedContent");e&&e.addArrayObserver(this,{willChange:"arrangedContentArrayWillChange",didChange:"arrangedContentArrayDidChange"})},_teardownArrangedContent:function(){var e=r.get(this,"arrangedContent");e&&e.removeArrayObserver(this,{willChange:"arrangedContentArrayWillChange",didChange:"arrangedContentArrayDidChange"})},arrangedContentWillChange:d,arrangedContentDidChange:d,objectAt:function(e){return r.get(this,"content")&&this.objectAtContent(e)},length:i.computed(function(){var e=r.get(this,"arrangedContent");return e?r.get(e,"length"):0}),_replace:function(e,t,n){var i=r.get(this,"content");return (i&&this.replaceContent(e,t,n), this)},replace:function(){if(r.get(this,"arrangedContent")!==r.get(this,"content"))throw new s["default"]("Using replace on an arranged ArrayProxy is not allowed.");this._replace.apply(this,arguments)},_insertAt:function(e,t){if(e>r.get(this,"content.length"))throw new s["default"](p);return (this._replace(e,0,[t]), this)},insertAt:function(e,t){if(r.get(this,"arrangedContent")===r.get(this,"content"))return this._insertAt(e,t);throw new s["default"]("Using insertAt on an arranged ArrayProxy is not allowed.")},removeAt:function(e,t){if("number"==typeof e){var n,i=r.get(this,"content"),a=r.get(this,"arrangedContent"),l=[];if(0>e||e>=r.get(this,"length"))throw new s["default"](p);for(void 0===t&&(t=1),n=e;e+t>n;n++)l.push(i.indexOf(a.objectAt(n)));for(l.sort(function(e,t){return t-e}),o.beginPropertyChanges(),n=0;ny;y++){var w=v[y];if("object"!=typeof w&&void 0!==w)throw new c["default"]("Ember.Object.create only accepts objects.");if(w)for(var x=m["default"](w),C=0,k=x.length;k>C;C++){var E=x[C],N=w[E];if(l.IS_BINDING.test(E)){var O=d.bindings;O?d.hasOwnProperty("bindings")||(O=d.bindings=a["default"](d.bindings)):O=d.bindings={},O[E]=N}var P=this[E],S=null!==P&&"object"==typeof P&&P.isDescriptor?P:void 0;if(g&&g.length>0&&u.indexOf(g,E)>=0){var T=this[E];N=T?"function"==typeof T.concat?T.concat(N):i.makeArray(T).concat(N):i.makeArray(N)}if(b&&b.length&&u.indexOf(b,E)>=0){ +var R=this[E];N=r["default"](R,N)}S?S.set(this,E,N):"function"!=typeof this.setUnknownProperty||E in this?this[E]=N:this.setUnknownProperty(E,N)}}}A(this,d);var M=arguments.length;if(0===M)this.init();else if(1===M)this.init(arguments[0]);else{for(var D=new Array(M),I=0;M>I;I++)D[I]=arguments[I];this.init.apply(this,D)}d.proto=p,o.finishChains(this),s.sendEvent(this,"init")};return (h.toString=l.Mixin.prototype.toString, h.willReopen=function(){n&&(h.PrototypeMixin=l.Mixin.create(h.PrototypeMixin)),n=!1}, h._initMixins=function(t){e=t}, h._initProperties=function(e){t=e}, h.proto=function(){var e=h.superclass;return (e&&e.proto(), n||(n=!0,h.PrototypeMixin.applyPartial(h.prototype)), this.prototype)}, h)}function C(e){return function(){return e}}var k=b["default"].schedule,E=l.Mixin._apply,A=l.Mixin.finishPartial,N=l.Mixin.prototype.reopen,O=!1,P=x();P.toString=function(){return"Ember.CoreObject"},P.PrototypeMixin=l.Mixin.create({reopen:function(){for(var e=arguments.length,t=Array(e),r=0;e>r;r++)t[r]=arguments[r];return (E(this,t,!0), this)},init:function(){},__defineNonEnumerable:function(e){h.defineProperty(this,e.name,e.descriptor)},concatenatedProperties:null,isDestroyed:!1,isDestroying:!1,destroy:function(){return this.isDestroying?void 0:(this.isDestroying=!0,k("actions",this,this.willDestroy),k("destroy",this,this._scheduledDestroy),this)},willDestroy:_.K,_scheduledDestroy:function(){this.isDestroyed||(y.destroy(this),this.isDestroyed=!0)},bind:function(e,t){return (t instanceof f.Binding||(t=f.Binding.from(t)), t.to(e).connect(this), t)},toString:function(){var e="function"==typeof this.toStringExtension,t=e?":"+this.toStringExtension():"",r="<"+this.constructor.toString()+":"+i.guidFor(this)+t+">";return (this.toString=C(r), r)}}),P.PrototypeMixin.ownerConstructor=P,P.__super__=null;var S={ClassMixin:l.REQUIRED,PrototypeMixin:l.REQUIRED,isClass:!0,isMethod:!1,extend:function(){var e,t=x();return (t.ClassMixin=l.Mixin.create(this.ClassMixin), t.PrototypeMixin=l.Mixin.create(this.PrototypeMixin), t.ClassMixin.ownerConstructor=t, t.PrototypeMixin.ownerConstructor=t, N.apply(t.PrototypeMixin,arguments), t.superclass=this, t.__super__=this.prototype, e=t.prototype=a["default"](this.prototype), e.constructor=t, i.generateGuid(e), i.meta(e).proto=e, t.ClassMixin.apply(t), t)},createWithMixins:t["default"].deprecateFunc(".createWithMixins is deprecated, please use .create or .extend accordingly",function(){for(var e=this,t=arguments.length,r=Array(t),n=0;t>n;n++)r[n]=arguments[n];return (r.length>0&&this._initMixins(r), new e)}),create:function(){for(var e=this,t=arguments.length,r=Array(t),n=0;t>n;n++)r[n]=arguments[n];return (r.length>0&&this._initProperties(r), new e)},reopen:function(){return (this.willReopen(), N.apply(this.PrototypeMixin,arguments), this)},reopenClass:function(){return (N.apply(this.ClassMixin,arguments), E(this,arguments,!1), this)},detect:function(e){if("function"!=typeof e)return!1;for(;e;){if(e===this)return!0;e=e.superclass}return!1},detectInstance:function(e){return e instanceof this},metaForProperty:function(e){var t=this.proto(),r=t[e],n=null!==r&&"object"==typeof r&&r.isDescriptor?r:void 0;return n._meta||{}},_computedProperties:v.computed(function(){O=!0;var e,t=this.proto(),r=[];for(var n in t)e=t[n],e instanceof v.ComputedProperty&&r.push({name:n,meta:e._meta});return r}).readOnly(),eachComputedProperty:function(e,t){for(var r,i,a={},o=n.get(this,"_computedProperties"),s=0,l=o.length;l>s;s++)r=o[s],i=r.name,e.call(t||this,r.name,r.meta||a)}};S._lazyInjections=function(){var e,t,r={},n=this.proto();for(e in n)t=n[e],t instanceof g["default"]&&(r[e]=t.type+":"+(t.name||e));return r};var T=l.Mixin.create(S);T.ownerConstructor=P,P.ClassMixin=T,T.apply(P),P.reopen({didDefineProperty:function(e,r,n){if(O!==!1&&n instanceof t["default"].ComputedProperty){var i=t["default"].meta(this.constructor).cache;i&&void 0!==i._computedProperties&&(i._computedProperties=void 0)}}}),e["default"]=P}),e("ember-runtime/system/deferred",["exports","ember-metal/core","ember-runtime/mixins/deferred","ember-runtime/system/object"],function(e,t,r,n){"use strict";var i=n["default"].extend(r["default"],{init:function(){this._super.apply(this,arguments)}});i.reopenClass({promise:function(e,t){var r=i.create();return (e.call(t,r), r)}}),e["default"]=i}),e("ember-runtime/system/each_proxy",["exports","ember-metal/core","ember-metal/property_get","ember-metal/utils","ember-runtime/utils","ember-metal/enumerable_utils","ember-metal/array","ember-runtime/mixins/array","ember-runtime/system/object","ember-metal/computed","ember-metal/observer","ember-metal/events","ember-metal/properties","ember-metal/property_events"],function(e,t,r,n,i,a,o,s,l,u,c,h,m,d){"use strict";function p(e,t,r,i,a){var o,s=r._objects;for(s||(s=r._objects={});--a>=i;){var l=e.objectAt(a);l&&(c._addBeforeObserver(l,t,r,"contentKeyWillChange"),c.addObserver(l,t,r,"contentKeyDidChange"),o=n.guidFor(l),s[o]||(s[o]=[]),s[o].push(a))}}function f(e,t,r,i,a){var s=r._objects;s||(s=r._objects={});for(var l,u;--a>=i;){var h=e.objectAt(a);h&&(c._removeBeforeObserver(h,t,r,"contentKeyWillChange"),c.removeObserver(h,t,r,"contentKeyDidChange"),u=n.guidFor(h),l=s[u],l[o.indexOf.call(l,a)]=null)}}var v=l["default"].extend(s["default"],{init:function(e,t,r){this._super.apply(this,arguments),this._keyName=t,this._owner=r,this._content=e},objectAt:function(e){var t=this._content.objectAt(e);return t&&r.get(t,this._keyName)},length:u.computed(function(){var e=this._content;return e?r.get(e,"length"):0})}),g=/^.+:(before|change)$/,b=l["default"].extend({init:function(e){this._super.apply(this,arguments),this._content=e,e.addArrayObserver(this),a.forEach(h.watchedEvents(this),function(e){this.didAddListener(e)},this)},unknownProperty:function(e,t){var r=new v(this._content,e,this);return (m.defineProperty(this,e,null,r), this.beginObservingContentKey(e), r)},arrayWillChange:function(e,t,r,n){var i,a,o=this._keys;a=r>0?t+r:-1,d.beginPropertyChanges(this);for(i in o)o.hasOwnProperty(i)&&(a>0&&f(e,i,this,t,a),d.propertyWillChange(this,i));d.propertyWillChange(this._content,"@each"),d.endPropertyChanges(this)},arrayDidChange:function(e,t,r,n){var i,a=this._keys;i=n>0?t+n:-1,d.changeProperties(function(){for(var r in a)a.hasOwnProperty(r)&&(i>0&&p(e,r,this,t,i),d.propertyDidChange(this,r));d.propertyDidChange(this._content,"@each")},this)},didAddListener:function(e){g.test(e)&&this.beginObservingContentKey(e.slice(0,-7))},didRemoveListener:function(e){g.test(e)&&this.stopObservingContentKey(e.slice(0,-7))},beginObservingContentKey:function(e){var t=this._keys;if(t||(t=this._keys={}),t[e])t[e]++;else{t[e]=1;var n=this._content,i=r.get(n,"length");p(n,e,this,0,i)}},stopObservingContentKey:function(e){var t=this._keys;if(t&&t[e]>0&&--t[e]<=0){var n=this._content,i=r.get(n,"length");f(n,e,this,0,i)}},contentKeyWillChange:function(e,t){d.propertyWillChange(this,t)},contentKeyDidChange:function(e,t){d.propertyDidChange(this,t)}});e.EachArray=v,e.EachProxy=b}),e("ember-runtime/system/lazy_load",["exports","ember-metal/core","ember-metal/array","ember-runtime/system/native_array"],function(e,t,r,n){"use strict";function i(e,r){var n=s[e];o[e]=o[e]||t["default"].A(),o[e].pushObject(r),n&&r(n)}function a(e,t){if(s[e]=t,"object"==typeof window&&"function"==typeof window.dispatchEvent&&"function"==typeof CustomEvent){var n=new CustomEvent(e,{detail:t,name:e});window.dispatchEvent(n)}o[e]&&r.forEach.call(o[e],function(e){e(t)})}e.onLoad=i,e.runLoadHooks=a;var o=t["default"].ENV.EMBER_LOAD_HOOKS||{},s={},l=s;e._loaded=l}),e("ember-runtime/system/namespace",["exports","ember-metal/core","ember-metal/property_get","ember-metal/array","ember-metal/utils","ember-metal/mixin","ember-runtime/system/object"],function(e,t,r,n,i,a,o){"use strict";function s(e,t,r){var n=e.length;f[e.join(".")]=t;for(var a in t)if(v.call(t,a)){var o=t[a];if(e[n]=a,o&&o.toString===h)o.toString=d(e.join(".")),o[b]=e.join(".");else if(o&&o.isNamespace){if(r[i.guidFor(o)])continue;r[i.guidFor(o)]=!0,s(e,o,r)}}e.length=n}function l(e,t){try{var r=e[t];return r&&r.isNamespace&&r}catch(n){}}function u(){var e,r=t["default"].lookup;if(!p.PROCESSED)for(var n in r)g.test(n)&&(!r.hasOwnProperty||r.hasOwnProperty(n))&&(e=l(r,n),e&&(e[b]=n))}function c(e){var t=e.superclass;return t?t[b]?t[b]:c(t):void 0}function h(){t["default"].BOOTED||this[b]||m();var e;if(this[b])e=this[b];else if(this._toString)e=this._toString;else{var r=c(this);e=r?"(subclass of "+r+")":"(unknown mixin)",this.toString=d(e)}return e}function m(){var e=!p.PROCESSED,r=t["default"].anyUnprocessedMixins;if(e&&(u(),p.PROCESSED=!0),e||r){for(var n,i=p.NAMESPACES,a=0,o=i.length;o>a;a++)n=i[a],s([n.toString()],n,{});t["default"].anyUnprocessedMixins=!1}}function d(e){return function(){return e}}var p=o["default"].extend({isNamespace:!0,init:function(){p.NAMESPACES.push(this),p.PROCESSED=!1},toString:function(){var e=r.get(this,"name")||r.get(this,"modulePrefix");return e?e:(u(),this[b])},nameClasses:function(){s([this.toString()],this,{})},destroy:function(){var e=p.NAMESPACES,r=this.toString();r&&(t["default"].lookup[r]=void 0,delete p.NAMESPACES_BY_ID[r]),e.splice(n.indexOf.call(e,this),1),this._super.apply(this,arguments)}});p.reopenClass({NAMESPACES:[t["default"]],NAMESPACES_BY_ID:{},PROCESSED:!1,processAll:m,byName:function(e){return (t["default"].BOOTED||m(), f[e])}});var f=p.NAMESPACES_BY_ID,v={}.hasOwnProperty,g=/^[A-Z]/,b=t["default"].NAME_KEY=i.GUID_KEY+"_name";a.Mixin.prototype.toString=h,e["default"]=p}),e("ember-runtime/system/native_array",["exports","ember-metal/core","ember-metal/property_get","ember-metal/enumerable_utils","ember-metal/mixin","ember-metal/array","ember-runtime/mixins/array","ember-runtime/mixins/mutable_array","ember-runtime/mixins/observable","ember-runtime/mixins/copyable","ember-runtime/mixins/freezable","ember-runtime/copy"],function(e,t,r,n,i,a,o,s,l,u,c,h){"use strict";var m=i.Mixin.create(s["default"],l["default"],u["default"],{get:function(e){return"length"===e?this.length:"number"==typeof e?this[e]:this._super(e)},objectAt:function(e){return this[e]},replace:function(e,t,i){if(this.isFrozen)throw c.FROZEN_ERROR;var a=i?r.get(i,"length"):0;return (this.arrayContentWillChange(e,t,a), 0===a?this.splice(e,t):n._replace(this,e,t,i), this.arrayContentDidChange(e,t,a), this)},unknownProperty:function(e,t){var r;return (void 0!==t&&void 0===r&&(r=this[e]=t), r)},indexOf:a.indexOf,lastIndexOf:a.lastIndexOf,copy:function(e){return e?this.map(function(e){return h["default"](e,!0)}):this.slice()}}),d=["length"];n.forEach(m.keys(),function(e){Array.prototype[e]&&d.push(e)}),e.NativeArray=m=m.without.apply(m,d);var p=function(e){return (void 0===e&&(e=[]), o["default"].detect(e)?e:m.apply(e))};m.activate=function(){m.apply(Array.prototype),e.A=p=function(e){return e||[]}},(t["default"].EXTEND_PROTOTYPES===!0||t["default"].EXTEND_PROTOTYPES.Array)&&m.activate(),t["default"].A=p,e.A=p,e.NativeArray=m,e["default"]=m}),e("ember-runtime/system/object",["exports","ember-runtime/system/core_object","ember-runtime/mixins/observable"],function(e,t,r){"use strict";var n=t["default"].extend(r["default"]);n.toString=function(){return"Ember.Object"},e["default"]=n}),e("ember-runtime/system/object_proxy",["exports","ember-runtime/system/object","ember-runtime/mixins/-proxy"],function(e,t,r){"use strict";e["default"]=t["default"].extend(r["default"])}),e("ember-runtime/system/service",["exports","ember-runtime/system/object","ember-runtime/inject"],function(e,t,r){"use strict";r.createInjectionHelper("service");var n=t["default"].extend();n.reopenClass({isServiceFactory:!0}),e["default"]=n}),e("ember-runtime/system/set",["exports","ember-metal/core","ember-metal/property_get","ember-metal/property_set","ember-metal/utils","ember-metal/is_none","ember-runtime/system/string","ember-runtime/system/core_object","ember-runtime/mixins/mutable_enumerable","ember-runtime/mixins/enumerable","ember-runtime/mixins/copyable","ember-runtime/mixins/freezable","ember-metal/error","ember-metal/property_events","ember-metal/mixin","ember-metal/computed"],function(e,t,r,n,i,a,o,s,l,u,c,h,m,d,p,f){"use strict";e["default"]=s["default"].extend(l["default"],c["default"],h.Freezable,{length:0,clear:function(){if(this.isFrozen)throw new m["default"](h.FROZEN_ERROR);var e=r.get(this,"length");if(0===e)return this;var t;this.enumerableContentWillChange(e,0),d.propertyWillChange(this,"firstObject"),d.propertyWillChange(this,"lastObject");for(var a=0;e>a;a++)t=i.guidFor(this[a]),delete this[t],delete this[a];return (n.set(this,"length",0), d.propertyDidChange(this,"firstObject"), d.propertyDidChange(this,"lastObject"), this.enumerableContentDidChange(e,0), this)},isEqual:function(e){if(!u["default"].detect(e))return!1;var t=r.get(this,"length");if(r.get(e,"length")!==t)return!1;for(;--t>=0;)if(!e.contains(this[t]))return!1;return!0},add:p.aliasMethod("addObject"),remove:p.aliasMethod("removeObject"),pop:function(){if(r.get(this,"isFrozen"))throw new m["default"](h.FROZEN_ERROR);var e=this.length>0?this[this.length-1]:null;return (this.remove(e), e)},push:p.aliasMethod("addObject"),shift:p.aliasMethod("pop"),unshift:p.aliasMethod("push"),addEach:p.aliasMethod("addObjects"),removeEach:p.aliasMethod("removeObjects"),init:function(e){this._super.apply(this,arguments),e&&this.addObjects(e)},nextObject:function(e){return this[e]},firstObject:f.computed(function(){return this.length>0?this[0]:void 0}),lastObject:f.computed(function(){return this.length>0?this[this.length-1]:void 0}),addObject:function(e){if(r.get(this,"isFrozen"))throw new m["default"](h.FROZEN_ERROR);if(a["default"](e))return this;var t,o=i.guidFor(e),s=this[o],l=r.get(this,"length");return s>=0&&l>s&&this[s]===e?this:(t=[e],this.enumerableContentWillChange(null,t),d.propertyWillChange(this,"lastObject"),l=r.get(this,"length"),this[o]=l,this[l]=e,n.set(this,"length",l+1),d.propertyDidChange(this,"lastObject"),this.enumerableContentDidChange(null,t),this)},removeObject:function(e){if(r.get(this,"isFrozen"))throw new m["default"](h.FROZEN_ERROR);if(a["default"](e))return this;var t,o,s=i.guidFor(e),l=this[s],u=r.get(this,"length"),c=0===l,p=l===u-1;return (l>=0&&u>l&&this[l]===e&&(o=[e],this.enumerableContentWillChange(o,null),c&&d.propertyWillChange(this,"firstObject"),p&&d.propertyWillChange(this,"lastObject"),u-1>l&&(t=this[u-1],this[l]=t,this[i.guidFor(t)]=l),delete this[s],delete this[u-1],n.set(this,"length",u-1),c&&d.propertyDidChange(this,"firstObject"),p&&d.propertyDidChange(this,"lastObject"),this.enumerableContentDidChange(o,null)), this)},contains:function(e){return this[i.guidFor(e)]>=0},copy:function(){var e=this.constructor,t=new e,a=r.get(this,"length");for(n.set(t,"length",a);--a>=0;)t[a]=this[a],t[i.guidFor(this[a])]=a;return t},toString:function(){var e,t=this.length,r=[];for(e=0;t>e;e++)r[e]=this[e];return o.fmt("Ember.Set<%@>",[r.join(",")])}})}),e("ember-runtime/system/string",["exports","ember-metal/core","ember-metal/utils","ember-runtime/utils","ember-metal/cache"],function(e,t,r,n,i){"use strict";function a(e,t){var i=t;if(!n.isArray(i)||arguments.length>2){i=new Array(arguments.length-1);for(var a=1,o=arguments.length;o>a;a++)i[a-1]=arguments[a]}var s=0;return e.replace(/%@([0-9]+)?/g,function(e,t){return (t=t?parseInt(t,10)-1:s++, e=i[t], null===e?"(null)":void 0===e?"":r.inspect(e))})}function o(e,r){return((!n.isArray(r)||arguments.length>2)&&(r=Array.prototype.slice.call(arguments,1)), e=t["default"].STRINGS[e]||e, a(e,r))}function s(e){return e.split(/\s+/)}function l(e){return O.get(e)}function u(e){return f.get(e)}function c(e){return b.get(e)}function h(e){return w.get(e)}function m(e){return k.get(e)}function d(e){return A.get(e)}var p=/[ _]/g,f=new i["default"](1e3,function(e){return l(e).replace(p,"-")}),v=/(\-|\_|\.|\s)+(.)?/g,g=/(^|\/)([A-Z])/g,b=new i["default"](1e3,function(e){return e.replace(v,function(e,t,r){return r?r.toUpperCase():""}).replace(g,function(e,t,r){return e.toLowerCase()})}),y=/(\-|\_|\.|\s)+(.)?/g,_=/(^|\/|\.)([a-z])/g,w=new i["default"](1e3,function(e){return e.replace(y,function(e,t,r){return r?r.toUpperCase():""}).replace(_,function(e,t,r){return e.toUpperCase()})}),x=/([a-z\d])([A-Z]+)/g,C=/\-|\s+/g,k=new i["default"](1e3,function(e){return e.replace(x,"$1_$2").replace(C,"_").toLowerCase()}),E=/(^|\/)([a-z])/g,A=new i["default"](1e3,function(e){return e.replace(E,function(e,t,r){return e.toUpperCase()})}),N=/([a-z\d])([A-Z])/g,O=new i["default"](1e3,function(e){return e.replace(N,"$1_$2").toLowerCase()});t["default"].STRINGS={},e["default"]={fmt:a,loc:o,w:s,decamelize:l,dasherize:u,camelize:c,classify:h,underscore:m,capitalize:d},e.fmt=a,e.loc=o,e.w=s,e.decamelize=l,e.dasherize=u,e.camelize=c,e.classify=h,e.underscore=m,e.capitalize=d}),e("ember-runtime/system/subarray",["exports","ember-metal/core","ember-metal/error","ember-metal/enumerable_utils"],function(e,t,r,n){"use strict";function i(e,t){this.type=e,this.count=t}function a(e,t){void 0===e&&(e=0),e>0?this._operations=[new i(o,e)]:this._operations=[]}var o="r",s="f";e["default"]=a,a.prototype={addItem:function(e,t){var r=-1,n=t?o:s,a=this;return (this._findOperation(e,function(s,l,u,c,h){var m,d;n===s.type?++s.count:e===u?a._operations.splice(l,0,new i(n,1)):(m=new i(n,1),d=new i(s.type,c-e+1),s.count=e-u,a._operations.splice(l+1,0,m,d)),t&&(r=s.type===o?h+(e-u):h),a._composeAt(l)},function(e){a._operations.push(new i(n,1)),t&&(r=e),a._composeAt(a._operations.length-1)}), r)},removeItem:function(e){var t=-1,n=this;return (this._findOperation(e,function(r,i,a,s,l){r.type===o&&(t=l+(e-a)),r.count>1?--r.count:(n._operations.splice(i,1),n._composeAt(i))},function(){throw new r["default"]("Can't remove an item that has never been added.")}), t)},_findOperation:function(e,t,r){var n,i,a,s,l,u=0;for(n=s=0,i=this._operations.length;i>n;s=l+1,++n){if(a=this._operations[n],l=s+a.count-1,e>=s&&l>=e)return void t(a,n,s,l,u);a.type===o&&(u+=a.count)}r(u)},_composeAt:function(e){var t,r=this._operations[e];r&&(e>0&&(t=this._operations[e-1],t.type===r.type&&(r.count+=t.count,this._operations.splice(e-1,1),--e)),en)){var i,o,s=this._findArrayOperation(e),u=s.operation,c=s.index,h=s.rangeStart;o=new a(l,n,t),u?s.split?(this._split(c,e-h,o),i=c+1):(this._operations.splice(c,0,o),i=c):(this._operations.push(o),i=c),this._composeInsert(i)}},removeItems:function(e,t){if(!(1>t)){var r,n,i=this._findArrayOperation(e),o=i.index,s=i.rangeStart;return (r=new a(u,t), i.split?(this._split(o,e-s,r),n=o+1):(this._operations.splice(o,0,r),n=o), this._composeDelete(n))}},apply:function(e){var t=[],r=0;n.forEach(this._operations,function(n,i){e(n.items,r,n.type,i),n.type!==u&&(r+=n.count,t=t.concat(n.items))}),this._operations=[new a(s,t.length,t)]},_findArrayOperation:function(e){var t,r,n,i,a,s=!1;for(t=n=0,a=this._operations.length;a>t;++t)if(r=this._operations[t],r.type!==u){if(i=n+r.count-1,e===n)break;if(e>n&&i>=e){s=!0;break}n=i+1}return new o(r,t,s,n)},_split:function(e,t,r){var n=this._operations[e],i=n.items.slice(t),o=new a(n.type,i.length,i);n.count=t,n.items=n.items.slice(0,t),this._operations.splice(e+1,0,r,o)},_composeInsert:function(e){var t=this._operations[e],r=this._operations[e-1],n=this._operations[e+1],i=r&&r.type,a=n&&n.type;i===l?(r.count+=t.count,r.items=r.items.concat(t.items),a===l?(r.count+=n.count,r.items=r.items.concat(n.items),this._operations.splice(e,2)):this._operations.splice(e,1)):a===l&&(t.count+=n.count,t.items=t.items.concat(n.items),this._operations.splice(e+1,1))},_composeDelete:function(e){var t,r,n,i=this._operations[e],a=i.count,o=this._operations[e-1],s=o&&o.type,c=!1,h=[];s===u&&(i=o,e-=1);for(var m=e+1;a>0;++m)t=this._operations[m],r=t.type,n=t.count,r!==u?(n>a?(h=h.concat(t.items.splice(0,a)),t.count-=a,m-=1,n=a,a=0):(n===a&&(c=!0),h=h.concat(t.items),a-=n),r===l&&(i.count-=n)):i.count+=n;return (i.count>0?this._operations.splice(e+1,m-1-e):this._operations.splice(e,c?2:1), h)},toString:function(){var e="";return (n.forEach(this._operations,function(t){e+=" "+t.type+":"+t.count}), e.substring(1))}}}),e("ember-runtime/utils",["exports","ember-runtime/mixins/array","ember-runtime/system/object","ember-metal/utils"],function(e,t,r,n){"use strict";function i(e){if(!e||e.setInterval)return!1;if(n.isArray(e))return!0;if(t["default"].detect(e))return!0;var r=a(e);return"array"===r?!0:void 0!==e.length&&"object"===r?!0:!1}function a(e){if(null===e)return"null";if(void 0===e)return"undefined";var t=o[s.call(e)]||"object";return("function"===t?r["default"].detect(e)&&(t="class"):"object"===t&&(e instanceof Error?t="error":e instanceof r["default"]?t="instance":e instanceof Date&&(t="date")), t)}e.isArray=i,e.typeOf=a;var o={"[object Boolean]":"boolean","[object Number]":"number","[object String]":"string","[object Function]":"function","[object Array]":"array","[object Date]":"date","[object RegExp]":"regexp","[object Object]":"object"},s=Object.prototype.toString}),e("ember-template-compiler",["exports","ember-metal/core","ember-template-compiler/system/precompile","ember-template-compiler/system/compile","ember-template-compiler/system/template","ember-template-compiler/plugins","ember-template-compiler/plugins/transform-each-in-to-block-params","ember-template-compiler/plugins/transform-with-as-to-hash","ember-template-compiler/plugins/transform-bind-attr-to-attributes","ember-template-compiler/plugins/transform-each-into-collection","ember-template-compiler/plugins/transform-single-arg-each","ember-template-compiler/plugins/transform-old-binding-syntax","ember-template-compiler/plugins/transform-old-class-binding-syntax","ember-template-compiler/plugins/transform-item-class","ember-template-compiler/plugins/transform-component-attrs-into-mut","ember-template-compiler/plugins/transform-component-curly-to-readonly","ember-template-compiler/plugins/transform-angle-bracket-components","ember-template-compiler/plugins/transform-input-on-to-onEvent","ember-template-compiler/plugins/deprecate-view-and-controller-paths","ember-template-compiler/plugins/deprecate-view-helper","ember-template-compiler/plugins/deprecate-with-controller","ember-template-compiler/plugins/deprecate-unbound-block-and-multi-param","ember-template-compiler/compat"],function(e,t,r,n,i,a,o,s,l,u,c,h,m,d,p,f,v,g,b,y,_,w,x){"use strict";a.registerPlugin("ast",s["default"]),a.registerPlugin("ast",o["default"]),a.registerPlugin("ast",l["default"]),a.registerPlugin("ast",c["default"]),a.registerPlugin("ast",u["default"]),a.registerPlugin("ast",h["default"]),a.registerPlugin("ast",m["default"]),a.registerPlugin("ast",d["default"]),a.registerPlugin("ast",p["default"]),a.registerPlugin("ast",f["default"]),a.registerPlugin("ast",v["default"]),a.registerPlugin("ast",g["default"]),a.registerPlugin("ast",b["default"]),a.registerPlugin("ast",y["default"]),a.registerPlugin("ast",_["default"]),a.registerPlugin("ast",w["default"]),e._Ember=t["default"],e.precompile=r["default"],e.compile=n["default"],e.template=i["default"],e.registerPlugin=a.registerPlugin}),e("ember-template-compiler/compat",["exports","ember-metal/core","ember-template-compiler/compat/precompile","ember-template-compiler/system/compile","ember-template-compiler/system/template"],function(e,t,r,n,i){"use strict";var a=t["default"].Handlebars=t["default"].Handlebars||{};a.precompile=r["default"],a.compile=n["default"],a.template=i["default"]}),e("ember-template-compiler/compat/precompile",["exports","ember-template-compiler/system/compile_options"],function(e,r){"use strict";var n,a;e["default"]=function(e){if((!n||!a)&&i.__loader.registry["htmlbars-compiler/compiler"]){var o=t("htmlbars-compiler/compiler");n=o.compile,a=o.compileSpec}if(!n||!a)throw new Error("Cannot call `precompile` without the template compiler loaded. Please load `ember-template-compiler.js` prior to calling `precompile`.");var s=void 0===arguments[1]?!0:arguments[1],l=s?n:a;return l(e,r["default"]())}}),e("ember-template-compiler/plugins",["exports"],function(e){"use strict";function t(e,t){if(!r[e])throw new Error('Attempting to register "'+t+'" as "'+e+'" which is not a valid HTMLBars plugin type.');r[e].push(t)}e.registerPlugin=t;var r={ast:[]};e["default"]=r}),e("ember-template-compiler/plugins/deprecate-unbound-block-and-multi-param",["exports","ember-metal/core","ember-template-compiler/system/calculate-location-display"],function(e,t,r){"use strict";function n(e){this.syntax=null,this.options=e||{}}n.prototype.transform=function(e){var t=this,n=new t.syntax.Walker,i=t.options.moduleName;return (n.visit(e,function(e){if(t.isBlockUsage(e)){r["default"](i,e.loc)}else if(t.hasMultipleParams(e)){r["default"](i,e.loc)}}), e)},n.prototype.isBlockUsage=function(e){return"BlockStatement"===e.type&&"unbound"===e.path.original},n.prototype.hasMultipleParams=function(e){return("BlockStatement"===e.type||"MustacheStatement"===e.type)&&"unbound"===e.path.original&&e.params.length>1},e["default"]=n}),e("ember-template-compiler/plugins/deprecate-view-and-controller-paths",["exports","ember-metal/core","ember-template-compiler/system/calculate-location-display"],function(e,t,r){"use strict";function n(e){this.syntax=null,this.options=e||{}}function i(e,t,r){if(r&&r.pairs){var n,i,o,s;for(n=0,i=r.pairs.length;i>n;n++)o=r.pairs[n],s=o.value.params,a(e,o,s)}}function a(e,t,r){if(r){var n,i,a;for(n=0,i=r.length;i>n;n++)a=r[n],o(e,t,a)}}function o(e,t,r){}function s(e){return"MustacheStatement"===e.type||"BlockStatement"===e.type}n.prototype.transform=function(e){var t=new this.syntax.Walker,r=this.options&&this.options.moduleName;return (t.visit(e,function(e){s(e)&&(o(r,e,e.path),a(r,e,e.params),i(r,e,e.hash))}), e)},e["default"]=n}),e("ember-template-compiler/plugins/deprecate-view-helper",["exports","ember-metal/core","ember-template-compiler/system/calculate-location-display"],function(e,t,r){"use strict";function n(e){this.syntax=null,this.options=e||{}}function i(e,t){var r=t.params.length&&t.params[0].value;r&&"select"===r&&a(e,t)}function a(e,t){}function o(e){return("MustacheStatement"===e.type||"BlockStatement"===e.type)&&"view"===e.path.parts[0]}n.prototype.transform=function(e){if(t["default"].ENV._ENABLE_LEGACY_VIEW_SUPPORT)return e;var r=new this.syntax.Walker,n=this.options&&this.options.moduleName;return (r.visit(e,function(e){o(e)&&i(n,e)}), e)},e["default"]=n}),e("ember-template-compiler/plugins/deprecate-with-controller",["exports","ember-metal/core","ember-template-compiler/system/calculate-location-display"],function(e,t,r){"use strict";function n(e){this.syntax=null,this.options=e||{}}function i(e,t){for(var r=0,n=e.pairs.length;n>r;r++){var i=e.pairs[r];if(i.key===t)return i}return!1}n.prototype.transform=function(e){var t=this,n=new t.syntax.Walker,i=t.options.moduleName;return (n.visit(e,function(e){if(t.validate(e)){r["default"](i,e.loc)}}), e)},n.prototype.validate=function(e){return("BlockStatement"===e.type||"MustacheStatement"===e.type)&&"with"===e.path.original&&i(e.hash,"controller")},e["default"]=n}),e("ember-template-compiler/plugins/transform-angle-bracket-components",["exports"],function(e){"use strict";function t(){this.syntax=null}function r(e){return"ComponentNode"===e.type}t.prototype.transform=function(e){var t=new this.syntax.Walker;return (t.visit(e,function(e){r(e)&&(e.tag="<"+e.tag+">")}), e)},e["default"]=t}),e("ember-template-compiler/plugins/transform-bind-attr-to-attributes",["exports","ember-metal/core","ember-template-compiler/system/string","ember-template-compiler/system/calculate-location-display"],function(e,t,r,n){"use strict";function i(e){this.syntax=null,this.options=e||{}}function a(e,t){var r=e.path.original;n["default"](t,e.path.loc);return"bind-attr"===r||"bindAttr"===r?!0:!1}function o(e,t){for(var r=0;r0&&r.parts.push(t.string(" "));var a=this.parseClass(n[i]);r.parts.push(a)}return r},i.prototype.parseClass=function(e){var r=this.syntax.builders,n=e.split(":");switch(n.length){case 1:return r.sexpr(r.path("-bind-attr-class"),[r.path(n[0]),r.string(s(n[0]))]);case 2:return""===n[0]?r.string(n[1]):r.sexpr(r.path("if"),[r.path(n[0]),r.string(n[1]),r.string("")]);case 3:return r.sexpr(r.path("if"),[r.path(n[0]),r.string(n[1]),r.string(n[2])]);default:t["default"].assert("Unsupported bind-attr class syntax: `"+e+"`")}},e["default"]=i}),e("ember-template-compiler/plugins/transform-component-attrs-into-mut",["exports"],function(e){"use strict";function t(){this.syntax=null}function r(e){return"BlockStatement"===e.type||"MustacheStatement"===e.type}function n(e,t){for(var r=0,n=e.length;n>r;r++)t(e[r])}t.prototype.transform=function(e){var t=this.syntax.builders,i=new this.syntax.Walker;return (i.visit(e,function(e){r(e)&&n(e.hash.pairs,function(e){var r=e.value;"PathExpression"===r.type&&(e.value=t.sexpr(t.path("@mut"),[e.value]))})}), e)},e["default"]=t}),e("ember-template-compiler/plugins/transform-component-curly-to-readonly",["exports"],function(e){"use strict";function t(){this.syntax=null}function r(e){return"ComponentNode"===e.type}function n(e,t){for(var r=0,n=e.length;n>r;r++)t(e[r])}t.prototype.transform=function(e){var t=this.syntax.builders,i=new this.syntax.Walker;return (i.visit(e,function(e){r(e)&&n(e.attributes,function(e){"MustacheStatement"===e.value.type&&(e.value.params.length||e.value.hash.pairs.length||(e.value=t.mustache(t.path("readonly"),[e.value.path],null,!e.value.escape)))})}), e)},e["default"]=t}),e("ember-template-compiler/plugins/transform-each-in-to-block-params",["exports","ember-metal/core","ember-template-compiler/system/calculate-location-display"],function(e,t,r){"use strict";function n(e){this.syntax=null,this.options=e}function i(e){return("BlockStatement"===e.type||"MustacheStatement"===e.type)&&"each"===e.path.original&&3===e.params.length&&"PathExpression"===e.params[1].type&&"in"===e.params[1].original}n.prototype.transform=function(e){var t=this.syntax.builders,n=new this.syntax.Walker,a=this.options.moduleName;return (n.visit(e,function(e){ +if(i(e)){var n=e.params.splice(0,2),o=n[0].original,s=void 0;if("BlockStatement"===e.type){if(s=r["default"](a,e.program.loc),e.program.blockParams.length)throw new Error("You cannot use keyword (`{{#each foo in bar}}`) and block params (`{{#each bar as |foo|}}`) at the same time "+s+".");e.program.blockParams=[o]}else s=r["default"](a,e.loc),e.hash.pairs.push(t.pair("keyword",t.string(o)))}}), e)},e["default"]=n}),e("ember-template-compiler/plugins/transform-each-in-to-hash",["exports"],function(e){"use strict";function t(e){this.syntax=null,this.options=e||{}}t.prototype.transform=function(e){var t=this,r=new t.syntax.Walker,n=t.syntax.builders;return (r.visit(e,function(e){if(t.validate(e)){if(e.program&&e.program.blockParams.length)throw new Error("You cannot use keyword (`{{each foo in bar}}`) and block params (`{{each bar as |foo|}}`) at the same time.");var r=e.sexpr.params.splice(0,2),i=r[0].original;e.sexpr.hash||(e.sexpr.hash=n.hash()),e.sexpr.hash.pairs.push(n.pair("keyword",n.string(i)))}}), e)},t.prototype.validate=function(e){return("BlockStatement"===e.type||"MustacheStatement"===e.type)&&"each"===e.sexpr.path.original&&3===e.sexpr.params.length&&"PathExpression"===e.sexpr.params[1].type&&"in"===e.sexpr.params[1].original},e["default"]=t}),e("ember-template-compiler/plugins/transform-each-into-collection",["exports","ember-metal/core","ember-template-compiler/system/calculate-location-display"],function(e,t,r){"use strict";function n(e){this.options=e,this.syntax=null}function i(e){return"BlockStatement"!==e.type&&"MustacheStatement"!==e.type||"each"!==e.path.original?!1:a(e.hash.pairs,function(e){var t=e.key;return"itemController"===t||"itemView"===t||"itemViewClass"===t||"tagName"===t||"emptyView"===t||"emptyViewClass"===t})}function a(e,t){for(var r=0,n=e.length;n>r;r++)if(t(e[r]))return e[r];return!1}e["default"]=n,n.prototype.transform=function(e){var t=this.options.moduleName,n=this.syntax.builders,a=new this.syntax.Walker;return (a.visit(e,function(e){var a=i(e);if(a){var o=(r["default"](t,a.loc),e.params.shift());e.path=n.path("collection"),e.params.unshift(n.string("-legacy-each"));var s=n.pair("content",o);s.loc=o.loc,e.hash.pairs.push(s)}}), e)}}),e("ember-template-compiler/plugins/transform-input-on-to-onEvent",["exports","ember-metal/core","ember-template-compiler/system/calculate-location-display"],function(e,t,r){"use strict";function n(e){this.syntax=null,this.options=e||{}}function i(e,t){for(var r=0,n=e.pairs.length;n>r;r++){var i=e.pairs[r];if(i.key===t)return i}return!1}function a(e,t){for(var r=[],n=0,i=e.pairs.length;i>n;n++){var a=e.pairs[n];a!==t&&r.push(a)}e.pairs=r}n.prototype.transform=function(e){var t=this,n=t.syntax.builders,o=new t.syntax.Walker,s=t.options.moduleName;return (o.visit(e,function(e){if(t.validate(e)){var o=i(e.hash,"action"),l=i(e.hash,"on"),u=i(e.hash,"onEvent"),c=l||u;r["default"](s,e.loc);if(c&&"StringLiteral"!==c.value.type)return void(c.key="onEvent");if(a(e.hash,c),a(e.hash,o),!o)return;c?c.key+'="'+c.value.value+'" ':"";c&&"keyPress"===c.value.value&&(c.value.value="key-press");(c?c.value.value:"enter")+'="'+o.value.original+'"';c||(c=n.pair("onEvent",n.string("enter"))),e.hash.pairs.push(n.pair(c.value.value,o.value))}}), e)},n.prototype.validate=function(e){return"MustacheStatement"===e.type&&"input"===e.path.original&&(i(e.hash,"action")||i(e.hash,"on")||i(e.hash,"onEvent"))},e["default"]=n}),e("ember-template-compiler/plugins/transform-item-class",["exports"],function(e){"use strict";function t(){this.syntax=null}function r(e){return("BlockStatement"===e.type||"MustacheStatement"===e.type)&&"collection"===e.path.original}function n(e,t){for(var r=0,n=e.length;n>r;r++)t(e[r])}e["default"]=t,t.prototype.transform=function(e){var t=this.syntax.builders,i=new this.syntax.Walker;return (i.visit(e,function(e){r(e)&&n(e.hash.pairs,function(e){var r=e.key,n=e.value;if("itemClass"===r&&"StringLiteral"!==n.type){var i=n.original,a=[n],o=[t.string(i),t.path(i)];a.push(t.sexpr(t.string("-normalize-class"),o));var s=t.sexpr(t.string("if"),a);e.value=s}})}), e)}}),e("ember-template-compiler/plugins/transform-old-binding-syntax",["exports","ember-metal/core","ember-template-compiler/system/calculate-location-display"],function(e,t,r){"use strict";function n(e){this.syntax=null,this.options=e}function i(e){return"BlockStatement"===e.type||"MustacheStatement"===e.type}function a(e,t){for(var r=0,n=e.length;n>r;r++)t(e[r])}e["default"]=n,n.prototype.transform=function(e){var t=this.options.moduleName,n=this.syntax.builders,o=new this.syntax.Walker;return (o.visit(e,function(e){i(e)&&a(e.hash.pairs,function(e){var i=e.key,a=e.value;r["default"](t,e.loc);if("classBinding"!==i&&"Binding"===i.substr(-7)){var o=i.slice(0,-7);e.key=o,"StringLiteral"===a.type&&(e.value=n.path(a.original))}})}), e)}}),e("ember-template-compiler/plugins/transform-old-class-binding-syntax",["exports"],function(e){"use strict";function t(e){this.syntax=null,this.options=e}function r(e,t,r){for(var n=0,i=e.length;i>n;n++){var a=e[n],o=a[0],s=a[1],l=a[2],u=void 0;if(""===o)u=r.string(s);else{var c=[r.path(o)];if(s)c.push(r.string(s));else{var h=[r.string(o),r.path(o)],m=r.hash();void 0!==s&&m.pairs.push(r.pair("activeClass",r.string(s))),void 0!==l&&m.pairs.push(r.pair("inactiveClass",r.string(l))),c.push(r.sexpr(r.string("-normalize-class"),h,m))}l&&c.push(r.string(l)),u=r.sexpr(r.string("if"),c)}t.push(u),t.push(r.string(" "))}}function n(e){return"BlockStatement"===e.type||"MustacheStatement"===e.type}function i(e,t){for(var r=0,n=e.length;n>r;r++)t(e[r],r)}function a(e){for(var t=e.split(" "),r=0,n=t.length;n>r;r++)t[r]=t[r].split(":");return t}e["default"]=t,t.prototype.transform=function(e){var t=this.syntax.builders,o=new this.syntax.Walker;return (o.visit(e,function(e){if(n(e)){var o=[],s=[],l=void 0;if(i(e.hash.pairs,function(e,t){var r=e.key;"classBinding"===r||"classNameBindings"===r?(s.push(t),o.push(e)):"class"===r&&(l=e)}),0!==o.length){var u=[];l?(u.push(l.value),u.push(t.string(" "))):(l=t.pair("class",null),e.hash.pairs.push(l)),i(s,function(t){e.hash.pairs.splice(t,1)}),i(o,function(e){var n=e.value,i=(e.loc,[]);if("StringLiteral"===n.type){var o=a(n.original);r(o,i,t),u.push.apply(u,i)}});var c=t.hash();l.value=t.sexpr(t.string("concat"),u,c)}}}), e)}}),e("ember-template-compiler/plugins/transform-single-arg-each",["exports"],function(e){"use strict";function t(){this.syntax=null}function r(e){return("BlockStatement"===e.type||"MustacheStatement"===e.type)&&"each"===e.path.original&&0===e.params.length}e["default"]=t,t.prototype.transform=function(e){var t=this.syntax.builders,n=new this.syntax.Walker;return (n.visit(e,function(e){r(e)&&e.params.push(t.path("this"))}), e)}}),e("ember-template-compiler/plugins/transform-with-as-to-hash",["exports","ember-template-compiler/system/calculate-location-display"],function(e,t){"use strict";function r(e){this.syntax=null,this.options=e||{}}r.prototype.transform=function(e){var r=this,n=new r.syntax.Walker,i=this.options.moduleName;return (n.visit(e,function(e){if(r.validate(e)){if(e.program&&e.program.blockParams.length)throw new Error("You cannot use keyword (`{{with foo as bar}}`) and block params (`{{with foo as |bar|}}`) at the same time.");var n=(t["default"](i,e.program.loc),e.params.splice(1,2)),a=n[1].original;e.program.blockParams=[a]}}), e)},r.prototype.validate=function(e){return"BlockStatement"===e.type&&"with"===e.path.original&&3===e.params.length&&"PathExpression"===e.params[1].type&&"as"===e.params[1].original},e["default"]=r}),e("ember-template-compiler/system/calculate-location-display",["exports"],function(e){"use strict";function t(e,t){var r=t||{},n=r.start||{},i=n.column,a=n.line,o="";return (e&&(o+="'"+e+"' "), void 0!==a&&void 0!==i&&(e&&(o+="@ "),o+="L"+a+":C"+i), o&&(o="("+o+") "), o)}e["default"]=t}),e("ember-template-compiler/system/compile",["exports","ember-template-compiler/system/compile_options","ember-template-compiler/system/template"],function(e,r,n){"use strict";var a;e["default"]=function(e,o){if(!a&&i.__loader.registry["htmlbars-compiler/compiler"]&&(a=t("htmlbars-compiler/compiler").compile),!a)throw new Error("Cannot call `compile` without the template compiler loaded. Please load `ember-template-compiler.js` prior to calling `compile`.");var s=a(e,r["default"](o));return n["default"](s)}}),e("ember-template-compiler/system/compile_options",["exports","ember-metal/core","ember-metal/merge","ember-template-compiler/plugins"],function(e,t,r,n){"use strict";e["default"]=function(e){var t=!0,i=void 0;i=e===!0?{}:r.assign({},e),i.disableComponentGeneration=t;var a={ast:n["default"].ast.slice()};return (i.plugins&&i.plugins.ast&&(a.ast=a.ast.concat(i.plugins.ast)), i.plugins=a, i.buildMeta=function(e){return{revision:"Ember@1.13.12",loc:e.loc,moduleName:i.moduleName}}, i)}}),e("ember-template-compiler/system/precompile",["exports","ember-template-compiler/system/compile_options"],function(e,r){"use strict";var n;e["default"]=function(e,a){if(!n&&i.__loader.registry["htmlbars-compiler/compiler"]&&(n=t("htmlbars-compiler/compiler").compileSpec),!n)throw new Error("Cannot call `compileSpec` without the template compiler loaded. Please load `ember-template-compiler.js` prior to calling `compileSpec`.");return n(e,r["default"](a))}}),e("ember-template-compiler/system/string",["exports"],function(e){"use strict";function t(e){return e.replace(n,"$1_$2").toLowerCase()}function r(e){return t(e).replace(i,"-")}e.decamelize=t,e.dasherize=r;var n=/([a-z\d])([A-Z])/g,i=/[ _]/g}),e("ember-template-compiler/system/template",["exports","htmlbars-runtime/hooks"],function(e,t){"use strict";e["default"]=function(e){return (e.render||(e=t.wrap(e)), e.isTop=!0, e.isMethod=!1, e)}}),e("ember-views",["exports","ember-runtime","ember-views/system/jquery","ember-views/system/utils","ember-views/compat/render_buffer","ember-views/system/ext","ember-views/views/states","ember-metal-views/renderer","ember-views/views/core_view","ember-views/views/view","ember-views/views/container_view","ember-views/views/collection_view","ember-views/views/component","ember-views/system/event_dispatcher","ember-views/mixins/view_target_action_support","ember-views/component_lookup","ember-views/views/checkbox","ember-views/mixins/text_support","ember-views/views/text_field","ember-views/views/text_area","ember-views/views/select","ember-views/compat/metamorph_view","ember-views/views/legacy_each_view"],function(e,t,r,n,i,a,o,s,l,u,c,h,m,d,p,f,v,g,b,y,_,w,x){"use strict";t["default"].$=r["default"],t["default"].ViewTargetActionSupport=p["default"],t["default"].RenderBuffer=i["default"];var C=t["default"].ViewUtils={};C.isSimpleClick=n.isSimpleClick,C.getViewClientRects=n.getViewClientRects,C.getViewBoundingClientRect=n.getViewBoundingClientRect,t["default"].View=u.DeprecatedView,t["default"].View.states=o.states,t["default"].View.cloneStates=o.cloneStates,t["default"].View._Renderer=s["default"],t["default"].Checkbox=v["default"],t["default"].TextField=b["default"],t["default"].TextArea=y["default"],t["default"].SelectOption=_.SelectOption,t["default"].SelectOptgroup=_.SelectOptgroup,t["default"].TextSupport=g["default"],t["default"].ComponentLookup=f["default"],t["default"].Component=m["default"],t["default"].EventDispatcher=d["default"],t["default"].Select=_.DeprecatedSelect,t["default"].CoreView=l.DeprecatedCoreView,t["default"].ContainerView=c.DeprecatedContainerView,t["default"].CollectionView=h.DeprecatedCollectionView,t["default"]._Metamorph=w._Metamorph,t["default"]._MetamorphView=w["default"],t["default"]._LegacyEachView=x["default"],e["default"]=t["default"]}),e("ember-views/compat/attrs-proxy",["exports","ember-metal/mixin","ember-metal/utils","ember-metal/property_events","ember-metal/events","ember-metal/empty_object"],function(e,t,r,n,i,a){"use strict";function o(e){return"You tried to look up an attribute directly on the component. This is deprecated. Use attrs."+e+" instead."}function s(e){return e&&e[u]}function l(e){var t=e.constructor;if(!t.__avoidPropagating){t.__avoidPropagating=new a["default"];var r=void 0,n=void 0;for(r=0,n=e.concatenatedProperties.length;n>r;r++){var i=e.concatenatedProperties[r];t.__avoidPropagating[i]=!0}for(r=0,n=e.mergedProperties.length;n>r;r++){var i=e.mergedProperties[r];t.__avoidPropagating[i]=!0}}}e.deprecation=o;var u=r.symbol("MUTABLE_CELL");e.MUTABLE_CELL=u;var c={attrs:null,init:function(){this._super.apply(this,arguments),l(this)},getAttr:function(e){var t=this.attrs;if(t)return this.getAttrFor(t,e)},getAttrFor:function(e,t){var r=e[t];return s(r)?r.value:r},setAttr:function(e,t){var r=this.attrs,n=r[e];if(!s(n))throw new Error("You can't update attrs."+e+", because it's not mutable");n.update(t)},_propagateAttrsToThis:function(){var e=this.attrs;for(var t in e)"attrs"===t||this.constructor.__avoidPropagating[t]||this.set(t,this.getAttr(t))},initializeShape:i.on("init",function(){this._isDispatchingAttrs=!1}),_internalDidReceiveAttrs:function(){this._super(),this._isDispatchingAttrs=!0,this._propagateAttrsToThis(),this._isDispatchingAttrs=!1},unknownProperty:function(e){if(!this._isAngleBracket){var t=this.attrs;if(t&&e in t){var r=t[e];return r&&r[u]?r.value:r}}}};c[n.PROPERTY_DID_CHANGE]=function(e){this._isAngleBracket||this._isDispatchingAttrs||this.currentState&&this.currentState.legacyPropertyDidChange(this,e)},e["default"]=t.Mixin.create(c)}),e("ember-views/compat/metamorph_view",["exports","ember-metal/core","ember-views/views/view","ember-metal/mixin"],function(e,t,r,n){"use strict";var i=n.Mixin.create({tagName:"",__metamorphType:"Ember._Metamorph",instrumentName:"metamorph",init:function(){this._super.apply(this,arguments)}});e._Metamorph=i,e["default"]=r["default"].extend(i,{__metamorphType:"Ember._MetamorphView"})}),e("ember-views/compat/render_buffer",["exports","ember-views/system/jquery","ember-metal/core","ember-metal/platform/create","dom-helper/prop","ember-views/system/platform"],function(e,t,r,n,i,a){"use strict";function o(e,t,r){if(m=m||{tr:e.createElement("tbody"),col:e.createElement("colgroup")},"TABLE"===r.tagName){var n=d.exec(t);if(n)return m[n[1].toLowerCase()]}}function s(){this.seen=n["default"](null),this.list=[]}function l(e){return e&&p.test(e)?e.replace(f,""):e}function u(e){var t={"<":"<",">":">",'"':""","'":"'","`":"`"},r=function(e){return t[e]||"&"},n=e.toString();return g.test(n)?n.replace(v,r):n}function c(e,t,r){var n=[];e.render(n);var i=r.parseHTML(n.join(""),t);return i}function h(e){this.buffer=null,this.childViews=[],this.attrNodes=[],this.dom=e,this.tagName=void 0,this.buffer=null,this._element=null,this._outerContextualElement=void 0,this.elementClasses=null,this.elementId=null,this.elementAttributes=null,this.elementProperties=null,this.elementTag=null,this.elementStyle=null}e.renderComponentWithBuffer=c,e["default"]=h;var m,d=/(?:"'`]/g,g=/[&<>"'`]/;h.prototype={reset:function(e,t){this.tagName=e,this.buffer=null,this._element=null,this._outerContextualElement=t,this.elementClasses=null,this.elementId=null,this.elementAttributes=null,this.elementProperties=null,this.elementTag=null,this.elementStyle=null,this.childViews.length=0,this.attrNodes.length=0},_element:null,_outerContextualElement:null,elementClasses:null,classes:null,elementId:null,elementAttributes:null,elementProperties:null,elementTag:null,elementStyle:null,pushChildView:function(e){var t=this.childViews.length;this.childViews[t]=e,this.push("")},pushAttrNode:function(e){var t=this.attrNodes.length;this.attrNodes[t]=e},hydrateMorphs:function(e){for(var t=this.childViews,r=this._element,n=0,i=t.length;i>n;n++){var a=t[n],o=r.querySelector("#morph-"+n),s=o.parentNode;a._morph=this.dom.insertMorphBefore(s,o,1===s.nodeType?s:e),s.removeChild(o)}},push:function(e){return("string"==typeof e?(null===this.buffer&&(this.buffer=""),this.buffer+=e):this.buffer=e, this)},addClass:function(e){return (this.elementClasses=this.elementClasses||new s, this.elementClasses.add(e), this.classes=this.elementClasses.list, this)},setClasses:function(e){this.elementClasses=null;var t,r=e.length;for(t=0;r>t;t++)this.addClass(e[t])},id:function(e){return (this.elementId=e, this)},attr:function(e,t){var r=this.elementAttributes=this.elementAttributes||{};return 1===arguments.length?r[e]:(r[e]=t,this)},removeAttr:function(e){var t=this.elementAttributes;return (t&&delete t[e], this)},prop:function(e,t){var r=this.elementProperties=this.elementProperties||{};return 1===arguments.length?r[e]:(r[e]=t,this)},removeProp:function(e){var t=this.elementProperties;return (t&&delete t[e], this)},style:function(e,t){return (this.elementStyle=this.elementStyle||{}, this.elementStyle[e]=t, this)},generateElement:function(){var e,t,r,n=this.tagName,o=this.elementId,s=this.classes,c=this.elementAttributes,h=this.elementProperties,m=this.elementStyle,d="";r=!a.canSetNameOnInputs&&c&&c.name?"<"+l(n)+' name="'+u(c.name)+'">':n;var p=this.dom.createElement(r,this.outerContextualElement());if(o&&(this.dom.setAttribute(p,"id",o),this.elementId=null),s&&(this.dom.setAttribute(p,"class",s.join(" ")),this.classes=null,this.elementClasses=null),m){for(t in m)d+=t+":"+m[t]+";";this.dom.setAttribute(p,"style",d),this.elementStyle=null}if(c){for(e in c)this.dom.setAttribute(p,e,c[e]);this.elementAttributes=null}if(h){for(t in h){var f=i.normalizeProperty(p,t),v=f.normalized;this.dom.setPropertyStrict(p,v,h[t])}this.elementProperties=null}return this._element=p},element:function(){if(this._element&&this.attrNodes.length>0){var e,t,r,n;for(e=0,t=this.attrNodes.length;t>e;e++)n=this.attrNodes[e],r=this.dom.createAttrMorph(this._element,n.attrName),n._morph=r}var i=this.innerContent();if(null===i)return this._element;var a=this.innerContextualElement(i);if(this.dom.detectNamespace(a),this._element||(this._element=this.dom.createDocumentFragment()),i.nodeType)this._element.appendChild(i);else{var o=this.dom.parseHTML(i,a);this._element.appendChild(o)}return (this.childViews.length>0&&this.hydrateMorphs(a), this._element)},string:function(){if(this._element){var e=this.element(),r=e.outerHTML;return"undefined"==typeof r?t["default"]("
").append(e).html():r}return this.innerString()},outerContextualElement:function(){return (void 0===this._outerContextualElement&&(this.outerContextualElement=document.body), this._outerContextualElement)},innerContextualElement:function(e){var t;t=this._element&&1===this._element.nodeType?this._element:this.outerContextualElement();var r;return (e&&(r=o(this.dom,e,t)), r||t)},innerString:function(){var e=this.innerContent();return e&&!e.nodeType?e:void 0},innerContent:function(){return this.buffer}}}),e("ember-views/component_lookup",["exports","ember-metal/core","ember-runtime/system/object","ember-htmlbars/system/lookup-helper"],function(e,t,r,n){"use strict";e["default"]=r["default"].extend({invalidName:function(e){return n.CONTAINS_DASH_CACHE.get(e)?void 0:!0},lookupFactory:function(e,r){r=r||this.container;var n="component:"+e,i="template:components/"+e,a=r&&r._registry.has(i);a&&r._registry.injection(n,"layout",i);var o=r.lookupFactory(n);return a||o?(o||(r._registry.register(n,t["default"].Component),o=r.lookupFactory(n)),o):void 0},componentFor:function(e,t){if(!this.invalidName(e)){var r="component:"+e;return t.lookupFactory(r)}},layoutFor:function(e,t){if(!this.invalidName(e)){var r="template:components/"+e;return t.lookup(r)}}})}),e("ember-views/mixins/aria_role_support",["exports","ember-metal/mixin"],function(e,t){"use strict";e["default"]=t.Mixin.create({attributeBindings:["ariaRole:role"],ariaRole:null})}),e("ember-views/mixins/class_names_support",["exports","ember-metal/core","ember-metal/mixin","ember-runtime/system/native_array","ember-metal/utils"],function(e,t,r,n,i){"use strict";var a=[],o=r.Mixin.create({concatenatedProperties:["classNames","classNameBindings"],init:function(){this._super.apply(this,arguments),this.classNameBindings=n.A(this.classNameBindings.slice()),this.classNames=n.A(this.classNames.slice())},classNames:["ember-view"],classNameBindings:a});e["default"]=o}),e("ember-views/mixins/component_template_deprecation",["exports","ember-metal/core","ember-metal/property_get","ember-metal/mixin"],function(e,t,r,n){"use strict";e["default"]=n.Mixin.create({willMergeMixin:function(e){this._super.apply(this,arguments);var t,n,i=e.layoutName||e.layout||r.get(this,"layoutName");e.templateName&&!i&&(t="templateName",n="layoutName",e.layoutName=e.templateName,delete e.templateName),e.template&&!i&&(t="template",n="layout",e.layout=e.template,delete e.template)}})}),e("ember-views/mixins/empty_view_support",["exports","ember-metal/mixin","ember-views/views/view","ember-metal/property_get","ember-metal/property_set","ember-metal/computed"],function(e,t,r,n,i,a){"use strict";e["default"]=t.Mixin.create({emptyViewClass:r["default"],emptyView:null,_emptyView:a.computed("emptyView","attrs.emptyViewClass","emptyViewClass",function(){var e=n.get(this,"emptyView"),t=this.getAttr("emptyViewClass"),r=n.get(this,"emptyViewClass"),a=n.get(this,"_itemViewInverse"),o=e||t;if(a&&o){if(o.extend)return o.extend({template:a});i.set(o,"template",a)}else if(a&&r)return r.extend({template:a});return o})})}),e("ember-views/mixins/instrumentation_support",["exports","ember-metal/mixin","ember-metal/computed","ember-metal/property_get"],function(e,t,r,n){"use strict";var i=t.Mixin.create({instrumentDisplay:r.computed(function(){return this.helperName?"{{"+this.helperName+"}}":void 0}),instrumentName:"view",instrumentDetails:function(e){e.template=n.get(this,"templateName"),this._super(e)}});e["default"]=i}),e("ember-views/mixins/legacy_view_support",["exports","ember-metal/core","ember-metal/mixin","ember-metal/property_get"],function(e,t,r,n){"use strict";var i=r.Mixin.create({beforeRender:function(e){},afterRender:function(e){},walkChildViews:function(e){for(var t=this.childViews.slice();t.length;){var r=t.pop();e(r),t.push.apply(t,r.childViews)}},mutateChildViews:function(e){for(var t,r=n.get(this,"childViews"),i=r.length;--i>=0;)t=r[i],e(this,t,i);return this},removeAllChildren:function(){return this.mutateChildViews(function(e,t){e.removeChild(t)})},destroyAllChildren:function(){return this.mutateChildViews(function(e,t){t.destroy()})},nearestChildOf:function(e){for(var t=n.get(this,"parentView");t;){if(n.get(t,"parentView")instanceof e)return t;t=n.get(t,"parentView")}},nearestInstanceOf:function(e){for(var t=n.get(this,"parentView");t;){if(t instanceof e)return t;t=n.get(t,"parentView")}}});e["default"]=i}),e("ember-views/mixins/normalized_rerender_if_needed",["exports","ember-metal/property_get","ember-metal/mixin","ember-metal/merge","ember-views/views/states"],function(e,t,r,n,i){"use strict";var a=i.cloneStates(i.states);n["default"](a._default,{rerenderIfNeeded:function(){return this}}),n["default"](a.inDOM,{rerenderIfNeeded:function(e){e.normalizedValue()!==e._lastNormalizedValue&&e.rerender()}}),e["default"]=r.Mixin.create({_states:a,normalizedValue:function(){var e=this.lazyValue.value(),r=t.get(this,"valueNormalizerFunc");return r?r(e):e},rerenderIfNeeded:function(){this.currentState.rerenderIfNeeded(this)}})}),e("ember-views/mixins/template_rendering_support",["exports","ember-metal/mixin"],function(e,t){"use strict";var n,i=t.Mixin.create({renderBlock:function(e,t){return (void 0===n&&(n=r("ember-htmlbars/system/render-view")), n.renderHTMLBarsBlock(this,e,t))}});e["default"]=i}),e("ember-views/mixins/text_support",["exports","ember-metal/property_get","ember-metal/property_set","ember-metal/mixin","ember-runtime/mixins/target_action_support"],function(e,t,r,n,i){"use strict";function a(e,r,n){var i=t.get(r,"attrs."+e)||t.get(r,e),a=t.get(r,"onEvent"),o=t.get(r,"value");(a===e||"keyPress"===a&&"key-press"===e)&&r.sendAction("action",o),r.sendAction(e,o),(i||a===e)&&(t.get(r,"bubbles")||n.stopPropagation())}var o=n.Mixin.create(i["default"],{value:"",attributeBindings:["autocapitalize","autocorrect","autofocus","disabled","form","maxlength","placeholder","readonly","required","selectionDirection","spellcheck","tabindex","title"],placeholder:null,disabled:!1,maxlength:null,init:function(){this._super.apply(this,arguments),this.on("paste",this,this._elementValueDidChange),this.on("cut",this,this._elementValueDidChange),this.on("input",this,this._elementValueDidChange)},action:null,onEvent:"enter",bubbles:!1,interpretKeyEvents:function(e){var t=o.KEY_EVENTS,r=t[e.keyCode];return (this._elementValueDidChange(), r?this[r](e):void 0)},_elementValueDidChange:function(){r.set(this,"value",this.readDOMAttr("value"))},change:function(e){this._elementValueDidChange(e)},insertNewline:function(e){a("enter",this,e),a("insert-newline",this,e)},cancel:function(e){a("escape-press",this,e)},focusIn:function(e){a("focus-in",this,e)},focusOut:function(e){this._elementValueDidChange(e),a("focus-out",this,e)},keyPress:function(e){a("key-press",this,e)},keyUp:function(e){this.interpretKeyEvents(e),this.sendAction("key-up",t.get(this,"value"),e)},keyDown:function(e){this.sendAction("key-down",t.get(this,"value"),e)}});o.KEY_EVENTS={13:"insertNewline",27:"cancel"},e["default"]=o}),e("ember-views/mixins/view_child_views_support",["exports","ember-metal/core","ember-metal/mixin","ember-metal/enumerable_utils","ember-metal/property_get","ember-metal/property_set","ember-metal/set_properties"],function(e,t,r,n,i,a,o){"use strict";var s=[];e["default"]=r.Mixin.create({childViews:s,init:function(){this._super.apply(this,arguments),this.childViews=t["default"].A(this.childViews.slice()),this.ownerView=this.ownerView||this},appendChild:function(e){this.linkChild(e),this.childViews.push(e)},destroyChild:function(e){e.destroy()},removeChild:function(e){if(!this.isDestroying){this.unlinkChild(e);var t=i.get(this,"childViews");return (n.removeObject(t,e), this)}},createChildView:function(e,t){if(!e)throw new TypeError("createChildViews first argument must exist");if(e.isView&&e.parentView===this&&e.container===this.container)return e;var r,n=t||{};if(n.parentView=this,n.renderer=this.renderer,n._viewRegistry=this._viewRegistry,e.isViewFactory)n.container=this.container,r=e.create(n),r.viewName&&a.set(this,r.viewName,r);else if("string"==typeof e){var i="view:"+e,s=this.container.lookupFactory(i);r=s.create(n)}else r=e,n.container=this.container,o["default"](r,n);return (this.linkChild(r), r)},linkChild:function(e){e.container=this.container,i.get(e,"parentView")!==this&&(a.set(e,"parentView",this),e.trigger("parentViewDidChange")),e.ownerView=this.ownerView},unlinkChild:function(e){a.set(e,"parentView",null),e.trigger("parentViewDidChange")}})}),e("ember-views/mixins/view_context_support",["exports","ember-metal/mixin","ember-metal/computed","ember-metal/property_get","ember-metal/property_set","ember-views/mixins/legacy_view_support","ember-metal/events"],function(e,t,r,n,i,a,o){"use strict";var s=t.Mixin.create(a["default"],{context:r.computed({get:function(){return n.get(this,"_context")},set:function(e,t){return (i.set(this,"_context",t), t)}})["volatile"](),_context:r.computed({get:function(){var e,t;return(t=n.get(this,"controller"))?t:(e=this.parentView,e?n.get(e,"_context"):null)},set:function(e,t){return t}}),_controller:null,controller:r.computed({get:function(){return this._controller?this._controller:this.parentView?n.get(this.parentView,"controller"):null},set:function(e,t){return (this._controller=t, t)}}),_legacyControllerDidChange:t.observer("controller",function(){this.walkChildViews(function(e){return e.notifyPropertyChange("controller")})}),_notifyControllerChange:o.on("parentViewDidChange",function(){this.notifyPropertyChange("controller")})});e["default"]=s}),e("ember-views/mixins/view_state_support",["exports","ember-metal/core","ember-metal/mixin"],function(e,t,r){"use strict";var n=r.Mixin.create({transitionTo:function(e){this._transitionTo(e)},_transitionTo:function(e){var t=this.currentState,r=this.currentState=this._states[e];this._state=e,t&&t.exit&&t.exit(this),r.enter&&r.enter(this)}});e["default"]=n}),e("ember-views/mixins/view_target_action_support",["exports","ember-metal/mixin","ember-runtime/mixins/target_action_support","ember-metal/alias"],function(e,t,r,n){"use strict";e["default"]=t.Mixin.create(r["default"],{target:n["default"]("controller"),actionContext:n["default"]("context")})}),e("ember-views/mixins/visibility_support",["exports","ember-metal/mixin","ember-metal/property_get","ember-metal/run_loop"],function(e,t,r,n){"use strict";function i(){return this}var a=t.Mixin.create({isVisible:!0,becameVisible:i,becameHidden:i,_isVisibleDidChange:t.observer("isVisible",function(){this._isVisible!==r.get(this,"isVisible")&&n["default"].scheduleOnce("render",this,this._toggleVisibility)}),_toggleVisibility:function(){var e=this.$(),t=r.get(this,"isVisible");this._isVisible!==t&&(this._isVisible=t,e&&(e.toggle(t),this._isAncestorHidden()||(t?this._notifyBecameVisible():this._notifyBecameHidden())))},_notifyBecameVisible:function(){this.trigger("becameVisible"),this.forEachChildView(function(e){var t=r.get(e,"isVisible");(t||null===t)&&e._notifyBecameVisible()})},_notifyBecameHidden:function(){this.trigger("becameHidden"),this.forEachChildView(function(e){var t=r.get(e,"isVisible");(t||null===t)&&e._notifyBecameHidden()})},_isAncestorHidden:function(){for(var e=r.get(this,"parentView");e;){if(r.get(e,"isVisible")===!1)return!0;e=r.get(e,"parentView")}return!1}});e["default"]=a}),e("ember-views/streams/class_name_binding",["exports","ember-metal/streams/utils","ember-metal/property_get","ember-runtime/system/string","ember-metal/utils"],function(e,t,r,n,i){"use strict";function a(e){var t,r,n=e.split(":"),i=n[0],a="";return (n.length>1&&(t=n[1],3===n.length&&(r=n[2]),a=":"+t,r&&(a+=":"+r)), {path:i,classNames:a,className:""===t?void 0:t,falsyClassName:r})}function o(e,t,a,o){if(i.isArray(t)&&(t=0!==r.get(t,"length")),a||o)return a&&t?a:o&&!t?o:null;if(t===!0){var s=e.split(".");return n.dasherize(s[s.length-1])}return t!==!1&&null!=t?t:null}function s(e,r,n){n=n||"";var i=a(r);if(""===i.path)return o(i.path,!0,i.className,i.falsyClassName);var s=e.getStream(n+i.path);return t.chain(s,function(){return o(i.path,t.read(s),i.className,i.falsyClassName)})}e.parsePropertyPath=a,e.classStringForValue=o,e.streamifyClassNameBinding=s}),e("ember-views/streams/should_display",["exports","ember-metal/platform/create","ember-metal/merge","ember-metal/property_get","ember-runtime/utils","ember-metal/streams/stream","ember-metal/streams/utils"],function(e,t,r,n,i,a,o){"use strict";function s(e){if(o.isStream(e))return new l(e);var t=e&&n.get(e,"isTruthy");return"boolean"==typeof t?t:i.isArray(e)?0!==n.get(e,"length"):!!e}function l(e){var t=e.get("isTruthy");this.init(),this.predicate=e,this.isTruthy=t,this.lengthDep=null,this.addDependency(e),this.addDependency(t)}e["default"]=s,l.prototype=t["default"](a["default"].prototype),r["default"](l.prototype,{compute:function(){var e=o.read(this.isTruthy);return"boolean"==typeof e?e:this.lengthDep?0!==this.lengthDep.getValue():!!o.read(this.predicate)},revalidate:function(){i.isArray(o.read(this.predicate))?this.lengthDep||(this.lengthDep=this.addMutableDependency(this.predicate.get("length"))):this.lengthDep&&(this.lengthDep.destroy(),this.lengthDep=null)}})}),e("ember-views/streams/utils",["exports","ember-metal/core","ember-metal/property_get","ember-metal/path_cache","ember-runtime/system/string","ember-metal/streams/utils","ember-runtime/mixins/controller"],function(e,t,r,n,i,a,o){"use strict";function s(e,t){var i,o=a.read(e);return i="string"==typeof o?n.isGlobal(o)?r.get(null,o):t.lookupFactory("view:"+o):o}function l(e,t){var r=a.read(e),n=t.lookup("component-lookup:main");return n.lookupFactory(r,t)}function u(e){if(a.isStream(e)){ +var t=e.value();if("controller"!==e.label)for(;o["default"].detect(t);)t=r.get(t,"model");return t}return e}e.readViewFactory=s,e.readComponentFactory=l,e.readUnwrappedModel=u}),e("ember-views/system/action_manager",["exports"],function(e){"use strict";function t(){}t.registeredActions={},e["default"]=t}),e("ember-views/system/build-component-template",["exports","htmlbars-runtime","ember-htmlbars/hooks/get-value","ember-metal/property_get","ember-metal/path_cache"],function(e,t,r,n,i){"use strict";function a(e,r,n){var i,a,o,s=e.component,l=e.layout,f=e.isAngleBracket;if(void 0===s&&(s=null),l&&l.raw){var v=c(n.templates,n.scope,n.self,s);i=h(l.raw,v,n.self,s,r),o=l.raw.meta}else n.templates&&n.templates["default"]&&(i=u(n.templates["default"],n.scope,n.self,s),o=n.templates["default"].meta);if(s)if(a=d(s),""!==a){var b=p(s,f,r,a),y=t.internal.manualElement(a,b);y.meta=o,i=m(y,i,s)}else g(s);return{createdElement:!!a,block:i}}function o(){y=!1}function s(){y=b}function l(e,r){return t.internal.blockFor(t.render,e,r)}function u(e,t,r,n){return l(e,{scope:t,self:r,options:{view:n}})}function c(e,t,r,n){if(e){var i={};for(var a in e)if(e.hasOwnProperty(a)){var o=e[a];o&&(i[a]=u(e[a],t,r,n))}return i}}function h(e,t,r,n,i){return l(e,{yieldTo:t,self:r||n,options:{view:n,attrs:i}})}function m(e,t,r){return l(e,{yieldTo:t,self:r,options:{view:r}})}function d(e){var t=e.tagName;return (null!==t&&"object"==typeof t&&t.isDescriptor&&(t=n.get(e,"tagName")), (null===t||void 0===t)&&(t=e._defaultTagName||"div"), t)}function p(e,t,i,a){var o,s,l="input"===a&&!y,u={},c=e.attributeBindings;if(i.id&&r["default"](i.id)?(u.id=r["default"](i.id),e.elementId=u.id):u.id=e.elementId,c)for(o=0,s=c.length;s>o;o++){var h,m,d=c[o],p=d.indexOf(":");if(-1!==p){var v=d.substring(0,p);h=d.substring(p+1),m="type"===h&&l?e.get(v)+"":["get","view."+v]}else i[d]?(h=d,m="type"===h&&l?r["default"](i[d])+"":["value",i[d]]):(h=d,m="type"===h&&l?e.get(d)+"":["get","view."+d]);u[h]=m}if(t)for(var g in i){var b=i[g];b&&("string"==typeof b||b.isConcat)&&(u[g]=["value",b])}i.tagName&&(e.tagName=i.tagName);var _=f(e,i);if(_&&(u["class"]=_),n.get(e,"isVisible")===!1){var w=["subexpr","-html-safe",["display: none;"],[]],x=u.style;x?u.style=["subexpr","concat",[x," ",w],[]]:u.style=w}return u}function f(e,t){var r,i,a=[],o=n.get(e,"classNames"),s=n.get(e,"classNameBindings");if(t["class"]&&("string"==typeof t["class"]?a.push(t["class"]):a.push(["subexpr","-normalize-class",[["value",t["class"].path],["value",t["class"]]],[]])),t.classBinding&&v(t.classBinding.split(" "),a),t.classNames&&a.push(["value",t.classNames]),o)for(r=0,i=o.length;i>r;r++)a.push(o[r]);return (s&&v(s,a), f.length?["subexpr","-join-classes",a,[]]:void 0)}function v(e,t){var r,n;for(r=0,n=e.length;n>r;r++){var a=e[r],o=a.split(":"),s=o[0],l=o[1],u=o[2];if(""!==s){var c=i.isGlobal(s)?s:"view."+s;t.push(["subexpr","-normalize-class",[["value",s],["get",c]],["activeClass",l,"inactiveClass",u]])}else t.push(l)}}function g(e){}e["default"]=a,e.disableInputTypeChanging=o,e.resetInputTypeChanging=s;var b=function(){var e=document.createDocumentFragment(),t=document.createElement("input");t.type="text";try{e.appendChild(t),t.setAttribute("type","password")}catch(r){return!1}return!0}(),y=b}),e("ember-views/system/event_dispatcher",["exports","ember-metal/core","ember-metal/property_get","ember-metal/property_set","ember-metal/is_none","ember-metal/run_loop","ember-runtime/system/string","ember-runtime/system/object","ember-views/system/jquery","ember-views/system/action_manager","ember-views/views/view","ember-metal/merge"],function(e,t,r,n,i,a,o,s,l,u,c,h){"use strict";e["default"]=s["default"].extend({events:{touchstart:"touchStart",touchmove:"touchMove",touchend:"touchEnd",touchcancel:"touchCancel",keydown:"keyDown",keyup:"keyUp",keypress:"keyPress",mousedown:"mouseDown",mouseup:"mouseUp",contextmenu:"contextMenu",click:"click",dblclick:"doubleClick",mousemove:"mouseMove",focusin:"focusIn",focusout:"focusOut",mouseenter:"mouseEnter",mouseleave:"mouseLeave",submit:"submit",input:"input",change:"change",dragstart:"dragStart",drag:"drag",dragenter:"dragEnter",dragleave:"dragLeave",dragover:"dragOver",drop:"drop",dragend:"dragEnd"},rootElement:"body",canDispatchToEventManager:!0,setup:function(e,t){var a,o=r.get(this,"events");h["default"](o,e||{}),i["default"](t)||n.set(this,"rootElement",t),t=l["default"](r.get(this,"rootElement")),t.addClass("ember-application");for(a in o)o.hasOwnProperty(a)&&this.setupHandler(t,a,o[a])},setupHandler:function(e,t,r){var n=this,i=this.container&&this.container.lookup("-view-registry:main")||c["default"].views;e.on(t+".ember",".ember-view",function(e,t){var a=i[this.id],o=!0,s=n.canDispatchToEventManager?n._findNearestEventManager(a,r):null;return (s&&s!==t?o=n._dispatchEvent(s,e,r,a):a&&(o=n._bubbleEvent(a,e,r)), o)}),e.on(t+".ember","[data-ember-action]",function(e){var t=l["default"](e.currentTarget).attr("data-ember-action"),n=u["default"].registeredActions[t];if(n)for(var i=0,a=n.length;a>i;i++){var o=n[i];if(o&&o.eventName===r)return o.handler(e)}})},_findNearestEventManager:function(e,t){for(var n=null;e&&(n=r.get(e,"eventManager"),!n||!n[t]);)e=r.get(e,"parentView");return n},_dispatchEvent:function(e,t,r,n){var i=!0,o=e[r];return("function"==typeof o?(i=a["default"](e,o,t,n),t.stopPropagation()):i=this._bubbleEvent(n,t,r), i)},_bubbleEvent:function(e,t,r){return a["default"].join(e,e.handleEvent,r,t)},destroy:function(){var e=r.get(this,"rootElement");return (l["default"](e).off(".ember","**").removeClass("ember-application"), this._super.apply(this,arguments))},toString:function(){return"(EventDispatcher)"}})}),e("ember-views/system/ext",["exports","ember-metal/run_loop"],function(e,t){"use strict";t["default"]._addQueue("render","actions"),t["default"]._addQueue("afterRender","render")}),e("ember-views/system/jquery",["exports","ember-metal/core","ember-metal/enumerable_utils","ember-metal/environment"],function(e,t,n,i){"use strict";var o;if(i["default"].hasDOM&&(o=t["default"].imports&&t["default"].imports.jQuery||a&&a.jQuery,o||"function"!=typeof r||(o=r("jquery")),o)){var s=["dragstart","drag","dragenter","dragleave","dragover","drop","dragend"];n.forEach(s,function(e){o.event.fixHooks[e]={props:["dataTransfer"]}})}e["default"]=o}),e("ember-views/system/lookup_partial",["exports","ember-metal/core","ember-metal/error"],function(e,t,r){"use strict";function n(e,t){if(null!=t){var r=t.split("/"),n=r[r.length-1];r[r.length-1]="_"+n;var a=r.join("/"),o=i(e,a,t);return o}}function i(e,t,n){if(n){if(!e.container)throw new r["default"]("Container was not found when looking up a views template. This is most likely due to manually instantiating an Ember.View. See: http://git.io/EKPpnA");return e.container.lookup("template:"+t)||e.container.lookup("template:"+n)}}e["default"]=n}),e("ember-views/system/platform",["exports","ember-metal/environment"],function(e,t){"use strict";var r=t["default"].hasDOM&&function(){var e=document.createElement("div"),t=document.createElement("input");return (t.setAttribute("name","foo"), e.appendChild(t), !!e.innerHTML.match("foo"))}();e.canSetNameOnInputs=r}),e("ember-views/system/utils",["exports"],function(e){"use strict";function t(e){var t=e.shiftKey||e.metaKey||e.altKey||e.ctrlKey,r=e.which>1;return!t&&!r}function r(e){var t=document.createRange();return (t.setStartBefore(e._renderNode.firstNode), t.setEndAfter(e._renderNode.lastNode), t)}function n(e){var t=r(e);return t.getClientRects()}function i(e){var t=r(e);return t.getBoundingClientRect()}e.isSimpleClick=t,e.getViewClientRects=n,e.getViewBoundingClientRect=i}),e("ember-views/views/checkbox",["exports","ember-metal/property_get","ember-metal/property_set","ember-views/views/view"],function(e,t,r,n){"use strict";e["default"]=n["default"].extend({instrumentDisplay:'{{input type="checkbox"}}',classNames:["ember-checkbox"],tagName:"input",attributeBindings:["type","checked","indeterminate","disabled","tabindex","name","autofocus","required","form"],type:"checkbox",checked:!1,disabled:!1,indeterminate:!1,init:function(){this._super.apply(this,arguments),this.on("change",this,this._updateElementValue)},didInsertElement:function(){this._super.apply(this,arguments),t.get(this,"element").indeterminate=!!t.get(this,"indeterminate")},_updateElementValue:function(){r.set(this,"checked",this.$().prop("checked"))}})}),e("ember-views/views/collection_view",["exports","ember-metal/core","ember-views/views/container_view","ember-views/views/view","ember-runtime/mixins/array","ember-metal/property_get","ember-metal/property_set","ember-runtime/system/string","ember-metal/computed","ember-metal/mixin","ember-views/streams/utils","ember-views/mixins/empty_view_support"],function(e,t,r,n,i,a,o,s,l,u,c,h){"use strict";function m(e,t){var r={};for(var n in t)if("itemViewClass"!==n&&"itemController"!==n&&"itemClassBinding"!==n&&t.hasOwnProperty(n)){var i=n.match(/^item(.)(.*)$/);if(i){var a=i[1].toLowerCase()+i[2];"class"===a||"classNames"===a?r.classNames=[t[n]]:r[a]=t[n],delete t[n]}}return (e&&(r.template=e), r)}function d(){}var p=r["default"].extend(h["default"],{content:null,itemViewClass:n["default"],init:function(){var e=this._super.apply(this,arguments);return (this._contentDidChange(), e)},_contentWillChange:u._beforeObserver("content",function(){var e=this.get("content");e&&e.removeArrayObserver(this);var t=e?a.get(e,"length"):0;this.arrayWillChange(e,0,t)}),_contentDidChange:u.observer("content",function(){var e=a.get(this,"content");e&&(this._assertArrayLike(e),e.addArrayObserver(this));var t=e?a.get(e,"length"):0;this.arrayDidChange(e,0,null,t)}),_assertArrayLike:function(e){},destroy:function(){if(this._super.apply(this,arguments)){var e=a.get(this,"content");return (e&&e.removeArrayObserver(this), this._createdEmptyView&&this._createdEmptyView.destroy(), this)}},arrayWillChange:function(e,t,r){this.replace(t,r,[])},arrayDidChange:function(e,t,r,n){var i,o,s,l,u,h,m=[];if(l=e?a.get(e,"length"):0){for(h=this._itemViewProps||{},u=this.getAttr("itemViewClass")||a.get(this,"itemViewClass"),u=c.readViewFactory(u,this.container),s=t;t+n>s;s++)o=e.objectAt(s),h._context=this.keyword?this.get("context"):o,h.content=o,h.contentIndex=s,i=this.createChildView(u,h),m.push(i);this.replace(t,0,m)}},createChildView:function(e,t){var r=this._super(e,t),n=a.get(r,"tagName");return((null===n||void 0===n)&&(n=p.CONTAINER_MAP[a.get(this,"tagName")],o.set(r,"tagName",n)), r)},_willRender:function(){var e=this.attrs,t=m(this._itemViewTemplate,e);this._itemViewProps=t;for(var r=a.get(this,"childViews"),n=0,i=r.length;i>n;n++)r[n].setProperties(t);"content"in e&&o.set(this,"content",this.getAttr("content")),"emptyView"in e&&o.set(this,"emptyView",this.getAttr("emptyView"))},_emptyViewTagName:l.computed("tagName",function(){var e=a.get(this,"tagName");return p.CONTAINER_MAP[e]||"div"})});p.CONTAINER_MAP={ul:"li",ol:"li",table:"tr",thead:"tr",tbody:"tr",tfoot:"tr",tr:"td",select:"option"};var f=p.CONTAINER_MAP;e.CONTAINER_MAP=f;var v=p.extend({init:function(){d(),this._super.apply(this,arguments)}});v.reopen=function(){return (d(), p.reopen.apply(p,arguments), this)},v.CONTAINER_MAP=f,e["default"]=p,e.DeprecatedCollectionView=v}),e("ember-views/views/component",["exports","ember-metal/core","ember-views/mixins/component_template_deprecation","ember-runtime/mixins/target_action_support","ember-views/views/view","ember-metal/property_get","ember-metal/property_set","ember-metal/is_none","ember-metal/computed","ember-views/compat/attrs-proxy"],function(e,t,r,n,i,a,o,s,l,u){"use strict";function c(e,t){return (t&&t[u.MUTABLE_CELL]&&(t=t.value), t)}var h=i["default"].extend(n["default"],r["default"],{isComponent:!0,controller:null,context:null,instrumentName:"component",instrumentDisplay:l.computed(function(){return this._debugContainerKey?"{{"+this._debugContainerKey.split(":")[1]+"}}":void 0}),init:function(){this._super.apply(this,arguments),o.set(this,"controller",this),o.set(this,"context",this)},template:l.computed({get:function(){return a.get(this,"_template")},set:function(e,t){return o.set(this,"_template",t)}}),_template:l.computed({get:function(){if(a.get(this,"_deprecatedFlagForBlockProvided"))return!0;var e=a.get(this,"templateName"),t=this.templateForName(e,"template");return t||a.get(this,"defaultTemplate")},set:function(e,t){return t}}),templateName:null,targetObject:l.computed("controller",function(e){if(this._targetObject)return this._targetObject;if(this._controller)return this._controller;var t=a.get(this,"parentView");return t?a.get(t,"controller"):null}),sendAction:function(e){for(var t=arguments.length,r=Array(t>1?t-1:0),n=1;t>n;n++)r[n-1]=arguments[n];var i;void 0===e&&(e="action"),i=a.get(this,"attrs."+e)||a.get(this,e),i=c(this,i),void 0!==i&&("function"==typeof i?i.apply(null,r):this.triggerAction({action:i,actionContext:r}))},send:function(e){for(var r=arguments.length,n=Array(r>1?r-1:0),i=1;r>i;i++)n[i-1]=arguments[i];var o,s=this._actions&&this._actions[e];if(s){var l=this._actions[e].apply(this,n)===!0;if(!l)return}if(o=a.get(this,"target")){var u;(u=o).send.apply(u,arguments)}else if(!s)throw new Error(t["default"].inspect(this)+" had no action handler for: "+e)}});h.reopenClass({isComponentFactory:!0}),e["default"]=h}),e("ember-views/views/container_view",["exports","ember-metal/core","ember-runtime/mixins/mutable_array","ember-views/views/view","ember-metal/property_get","ember-metal/property_set","ember-metal/enumerable_utils","ember-metal/mixin","ember-metal/events","ember-htmlbars/templates/container-view"],function(e,t,r,n,i,a,o,s,l,u){"use strict";function c(){}u["default"].meta.revision="Ember@1.13.12";var h=n["default"].extend(r["default"],{willWatchProperty:function(e){},init:function(){this._super.apply(this,arguments);var e=i.get(this,"childViews"),r=this.childViews=t["default"].A([]);o.forEach(e,function(e,t){var n;"string"==typeof e?(n=i.get(this,e),n=this.createChildView(n),a.set(this,e,n)):n=this.createChildView(e),r[t]=n},this);var n=i.get(this,"currentView");n&&(r.length||(r=this.childViews=t["default"].A(this.childViews.slice())),r.push(this.createChildView(n))),a.set(this,"length",r.length)},appendChild:function(e){e.parentView!==this&&this.linkChild(e)},_currentViewWillChange:s._beforeObserver("currentView",function(){var e=i.get(this,"currentView");e&&e.destroy()}),_currentViewDidChange:s.observer("currentView",function(){var e=i.get(this,"currentView");e&&this.pushObject(e)}),layout:u["default"],replace:function(e,t){var r=this,n=arguments.length<=2||void 0===arguments[2]?[]:arguments[2],s=i.get(n,"length"),l=i.get(this,"childViews");this.arrayContentWillChange(e,t,s);var u=l.slice(e,e+t);return (o.forEach(u,function(e){return r.unlinkChild(e)}), o.forEach(n,function(e){return r.linkChild(e)}), l.splice.apply(l,[e,t].concat(n)), this.notifyPropertyChange("childViews"), this.arrayContentDidChange(e,t,s), a.set(this,"length",l.length), this)},objectAt:function(e){return this.childViews[e]},_triggerChildWillDestroyElement:l.on("willDestroyElement",function(){var e=this.childViews;if(e)for(var t=0;ti;i++)n[i-1]=arguments[i];return t.apply(this,n)}},has:function(e){return"function"===l.typeOf(this[e])||this._super(e)},destroy:function(){return this._super.apply(this,arguments)?(this.currentState.cleanup(this),!this.ownerView._destroyingSubtreeForView&&this._renderNode&&u.internal.clearMorph(this._renderNode,this.ownerView.env,!0),this):void 0},clearRenderedChildren:c,_transitionTo:c,destroyElement:c});d.reopenClass({isViewFactory:!0});var p=d.extend({init:function(){this._super.apply(this,arguments)}});e.DeprecatedCoreView=p;var f;e["default"]=d}),e("ember-views/views/legacy_each_view",["exports","ember-htmlbars/templates/legacy-each","ember-metal/property_get","ember-metal/property_set","ember-metal/computed","ember-views/views/view","ember-views/views/collection_view","ember-views/mixins/empty_view_support"],function(e,t,r,n,i,a,o,s){"use strict";e["default"]=a["default"].extend(s["default"],{template:t["default"],tagName:"",_arrayController:i.computed(function(){var e=this.getAttr("itemController"),t=r.get(this,"container").lookupFactory("controller:array").create({_isVirtual:!0,parentController:r.get(this,"controller"),itemController:e,target:r.get(this,"controller"),_eachView:this,content:this.getAttr("content")});return t}),_willUpdate:function(e){var t=this.getAttrFor(e,"itemController");if(t){var i=r.get(this,"_arrayController");n.set(i,"content",this.getAttrFor(e,"content"))}},_arrangedContent:i.computed("attrs.content",function(){return this.getAttr("itemController")?r.get(this,"_arrayController"):this.getAttr("content")}),_itemTagName:i.computed(function(){var e=r.get(this,"tagName");return o.CONTAINER_MAP[e]})})}),e("ember-views/views/select",["exports","ember-metal/enumerable_utils","ember-metal/property_get","ember-metal/property_set","ember-views/views/view","ember-runtime/utils","ember-metal/is_none","ember-metal/computed","ember-runtime/system/native_array","ember-metal/mixin","ember-metal/properties","ember-htmlbars/templates/select","ember-htmlbars/templates/select-option","ember-htmlbars/templates/select-optgroup"],function(e,t,r,n,i,a,o,s,l,u,c,h,m,d){"use strict";function p(){}var f=h["default"],v=i["default"].extend({instrumentDisplay:"Ember.SelectOption",tagName:"option",attributeBindings:["value","selected"],defaultTemplate:m["default"],content:null,_willRender:function(){this.labelPathDidChange(),this.valuePathDidChange()},selected:s.computed(function(){var e=r.get(this,"value"),n=r.get(this,"attrs.selection");return r.get(this,"attrs.multiple")?n&&t.indexOf(n,e)>-1:e==r.get(this,"attrs.parentValue")}).property("attrs.content","attrs.selection"),labelPathDidChange:u.observer("attrs.optionLabelPath",function(){var e=r.get(this,"attrs.optionLabelPath");c.defineProperty(this,"label",s.computed.alias(e))}),valuePathDidChange:u.observer("attrs.optionValuePath",function(){var e=r.get(this,"attrs.optionValuePath");c.defineProperty(this,"value",s.computed.alias(e))})}),g=i["default"].extend({instrumentDisplay:"Ember.SelectOptgroup",tagName:"optgroup",defaultTemplate:d["default"],attributeBindings:["label"]}),b=i["default"].extend({instrumentDisplay:"Ember.Select",tagName:"select",classNames:["ember-select"],defaultTemplate:f,attributeBindings:["autofocus","autocomplete","disabled","form","multiple","name","required","size","tabindex"],multiple:!1,disabled:!1,required:!1,content:null,selection:null,value:s.computed({get:function(e){var t=r.get(this,"_valuePath");return t?r.get(this,"selection."+t):r.get(this,"selection")},set:function(e,t){return t}}).property("_valuePath","selection"),prompt:null,optionLabelPath:"content",optionValuePath:"content",optionGroupPath:null,groupView:g,groupedContent:s.computed(function(){var e=r.get(this,"optionGroupPath"),n=l.A(),i=r.get(this,"content")||[];return (t.forEach(i,function(t){var i=r.get(t,e);r.get(n,"lastObject.label")!==i&&n.pushObject({label:i,content:l.A()}),r.get(n,"lastObject.content").push(t)}), n)}).property("optionGroupPath","content.[]"),optionView:v,_change:function(e){r.get(this,"multiple")?this._changeMultiple(e):this._changeSingle(e)},selectionDidChange:u.observer("selection.[]",function(){var e=r.get(this,"selection");if(r.get(this,"multiple")){if(!a.isArray(e))return void n.set(this,"selection",l.A([e]));this._selectionDidChangeMultiple()}else this._selectionDidChangeSingle()}),valueDidChange:u.observer("value",function(){var e,t=r.get(this,"content"),n=r.get(this,"value"),i=r.get(this,"optionValuePath").replace(/^content\.?/,""),a=i?r.get(this,"selection."+i):r.get(this,"selection");n!==a&&(e=t?t.find(function(e){return n===(i?r.get(e,i):e)}):null,this.set("selection",e))}),_setDefaults:function(){var e=r.get(this,"selection"),t=r.get(this,"value");o["default"](e)||this.selectionDidChange(),o["default"](t)||this.valueDidChange(),o["default"](e)&&this._change(!1)},_changeSingle:function(e){var t=this.get("value"),i=e!==!1?this.$()[0].selectedIndex:this._selectedIndex(t),a=r.get(this,"content"),o=r.get(this,"prompt");if(a&&r.get(a,"length")){if(o&&0===i)return void n.set(this,"selection",null);o&&(i-=1),n.set(this,"selection",a.objectAt(i))}},_selectedIndex:function(e){var n=arguments.length<=1||void 0===arguments[1]?0:arguments[1],i=r.get(this,"contentValues"),a=t.indexOf(i,e),o=r.get(this,"prompt");return (o&&(a+=1), 0>a&&(a=n), a)},_changeMultiple:function(e){var i=e!==!1?this.$("option:selected"):[],o=r.get(this,"prompt"),s=o?1:0,l=r.get(this,"content"),u=r.get(this,"selection");if(l&&i){var c=i.map(function(){return this.index-s}),h=l.objectsAt([].slice.call(c));a.isArray(u)?t.replace(u,0,r.get(u,"length"),h):n.set(this,"selection",h)}},_selectionDidChangeSingle:function(){var e=r.get(this,"value"),t=this;e&&e.then?e.then(function(n){r.get(t,"value")===e&&t._setSelectedIndex(n)}):this._setSelectedIndex(e)},_setSelectedIndex:function(e){var t=r.get(this,"element");t&&(t.selectedIndex=this._selectedIndex(e,-1))},_valuePath:s.computed("optionValuePath",function(){var e=r.get(this,"optionValuePath");return e.replace(/^content\.?/,"")}),contentValues:s.computed("content.[]","_valuePath",function(){var e=r.get(this,"_valuePath"),n=r.get(this,"content")||[];return e?t.map(n,function(t){return r.get(t,e)}):t.map(n,function(e){return e})}),_selectionDidChangeMultiple:function(){var e,n=r.get(this,"content"),i=r.get(this,"selection"),a=n?t.indexesOf(n,i):[-1],o=r.get(this,"prompt"),s=o?1:0,l=this.$("option");l&&l.each(function(){e=this.index>-1?this.index-s:-1,this.selected=t.indexOf(a,e)>-1})},_willRender:function(){this._setDefaults()},init:function(){this._super.apply(this,arguments),this.on("change",this,this._change)}}),y=b.extend({init:function(){p(),this._super.apply(this,arguments)}});y.reopen=function(){return (p(), b.reopen.apply(b,arguments), this)},e["default"]=b,e.Select=b,e.DeprecatedSelect=y,e.SelectOption=v,e.SelectOptgroup=g}),e("ember-views/views/states",["exports","ember-metal/platform/create","ember-metal/merge","ember-views/views/states/default","ember-views/views/states/pre_render","ember-views/views/states/has_element","ember-views/views/states/in_dom","ember-views/views/states/destroying"],function(e,t,r,n,i,a,o,s){"use strict";function l(e){var n={};n._default={},n.preRender=t["default"](n._default),n.destroying=t["default"](n._default),n.hasElement=t["default"](n._default),n.inDOM=t["default"](n.hasElement);for(var i in e)e.hasOwnProperty(i)&&r["default"](n[i],e[i]);return n}e.cloneStates=l;var u={_default:n["default"],preRender:i["default"],inDOM:o["default"],hasElement:a["default"],destroying:s["default"]};e.states=u}),e("ember-views/views/states/default",["exports","ember-metal/error","ember-metal/property_get","ember-views/compat/attrs-proxy"],function(e,t,r,n){"use strict";e["default"]={appendChild:function(){throw new t["default"]("You can't use appendChild outside of the rendering process")},$:function(){},getElement:function(){return null},legacyPropertyDidChange:function(e,t){var i=e.attrs;if(i&&t in i){var a=i[t];if(a&&a[n.MUTABLE_CELL]){var o=r.get(e,t);if(o===a.value)return;a.update(o)}}},handleEvent:function(){return!0},cleanup:function(){},destroyElement:function(){},rerender:function(e){e.renderer.ensureViewNotRendering(e)},invokeObserver:function(){}}}),e("ember-views/views/states/destroying",["exports","ember-metal/merge","ember-metal/platform/create","ember-runtime/system/string","ember-views/views/states/default","ember-metal/error"],function(e,t,r,n,i,a){"use strict";var o="You can't call %@ on a view being destroyed",s=r["default"](i["default"]);t["default"](s,{appendChild:function(){throw new a["default"](n.fmt(o,["appendChild"]))},rerender:function(){throw new a["default"](n.fmt(o,["rerender"]))},destroyElement:function(){throw new a["default"](n.fmt(o,["destroyElement"]))}}),e["default"]=s}),e("ember-views/views/states/has_element",["exports","ember-views/views/states/default","ember-metal/merge","ember-metal/platform/create","ember-views/system/jquery","ember-metal/property_get","htmlbars-runtime"],function(e,t,r,n,i,a,o){"use strict";var s=n["default"](t["default"]);r["default"](s,{$:function(e,t){var r=e.element;return t?i["default"](t,r):i["default"](r)},getElement:function(e){var t=a.get(e,"parentView");return (t&&(t=a.get(t,"element")), t?e.findElementInParentElement(t):i["default"]("#"+a.get(e,"elementId"))[0])},rerender:function(e){e.renderer.ensureViewNotRendering(e);var t=e._renderNode;t.isDirty=!0,o.internal.visitChildren(t.childNodes,function(e){e.state&&e.state.manager&&(e.shouldReceiveAttrs=!0),e.isDirty=!0}),t.ownerNode.emberView.scheduleRevalidate(t,e.toString(),"rerendering")},cleanup:function(e){e.currentState.destroyElement(e)},destroyElement:function(e){return (e.renderer.remove(e,!1), e)},handleEvent:function(e,t,r){return e.has(t)?e.trigger(t,r):!0},invokeObserver:function(e,t){t.call(e)}}),e["default"]=s}),e("ember-views/views/states/in_dom",["exports","ember-metal/core","ember-metal/platform/create","ember-metal/merge","ember-metal/error","ember-metal/observer","ember-views/views/states/has_element"],function(e,t,r,n,i,a,o){"use strict";var s=r["default"](o["default"]);n["default"](s,{enter:function(e){""!==e.tagName&&e._register()},exit:function(e){e._unregister()},appendAttr:function(e,t){var r=e.childViews;return (r.length||(r=e.childViews=r.slice()), r.push(t), t.parentView=e, e.renderer.appendAttrTo(t,e.element,t.attrName), e.propertyDidChange("childViews"), t)}}),e["default"]=s}),e("ember-views/views/states/pre_render",["exports","ember-views/views/states/default","ember-metal/platform/create","ember-metal/merge"],function(e,t,r,n){"use strict";var i=r["default"](t["default"]);n["default"](i,{legacyPropertyDidChange:function(e,t){}}),e["default"]=i}),e("ember-views/views/text_area",["exports","ember-views/views/component","ember-views/mixins/text_support"],function(e,t,r){"use strict";e["default"]=t["default"].extend(r["default"],{instrumentDisplay:"{{textarea}}",classNames:["ember-text-area"],tagName:"textarea",attributeBindings:["rows","cols","name","selectionEnd","selectionStart","wrap","lang","dir","value"],rows:null,cols:null})}),e("ember-views/views/text_field",["exports","ember-metal/computed","ember-metal/environment","ember-metal/platform/create","ember-views/views/component","ember-views/mixins/text_support"],function(e,t,r,n,i,a){"use strict";function o(e){if(e in l)return l[e];if(!r["default"].hasDOM)return (l[e]=e, e);s||(s=document.createElement("input"));try{s.type=e}catch(t){}return l[e]=s.type===e}var s,l=n["default"](null);e["default"]=i["default"].extend(a["default"],{instrumentDisplay:'{{input type="text"}}',classNames:["ember-text-field"],tagName:"input",attributeBindings:["accept","autocomplete","autosave","dir","formaction","formenctype","formmethod","formnovalidate","formtarget","height","inputmode","lang","list","max","min","multiple","name","pattern","size","step","type","value","width"],defaultLayout:null,value:"",type:t.computed({get:function(){return"text"},set:function(e,t){var r="text";return (o(t)&&(r=t), r)}}),size:null,pattern:null,min:null,max:null})}),e("ember-views/views/view",["exports","ember-metal/core","ember-runtime/mixins/evented","ember-runtime/system/object","ember-metal/error","ember-metal/property_get","ember-metal/run_loop","ember-metal/observer","ember-metal/utils","ember-metal/computed","ember-metal/mixin","ember-metal/deprecate_property","ember-views/system/jquery","ember-views/system/ext","ember-views/views/core_view","ember-views/mixins/view_context_support","ember-views/mixins/view_child_views_support","ember-views/mixins/view_state_support","ember-views/mixins/template_rendering_support","ember-views/mixins/class_names_support","ember-views/mixins/legacy_view_support","ember-views/mixins/instrumentation_support","ember-views/mixins/aria_role_support","ember-views/mixins/visibility_support","ember-views/compat/attrs-proxy"],function(e,t,r,n,i,a,o,s,l,u,c,h,m,d,p,f,v,g,b,y,_,w,x,C,k){"use strict";function E(){return this}function A(){}t["default"].TEMPLATES={};var N=p["default"].extend(f["default"],v["default"],g["default"],b["default"],y["default"],_["default"],w["default"],C["default"],k["default"],x["default"],{concatenatedProperties:["attributeBindings"],isView:!0,templateName:null,layoutName:null,template:u.computed({get:function(){var e=a.get(this,"templateName"),t=this.templateForName(e,"template");return t||a.get(this,"defaultTemplate")},set:function(e,t){return void 0!==t?t:a.get(this,e)}}),layout:u.computed({get:function(e){var t=a.get(this,"layoutName"),r=this.templateForName(t,"layout");return r||a.get(this,"defaultLayout")},set:function(e,t){return t}}),templateForName:function(e,t){if(e){if(!this.container)throw new i["default"]("Container was not found when looking up a views template. This is most likely due to manually instantiating an Ember.View. See: http://git.io/EKPpnA");return this.container.lookup("template:"+e)}},_contextDidChange:c.observer("context",function(){this.rerender()}),nearestOfType:function(e){for(var t=a.get(this,"parentView"),r=e instanceof c.Mixin?function(t){return e.detect(t)}:function(t){return e.detect(t.constructor)};t;){if(r(t))return t;t=a.get(t,"parentView")}},nearestWithProperty:function(e){for(var t=a.get(this,"parentView");t;){if(e in t)return t;t=a.get(t,"parentView")}},rerender:function(){return this.currentState.rerender(this)},_rerender:function(){this.isDestroying||this.isDestroyed||this._renderer.renderTree(this,this.parentView)},_classStringForProperty:function(e){return N._classStringForValue(e.path,e.stream.value(),e.className,e.falsyClassName)},element:null,$:function(e){return this.currentState.$(this,e)},forEachChildView:function(e){var t=this.childViews;if(!t)return this;var r,n,i=t.length;for(n=0;i>n;n++)r=t[n],e(r);return this},appendTo:function(e){var t=m["default"](e);return (this.renderer.appendTo(this,t[0]), this)},renderToElement:function(e){e=e||"body";var t=this.renderer._dom.createElement(e);return (this.renderer.appendTo(this,t), t)},replaceIn:function(e){var t=m["default"](e);return (this.renderer.replaceIn(this,t[0]), this)},append:function(){return this.appendTo(document.body)},remove:function(){this.removedFromDOM||this.destroyElement(),this._willInsert=!1},elementId:null,findElementInParentElement:function(e){var t="#"+this.elementId;return m["default"](t)[0]||m["default"](t,e)[0]},createElement:function(){return this.element?this:(this.renderer.createElement(this), +this)},willInsertElement:E,didInsertElement:E,willClearRender:E,destroyElement:function(){return this.currentState.destroyElement(this)},willDestroyElement:E,parentViewDidChange:E,tagName:null,readDOMAttr:function(e){var t=this._renderNode.childNodes.filter(function(t){return t.attrName===e})[0];return t?t.getContent():null},init:function(){this.elementId||(this.elementId=l.guidFor(this)),this.scheduledRevalidation=!1,this._super.apply(this,arguments),this._viewRegistry||(this._viewRegistry=N.views),this.renderer.componentInitAttrs(this,this.attrs||{})},__defineNonEnumerable:function(e){this[e.name]=e.descriptor.value},revalidate:function(){this.renderer.revalidateTopLevelView(this),this.scheduledRevalidation=!1},scheduleRevalidate:function(e,t,r){return e&&!this._dispatching&&e.guid in this.env.renderedNodes?void o["default"].scheduleOnce("render",this,this.revalidate):void((!this.scheduledRevalidation||this._dispatching)&&(this.scheduledRevalidation=!0,o["default"].scheduleOnce("render",this,this.revalidate)))},appendAttr:function(e,t){return this.currentState.appendAttr(this,e,t)},templateRenderer:null,removeFromParent:function(){var e=this.parentView;return (this.remove(), e&&e.removeChild(this), this)},destroy:function(){var e=this.parentView,t=this.viewName;return this._super.apply(this,arguments)?(t&&e&&e.set(t,null),this.lastResult&&this.lastResult.destroy(),this):void 0},handleEvent:function(e,t){return this.currentState.handleEvent(this,e,t)},_register:function(){this._viewRegistry[this.elementId]=this},_unregister:function(){delete this._viewRegistry[this.elementId]},registerObserver:function(e,t,r,n){if(n||"function"!=typeof r||(n=r,r=null),e&&"object"==typeof e){var i=this._wrapAsScheduled(n);s.addObserver(e,t,r,i),this.one("willClearRender",function(){s.removeObserver(e,t,r,i)})}},_wrapAsScheduled:function(e){var t=this,r=function(){t.currentState.invokeObserver(this,e)},n=function(){o["default"].scheduleOnce("render",this,r)};return n}});h.deprecateProperty(N.prototype,"state","_state"),h.deprecateProperty(N.prototype,"states","_states");var O=n["default"].extend(r["default"]).create();N.addMutationListener=function(e){O.on("change",e)},N.removeMutationListener=function(e){O.off("change",e)},N.notifyMutationListeners=function(){O.trigger("change")},N.reopenClass({views:{},childViewsProperty:v.childViewsProperty});var P=N.extend({init:function(){A(),this._super.apply(this,arguments)}});P.reopen=function(){return (A(), N.reopen.apply(N,arguments), this)},e["default"]=N,e.ViewContextSupport=f["default"],e.ViewChildViewsSupport=v["default"],e.ViewStateSupport=g["default"],e.TemplateRenderingSupport=b["default"],e.ClassNamesSupport=y["default"],e.DeprecatedView=P}),e("ember",["exports","ember-metal","ember-runtime","ember-views","ember-routing","ember-application","ember-extension-support","ember-htmlbars","ember-routing-htmlbars","ember-routing-views","ember-metal/environment","ember-runtime/system/lazy_load"],function(e,r,n,a,o,s,l,u,c,h,m,d){"use strict";i.__loader.registry["ember-template-compiler"]&&t("ember-template-compiler"),i.__loader.registry["ember-testing"]&&t("ember-testing"),d.runLoadHooks("Ember")}),e("htmlbars-runtime",["exports","./htmlbars-runtime/hooks","./htmlbars-runtime/render","../htmlbars-util/morph-utils","../htmlbars-util/template-utils","./htmlbars-runtime/expression-visitor","htmlbars-runtime/hooks"],function(e,t,r,n,i,a,o){"use strict";var s={blockFor:i.blockFor,manualElement:r.manualElement,hostBlock:o.hostBlock,continueBlock:o.continueBlock,hostYieldWithShadowTemplate:o.hostYieldWithShadowTemplate,visitChildren:n.visitChildren,validateChildMorphs:a.validateChildMorphs,clearMorph:i.clearMorph};e.hooks=t["default"],e.render=r["default"],e.internal=s}),e("htmlbars-runtime/expression-visitor",["exports","../htmlbars-util/object-utils","../htmlbars-util/morph-utils"],function(e,t,r){"use strict";function n(e,t,n,i){var a=t.isDirty,s=t.isSubtreeDirty,l=e;s&&(n=o),a||s?i(n):(t.buildChildEnv&&(l=t.buildChildEnv(t.state,l)),r.validateChildMorphs(l,t,n))}function i(e,t,r){return void 0!==e.hooks.keywords[r]||e.hooks.hasHelper(e,t,r)}var a={acceptExpression:function(e,t,r){var n={value:null};if("object"!=typeof e||null===e)return (n.value=e, n);switch(e[0]){case"value":n.value=e[1];break;case"get":n.value=this.get(e,t,r);break;case"subexpr":n.value=this.subexpr(e,t,r);break;case"concat":n.value=this.concat(e,t,r)}return n},acceptParams:function(e,t,r){for(var n=new Array(e.length),i=0,a=e.length;a>i;i++)n[i]=this.acceptExpression(e[i],t,r).value;return n},acceptHash:function(e,t,r){for(var n={},i=0,a=e.length;a>i;i+=2)n[e[i]]=this.acceptExpression(e[i+1],t,r).value;return n},get:function(e,t,r){return t.hooks.get(t,r,e[1])},subexpr:function(e,t,r){var n=e[1],i=e[2],a=e[3];return t.hooks.subexpr(t,r,n,this.acceptParams(i,t,r),this.acceptHash(a,t,r))},concat:function(e,t,r){return t.hooks.concat(t,this.acceptParams(e[1],t,r))},linkParamsAndHash:function(e,t,n,i,a,o){return (n.linkedParams?(a=n.linkedParams.params,o=n.linkedParams.hash):(a=a&&this.acceptParams(a,e,t),o=o&&this.acceptHash(o,e,t)), r.linkParams(e,t,n,i,a,o), [a,o])}},o=t.merge(Object.create(a),{block:function(e,t,r,n,i,a){var o=e[1],s=e[2],l=e[3],u=e[4],c=e[5],h=this.linkParamsAndHash(r,n,t,o,s,l);t.isDirty=t.isSubtreeDirty=!1,r.hooks.block(t,r,n,o,h[0],h[1],null===u?null:i.templates[u],null===c?null:i.templates[c],a)},inline:function(e,t,r,n,i){var a=e[1],o=e[2],s=e[3],l=this.linkParamsAndHash(r,n,t,a,o,s);t.isDirty=t.isSubtreeDirty=!1,r.hooks.inline(t,r,n,a,l[0],l[1],i)},content:function(e,t,n,a,o){var s=e[1];if(t.isDirty=t.isSubtreeDirty=!1,i(n,a,s))return (n.hooks.inline(t,n,a,s,[],{},o), void(t.linkedResult&&r.linkParams(n,a,t,"@content-helper",[t.linkedResult],null)));var l;l=t.linkedParams?t.linkedParams.params:[n.hooks.get(n,a,s)],r.linkParams(n,a,t,"@range",l,null),n.hooks.range(t,n,a,s,l[0],o)},element:function(e,t,r,n,i){var a=e[1],o=e[2],s=e[3],l=this.linkParamsAndHash(r,n,t,a,o,s);t.isDirty=t.isSubtreeDirty=!1,r.hooks.element(t,r,n,a,l[0],l[1],i)},attribute:function(e,t,r,n){var i=e[1],a=e[2],o=this.linkParamsAndHash(r,n,t,"@attribute",[a],null);t.isDirty=t.isSubtreeDirty=!1,r.hooks.attribute(t,r,n,i,o[0][0])},component:function(e,t,r,n,i,a){var o=e[1],s=e[2],l=e[3],u=e[4],c=this.linkParamsAndHash(r,n,t,o,[],s),h={"default":i.templates[l],inverse:i.templates[u]};t.isDirty=t.isSubtreeDirty=!1,r.hooks.component(t,r,n,o,c[0],c[1],h,a)},attributes:function(e,t,r,n,i,a){var o=e[1];r.hooks.attributes(t,r,n,o,i,a)}});e.AlwaysDirtyVisitor=o,e["default"]=t.merge(Object.create(a),{block:function(e,t,r,i,a,s){n(r,t,s,function(n){o.block(e,t,r,i,a,n)})},inline:function(e,t,r,i,a){n(r,t,a,function(n){o.inline(e,t,r,i,n)})},content:function(e,t,r,i,a){n(r,t,a,function(n){o.content(e,t,r,i,n)})},element:function(e,t,r,i,a,s){n(r,t,s,function(n){o.element(e,t,r,i,a,n)})},attribute:function(e,t,r,i,a){n(r,t,null,function(){o.attribute(e,t,r,i,a)})},component:function(e,t,r,i,a,s){n(r,t,s,function(n){o.component(e,t,r,i,a,n)})},attributes:function(e,t,r,n,i,a){o.attributes(e,t,r,n,i,a)}})}),e("htmlbars-runtime/hooks",["exports","./render","../morph-range/morph-list","../htmlbars-util/object-utils","../htmlbars-util/morph-utils","../htmlbars-util/template-utils"],function(e,t,r,n,i,a){"use strict";function o(e){return null===e?null:{meta:e.meta,arity:e.arity,raw:e,render:function(r,n,i,a){var o=n.hooks.createFreshScope();return (i=i||{}, i.self=r, i.blockArguments=a, t["default"](e,n,o,i))}}}function s(e,t,r,n,i,a){if(!e)return{yieldIn:h(null,t,r,n,i,a)};var o=l(e,t,r,n,i,a);return{meta:e.meta,arity:e.arity,"yield":o,yieldItem:u(e,t,r,n,i,a),yieldIn:h(e,t,r,n,i,a),raw:e,render:function(e,t){o(t,e)}}}function l(e,r,n,i,o,s){return function(l,u){o.morphToClear=null,i.morphList&&(a.clearMorphList(i.morphList,i,r),o.morphListToClear=null);var h=n;return i.lastYielded&&c(e,i.lastYielded)?i.lastResult.revalidateWith(r,void 0,u,l,s):((void 0!==u||null===n||e.arity)&&(h=r.hooks.createChildScope(n)),i.lastYielded={self:u,template:e,shadowTemplate:null},void t["default"](e,r,h,{renderNode:i,self:u,blockArguments:l}))}}function u(e,n,i,a,o,s){function u(e){for(var t=c;t.key!==e;)h[t.key]=t,t=t.nextMorph;return (c=t.nextMorph, t)}var c=null,h={},m=a.morphList;return (m&&(c=m.firstChildMorph), function(m,d,p){if("string"!=typeof m)throw new Error("You must provide a string key when calling `yieldItem`; you provided "+m);o.morphListToClear=null,a.lastYielded=null;var f,v;a.morphList||(a.morphList=new r["default"],a.morphMap={},a.setMorphList(a.morphList)),f=a.morphList,v=a.morphMap;var g=o.handledMorphs,b=void 0;if(m in g){var y=o.collisions;void 0===y&&(y=o.collisions={});var _=0|y[m];y[m]=++_,b=m+"--z8mS2hvDW0A--"+_}else b=m;if(c&&c.key===b)l(e,n,i,c,o,s)(d,p),c=c.nextMorph,g[b]=c;else if(void 0!==v[b]){var w=v[b];b in h?f.insertBeforeMorph(w,c):u(b),g[w.key]=w,l(e,n,i,w,o,s)(d,p)}else{var x=t.createChildMorph(n.dom,a);x.key=b,v[b]=g[b]=x,f.insertBeforeMorph(x,c),l(e,n,i,x,o,s)(d,p)}o.morphListToPrune=f,a.childNodes=null})}function c(e,t){return!t.shadowTemplate&&e===t.template}function h(e,t,r,n,i,a){var o=m(e,t,r,n,i,a);return function(e,r){o(e,t,r,[])}}function m(e,r,n,i,a,o){function s(r,i,a,o,s,l){if(o.lastResult)o.lastResult.revalidateWith(r,void 0,void 0,i,l);else{var u=n;e.arity&&(u=r.hooks.createChildScope(n)),t["default"](e,r,u,{renderNode:o,self:a,blockArguments:i})}}return function(r,l,u,c){if(a.morphToClear=null,i.lastYielded&&d(e,r,i.lastYielded))return i.lastResult.revalidateWith(l,void 0,u,c,o);var h=l.hooks.createFreshScope();l.hooks.bindShadowScope(l,n,h,a.shadowOptions),s.arity=e.arity,l.hooks.bindBlock(l,h,s),i.lastYielded={self:u,template:e,shadowTemplate:r},t["default"](r.raw,l,h,{renderNode:i,self:u,blockArguments:c})}}function d(e,t,r){return e===r.template&&t===r.shadowTemplate}function p(e,t,r,n,i,o){var l=i.lastResult?i:null,u=new a.RenderState(l,i.morphList||null);return{templates:{template:s(e,r,n,i,u,o),inverse:s(t,r,n,i,u,o)},renderState:u}}function f(e){return{arity:e.template.arity,"yield":e.template["yield"],yieldItem:e.template.yieldItem,yieldIn:e.template.yieldIn}}function v(e,t){return t?e.hooks.createChildScope(t):e.hooks.createFreshScope()}function g(){return{self:null,blocks:{},locals:{},localPresent:{}}}function b(e){return e.hooks.createFreshScope()}function y(e){var t=Object.create(e);return (t.locals=Object.create(e.locals), t)}function _(e,t,r){t.self=r}function w(e,t,r){e.hooks.bindSelf(e,t,r)}function x(e,t,r,n){t.localPresent[r]=!0,t.locals[r]=n}function C(e,t,r,n){e.hooks.bindLocal(e,t,r,n)}function k(e,t,r){var n=arguments.length<=3||void 0===arguments[3]?"default":arguments[3];t.blocks[n]=r}function E(e,t,r,n,i,a,o,s,l){O(e,t,r,n,i,a,o,s,l)||A(e,t,r,n,i,a,o,s,l)}function A(e,t,r,n,i,a,o,s,l){N(e,t,r,o,s,null,l,function(o){var s=t.hooks.lookupHelper(t,r,n);return t.hooks.invokeHelper(e,t,r,l,i,a,s,o.templates,f(o.templates))})}function N(e,t,r,n,i,o,s,l){var u=p(n,i,t,r,e,s);a.renderAndCleanup(e,t,u,o,l)}function O(e,t,r,n,i,a,o,s,l){if(!n)return!1;var u=t.hooks.classify(t,r,n);if(u){switch(u){case"component":t.hooks.component(e,t,r,n,i,a,{"default":o,inverse:s},l);break;case"inline":t.hooks.inline(e,t,r,n,i,a,l);break;case"block":t.hooks.block(e,t,r,n,i,a,o,s,l);break;default:throw new Error("Internal HTMLBars redirection to "+u+" not supported")}return!0}return P(n,e,t,r,i,a,o,s,l)?!0:!1}function P(e,t,r,o,s,l,u,c,h){var m=r.hooks.keywords[e];if(!m)return!1;if("function"==typeof m)return m(t,r,o,s,l,u,c,h);m.willRender&&m.willRender(t,r);var d,p;m.setupState&&(d=n.shallowCopy(t.state),p=t.state=m.setupState(d,r,o,s,l)),m.childEnv&&(r=m.childEnv(t.state,r),t.buildChildEnv=m.childEnv);var f=!t.rendered;if(m.isEmpty){var v=m.isEmpty(t.state,r,o,s,l);if(v)return (f||a.clearMorph(t,r,!1), !0)}if(f)return (m.render&&m.render(t,r,o,s,l,u,c,h), t.rendered=!0, !0);var g;if(g=m.isStable?m.isStable(d,p):S(d,p)){if(m.rerender){var b=m.rerender(t,r,o,s,l,u,c,h);r=b||r}return (i.validateChildMorphs(r,t,h), !0)}return (a.clearMorph(t,r,!1), m.render?(m.render(t,r,o,s,l,u,c,h),t.rendered=!0,!0):void 0)}function S(e,t){if(n.keyLength(e)!==n.keyLength(t))return!1;for(var r in e)if(e[r]!==t[r])return!1;return!0}function T(){}function R(e,t,r,n,a,o,s){if(!O(e,t,r,n,a,o,null,null,s)){var l=void 0,u=void 0;if(e.linkedResult)l=t.hooks.getValue(e.linkedResult),u=!0;else{var c=p(null,null,t,r,e),h=t.hooks.lookupHelper(t,r,n),m=t.hooks.invokeHelper(e,t,r,s,a,o,h,c.templates,f(c.templates));m&&m.link&&(e.linkedResult=m.value,i.linkParams(t,r,e,"@content-helper",[e.linkedResult],null)),m&&"value"in m&&(l=t.hooks.getValue(m.value),u=!0)}u&&(e.lastValue!==l&&e.setContent(l),e.lastValue=l)}}function M(e,t,r,n,i,a,o,s,l){P(e,t,r,n,i,a,o,s,l)}function D(e,t,r,n,i,a,o,s,l){var u=I(t,i),c=V(t,a);return{value:o.call(l,u,c,s)}}function I(e,t){for(var r=new Array(t.length),n=0,i=t.length;i>n;n++)r[n]=e.hooks.getCellOrValue(t[n]);return r}function V(e,t){var r={};for(var n in t)r[n]=e.hooks.getCellOrValue(t[n]);return r}function j(){return null}function L(e,t,r,n){var i=t.partials[n];return i.render(r.self,t,{}).fragment}function F(e,t,r,n,i,a){O(e,t,r,n,[i],{},null,null,a)||(i=t.hooks.getValue(i),e.lastValue!==i&&e.setContent(i),e.lastValue=i)}function B(e,t,r,n,i,a,o){if(!O(e,t,r,n,i,a,null,null,o)){var s=t.hooks.lookupHelper(t,r,n);s&&t.hooks.invokeHelper(null,t,r,null,i,a,s,{element:e.element})}}function H(e,t,r,n,i){i=t.hooks.getValue(i),e.lastValue!==i&&e.setContent(i),e.lastValue=i}function z(e,t,r,n,i){var a=e.hooks.lookupHelper(e,t,r),o=e.hooks.invokeHelper(null,e,t,null,n,i,a,{});return o&&"value"in o?e.hooks.getValue(o.value):void 0}function U(e,t,r){if(""===r)return t.self;for(var n=r.split("."),i=e.hooks.getRoot(t,n[0])[0],a=1;an;n++)r+=e.hooks.getValue(t[n]);return r}function $(e,r,n,i,a,o){var s=r.dom.createElement(i);for(var l in a)s.setAttribute(l,r.hooks.getValue(a[l]));var u=t["default"](o,r,n,{}).fragment;s.appendChild(u),e.setNode(s)}function J(e,t,r){return void 0!==e.helpers[r]}function X(e,t,r){return e.helpers[r]}function Z(){}function ee(e,t){e.hooks.bindScope(e,t)}e.wrap=o,e.wrapForHelper=s,e.hostYieldWithShadowTemplate=m,e.createScope=v,e.createFreshScope=g,e.bindShadowScope=b,e.createChildScope=y,e.bindSelf=_,e.updateSelf=w,e.bindLocal=x,e.updateLocal=C,e.bindBlock=k,e.block=E,e.continueBlock=A,e.hostBlock=N,e.handleRedirect=O,e.handleKeyword=P,e.linkRenderNode=T,e.inline=R,e.keyword=M,e.invokeHelper=D,e.classify=j,e.partial=L,e.range=F,e.element=B,e.attribute=H,e.subexpr=z,e.get=U,e.getRoot=q,e.getChild=W,e.getValue=K,e.getCellOrValue=G,e.component=Q,e.concat=Y,e.hasHelper=J,e.lookupHelper=X,e.bindScope=Z,e.updateScope=ee;var te={partial:function(e,t,r,n){var i=t.hooks.partial(e,t,r,n[0]);return (e.setContent(i), !0)},"yield":function(e,t,r,n,i,a,o,s){var l=t.hooks.getValue(i.to)||"default";return (r.blocks[l]&&r.blocks[l](t,n,i.self,e,r,s), !0)},hasBlock:function(e,t,r,n){var i=t.hooks.getValue(n[0])||"default";return!!r.blocks[i]},hasBlockParams:function(e,t,r,n){var i=t.hooks.getValue(n[0])||"default";return!(!r.blocks[i]||!r.blocks[i].arity)}};e.keywords=te,e["default"]={bindLocal:x,bindSelf:_,bindScope:Z,classify:j,component:Q,concat:Y,createFreshScope:g,getChild:W,getRoot:q,getValue:K,getCellOrValue:G,keywords:te,linkRenderNode:T,partial:L,subexpr:z,bindBlock:k,bindShadowScope:b,updateLocal:C,updateSelf:w,updateScope:ee,createChildScope:y,hasHelper:J,lookupHelper:X,invokeHelper:D,cleanupRenderNode:null,destroyRenderNode:null,willCleanupTree:null,didCleanupTree:null,willRenderNode:null,didRenderNode:null,attribute:H,block:E,createScope:v,element:B,get:U,inline:R,range:F,keyword:M}}),e("htmlbars-runtime/morph",["exports","../morph-range"],function(e,t){"use strict";function r(e,t){this.super$constructor(e,t),this.state={},this.ownerNode=null,this.isDirty=!1,this.isSubtreeDirty=!1,this.lastYielded=null,this.lastResult=null,this.lastValue=null,this.buildChildEnv=null,this.morphList=null,this.morphMap=null,this.key=null,this.linkedParams=null,this.linkedResult=null,this.childNodes=null,this.rendered=!1,this.guid="range"+n++}var n=1;r.empty=function(e,t){var n=new r(e,t);return (n.clear(), n)},r.create=function(e,t,n){var i=new r(e,t);return (i.setNode(n), i)},r.attach=function(e,t,n,i){var a=new r(e,t);return (a.setRange(n,i), a)};var i=r.prototype=Object.create(t["default"].prototype);i.constructor=r,i.super$constructor=t["default"],e["default"]=r}),e("htmlbars-runtime/render",["exports","../htmlbars-util/array-utils","../htmlbars-util/morph-utils","./expression-visitor","./morph","../htmlbars-util/template-utils","../htmlbars-util/void-tag-names"],function(e,t,r,n,i,a,o){"use strict";function s(e,t,r,n){var i,a=t.dom;n&&(n.renderNode?i=n.renderNode.contextualElement:n.contextualElement&&(i=n.contextualElement)),a.detectNamespace(i);var o=l.build(t,r,e,n,i);return (o.render(), o)}function l(e,t,r,n,i,a,o,s,l){this.root=n,this.fragment=o,this.nodes=a,this.template=s,this.statements=s.statements.slice(),this.env=e,this.scope=t,this.shouldSetContent=l,this.bindScope(),void 0!==r.attributes&&(a.push({state:{}}),this.statements.push(["attributes",c(r.attributes)])),void 0!==r.self&&this.bindSelf(r.self),void 0!==r.blockArguments&&this.bindLocals(r.blockArguments),this.initializeNodes(i)}function u(e,t){var r=[];for(var n in t)"string"!=typeof t[n]&&r.push(["attribute",n,t[n]]);r.push(["content","yield"]);var i={arity:0,cachedFragment:null,hasRendered:!1,buildFragment:function(r){var n=r.createDocumentFragment();"svg"===e&&r.setNamespace(p);var i=r.createElement(e);for(var a in t)"string"==typeof t[a]&&r.setAttribute(i,a,t[a]);if(!o["default"][e]){var s=r.createComment("");r.appendChild(i,s)}return (r.appendChild(n,i), n)},buildRenderNodes:function(e,r){var n=e.childAt(r,[0]),i=[];for(var a in t)"string"!=typeof t[a]&&i.push(e.createAttrMorph(n,a));return (i.push(e.createMorphAt(n,0,0)), i)},statements:r,locals:[],templates:[]};return i}function c(e){var t=[];for(var r in e)"string"!=typeof e[r]&&t.push(["attribute",r,e[r]]);var n={arity:0,cachedFragment:null,hasRendered:!1,buildFragment:function(t){var r=this.element;"http://www.w3.org/2000/svg"===r.namespaceURI&&t.setNamespace(p);for(var n in e)"string"==typeof e[n]&&t.setAttribute(r,n,e[n]);return r},buildRenderNodes:function(t){var r=this.element,n=[];for(var i in e)"string"!=typeof e[i]&&n.push(t.createAttrMorph(r,i));return n},statements:t,locals:[],templates:[],element:null};return n}function h(e,t){e.ownerNode=t}function m(e,t,r){var n=i["default"].empty(e,r||t.contextualElement);return (h(n,t.ownerNode), n)}function d(e,t){var r,n=t.dom;return (t.useFragmentCache&&n.canClone?(null===e.cachedFragment&&(r=e.buildFragment(n),e.hasRendered?e.cachedFragment=r:e.hasRendered=!0),e.cachedFragment&&(r=n.cloneNode(e.cachedFragment,!0))):r||(r=e.buildFragment(n)), r)}e["default"]=s,e.manualElement=u,e.attachAttributes=c,e.createChildMorph=m,e.getCachedFragment=d;var p="http://www.w3.org/2000/svg";l.build=function(e,t,n,i,o){var s,u,c,m=e.dom,p=d(n,e),f=n.buildRenderNodes(m,p,o);return (i&&i.renderNode?(s=i.renderNode,u=s.ownerNode,c=!0):(s=m.createMorph(null,p.firstChild,p.lastChild,o),u=s,h(s,u),c=!1), s.childNodes&&r.visitChildren(s.childNodes,function(t){a.clearMorph(t,e,!0)}), s.childNodes=f, new l(e,t,i,s,u,f,p,n,c))},l.prototype.initializeNodes=function(e){t.forEach(this.root.childNodes,function(t){h(t,e)})},l.prototype.render=function(){this.root.lastResult=this,this.root.rendered=!0,this.populateNodes(n.AlwaysDirtyVisitor),this.shouldSetContent&&this.root.setContent&&this.root.setContent(this.fragment)},l.prototype.dirty=function(){r.visitChildren([this.root],function(e){e.isDirty=!0})},l.prototype.revalidate=function(e,t,r,i){this.revalidateWith(e,i,t,r,n["default"])},l.prototype.rerender=function(e,t,r,i){this.revalidateWith(e,i,t,r,n.AlwaysDirtyVisitor)},l.prototype.revalidateWith=function(e,t,r,n,i){void 0!==e&&(this.env=e),void 0!==t&&(this.scope=t),this.updateScope(),void 0!==r&&this.updateSelf(r),void 0!==n&&this.updateLocals(n),this.populateNodes(i)},l.prototype.destroy=function(){var e=this.root;a.clearMorph(e,this.env,!0)},l.prototype.populateNodes=function(e){var t,r,n=this.env,i=this.scope,a=this.template,o=this.nodes,s=this.statements;for(t=0,r=s.length;r>t;t++){var l=s[t],u=o[t];switch(n.hooks.willRenderNode&&n.hooks.willRenderNode(u,n,i),l[0]){case"block":e.block(l,u,n,i,a,e);break;case"inline":e.inline(l,u,n,i,e);break;case"content":e.content(l,u,n,i,e);break;case"element":e.element(l,u,n,i,a,e);break;case"attribute":e.attribute(l,u,n,i);break;case"component":e.component(l,u,n,i,a,e);break;case"attributes":e.attributes(l,u,n,i,this.fragment,e)}n.hooks.didRenderNode&&n.hooks.didRenderNode(u,n,i)}},l.prototype.bindScope=function(){this.env.hooks.bindScope(this.env,this.scope)},l.prototype.updateScope=function(){this.env.hooks.updateScope(this.env,this.scope)},l.prototype.bindSelf=function(e){this.env.hooks.bindSelf(this.env,this.scope,e)},l.prototype.updateSelf=function(e){this.env.hooks.updateSelf(this.env,this.scope,e)},l.prototype.bindLocals=function(e){for(var t=this.template.locals,r=0,n=t.length;n>r;r++)this.env.hooks.bindLocal(this.env,this.scope,t[r],e[r])},l.prototype.updateLocals=function(e){for(var t=this.template.locals,r=0,n=t.length;n>r;r++)this.env.hooks.updateLocal(this.env,this.scope,t[r],e[r])}}),e("htmlbars-util",["exports","./htmlbars-util/safe-string","./htmlbars-util/handlebars/utils","./htmlbars-util/namespaces","./htmlbars-util/morph-utils"],function(e,t,r,n,i){"use strict";e.SafeString=t["default"],e.escapeExpression=r.escapeExpression,e.getAttrNamespace=n.getAttrNamespace,e.validateChildMorphs=i.validateChildMorphs,e.linkParams=i.linkParams,e.dump=i.dump}),e("htmlbars-util/array-utils",["exports"],function(e){"use strict";function t(e,t,r){var n,i;if(void 0===r)for(n=0,i=e.length;i>n;n++)t(e[n],n,e);else for(n=0,i=e.length;i>n;n++)t.call(r,e[n],n,e)}function r(e,t){var r,n,i=[];for(r=0,n=e.length;n>r;r++)i.push(t(e[r],r,e));return i}e.forEach=t,e.map=r;var n;n=Array.prototype.indexOf?function(e,t,r){return e.indexOf(t,r)}:function(e,t,r){void 0===r||null===r?r=0:0>r&&(r=Math.max(0,e.length+r));for(var n=r,i=e.length;i>n;n++)if(e[n]===t)return n;return-1};var i=Array.isArray||function(e){return"[object Array]"===Object.prototype.toString.call(e)};e.isArray=i;var a=n;e.indexOfArray=a}),e("htmlbars-util/handlebars/safe-string",["exports"],function(e){"use strict";function t(e){this.string=e}t.prototype.toString=t.prototype.toHTML=function(){return""+this.string},e["default"]=t}),e("htmlbars-util/handlebars/utils",["exports"],function(e){"use strict";function t(e){return l[e]}function r(e){for(var t=1;tr;r++)if(e[r]===t)return r;return-1}function i(e){if("string"!=typeof e){if(e&&e.toHTML)return e.toHTML();if(null==e)return"";if(!e)return e+"";e=""+e}return c.test(e)?e.replace(u,t):e}function a(e){return e||0===e?d(e)&&0===e.length?!0:!1:!0}function o(e,t){return (e.path=t, e)}function s(e,t){return(e?e+".":"")+t}e.extend=r,e.indexOf=n,e.escapeExpression=i,e.isEmpty=a,e.blockParams=o,e.appendContextPath=s;var l={"&":"&","<":"<",">":">",'"':""","'":"'","`":"`"},u=/[&<>"'`]/g,c=/[&<>"'`]/,h=Object.prototype.toString;e.toString=h;var m=function(e){return"function"==typeof e};m(/x/)&&(e.isFunction=m=function(e){return"function"==typeof e&&"[object Function]"===h.call(e)});var m;e.isFunction=m;var d=Array.isArray||function(e){return e&&"object"==typeof e?"[object Array]"===h.call(e):!1};e.isArray=d}),e("htmlbars-util/morph-utils",["exports"],function(e){"use strict";function t(e,t){if(e&&0!==e.length)for(e=e.slice();e.length;){var r=e.pop();if(t(r),r.childNodes)e.push.apply(e,r.childNodes);else if(r.firstChildMorph)for(var n=r.firstChildMorph;n;)e.push(n),n=n.nextMorph;else if(r.morphList)for(var n=r.morphList.firstChildMorph;n;)e.push(n),n=n.nextMorph}}function r(e,t,n){var i=t.morphList;if(t.morphList)for(var a=i.firstChildMorph;a;){var o=a.nextMorph;r(e,a,n),a=o}else if(t.lastResult)t.lastResult.revalidateWith(e,void 0,void 0,void 0,n);else if(t.childNodes)for(var s=0,l=t.childNodes.length;l>s;s++)r(e,t.childNodes[s],n)}function n(e,t,r,n,i,a){r.linkedParams||e.hooks.linkRenderNode(r,e,t,n,i,a)&&(r.linkedParams={params:i,hash:a})}function i(e){if(console.group(e,e.isDirty),e.childNodes)a(e.childNodes,i);else if(e.firstChildMorph)for(var t=e.firstChildMorph;t;)i(t),t=t.nextMorph;else e.morphList&&i(e.morphList);console.groupEnd()}function a(e,t){for(var r=0,n=e.length;n>r;r++)t(e[r])}e.visitChildren=t,e.validateChildMorphs=r,e.linkParams=n,e.dump=i}),e("htmlbars-util/namespaces",["exports"],function(e){"use strict";function t(e){var t,n=e.indexOf(":");if(-1!==n){var i=e.slice(0,n);t=r[i]}return t||null}e.getAttrNamespace=t;var r={html:"http://www.w3.org/1999/xhtml",mathml:"http://www.w3.org/1998/Math/MathML",svg:"http://www.w3.org/2000/svg",xlink:"http://www.w3.org/1999/xlink",xml:"http://www.w3.org/XML/1998/namespace"}}),e("htmlbars-util/object-utils",["exports"],function(e){"use strict";function t(e,t){for(var r in t)e.hasOwnProperty(r)||(e[r]=t[r]);return e}function r(e){return t({},e)}function n(e){var t={};for(var r in e)e.hasOwnProperty(r)&&(t[r]=!0);return t}function i(e){var t=0;for(var r in e)e.hasOwnProperty(r)&&t++;return t}e.merge=t,e.shallowCopy=r,e.keySet=n,e.keyLength=i}),e("htmlbars-util/quoting",["exports"],function(e){"use strict";function t(e){return (e=e.replace(/\\/g,"\\\\"), e=e.replace(/"/g,'\\"'), e=e.replace(/\n/g,"\\n"))}function r(e){return'"'+t(e)+'"'}function n(e){return"["+e+"]"}function i(e){return"{"+e.join(", ")+"}"}function a(e,t){for(var r="";t--;)r+=e;return r}e.hash=i,e.repeat=a,e.escapeString=t,e.string=r,e.array=n}),e("htmlbars-util/safe-string",["exports","./handlebars/safe-string"],function(e,t){"use strict";e["default"]=t["default"]}),e("htmlbars-util/template-utils",["exports","../htmlbars-util/morph-utils"],function(e,t){"use strict";function r(e,t){this.morphListToClear=t,this.morphListToPrune=null,this.handledMorphs={},this.collisions=void 0,this.morphToClear=e,this.shadowOptions=null}function n(e,t,n){var o=function(o,s,l,u,c,h){if(u.lastResult)u.lastResult.revalidateWith(o,void 0,l,s,h);else{var m={renderState:new r(u)},d=n.scope,p=d?o.hooks.createChildScope(d):o.hooks.createFreshScope(),f=n.attributes;o.hooks.bindShadowScope(o,c,p,n.options),void 0!==l?o.hooks.bindSelf(o,p,l):void 0!==n.self&&o.hooks.bindSelf(o,p,n.self),i(o,p,n.yieldTo),a(u,o,m,null,function(){m.renderState.morphToClear=null,e(t,o,p,{renderNode:u,blockArguments:s,attributes:f})})}};return (o.arity=t.arity, o)}function i(e,t,r){if(r)if("function"==typeof r)e.hooks.bindBlock(e,t,r);else for(var n in r)r.hasOwnProperty(n)&&e.hooks.bindBlock(e,t,r[n],n)}function a(e,t,r,n,i){var a=r.renderState;a.collisions=void 0,a.shadowOptions=n;var l=i(r);if(!l||!l.handled){var u=e.morphMap,c=a.morphListToPrune;if(c)for(var h=a.handledMorphs,m=c.firstChildMorph;m;){var d=m.nextMorph;m.key in h||(delete u[m.key],o(m,t,!0),m.destroy()),m=d}c=a.morphListToClear,c&&s(c,e,t);var p=a.morphToClear;p&&o(p,t)}}function o(e,r,n){function i(e){a&&a(e),o&&o(e)}var a=r.hooks.cleanupRenderNode,o=r.hooks.destroyRenderNode,s=r.hooks.willCleanupTree,l=r.hooks.didCleanupTree;s&&s(r,e,n),a&&a(e),n&&o&&o(e),t.visitChildren(e.childNodes,i),e.clear(),l&&l(r,e,n),e.lastResult=null,e.lastYielded=null,e.childNodes=null}function s(e,t,r){for(var n=e.firstChildMorph;n;){var i=n.nextMorph;delete t.morphMap[n.key],o(n,r,!0),n.destroy(),n=i}e.clear(),t.morphList=null}e.RenderState=r,e.blockFor=n,e.renderAndCleanup=a,e.clearMorph=o,e.clearMorphList=s}),e("htmlbars-util/void-tag-names",["exports","./array-utils"],function(e,t){"use strict";var r="area base br col command embed hr img input keygen link meta param source track wbr",n={};t.forEach(r.split(" "),function(e){n[e]=!0}),e["default"]=n}),e("morph-attr",["exports","./morph-attr/sanitize-attribute-value","./dom-helper/prop","./dom-helper/build-html-dom","./htmlbars-util"],function(e,t,r,n,i){"use strict";function a(){return this.domHelper.getPropertyStrict(this.element,this.attrName)}function o(e){this._renderedInitially!==!0&&r.isAttrRemovalValue(e)||this.domHelper.setPropertyStrict(this.element,this.attrName,e),this._renderedInitially=!0}function s(){return this.domHelper.getAttribute(this.element,this.attrName)}function l(e){r.isAttrRemovalValue(e)?this.domHelper.removeAttribute(this.element,this.attrName):this.domHelper.setAttribute(this.element,this.attrName,e)}function u(){return this.domHelper.getAttributeNS(this.element,this.namespace,this.attrName)}function c(e){r.isAttrRemovalValue(e)?this.domHelper.removeAttribute(this.element,this.attrName):this.domHelper.setAttributeNS(this.element,this.namespace,this.attrName,e)}function h(e,t,h,p){if(this.element=e,this.domHelper=h,this.namespace=void 0!==p?p:i.getAttrNamespace(t),this.state={},this.isDirty=!1,this.isSubtreeDirty=!1,this.escaped=!0,this.lastValue=m,this.lastResult=null,this.lastYielded=null,this.childNodes=null,this.linkedParams=null,this.linkedResult=null,this.guid="attr"+d++,this.ownerNode=null,this.rendered=!1,this._renderedInitially=!1,this.namespace)this._update=c,this._get=u,this.attrName=t;else{var f=r.normalizeProperty(this.element,t),v=f.normalized,g=f.type;e.namespaceURI===n.svgNamespace||"style"===t||"attr"===g?(this._update=l,this._get=s,this.attrName=v):(this._update=o,this._get=a,this.attrName=v)}}var m={unset:!0},d=1;h.prototype.setContent=function(e){if(this.lastValue!==e)if(this.lastValue=e,this.escaped){var r=t.sanitizeAttributeValue(this.domHelper,this.element,this.attrName,e);this._update(r,this.namespace)}else this._update(e,this.namespace)},h.prototype.getContent=function(){var e=this.lastValue=this._get();return e},h.prototype.clear=function(){},h.prototype.destroy=function(){this.element=null,this.domHelper=null},e["default"]=h,e.sanitizeAttributeValue=t.sanitizeAttributeValue}),e("morph-attr/sanitize-attribute-value",["exports"],function(e){"use strict";function t(e,t,s,l){var u;if(u=t?t.tagName.toUpperCase():null,l&&l.toHTML)return l.toHTML();if((null===u||n[u])&&a[s]){var c=e.protocolForURL(l);if(r[c]===!0)return"unsafe:"+l}return i[u]&&o[s]?"unsafe:"+l:l}e.sanitizeAttributeValue=t;var r={"javascript:":!0,"vbscript:":!0},n={A:!0,BODY:!0,LINK:!0,IMG:!0,IFRAME:!0,BASE:!0,FORM:!0},i={EMBED:!0},a={href:!0,src:!0,background:!0,action:!0};e.badAttributes=a;var o={src:!0}}),e("morph-range",["exports","./morph-range/utils"],function(e,t){"use strict";function r(e,t){this.domHelper=e,this.contextualElement=t,this.firstNode=null,this.lastNode=null,this.parseTextAsHTML=!1,this.parentMorphList=null,this.previousMorph=null,this.nextMorph=null}r.empty=function(e,t){var n=new r(e,t);return (n.clear(), n)},r.create=function(e,t,n){var i=new r(e,t);return (i.setNode(n), i)},r.attach=function(e,t,n,i){var a=new r(e,t);return (a.setRange(n,i), a)},r.prototype.setContent=function(e){if(null===e||void 0===e)return this.clear();var t=typeof e;switch(t){case"string":return this.parseTextAsHTML?this.domHelper.setMorphHTML(this,e):this.setText(e);case"object":if("number"==typeof e.nodeType)return this.setNode(e);if("function"==typeof e.toHTML)return this.setHTML(e.toHTML());if(this.parseTextAsHTML)return this.setHTML(e.toString());case"boolean":case"number":return this.setText(e.toString());default:throw new TypeError("unsupported content")}},r.prototype.clear=function(){var e=this.setNode(this.domHelper.createComment("")); +return e},r.prototype.setText=function(e){var t=this.firstNode,r=this.lastNode;return t&&r===t&&3===t.nodeType?(t.nodeValue=e,t):this.setNode(e?this.domHelper.createTextNode(e):this.domHelper.createComment(""))},r.prototype.setNode=function(e){var t,r;switch(e.nodeType){case 3:t=e,r=e;break;case 11:t=e.firstChild,r=e.lastChild,null===t&&(t=this.domHelper.createComment(""),e.appendChild(t),r=t);break;default:t=e,r=e}return (this.setRange(t,r), e)},r.prototype.setRange=function(e,r){var n=this.firstNode;if(null!==n){var i=n.parentNode;null!==i&&(t.insertBefore(i,e,r,n),t.clear(i,n,this.lastNode))}this.firstNode=e,this.lastNode=r,this.parentMorphList&&(this._syncFirstNode(),this._syncLastNode())},r.prototype.destroy=function(){this.unlink();var e=this.firstNode,r=this.lastNode,n=e&&e.parentNode;this.firstNode=null,this.lastNode=null,t.clear(n,e,r)},r.prototype.unlink=function(){var e=this.parentMorphList,t=this.previousMorph,r=this.nextMorph;if(t?r?(t.nextMorph=r,r.previousMorph=t):(t.nextMorph=null,e.lastChildMorph=t):r?(r.previousMorph=null,e.firstChildMorph=r):e&&(e.lastChildMorph=e.firstChildMorph=null),this.parentMorphList=null,this.nextMorph=null,this.previousMorph=null,e&&e.mountedMorph){if(!e.firstChildMorph)return void e.mountedMorph.clear();e.firstChildMorph._syncFirstNode(),e.lastChildMorph._syncLastNode()}},r.prototype.setHTML=function(e){var t=this.domHelper.parseHTML(e,this.contextualElement);return this.setNode(t)},r.prototype.setMorphList=function(e){e.mountedMorph=this,this.clear();var t=this.firstNode;if(e.firstChildMorph){this.firstNode=e.firstChildMorph.firstNode,this.lastNode=e.lastChildMorph.lastNode;for(var r=e.firstChildMorph;r;){var n=r.nextMorph;r.insertBeforeNode(t,null),r=n}t.parentNode.removeChild(t)}},r.prototype._syncFirstNode=function(){for(var e,t=this;(e=t.parentMorphList)&&null!==e.mountedMorph&&t===e.firstChildMorph&&t.firstNode!==e.mountedMorph.firstNode;)e.mountedMorph.firstNode=t.firstNode,t=e.mountedMorph},r.prototype._syncLastNode=function(){for(var e,t=this;(e=t.parentMorphList)&&null!==e.mountedMorph&&t===e.lastChildMorph&&t.lastNode!==e.mountedMorph.lastNode;)e.mountedMorph.lastNode=t.lastNode,t=e.mountedMorph},r.prototype.insertBeforeNode=function(e,r){t.insertBefore(e,this.firstNode,this.lastNode,r)},r.prototype.appendToNode=function(e){t.insertBefore(e,this.firstNode,this.lastNode,null)},e["default"]=r}),e("morph-range/morph-list",["exports","./utils"],function(e,t){"use strict";function r(){this.firstChildMorph=null,this.lastChildMorph=null,this.mountedMorph=null}var n=r.prototype;n.clear=function(){for(var e=this.firstChildMorph;e;){var t=e.nextMorph;e.previousMorph=null,e.nextMorph=null,e.parentMorphList=null,e=t}this.firstChildMorph=this.lastChildMorph=null},n.destroy=function(){},n.appendMorph=function(e){this.insertBeforeMorph(e,null)},n.insertBeforeMorph=function(e,r){if(null!==e.parentMorphList&&e.unlink(),r&&r.parentMorphList!==this)throw new Error("The morph before which the new morph is to be inserted is not a child of this morph.");var n=this.mountedMorph;if(n){var i=n.firstNode.parentNode,a=r?r.firstNode:n.lastNode.nextSibling;t.insertBefore(i,e.firstNode,e.lastNode,a),this.firstChildMorph||t.clear(this.mountedMorph.firstNode.parentNode,this.mountedMorph.firstNode,this.mountedMorph.lastNode)}e.parentMorphList=this;var o=r?r.previousMorph:this.lastChildMorph;o?(o.nextMorph=e,e.previousMorph=o):this.firstChildMorph=e,r?(r.previousMorph=e,e.nextMorph=r):this.lastChildMorph=e,this.firstChildMorph._syncFirstNode(),this.lastChildMorph._syncLastNode()},n.removeChildMorph=function(e){if(e.parentMorphList!==this)throw new Error("Cannot remove a morph from a parent it is not inside of");e.destroy()},e["default"]=r}),e("morph-range/morph-list.umd",["exports","./morph-list"],function(t,r){"use strict";!function(r,n){"function"==typeof e&&e.amd?e([],n):"object"==typeof t?module.exports=n():r.MorphList=n()}(void 0,function(){return r["default"]})}),e("morph-range/utils",["exports"],function(e){"use strict";function t(e,t,r){if(e){var n,i=t;do{if(n=i.nextSibling,e.removeChild(i),i===r)break;i=n}while(i)}}function r(e,t,r,n){var i,a=t;do{if(i=a.nextSibling,e.insertBefore(a,n),a===r)break;a=i}while(a)}e.clear=t,e.insertBefore=r}),e("route-recognizer",["exports","./route-recognizer/dsl"],function(e,t){"use strict";function r(e){return"[object Array]"===Object.prototype.toString.call(e)}function n(e){this.string=e}function i(e){this.name=e}function a(e){this.name=e}function o(){}function s(e,t,r){"/"===e.charAt(0)&&(e=e.substr(1));for(var s=e.split("/"),l=[],u=0,c=s.length;c>u;u++){var h,m=s[u];(h=m.match(/^:([^\/]+)$/))?(l.push(new i(h[1])),t.push(h[1]),r.dynamics++):(h=m.match(/^\*([^\/]+)$/))?(l.push(new a(h[1])),t.push(h[1]),r.stars++):""===m?l.push(new o):(l.push(new n(m)),r.statics++)}return l}function l(e){this.charSpec=e,this.nextStates=[]}function u(e){return e.sort(function(e,t){if(e.types.stars!==t.types.stars)return e.types.stars-t.types.stars;if(e.types.stars){if(e.types.statics!==t.types.statics)return t.types.statics-e.types.statics;if(e.types.dynamics!==t.types.dynamics)return t.types.dynamics-e.types.dynamics}return e.types.dynamics!==t.types.dynamics?e.types.dynamics-t.types.dynamics:e.types.statics!==t.types.statics?t.types.statics-e.types.statics:0})}function c(e,t){for(var r=[],n=0,i=e.length;i>n;n++){var a=e[n];r=r.concat(a.match(t))}return r}function h(e){this.queryParams=e||{}}function m(e,t,r){for(var n=e.handlers,i=e.regex,a=t.match(i),o=1,s=new h(r),l=0,u=n.length;u>l;l++){for(var c=n[l],m=c.names,d={},p=0,f=m.length;f>p;p++)d[m[p]]=a[o++];s.push({handler:c.handler,params:d,isDynamic:!!m.length})}return s}function d(e,t){return (t.eachChar(function(t){e=e.put(t)}), e)}function p(e){return (e=e.replace(/\+/gm,"%20"), decodeURIComponent(e))}var f=["/",".","*","+","?","|","(",")","[","]","{","}","\\"],v=new RegExp("(\\"+f.join("|\\")+")","g");n.prototype={eachChar:function(e){for(var t,r=this.string,n=0,i=r.length;i>n;n++)t=r.charAt(n),e({validChars:t})},regex:function(){return this.string.replace(v,"\\$1")},generate:function(){return this.string}},i.prototype={eachChar:function(e){e({invalidChars:"/",repeat:!0})},regex:function(){return"([^/]+)"},generate:function(e){return e[this.name]}},a.prototype={eachChar:function(e){e({invalidChars:"",repeat:!0})},regex:function(){return"(.+)"},generate:function(e){return e[this.name]}},o.prototype={eachChar:function(){},regex:function(){return""},generate:function(){return""}},l.prototype={get:function(e){for(var t=this.nextStates,r=0,n=t.length;n>r;r++){var i=t[r],a=i.charSpec.validChars===e.validChars;if(a=a&&i.charSpec.invalidChars===e.invalidChars)return i}},put:function(e){var t;return(t=this.get(e))?t:(t=new l(e),this.nextStates.push(t),e.repeat&&t.nextStates.push(t),t)},match:function(e){for(var t,r,n,i=this.nextStates,a=[],o=0,s=i.length;s>o;o++)t=i[o],r=t.charSpec,"undefined"!=typeof(n=r.validChars)?-1!==n.indexOf(e)&&a.push(t):"undefined"!=typeof(n=r.invalidChars)&&-1===n.indexOf(e)&&a.push(t);return a}};var g=Object.create||function(e){function t(){}return (t.prototype=e, new t)};h.prototype=g({splice:Array.prototype.splice,slice:Array.prototype.slice,push:Array.prototype.push,length:0,queryParams:null});var b=function(){this.rootState=new l,this.names={}};b.prototype={add:function(e,t){for(var r,n=this.rootState,i="^",a={statics:0,dynamics:0,stars:0},l=[],u=[],c=!0,h=0,m=e.length;m>h;h++){var p=e[h],f=[],v=s(p.path,f,a);u=u.concat(v);for(var g=0,b=v.length;b>g;g++){var y=v[g];y instanceof o||(c=!1,n=n.put({validChars:"/"}),i+="/",n=d(n,y),i+=y.regex())}var _={handler:p.handler,names:f};l.push(_)}c&&(n=n.put({validChars:"/"}),i+="/"),n.handlers=l,n.regex=new RegExp(i+"$"),n.types=a,(r=t&&t.as)&&(this.names[r]={segments:u,handlers:l})},handlersFor:function(e){var t=this.names[e],r=[];if(!t)throw new Error("There is no route named "+e);for(var n=0,i=t.handlers.length;i>n;n++)r.push(t.handlers[n]);return r},hasRoute:function(e){return!!this.names[e]},generate:function(e,t){var r=this.names[e],n="";if(!r)throw new Error("There is no route named "+e);for(var i=r.segments,a=0,s=i.length;s>a;a++){var l=i[a];l instanceof o||(n+="/",n+=l.generate(t))}return("/"!==n.charAt(0)&&(n="/"+n), t&&t.queryParams&&(n+=this.generateQueryString(t.queryParams,r.handlers)), n)},generateQueryString:function(e,t){var n=[],i=[];for(var a in e)e.hasOwnProperty(a)&&i.push(a);i.sort();for(var o=0,s=i.length;s>o;o++){a=i[o];var l=e[a];if(null!=l){var u=encodeURIComponent(a);if(r(l))for(var c=0,h=l.length;h>c;c++){var m=a+"[]="+encodeURIComponent(l[c]);n.push(m)}else u+="="+encodeURIComponent(l),n.push(u)}}return 0===n.length?"":"?"+n.join("&")},parseQueryString:function(e){for(var t=e.split("&"),r={},n=0;n2&&"[]"===o.slice(s-2)&&(l=!0,o=o.slice(0,s-2),r[o]||(r[o]=[])),i=a[1]?p(a[1]):""),l?r[o].push(i):r[o]=i}return r},recognize:function(e){var t,r,n,i,a=[this.rootState],o={},s=!1;if(i=e.indexOf("?"),-1!==i){var l=e.substr(i+1,e.length);e=e.substr(0,i),o=this.parseQueryString(l)}for(e=decodeURI(e),"/"!==e.charAt(0)&&(e="/"+e),t=e.length,t>1&&"/"===e.charAt(t-1)&&(e=e.substr(0,t-1),s=!0),r=0,n=e.length;n>r&&(a=c(a,e.charAt(r)),a.length);r++);var h=[];for(r=0,n=a.length;n>r;r++)a[r].handlers&&h.push(a[r]);a=u(h);var d=h[0];return d&&d.handlers?(s&&"(.+)$"===d.regex.source.slice(-5)&&(e+="/"),m(d,e,o)):void 0}},b.prototype.map=t["default"],b.VERSION="0.1.5",e["default"]=b}),e("route-recognizer/dsl",["exports"],function(e){"use strict";function t(e,t,r){this.path=e,this.matcher=t,this.delegate=r}function r(e){this.routes={},this.children={},this.target=e}function n(e,r,i){return function(a,o){var s=e+a;return o?void o(n(s,r,i)):new t(e+a,r,i)}}function i(e,t,r){for(var n=0,i=0,a=e.length;a>i;i++)n+=e[i].path.length;t=t.substr(n);var o={path:t,handler:r};e.push(o)}function a(e,t,r,n){var o=t.routes;for(var s in o)if(o.hasOwnProperty(s)){var l=e.slice();i(l,s,o[s]),t.children[s]?a(l,t.children[s],r,n):r.call(n,l)}}t.prototype={to:function(e,t){var r=this.delegate;if(r&&r.willAddRoute&&(e=r.willAddRoute(this.matcher.target,e)),this.matcher.add(this.path,e),t){if(0===t.length)throw new Error("You must have an argument in the function passed to `to`");this.matcher.addChild(this.path,e,t,this.delegate)}return this}},r.prototype={add:function(e,t){this.routes[e]=t},addChild:function(e,t,i,a){var o=new r(t);this.children[e]=o;var s=n(e,o,a);a&&a.contextEntered&&a.contextEntered(t,s),i(s)}},e["default"]=function(e,t){var i=new r;e(n("",i,this.delegate)),a([],i,function(e){t?t(this,e):this.add(e)},this)}}),e("router",["exports","./router/router"],function(e,t){"use strict";e["default"]=t["default"]}),e("router/handler-info",["exports","./utils","rsvp/promise"],function(e,t,r){"use strict";function n(e){var r=e||{};t.merge(this,r),this.initialize(r)}function i(e,t){if(!e^!t)return!1;if(!e)return!0;for(var r in e)if(e.hasOwnProperty(r)&&e[r]!==t[r])return!1;return!0}n.prototype={name:null,handler:null,params:null,context:null,factory:null,initialize:function(){},log:function(e,t){e.log&&e.log(this.name+": "+t)},promiseLabel:function(e){return t.promiseLabel("'"+this.name+"' "+e)},getUnresolved:function(){return this},serialize:function(){return this.params||{}},resolve:function(e,n){var i=t.bind(this,this.checkForAbort,e),a=t.bind(this,this.runBeforeModelHook,n),o=t.bind(this,this.getModel,n),s=t.bind(this,this.runAfterModelHook,n),l=t.bind(this,this.becomeResolved,n);return r["default"].resolve(void 0,this.promiseLabel("Start handler")).then(i,null,this.promiseLabel("Check for abort")).then(a,null,this.promiseLabel("Before model")).then(i,null,this.promiseLabel("Check if aborted during 'beforeModel' hook")).then(o,null,this.promiseLabel("Model")).then(i,null,this.promiseLabel("Check if aborted in 'model' hook")).then(s,null,this.promiseLabel("After model")).then(i,null,this.promiseLabel("Check if aborted in 'afterModel' hook")).then(l,null,this.promiseLabel("Become resolved"))},runBeforeModelHook:function(e){return (e.trigger&&e.trigger(!0,"willResolveModel",e,this.handler), this.runSharedModelHook(e,"beforeModel",[]))},runAfterModelHook:function(e,t){var r=this.name;return (this.stashResolvedModel(e,t), this.runSharedModelHook(e,"afterModel",[t]).then(function(){return e.resolvedModels[r]},null,this.promiseLabel("Ignore fulfillment value and return model value")))},runSharedModelHook:function(e,n,i){this.log(e,"calling "+n+" hook"),this.queryParams&&i.push(this.queryParams),i.push(e);var a=t.applyHook(this.handler,n,i);return (a&&a.isTransition&&(a=null), r["default"].resolve(a,this.promiseLabel("Resolve value returned from one of the model hooks")))},getModel:null,checkForAbort:function(e,t){return r["default"].resolve(e(),this.promiseLabel("Check for abort")).then(function(){return t},null,this.promiseLabel("Ignore fulfillment value and continue"))},stashResolvedModel:function(e,t){e.resolvedModels=e.resolvedModels||{},e.resolvedModels[this.name]=t},becomeResolved:function(e,t){var r=this.serialize(t);return (e&&(this.stashResolvedModel(e,t),e.params=e.params||{},e.params[this.name]=r), this.factory("resolved",{context:t,name:this.name,handler:this.handler,params:r}))},shouldSupercede:function(e){if(!e)return!0;var t=e.context===this.context;return e.name!==this.name||this.hasOwnProperty("context")&&!t||this.hasOwnProperty("params")&&!i(this.params,e.params)}},e["default"]=n}),e("router/handler-info/factory",["exports","router/handler-info/resolved-handler-info","router/handler-info/unresolved-handler-info-by-object","router/handler-info/unresolved-handler-info-by-param"],function(e,t,r,n){"use strict";function i(e,t){var r=i.klasses[e],n=new r(t||{});return (n.factory=i, n)}i.klasses={resolved:t["default"],param:n["default"],object:r["default"]},e["default"]=i}),e("router/handler-info/resolved-handler-info",["exports","../handler-info","router/utils","rsvp/promise"],function(e,t,r,n){"use strict";var i=r.subclass(t["default"],{resolve:function(e,t){return (t&&t.resolvedModels&&(t.resolvedModels[this.name]=this.context), n["default"].resolve(this,this.promiseLabel("Resolve")))},getUnresolved:function(){return this.factory("param",{name:this.name,handler:this.handler,params:this.params})},isResolved:!0});e["default"]=i}),e("router/handler-info/unresolved-handler-info-by-object",["exports","../handler-info","router/utils","rsvp/promise"],function(e,t,r,n){"use strict";var i=r.subclass(t["default"],{getModel:function(e){return (this.log(e,this.name+": resolving provided model"), n["default"].resolve(this.context))},initialize:function(e){this.names=e.names||[],this.context=e.context},serialize:function(e){var t=e||this.context,n=this.names,i=this.handler,a={};if(r.isParam(t))return (a[n[0]]=t, a);if(i.serialize)return i.serialize(t,n);if(1===n.length){var o=n[0];return(/_id$/.test(o)?a[o]=t.id:a[o]=t, a)}}});e["default"]=i}),e("router/handler-info/unresolved-handler-info-by-param",["exports","../handler-info","router/utils"],function(e,t,r){"use strict";var n=r.subclass(t["default"],{initialize:function(e){this.params=e.params||{}},getModel:function(e){var t=this.params;e&&e.queryParams&&(t={},r.merge(t,this.params),t.queryParams=e.queryParams);var n=this.handler,i=r.resolveHook(n,"deserialize")||r.resolveHook(n,"model");return this.runSharedModelHook(e,i,[t])}});e["default"]=n}),e("router/router",["exports","route-recognizer","rsvp/promise","./utils","./transition-state","./transition","./transition-intent/named-transition-intent","./transition-intent/url-transition-intent","./handler-info"],function(e,t,r,n,i,a,o,s,l){"use strict";function u(e){var r=e||{};this.getHandler=r.getHandler||this.getHandler,this.updateURL=r.updateURL||this.updateURL,this.replaceURL=r.replaceURL||this.replaceURL,this.didTransition=r.didTransition||this.didTransition,this.willTransition=r.willTransition||this.willTransition,this.delegate=r.delegate||this.delegate,this.triggerEvent=r.triggerEvent||this.triggerEvent,this.log=r.log||this.log,this.recognizer=new t["default"],this.reset()}function c(e,t){var r,i=!!this.activeTransition,o=i?this.activeTransition.state:this.state,s=e.applyToState(o,this.recognizer,this.getHandler,t),l=n.getChangelist(o.queryParams,s.queryParams);return b(s.handlerInfos,o.handlerInfos)?l&&(r=this.queryParamsTransition(l,i,o,s))?r:this.activeTransition||new a.Transition(this):t?void m(this,s):(r=new a.Transition(this,e,s),this.activeTransition&&this.activeTransition.abort(),this.activeTransition=r,r.promise=r.promise.then(function(e){return v(r,e.state)},null,n.promiseLabel("Settle transition promise when transition is finalized")),i||_(this,s,r),h(this,s,l),r)}function h(e,t,r){r&&(e._changedQueryParams=r.all,n.trigger(e,t.handlerInfos,!0,["queryParamsDidChange",r.changed,r.all,r.removed]),e._changedQueryParams=null)}function m(e,t,r){var i,a,o,s=p(e.state,t);for(i=0,a=s.exited.length;a>i;i++)o=s.exited[i].handler,delete o.context,n.callHook(o,"reset",!0,r),n.callHook(o,"exit",r);var l=e.oldState=e.state;e.state=t;var u=e.currentHandlerInfos=s.unchanged.slice();try{for(i=0,a=s.reset.length;a>i;i++)o=s.reset[i].handler,n.callHook(o,"reset",!1,r);for(i=0,a=s.updatedContext.length;a>i;i++)d(u,s.updatedContext[i],!1,r);for(i=0,a=s.entered.length;a>i;i++)d(u,s.entered[i],!0,r)}catch(c){throw (e.state=l, e.currentHandlerInfos=l.handlerInfos, c)}e.state.queryParams=y(e,u,t.queryParams,r)}function d(e,t,r,i){var o=t.handler,s=t.context;if(r&&n.callHook(o,"enter",i),i&&i.isAborted)throw new a.TransitionAborted;if(o.context=s,n.callHook(o,"contextDidChange"),n.callHook(o,"setup",s,i),i&&i.isAborted)throw new a.TransitionAborted;return (e.push(t), !0)}function p(e,t){var r,n,i,a=e.handlerInfos,o=t.handlerInfos,s={updatedContext:[],exited:[],entered:[],unchanged:[]},l=!1;for(n=0,i=o.length;i>n;n++){var u=a[n],c=o[n];u&&u.handler===c.handler||(r=!0),r?(s.entered.push(c),u&&s.exited.unshift(u)):l||u.context!==c.context?(l=!0,s.updatedContext.push(c)):s.unchanged.push(u)}for(n=o.length,i=a.length;i>n;n++)s.exited.unshift(a[n]);return (s.reset=s.updatedContext.slice(), s.reset.reverse(), s)}function f(e,t,r){var i=e.urlMethod;if(i){for(var a=e.router,o=t.handlerInfos,s=o[o.length-1].name,l={},u=o.length-1;u>=0;--u){var c=o[u];n.merge(l,c.params),c.handler.inaccessibleByURL&&(i=null)}if(i){l.queryParams=e._visibleQueryParams||t.queryParams;var h=a.recognizer.generate(s,l);"replace"===i?a.replaceURL(h):a.updateURL(h)}}}function v(e,t){try{n.log(e.router,e.sequence,"Resolved all models on destination route; finalizing transition.");var i=e.router,o=t.handlerInfos;e.sequence;return (m(i,t,e), e.isAborted?(i.state.handlerInfos=i.currentHandlerInfos,r["default"].reject(a.logAbort(e))):(f(e,t,e.intent.url),e.isActive=!1,i.activeTransition=null,n.trigger(i,i.currentHandlerInfos,!0,["didTransition"]),i.didTransition&&i.didTransition(i.currentHandlerInfos),n.log(i,e.sequence,"TRANSITION COMPLETE."),o[o.length-1].handler))}catch(s){if(!(s instanceof a.TransitionAborted)){var l=e.state.handlerInfos;e.trigger(!0,"error",s,e,l[l.length-1].handler),e.abort()}throw s}}function g(e,t,r){var i=t[0]||"/",a=t[t.length-1],l={};a&&a.hasOwnProperty("queryParams")&&(l=w.call(t).queryParams);var u;if(0===t.length){n.log(e,"Updating query params");var c=e.state.handlerInfos;u=new o["default"]({name:c[c.length-1].name,contexts:[],queryParams:l})}else"/"===i.charAt(0)?(n.log(e,"Attempting URL transition to "+i),u=new s["default"]({url:i})):(n.log(e,"Attempting transition to "+i),u=new o["default"]({name:t[0],contexts:n.slice.call(t,1),queryParams:l}));return e.transitionByIntent(u,r)}function b(e,t){if(e.length!==t.length)return!1;for(var r=0,n=e.length;n>r;++r)if(e[r]!==t[r])return!1;return!0}function y(e,t,r,i){for(var a in r)r.hasOwnProperty(a)&&null===r[a]&&delete r[a];var o=[];n.trigger(e,t,!0,["finalizeQueryParamChange",r,o,i]),i&&(i._visibleQueryParams={});for(var s={},l=0,u=o.length;u>l;++l){var c=o[l];s[c.key]=c.value,i&&c.visible!==!1&&(i._visibleQueryParams[c.key]=c.value)}return s}function _(e,t,r){var i,a,o,s,l,u,c=e.state.handlerInfos,h=[],m=null;for(s=c.length,o=0;s>o;o++){if(l=c[o],u=t.handlerInfos[o],!u||l.name!==u.name){m=o;break}u.isResolved||h.push(l)}null!==m&&(i=c.slice(m,s),a=function(e){for(var t=0,r=i.length;r>t;t++)if(i[t].name===e)return!0;return!1}),n.trigger(e,c,!0,["willTransition",r]),e.willTransition&&e.willTransition(c,t.handlerInfos,r)}var w=Array.prototype.pop;u.prototype={map:function(e){this.recognizer.delegate=this.delegate,this.recognizer.map(e,function(e,t){for(var r=t.length-1,n=!0;r>=0&&n;--r){var i=t[r];e.add(t,{as:i.handler}),n="/"===i.path||""===i.path||".index"===i.handler.slice(-6)}})},hasRoute:function(e){return this.recognizer.hasRoute(e)},getHandler:function(){},queryParamsTransition:function(e,t,r,i){var o=this;if(h(this,i,e),!t&&this.activeTransition)return this.activeTransition;var s=new a.Transition(this);return (s.queryParamsOnly=!0, r.queryParams=y(this,i.handlerInfos,i.queryParams,s), s.promise=s.promise.then(function(e){return (f(s,r,!0), o.didTransition&&o.didTransition(o.currentHandlerInfos), e)},null,n.promiseLabel("Transition complete")), s)},transitionByIntent:function(e,t){try{return c.apply(this,arguments)}catch(r){return new a.Transition(this,e,null,r)}},reset:function(){this.state&&n.forEach(this.state.handlerInfos.slice().reverse(),function(e){var t=e.handler;n.callHook(t,"exit")}),this.state=new i["default"],this.currentHandlerInfos=null},activeTransition:null,handleURL:function(e){var t=n.slice.call(arguments);return("/"!==e.charAt(0)&&(t[0]="/"+e), g(this,t).method(null))},updateURL:function(){throw new Error("updateURL is not implemented")},replaceURL:function(e){this.updateURL(e)},transitionTo:function(e){return g(this,arguments)},intermediateTransitionTo:function(e){return g(this,arguments,!0)},refresh:function(e){for(var t=this.activeTransition?this.activeTransition.state:this.state,r=t.handlerInfos,i={},a=0,s=r.length;s>a;++a){var l=r[a];i[l.name]=l.params||{}}n.log(this,"Starting a refresh transition");var u=new o["default"]({name:r[r.length-1].name,pivotHandler:e||r[0].handler,contexts:[],queryParams:this._changedQueryParams||t.queryParams||{}});return this.transitionByIntent(u,!1)},replaceWith:function(e){return g(this,arguments).method("replace")},generate:function(e){for(var t=n.extractQueryParams(n.slice.call(arguments,1)),r=t[0],i=t[1],a=new o["default"]({name:e,contexts:r}),s=a.applyToState(this.state,this.recognizer,this.getHandler),l={},u=0,c=s.handlerInfos.length;c>u;++u){var h=s.handlerInfos[u],m=h.serialize();n.merge(l,m)}return (l.queryParams=i, this.recognizer.generate(e,l))},applyIntent:function(e,t){var r=new o["default"]({name:e,contexts:t}),n=this.activeTransition&&this.activeTransition.state||this.state;return r.applyToState(n,this.recognizer,this.getHandler)},isActiveIntent:function(e,t,r,a){var s,l,u=a||this.state,c=u.handlerInfos;if(!c.length)return!1;var h=c[c.length-1].name,m=this.recognizer.handlersFor(h),d=0;for(l=m.length;l>d&&(s=c[d],s.name!==e);++d);if(d===m.length)return!1;var p=new i["default"];p.handlerInfos=c.slice(0,d+1),m=m.slice(0,d+1);var f=new o["default"]({name:h,contexts:t}),v=f.applyToHandlers(p,m,this.getHandler,h,!0,!0),g=b(v.handlerInfos,p.handlerInfos);if(!r||!g)return g;var y={};n.merge(y,r);var _=u.queryParams;for(var w in _)_.hasOwnProperty(w)&&y.hasOwnProperty(w)&&(y[w]=_[w]);return g&&!n.getChangelist(y,r)},isActive:function(e){var t=n.extractQueryParams(n.slice.call(arguments,1));return this.isActiveIntent(e,t[0],t[1])},trigger:function(e){var t=n.slice.call(arguments);n.trigger(this,this.currentHandlerInfos,!1,t)},log:null},e["default"]=u}),e("router/transition-intent",["exports","./utils"],function(e,t){"use strict";function r(e){this.initialize(e),this.data=this.data||{}}r.prototype={initialize:null,applyToState:null},e["default"]=r}),e("router/transition-intent/named-transition-intent",["exports","../transition-intent","../transition-state","../handler-info/factory","../utils"],function(e,t,r,n,i){"use strict";e["default"]=i.subclass(t["default"],{name:null,pivotHandler:null,contexts:null,queryParams:null,initialize:function(e){this.name=e.name,this.pivotHandler=e.pivotHandler,this.contexts=e.contexts||[],this.queryParams=e.queryParams},applyToState:function(e,t,r,n){var a=i.extractQueryParams([this.name].concat(this.contexts)),o=a[0],s=(a[1],t.handlersFor(o[0])),l=s[s.length-1].handler;return this.applyToHandlers(e,s,r,l,n)},applyToHandlers:function(e,t,n,a,o,s){var l,u,c=new r["default"],h=this.contexts.slice(0),m=t.length;if(this.pivotHandler)for(l=0,u=t.length;u>l;++l)if(n(t[l].handler)===this.pivotHandler){m=l;break}!this.pivotHandler;for(l=t.length-1;l>=0;--l){var d=t[l],p=d.handler,f=n(p),v=e.handlerInfos[l],g=null;if(g=d.names.length>0?l>=m?this.createParamHandlerInfo(p,f,d.names,h,v):this.getHandlerInfoForDynamicSegment(p,f,d.names,h,v,a,l):this.createParamHandlerInfo(p,f,d.names,h,v),s){g=g.becomeResolved(null,g.context);var b=v&&v.context;d.names.length>0&&g.context===b&&(g.params=v&&v.params),g.context=b}var y=v;(l>=m||g.shouldSupercede(v))&&(m=Math.min(l,m),y=g),o&&!s&&(y=y.becomeResolved(null,y.context)),c.handlerInfos.unshift(y)}if(h.length>0)throw new Error("More context objects were passed than there are dynamic segments for the route: "+a);return (o||this.invalidateChildren(c.handlerInfos,m), i.merge(c.queryParams,this.queryParams||{}), c)},invalidateChildren:function(e,t){for(var r=t,n=e.length;n>r;++r){e[r];e[r]=e[r].getUnresolved()}},getHandlerInfoForDynamicSegment:function(e,t,r,a,o,s,l){var u;r.length;if(a.length>0){if(u=a[a.length-1],i.isParam(u))return this.createParamHandlerInfo(e,t,r,a,o);a.pop()}else{if(o&&o.name===e)return o;if(!this.preTransitionState)return o;var c=this.preTransitionState.handlerInfos[l];u=c&&c.context}return n["default"]("object",{name:e,handler:t,context:u,names:r})},createParamHandlerInfo:function(e,t,r,a,o){for(var s={},l=r.length;l--;){var u=o&&e===o.name&&o.params||{},c=a[a.length-1],h=r[l];if(i.isParam(c))s[h]=""+a.pop();else{if(!u.hasOwnProperty(h))throw new Error("You didn't provide enough string/numeric parameters to satisfy all of the dynamic segments for route "+e);s[h]=u[h]}}return n["default"]("param",{name:e,handler:t,params:s})}})}),e("router/transition-intent/url-transition-intent",["exports","../transition-intent","../transition-state","../handler-info/factory","../utils","./../unrecognized-url-error"],function(e,t,r,n,i,a){"use strict";e["default"]=i.subclass(t["default"],{url:null,initialize:function(e){this.url=e.url},applyToState:function(e,t,o){var s,l,u=new r["default"],c=t.recognize(this.url);if(!c)throw new a["default"](this.url);var h=!1;for(s=0,l=c.length;l>s;++s){var m=c[s],d=m.handler,p=o(d);if(p.inaccessibleByURL)throw new a["default"](this.url);var f=n["default"]("param",{name:d,handler:p,params:m.params}),v=e.handlerInfos[s];h||f.shouldSupercede(v)?(h=!0,u.handlerInfos[s]=f):u.handlerInfos[s]=v}return (i.merge(u.queryParams,c.queryParams), u)}})}),e("router/transition-state",["exports","./handler-info","./utils","rsvp/promise"],function(e,t,r,n){"use strict";function i(e){this.handlerInfos=[],this.queryParams={},this.params={}}i.prototype={handlerInfos:null,queryParams:null,params:null,promiseLabel:function(e){var t="";return (r.forEach(this.handlerInfos,function(e){""!==t&&(t+="."),t+=e.name}), r.promiseLabel("'"+t+"': "+e))},resolve:function(e,t){function i(){return n["default"].resolve(e(),u.promiseLabel("Check if should continue"))["catch"](function(e){return (c=!0, n["default"].reject(e))},u.promiseLabel("Handle abort"))}function a(e){var r=u.handlerInfos,i=t.resolveIndex>=r.length?r.length-1:t.resolveIndex;return n["default"].reject({error:e,handlerWithError:u.handlerInfos[i].handler,wasAborted:c,state:u})}function o(e){var n=u.handlerInfos[t.resolveIndex].isResolved;if(u.handlerInfos[t.resolveIndex++]=e,!n){var a=e.handler;r.callHook(a,"redirect",e.context,t)}return i().then(s,null,u.promiseLabel("Resolve handler"))}function s(){if(t.resolveIndex===u.handlerInfos.length)return{error:null,state:u};var e=u.handlerInfos[t.resolveIndex];return e.resolve(i,t).then(o,null,u.promiseLabel("Proceed"))}var l=this.params;r.forEach(this.handlerInfos,function(e){l[e.name]=e.params||{}}),t=t||{},t.resolveIndex=0;var u=this,c=!1;return n["default"].resolve(null,this.promiseLabel("Start transition")).then(s,null,this.promiseLabel("Resolve handler"))["catch"](a,this.promiseLabel("Handle error"))}},e["default"]=i}),e("router/transition",["exports","rsvp/promise","./handler-info","./utils"],function(e,t,r,n){"use strict";function i(e,r,o,s){function l(){return u.isAborted?t["default"].reject(void 0,n.promiseLabel("Transition aborted - reject")):void 0}var u=this;if(this.state=o||e.state,this.intent=r,this.router=e,this.data=this.intent&&this.intent.data||{},this.resolvedModels={},this.queryParams={},s)return (this.promise=t["default"].reject(s), void(this.error=s));if(o){this.params=o.params,this.queryParams=o.queryParams,this.handlerInfos=o.handlerInfos;var c=o.handlerInfos.length;c&&(this.targetName=o.handlerInfos[c-1].name);for(var h=0;c>h;++h){var m=o.handlerInfos[h];if(!m.isResolved)break;this.pivotHandler=m.handler}this.sequence=i.currentSequence++,this.promise=o.resolve(l,this)["catch"](function(e){return e.wasAborted||u.isAborted?t["default"].reject(a(u)):(u.trigger("error",e.error,u,e.handlerWithError),u.abort(),t["default"].reject(e.error))},n.promiseLabel("Handle Abort"))}else this.promise=t["default"].resolve(this.state),this.params={}}function a(e){return (n.log(e.router,e.sequence,"detected abort."), new o)}function o(e){this.message=e||"TransitionAborted",this.name="TransitionAborted"}i.currentSequence=0,i.prototype={targetName:null,urlMethod:"update",intent:null,params:null,pivotHandler:null,resolveIndex:0,handlerInfos:null,resolvedModels:null,isActive:!0,state:null,queryParamsOnly:!1,isTransition:!0,isExiting:function(e){for(var t=this.handlerInfos,r=0,n=t.length;n>r;++r){var i=t[r];if(i.name===e||i.handler===e)return!1}return!0},promise:null,data:null,then:function(e,t,r){return this.promise.then(e,t,r)},"catch":function(e,t){return this.promise["catch"](e,t)},"finally":function(e,t){return this.promise["finally"](e,t)},abort:function(){return this.isAborted?this:(n.log(this.router,this.sequence,this.targetName+": transition was aborted"),this.intent.preTransitionState=this.router.state,this.isAborted=!0,this.isActive=!1,this.router.activeTransition=null,this)},retry:function(){return (this.abort(), this.router.transitionByIntent(this.intent,!1))},method:function(e){return (this.urlMethod=e, this)},trigger:function(e){var t=n.slice.call(arguments);"boolean"==typeof e?t.shift():e=!1,n.trigger(this.router,this.state.handlerInfos.slice(0,this.resolveIndex+1),e,t)},followRedirects:function(){var e=this.router;return this.promise["catch"](function(r){return e.activeTransition?e.activeTransition.followRedirects():t["default"].reject(r)})},toString:function(){return"Transition (sequence "+this.sequence+")"},log:function(e){n.log(this.router,this.sequence,e)}},i.prototype.send=i.prototype.trigger,e.Transition=i,e.logAbort=a,e.TransitionAborted=o}),e("router/unrecognized-url-error",["exports","./utils"],function(e,t){"use strict";function r(e){this.message=e||"UnrecognizedURLError",this.name="UnrecognizedURLError",Error.call(this)}r.prototype=t.oCreate(Error.prototype),e["default"]=r}),e("router/utils",["exports"],function(e){"use strict";function t(e,t){for(var r in t)t.hasOwnProperty(r)&&(e[r]=t[r])}function r(e){var t,r,n=e&&e.length;return n&&n>0&&e[n-1]&&e[n-1].hasOwnProperty("queryParams")?(r=e[n-1].queryParams,t=v.call(e,0,n-1),[t,r]):[e,null]}function n(e){for(var t in e)if("number"==typeof e[t])e[t]=""+e[t];else if(g(e[t]))for(var r=0,n=e[t].length;n>r;r++)e[t][r]=""+e[t][r]}function i(e,t,r){e.log&&(3===arguments.length?e.log("Transition #"+t+": "+r):(r=t,e.log(r)))}function a(e,t){var r=arguments;return function(n){var i=v.call(r,2);return (i.push(n), t.apply(e,i))}}function o(e){return"string"==typeof e||e instanceof String||"number"==typeof e||e instanceof Number}function s(e,t){for(var r=0,n=e.length;n>r&&!1!==t(e[r]);r++);}function l(e,t,r,n){if(e.triggerEvent)return void e.triggerEvent(t,r,n);var i=n.shift();if(!t){if(r)return;throw new Error("Could not trigger event '"+i+"'. There are no active handlers")}for(var a=!1,o=t.length-1;o>=0;o--){var s=t[o],l=s.handler;if(l.events&&l.events[i]){if(l.events[i].apply(l,n)!==!0)return;a=!0}}if(!a&&!r)throw new Error("Nothing handled the event '"+i+"'.")}function u(e,r){var i,a={all:{},changed:{},removed:{}};t(a.all,r);var o=!1;n(e),n(r);for(i in e)e.hasOwnProperty(i)&&(r.hasOwnProperty(i)||(o=!0,a.removed[i]=e[i]));for(i in r)if(r.hasOwnProperty(i))if(g(e[i])&&g(r[i]))if(e[i].length!==r[i].length)a.changed[i]=r[i],o=!0;else for(var s=0,l=e[i].length;l>s;s++)e[i][s]!==r[i][s]&&(a.changed[i]=r[i],o=!0);else e[i]!==r[i]&&(a.changed[i]=r[i],o=!0);return o&&a}function c(e){return"Router: "+e}function h(e,r){function n(t){e.call(this,t||{})}return (n.prototype=b(e.prototype), t(n.prototype,r), n)}function m(e,t){if(e){var r="_"+t;return e[r]&&r||e[t]&&t}}function d(e,t,r,n){var i=m(e,t);return i&&e[i].call(e,r,n)}function p(e,t,r){var n=m(e,t);return n?0===r.length?e[n].call(e):1===r.length?e[n].call(e,r[0]):2===r.length?e[n].call(e,r[0],r[1]):e[n].apply(e,r):void 0}e.extractQueryParams=r,e.log=i,e.bind=a,e.forEach=s,e.trigger=l,e.getChangelist=u,e.promiseLabel=c,e.subclass=h;var f,v=Array.prototype.slice;f=Array.isArray?Array.isArray:function(e){return"[object Array]"===Object.prototype.toString.call(e)};var g=f;e.isArray=g;var b=Object.create||function(e){function t(){}return (t.prototype=e, new t)};e.oCreate=b,e.merge=t,e.slice=v,e.isParam=o,e.coerceQueryParamsToString=n,e.callHook=d,e.resolveHook=m,e.applyHook=p}),e("rsvp",["exports","./rsvp/promise","./rsvp/events","./rsvp/node","./rsvp/all","./rsvp/all-settled","./rsvp/race","./rsvp/hash","./rsvp/hash-settled","./rsvp/rethrow","./rsvp/defer","./rsvp/config","./rsvp/map","./rsvp/resolve","./rsvp/reject","./rsvp/filter","./rsvp/asap"],function(e,t,r,n,i,a,o,s,l,u,c,h,m,d,p,f,v){"use strict";function g(e,t){h.config.async(e,t)}function b(){h.config.on.apply(h.config,arguments)}function y(){h.config.off.apply(h.config,arguments)}h.config.async=v["default"];var _=d["default"];if("undefined"!=typeof window&&"object"==typeof window.__PROMISE_INSTRUMENTATION__){var w=window.__PROMISE_INSTRUMENTATION__;h.configure("instrument",!0);for(var x in w)w.hasOwnProperty(x)&&b(x,w[x])}e.cast=_,e.Promise=t["default"],e.EventTarget=r["default"],e.all=i["default"],e.allSettled=a["default"],e.race=o["default"],e.hash=s["default"],e.hashSettled=l["default"],e.rethrow=u["default"],e.defer=c["default"],e.denodeify=n["default"],e.configure=h.configure,e.on=b,e.off=y,e.resolve=d["default"],e.reject=p["default"],e.async=g,e.map=m["default"],e.filter=f["default"]}),e("rsvp.umd",["exports","./rsvp"],function(t,r){"use strict";var n={race:r.race,Promise:r.Promise,allSettled:r.allSettled,hash:r.hash,hashSettled:r.hashSettled,denodeify:r.denodeify,on:r.on,off:r.off,map:r.map,filter:r.filter,resolve:r.resolve,reject:r.reject,all:r.all,rethrow:r.rethrow,defer:r.defer,EventTarget:r.EventTarget,configure:r.configure,async:r.async};"function"==typeof e&&e.amd?e(function(){return n}):"undefined"!=typeof module&&module.exports&&(module.exports=n)}),e("rsvp/-internal",["exports","./utils","./instrument","./config"],function(e,t,r,n){"use strict";function i(){return new TypeError("A promises callback cannot return that same promise.")}function a(){}function o(e){try{return e.then}catch(t){return (k.error=t, k)}}function s(e,t,r,n){try{e.call(t,r,n)}catch(i){return i}}function l(e,t,r){n.config.async(function(e){var n=!1,i=s(r,t,function(r){n||(n=!0,t!==r?h(e,r):d(e,r))},function(t){n||(n=!0,p(e,t))},"Settle: "+(e._label||" unknown promise"));!n&&i&&(n=!0,p(e,i))},e)}function u(e,t){t._state===x?d(e,t._result):e._state===C?p(e,t._result):f(t,void 0,function(r){t!==r?h(e,r):d(e,r)},function(t){p(e,t)})}function c(e,r){if(r.constructor===e.constructor)u(e,r);else{var n=o(r);n===k?p(e,k.error):void 0===n?d(e,r):t.isFunction(n)?l(e,r,n):d(e,r)}}function h(e,r){e===r?d(e,r):t.objectOrFunction(r)?c(e,r):d(e,r)}function m(e){e._onerror&&e._onerror(e._result),v(e)}function d(e,t){e._state===w&&(e._result=t,e._state=x,0===e._subscribers.length?n.config.instrument&&r["default"]("fulfilled",e):n.config.async(v,e))}function p(e,t){e._state===w&&(e._state=C,e._result=t,n.config.async(m,e))}function f(e,t,r,i){var a=e._subscribers,o=a.length;e._onerror=null,a[o]=t,a[o+x]=r,a[o+C]=i,0===o&&e._state&&n.config.async(v,e)}function v(e){var t=e._subscribers,i=e._state;if(n.config.instrument&&r["default"](i===x?"fulfilled":"rejected",e),0!==t.length){for(var a,o,s=e._result,l=0;le;e+=2){var t=v[e],r=v[e+1];t(r),v[e]=void 0,v[e+1]=void 0}h=0}function u(){try{var e=r("vertx");e.runOnLoop||e.runOnContext;return i()}catch(t){return s()}}e["default"]=t;var c,h=0,m="undefined"!=typeof window?window:void 0,d=m||{},p=d.MutationObserver||d.WebKitMutationObserver,f="undefined"!=typeof Uint8ClampedArray&&"undefined"!=typeof importScripts&&"undefined"!=typeof MessageChannel,v=new Array(1e3);c="undefined"!=typeof process&&"[object process]"==={}.toString.call(process)?n():p?a():f?o():void 0===m&&"function"==typeof r?u():s()}),e("rsvp/config",["exports","./events"],function(e,t){"use strict";function r(e,t){return"onerror"===e?void n.on("error",t):2!==arguments.length?n[e]:void(n[e]=t)}var n={instrument:!1};t["default"].mixin(n),e.config=n,e.configure=r}),e("rsvp/defer",["exports","./promise"],function(e,t){"use strict";function r(e){var r={};return (r.promise=new t["default"](function(e,t){r.resolve=e,r.reject=t},e), r)}e["default"]=r}),e("rsvp/enumerator",["exports","./utils","./-internal"],function(e,t,r){"use strict";function n(e,t,n){return e===r.FULFILLED?{state:"fulfilled",value:n}:{state:"rejected",reason:n}}function i(e,t,n,i){this._instanceConstructor=e,this.promise=new e(r.noop,i),this._abortOnReject=n,this._validateInput(t)?(this._input=t,this.length=t.length,this._remaining=t.length,this._init(),0===this.length?r.fulfill(this.promise,this._result):(this.length=this.length||0,this._enumerate(),0===this._remaining&&r.fulfill(this.promise,this._result))):r.reject(this.promise,this._validationError())}e.makeSettledResult=n,i.prototype._validateInput=function(e){return t.isArray(e)},i.prototype._validationError=function(){return new Error("Array Methods must be provided an Array")},i.prototype._init=function(){this._result=new Array(this.length)},e["default"]=i,i.prototype._enumerate=function(){for(var e=this.length,t=this.promise,n=this._input,i=0;t._state===r.PENDING&&e>i;i++)this._eachEntry(n[i],i)},i.prototype._eachEntry=function(e,n){var i=this._instanceConstructor;t.isMaybeThenable(e)?e.constructor===i&&e._state!==r.PENDING?(e._onerror=null,this._settledAt(e._state,n,e._result)):this._willSettleAt(i.resolve(e),n):(this._remaining--,this._result[n]=this._makeResult(r.FULFILLED,n,e))},i.prototype._settledAt=function(e,t,n){var i=this.promise;i._state===r.PENDING&&(this._remaining--,this._abortOnReject&&e===r.REJECTED?r.reject(i,n):this._result[t]=this._makeResult(e,t,n)),0===this._remaining&&r.fulfill(i,this._result)},i.prototype._makeResult=function(e,t,r){return r},i.prototype._willSettleAt=function(e,t){var n=this;r.subscribe(e,void 0,function(e){n._settledAt(r.FULFILLED,t,e)},function(e){n._settledAt(r.REJECTED,t,e)})}}),e("rsvp/events",["exports"],function(e){"use strict";function t(e,t){for(var r=0,n=e.length;n>r;r++)if(e[r]===t)return r;return-1}function r(e){var t=e._promiseCallbacks;return (t||(t=e._promiseCallbacks={}), t)}e["default"]={mixin:function(e){return (e.on=this.on, e.off=this.off, e.trigger=this.trigger, e._promiseCallbacks=void 0, e)},on:function(e,n){var i,a=r(this);i=a[e],i||(i=a[e]=[]),-1===t(i,n)&&i.push(n)},off:function(e,n){var i,a,o=r(this);return n?(i=o[e],a=t(i,n),void(-1!==a&&i.splice(a,1))):void(o[e]=[])},trigger:function(e,t){var n,i,a=r(this);if(n=a[e])for(var o=0;os;s++)o[s]=n(e[s]);return t["default"].all(o,i).then(function(t){for(var r=new Array(a),n=0,i=0;a>i;i++)t[i]&&(r[n]=e[i],n++);return (r.length=n, r)})})}e["default"]=n}),e("rsvp/hash-settled",["exports","./promise","./enumerator","./promise-hash","./utils"],function(e,t,r,n,i){"use strict";function a(e,t,r){this._superConstructor(e,t,!1,r)}function o(e,r){return new a(t["default"],e,r).promise}e["default"]=o,a.prototype=i.o_create(n["default"].prototype),a.prototype._superConstructor=r["default"],a.prototype._makeResult=r.makeSettledResult,a.prototype._validationError=function(){return new Error("hashSettled must be called with an object")}}),e("rsvp/hash",["exports","./promise","./promise-hash"],function(e,t,r){"use strict";function n(e,n){return new r["default"](t["default"],e,n).promise}e["default"]=n}),e("rsvp/instrument",["exports","./config","./utils"],function(e,t,r){"use strict";function n(){setTimeout(function(){for(var e,r=0;rs;s++)o[s]=n(e[s]);return t["default"].all(o,i)})}e["default"]=n}),e("rsvp/node",["exports","./promise","./-internal","./utils"],function(e,t,r,n){"use strict";function i(){this.value=void 0}function a(e){try{return e.then}catch(t){return (p.value=t, p)}}function o(e,t,r){try{e.apply(t,r)}catch(n){return (p.value=n, p)}}function s(e,t){for(var r,n,i={},a=e.length,o=new Array(a),s=0;a>s;s++)o[s]=e[s];for(n=0;nn;n++)r[n-1]=e[n];return r}function u(e,t){return{then:function(r,n){return e.call(t,r,n)}}}function c(e,i){var a=function(){for(var a,o=this,c=arguments.length,p=new Array(c+1),v=!1,g=0;c>g;++g){if(a=arguments[g],!v){if(v=d(a),v===f){var b=new t["default"](r.noop);return (r.reject(b,f.value), b)}v&&v!==!0&&(a=u(v,a))}p[g]=a}var y=new t["default"](r.noop);return (p[c]=function(e,t){e?r.reject(y,e):void 0===i?r.resolve(y,t):i===!0?r.resolve(y,l(arguments)):n.isArray(i)?r.resolve(y,s(arguments,i)):r.resolve(y,t)}, v?m(y,p,e,o):h(y,p,e,o))};return (a.__proto__=e, a)}function h(e,t,n,i){var a=o(n,i,t);return (a===p&&r.reject(e,a.value), e)}function m(e,n,i,a){return t["default"].all(n).then(function(t){var n=o(i,a,t);return (n===p&&r.reject(e,n.value), e)})}function d(e){return e&&"object"==typeof e?e.constructor===t["default"]?!0:a(e):!1}e["default"]=c;var p=new i,f=new i}),e("rsvp/promise-hash",["exports","./enumerator","./-internal","./utils"],function(e,t,r,n){"use strict";function i(e,t,r){this._superConstructor(e,t,!0,r)}e["default"]=i,i.prototype=n.o_create(t["default"].prototype),i.prototype._superConstructor=t["default"],i.prototype._init=function(){this._result={}},i.prototype._validateInput=function(e){return e&&"object"==typeof e},i.prototype._validationError=function(){return new Error("Promise.hash must be called with an object")},i.prototype._enumerate=function(){var e=this.promise,t=this._input,n=[];for(var i in t)e._state===r.PENDING&&t.hasOwnProperty(i)&&n.push({position:i,entry:t[i]});var a=n.length;this._remaining=a;for(var o,s=0;e._state===r.PENDING&&a>s;s++)o=n[s],this._eachEntry(o.entry,o.position)}}),e("rsvp/promise",["exports","./config","./instrument","./utils","./-internal","./promise/all","./promise/race","./promise/resolve","./promise/reject"],function(e,t,r,n,i,a,o,s,l){"use strict";function u(){throw new TypeError("You must pass a resolver function as the first argument to the promise constructor")}function c(){throw new TypeError("Failed to construct 'Promise': Please use the 'new' operator, this object constructor cannot be called as a function.")}function h(e,a){this._id=d++,this._label=a,this._state=void 0,this._result=void 0,this._subscribers=[],t.config.instrument&&r["default"]("created",this),i.noop!==e&&(n.isFunction(e)||u(),this instanceof h||c(),i.initializePromise(this,e))}var m="rsvp_"+n.now()+"-",d=0;e["default"]=h,h.cast=s["default"],h.all=a["default"],h.race=o["default"],h.resolve=s["default"],h.reject=l["default"],h.prototype={constructor:h,_guidKey:m,_onerror:function(e){t.config.trigger("error",e)},then:function(e,n,a){var o=this,s=o._state;if(s===i.FULFILLED&&!e||s===i.REJECTED&&!n)return (t.config.instrument&&r["default"]("chained",this,this), this);o._onerror=null;var l=new this.constructor(i.noop,a),u=o._result;if(t.config.instrument&&r["default"]("chained",o,l),s){var c=arguments[s-1];t.config.async(function(){i.invokeCallback(s,l,c,u)})}else i.subscribe(o,l,e,n);return l},"catch":function(e,t){return this.then(null,e,t)},"finally":function(e,t){var r=this.constructor;return this.then(function(t){return r.resolve(e()).then(function(){return t})},function(t){return r.resolve(e()).then(function(){throw t})},t)}}}),e("rsvp/promise/all",["exports","../enumerator"],function(e,t){"use strict";function r(e,r){return new t["default"](this,e,!0,r).promise}e["default"]=r}),e("rsvp/promise/race",["exports","../utils","../-internal"],function(e,t,r){"use strict";function n(e,n){function i(e){r.resolve(s,e)}function a(e){r.reject(s,e)}var o=this,s=new o(r.noop,n);if(!t.isArray(e))return (r.reject(s,new TypeError("You must pass an array to race.")), s);for(var l=e.length,u=0;s._state===r.PENDING&&l>u;u++)r.subscribe(o.resolve(e[u]),void 0,i,a);return s}e["default"]=n}),e("rsvp/promise/reject",["exports","../-internal"],function(e,t){"use strict";function r(e,r){var n=this,i=new n(t.noop,r);return (t.reject(i,e), i)}e["default"]=r}),e("rsvp/promise/resolve",["exports","../-internal"],function(e,t){"use strict";function r(e,r){var n=this;if(e&&"object"==typeof e&&e.constructor===n)return e;var i=new n(t.noop,r);return (t.resolve(i,e), i)}e["default"]=r}),e("rsvp/race",["exports","./promise"],function(e,t){"use strict";function r(e,r){return t["default"].race(e,r)}e["default"]=r}),e("rsvp/reject",["exports","./promise"],function(e,t){"use strict";function r(e,r){return t["default"].reject(e,r)}e["default"]=r}),e("rsvp/resolve",["exports","./promise"],function(e,t){"use strict";function r(e,r){return t["default"].resolve(e,r)}e["default"]=r}),e("rsvp/rethrow",["exports"],function(e){"use strict";function t(e){throw (setTimeout(function(){throw e}), e)}e["default"]=t}),e("rsvp/utils",["exports"],function(e){"use strict";function t(e){return"function"==typeof e||"object"==typeof e&&null!==e}function r(e){return"function"==typeof e}function n(e){return"object"==typeof e&&null!==e}function i(){}e.objectOrFunction=t,e.isFunction=r,e.isMaybeThenable=n;var a;a=Array.isArray?Array.isArray:function(e){return"[object Array]"===Object.prototype.toString.call(e)};var o=a;e.isArray=o;var s=Date.now||function(){return(new Date).getTime()};e.now=s;var l=Object.create||function(e){if(arguments.length>1)throw new Error("Second argument not supported");if("object"!=typeof e)throw new TypeError("Argument must be an object");return (i.prototype=e, new i)};e.o_create=l}),t("ember")}(); +//# sourceMappingURL=ember.min.map \ No newline at end of file diff --git a/test/vendor/es6-promise.auto.js b/test/vendor/es6-promise.auto.js new file mode 100644 index 0000000..632b869 --- /dev/null +++ b/test/vendor/es6-promise.auto.js @@ -0,0 +1,1159 @@ +/*! + * @overview es6-promise - a tiny implementation of Promises/A+. + * @copyright Copyright (c) 2014 Yehuda Katz, Tom Dale, Stefan Penner and contributors (Conversion to ES6 API by Jake Archibald) + * @license Licensed under MIT license + * See https://raw.githubusercontent.com/stefanpenner/es6-promise/master/LICENSE + * @version 4.0.5 + */ + +(function (global, factory) { + typeof exports === 'object' && typeof module !== 'undefined' ? module.exports = factory() : + typeof define === 'function' && define.amd ? define(factory) : + (global.ES6Promise = factory()); +}(this, (function () { 'use strict'; + +function objectOrFunction(x) { + return typeof x === 'function' || typeof x === 'object' && x !== null; +} + +function isFunction(x) { + return typeof x === 'function'; +} + +var _isArray = undefined; +if (!Array.isArray) { + _isArray = function (x) { + return Object.prototype.toString.call(x) === '[object Array]'; + }; +} else { + _isArray = Array.isArray; +} + +var isArray = _isArray; + +var len = 0; +var vertxNext = undefined; +var customSchedulerFn = undefined; + +var asap = function asap(callback, arg) { + queue[len] = callback; + queue[len + 1] = arg; + len += 2; + if (len === 2) { + // If len is 2, that means that we need to schedule an async flush. + // If additional callbacks are queued before the queue is flushed, they + // will be processed by this flush that we are scheduling. + if (customSchedulerFn) { + customSchedulerFn(flush); + } else { + scheduleFlush(); + } + } +}; + +function setScheduler(scheduleFn) { + customSchedulerFn = scheduleFn; +} + +function setAsap(asapFn) { + asap = asapFn; +} + +var browserWindow = typeof window !== 'undefined' ? window : undefined; +var browserGlobal = browserWindow || {}; +var BrowserMutationObserver = browserGlobal.MutationObserver || browserGlobal.WebKitMutationObserver; +var isNode = typeof self === 'undefined' && typeof process !== 'undefined' && ({}).toString.call(process) === '[object process]'; + +// test for web worker but not in IE10 +var isWorker = typeof Uint8ClampedArray !== 'undefined' && typeof importScripts !== 'undefined' && typeof MessageChannel !== 'undefined'; + +// node +function useNextTick() { + // node version 0.10.x displays a deprecation warning when nextTick is used recursively + // see https://github.com/cujojs/when/issues/410 for details + return function () { + return process.nextTick(flush); + }; +} + +// vertx +function useVertxTimer() { + if (typeof vertxNext !== 'undefined') { + return function () { + vertxNext(flush); + }; + } + + return useSetTimeout(); +} + +function useMutationObserver() { + var iterations = 0; + var observer = new BrowserMutationObserver(flush); + var node = document.createTextNode(''); + observer.observe(node, { characterData: true }); + + return function () { + node.data = iterations = ++iterations % 2; + }; +} + +// web worker +function useMessageChannel() { + var channel = new MessageChannel(); + channel.port1.onmessage = flush; + return function () { + return channel.port2.postMessage(0); + }; +} + +function useSetTimeout() { + // Store setTimeout reference so es6-promise will be unaffected by + // other code modifying setTimeout (like sinon.useFakeTimers()) + var globalSetTimeout = setTimeout; + return function () { + return globalSetTimeout(flush, 1); + }; +} + +var queue = new Array(1000); +function flush() { + for (var i = 0; i < len; i += 2) { + var callback = queue[i]; + var arg = queue[i + 1]; + + callback(arg); + + queue[i] = undefined; + queue[i + 1] = undefined; + } + + len = 0; +} + +function attemptVertx() { + try { + var r = require; + var vertx = r('vertx'); + vertxNext = vertx.runOnLoop || vertx.runOnContext; + return useVertxTimer(); + } catch (e) { + return useSetTimeout(); + } +} + +var scheduleFlush = undefined; +// Decide what async method to use to triggering processing of queued callbacks: +if (isNode) { + scheduleFlush = useNextTick(); +} else if (BrowserMutationObserver) { + scheduleFlush = useMutationObserver(); +} else if (isWorker) { + scheduleFlush = useMessageChannel(); +} else if (browserWindow === undefined && typeof require === 'function') { + scheduleFlush = attemptVertx(); +} else { + scheduleFlush = useSetTimeout(); +} + +function then(onFulfillment, onRejection) { + var _arguments = arguments; + + var parent = this; + + var child = new this.constructor(noop); + + if (child[PROMISE_ID] === undefined) { + makePromise(child); + } + + var _state = parent._state; + + if (_state) { + (function () { + var callback = _arguments[_state - 1]; + asap(function () { + return invokeCallback(_state, child, callback, parent._result); + }); + })(); + } else { + subscribe(parent, child, onFulfillment, onRejection); + } + + return child; +} + +/** + `Promise.resolve` returns a promise that will become resolved with the + passed `value`. It is shorthand for the following: + + ```javascript + let promise = new Promise(function(resolve, reject){ + resolve(1); + }); + + promise.then(function(value){ + // value === 1 + }); + ``` + + Instead of writing the above, your code now simply becomes the following: + + ```javascript + let promise = Promise.resolve(1); + + promise.then(function(value){ + // value === 1 + }); + ``` + + @method resolve + @static + @param {Any} value value that the returned promise will be resolved with + Useful for tooling. + @return {Promise} a promise that will become fulfilled with the given + `value` +*/ +function resolve(object) { + /*jshint validthis:true */ + var Constructor = this; + + if (object && typeof object === 'object' && object.constructor === Constructor) { + return object; + } + + var promise = new Constructor(noop); + _resolve(promise, object); + return promise; +} + +var PROMISE_ID = Math.random().toString(36).substring(16); + +function noop() {} + +var PENDING = void 0; +var FULFILLED = 1; +var REJECTED = 2; + +var GET_THEN_ERROR = new ErrorObject(); + +function selfFulfillment() { + return new TypeError("You cannot resolve a promise with itself"); +} + +function cannotReturnOwn() { + return new TypeError('A promises callback cannot return that same promise.'); +} + +function getThen(promise) { + try { + return promise.then; + } catch (error) { + GET_THEN_ERROR.error = error; + return GET_THEN_ERROR; + } +} + +function tryThen(then, value, fulfillmentHandler, rejectionHandler) { + try { + then.call(value, fulfillmentHandler, rejectionHandler); + } catch (e) { + return e; + } +} + +function handleForeignThenable(promise, thenable, then) { + asap(function (promise) { + var sealed = false; + var error = tryThen(then, thenable, function (value) { + if (sealed) { + return; + } + sealed = true; + if (thenable !== value) { + _resolve(promise, value); + } else { + fulfill(promise, value); + } + }, function (reason) { + if (sealed) { + return; + } + sealed = true; + + _reject(promise, reason); + }, 'Settle: ' + (promise._label || ' unknown promise')); + + if (!sealed && error) { + sealed = true; + _reject(promise, error); + } + }, promise); +} + +function handleOwnThenable(promise, thenable) { + if (thenable._state === FULFILLED) { + fulfill(promise, thenable._result); + } else if (thenable._state === REJECTED) { + _reject(promise, thenable._result); + } else { + subscribe(thenable, undefined, function (value) { + return _resolve(promise, value); + }, function (reason) { + return _reject(promise, reason); + }); + } +} + +function handleMaybeThenable(promise, maybeThenable, then$$) { + if (maybeThenable.constructor === promise.constructor && then$$ === then && maybeThenable.constructor.resolve === resolve) { + handleOwnThenable(promise, maybeThenable); + } else { + if (then$$ === GET_THEN_ERROR) { + _reject(promise, GET_THEN_ERROR.error); + } else if (then$$ === undefined) { + fulfill(promise, maybeThenable); + } else if (isFunction(then$$)) { + handleForeignThenable(promise, maybeThenable, then$$); + } else { + fulfill(promise, maybeThenable); + } + } +} + +function _resolve(promise, value) { + if (promise === value) { + _reject(promise, selfFulfillment()); + } else if (objectOrFunction(value)) { + handleMaybeThenable(promise, value, getThen(value)); + } else { + fulfill(promise, value); + } +} + +function publishRejection(promise) { + if (promise._onerror) { + promise._onerror(promise._result); + } + + publish(promise); +} + +function fulfill(promise, value) { + if (promise._state !== PENDING) { + return; + } + + promise._result = value; + promise._state = FULFILLED; + + if (promise._subscribers.length !== 0) { + asap(publish, promise); + } +} + +function _reject(promise, reason) { + if (promise._state !== PENDING) { + return; + } + promise._state = REJECTED; + promise._result = reason; + + asap(publishRejection, promise); +} + +function subscribe(parent, child, onFulfillment, onRejection) { + var _subscribers = parent._subscribers; + var length = _subscribers.length; + + parent._onerror = null; + + _subscribers[length] = child; + _subscribers[length + FULFILLED] = onFulfillment; + _subscribers[length + REJECTED] = onRejection; + + if (length === 0 && parent._state) { + asap(publish, parent); + } +} + +function publish(promise) { + var subscribers = promise._subscribers; + var settled = promise._state; + + if (subscribers.length === 0) { + return; + } + + var child = undefined, + callback = undefined, + detail = promise._result; + + for (var i = 0; i < subscribers.length; i += 3) { + child = subscribers[i]; + callback = subscribers[i + settled]; + + if (child) { + invokeCallback(settled, child, callback, detail); + } else { + callback(detail); + } + } + + promise._subscribers.length = 0; +} + +function ErrorObject() { + this.error = null; +} + +var TRY_CATCH_ERROR = new ErrorObject(); + +function tryCatch(callback, detail) { + try { + return callback(detail); + } catch (e) { + TRY_CATCH_ERROR.error = e; + return TRY_CATCH_ERROR; + } +} + +function invokeCallback(settled, promise, callback, detail) { + var hasCallback = isFunction(callback), + value = undefined, + error = undefined, + succeeded = undefined, + failed = undefined; + + if (hasCallback) { + value = tryCatch(callback, detail); + + if (value === TRY_CATCH_ERROR) { + failed = true; + error = value.error; + value = null; + } else { + succeeded = true; + } + + if (promise === value) { + _reject(promise, cannotReturnOwn()); + return; + } + } else { + value = detail; + succeeded = true; + } + + if (promise._state !== PENDING) { + // noop + } else if (hasCallback && succeeded) { + _resolve(promise, value); + } else if (failed) { + _reject(promise, error); + } else if (settled === FULFILLED) { + fulfill(promise, value); + } else if (settled === REJECTED) { + _reject(promise, value); + } +} + +function initializePromise(promise, resolver) { + try { + resolver(function resolvePromise(value) { + _resolve(promise, value); + }, function rejectPromise(reason) { + _reject(promise, reason); + }); + } catch (e) { + _reject(promise, e); + } +} + +var id = 0; +function nextId() { + return id++; +} + +function makePromise(promise) { + promise[PROMISE_ID] = id++; + promise._state = undefined; + promise._result = undefined; + promise._subscribers = []; +} + +function Enumerator(Constructor, input) { + this._instanceConstructor = Constructor; + this.promise = new Constructor(noop); + + if (!this.promise[PROMISE_ID]) { + makePromise(this.promise); + } + + if (isArray(input)) { + this._input = input; + this.length = input.length; + this._remaining = input.length; + + this._result = new Array(this.length); + + if (this.length === 0) { + fulfill(this.promise, this._result); + } else { + this.length = this.length || 0; + this._enumerate(); + if (this._remaining === 0) { + fulfill(this.promise, this._result); + } + } + } else { + _reject(this.promise, validationError()); + } +} + +function validationError() { + return new Error('Array Methods must be provided an Array'); +}; + +Enumerator.prototype._enumerate = function () { + var length = this.length; + var _input = this._input; + + for (var i = 0; this._state === PENDING && i < length; i++) { + this._eachEntry(_input[i], i); + } +}; + +Enumerator.prototype._eachEntry = function (entry, i) { + var c = this._instanceConstructor; + var resolve$$ = c.resolve; + + if (resolve$$ === resolve) { + var _then = getThen(entry); + + if (_then === then && entry._state !== PENDING) { + this._settledAt(entry._state, i, entry._result); + } else if (typeof _then !== 'function') { + this._remaining--; + this._result[i] = entry; + } else if (c === Promise) { + var promise = new c(noop); + handleMaybeThenable(promise, entry, _then); + this._willSettleAt(promise, i); + } else { + this._willSettleAt(new c(function (resolve$$) { + return resolve$$(entry); + }), i); + } + } else { + this._willSettleAt(resolve$$(entry), i); + } +}; + +Enumerator.prototype._settledAt = function (state, i, value) { + var promise = this.promise; + + if (promise._state === PENDING) { + this._remaining--; + + if (state === REJECTED) { + _reject(promise, value); + } else { + this._result[i] = value; + } + } + + if (this._remaining === 0) { + fulfill(promise, this._result); + } +}; + +Enumerator.prototype._willSettleAt = function (promise, i) { + var enumerator = this; + + subscribe(promise, undefined, function (value) { + return enumerator._settledAt(FULFILLED, i, value); + }, function (reason) { + return enumerator._settledAt(REJECTED, i, reason); + }); +}; + +/** + `Promise.all` accepts an array of promises, and returns a new promise which + is fulfilled with an array of fulfillment values for the passed promises, or + rejected with the reason of the first passed promise to be rejected. It casts all + elements of the passed iterable to promises as it runs this algorithm. + + Example: + + ```javascript + let promise1 = resolve(1); + let promise2 = resolve(2); + let promise3 = resolve(3); + let promises = [ promise1, promise2, promise3 ]; + + Promise.all(promises).then(function(array){ + // The array here would be [ 1, 2, 3 ]; + }); + ``` + + If any of the `promises` given to `all` are rejected, the first promise + that is rejected will be given as an argument to the returned promises's + rejection handler. For example: + + Example: + + ```javascript + let promise1 = resolve(1); + let promise2 = reject(new Error("2")); + let promise3 = reject(new Error("3")); + let promises = [ promise1, promise2, promise3 ]; + + Promise.all(promises).then(function(array){ + // Code here never runs because there are rejected promises! + }, function(error) { + // error.message === "2" + }); + ``` + + @method all + @static + @param {Array} entries array of promises + @param {String} label optional string for labeling the promise. + Useful for tooling. + @return {Promise} promise that is fulfilled when all `promises` have been + fulfilled, or rejected if any of them become rejected. + @static +*/ +function all(entries) { + return new Enumerator(this, entries).promise; +} + +/** + `Promise.race` returns a new promise which is settled in the same way as the + first passed promise to settle. + + Example: + + ```javascript + let promise1 = new Promise(function(resolve, reject){ + setTimeout(function(){ + resolve('promise 1'); + }, 200); + }); + + let promise2 = new Promise(function(resolve, reject){ + setTimeout(function(){ + resolve('promise 2'); + }, 100); + }); + + Promise.race([promise1, promise2]).then(function(result){ + // result === 'promise 2' because it was resolved before promise1 + // was resolved. + }); + ``` + + `Promise.race` is deterministic in that only the state of the first + settled promise matters. For example, even if other promises given to the + `promises` array argument are resolved, but the first settled promise has + become rejected before the other promises became fulfilled, the returned + promise will become rejected: + + ```javascript + let promise1 = new Promise(function(resolve, reject){ + setTimeout(function(){ + resolve('promise 1'); + }, 200); + }); + + let promise2 = new Promise(function(resolve, reject){ + setTimeout(function(){ + reject(new Error('promise 2')); + }, 100); + }); + + Promise.race([promise1, promise2]).then(function(result){ + // Code here never runs + }, function(reason){ + // reason.message === 'promise 2' because promise 2 became rejected before + // promise 1 became fulfilled + }); + ``` + + An example real-world use case is implementing timeouts: + + ```javascript + Promise.race([ajax('foo.json'), timeout(5000)]) + ``` + + @method race + @static + @param {Array} promises array of promises to observe + Useful for tooling. + @return {Promise} a promise which settles in the same way as the first passed + promise to settle. +*/ +function race(entries) { + /*jshint validthis:true */ + var Constructor = this; + + if (!isArray(entries)) { + return new Constructor(function (_, reject) { + return reject(new TypeError('You must pass an array to race.')); + }); + } else { + return new Constructor(function (resolve, reject) { + var length = entries.length; + for (var i = 0; i < length; i++) { + Constructor.resolve(entries[i]).then(resolve, reject); + } + }); + } +} + +/** + `Promise.reject` returns a promise rejected with the passed `reason`. + It is shorthand for the following: + + ```javascript + let promise = new Promise(function(resolve, reject){ + reject(new Error('WHOOPS')); + }); + + promise.then(function(value){ + // Code here doesn't run because the promise is rejected! + }, function(reason){ + // reason.message === 'WHOOPS' + }); + ``` + + Instead of writing the above, your code now simply becomes the following: + + ```javascript + let promise = Promise.reject(new Error('WHOOPS')); + + promise.then(function(value){ + // Code here doesn't run because the promise is rejected! + }, function(reason){ + // reason.message === 'WHOOPS' + }); + ``` + + @method reject + @static + @param {Any} reason value that the returned promise will be rejected with. + Useful for tooling. + @return {Promise} a promise rejected with the given `reason`. +*/ +function reject(reason) { + /*jshint validthis:true */ + var Constructor = this; + var promise = new Constructor(noop); + _reject(promise, reason); + return promise; +} + +function needsResolver() { + throw new TypeError('You must pass a resolver function as the first argument to the promise constructor'); +} + +function needsNew() { + throw new TypeError("Failed to construct 'Promise': Please use the 'new' operator, this object constructor cannot be called as a function."); +} + +/** + Promise objects represent the eventual result of an asynchronous operation. The + primary way of interacting with a promise is through its `then` method, which + registers callbacks to receive either a promise's eventual value or the reason + why the promise cannot be fulfilled. + + Terminology + ----------- + + - `promise` is an object or function with a `then` method whose behavior conforms to this specification. + - `thenable` is an object or function that defines a `then` method. + - `value` is any legal JavaScript value (including undefined, a thenable, or a promise). + - `exception` is a value that is thrown using the throw statement. + - `reason` is a value that indicates why a promise was rejected. + - `settled` the final resting state of a promise, fulfilled or rejected. + + A promise can be in one of three states: pending, fulfilled, or rejected. + + Promises that are fulfilled have a fulfillment value and are in the fulfilled + state. Promises that are rejected have a rejection reason and are in the + rejected state. A fulfillment value is never a thenable. + + Promises can also be said to *resolve* a value. If this value is also a + promise, then the original promise's settled state will match the value's + settled state. So a promise that *resolves* a promise that rejects will + itself reject, and a promise that *resolves* a promise that fulfills will + itself fulfill. + + + Basic Usage: + ------------ + + ```js + let promise = new Promise(function(resolve, reject) { + // on success + resolve(value); + + // on failure + reject(reason); + }); + + promise.then(function(value) { + // on fulfillment + }, function(reason) { + // on rejection + }); + ``` + + Advanced Usage: + --------------- + + Promises shine when abstracting away asynchronous interactions such as + `XMLHttpRequest`s. + + ```js + function getJSON(url) { + return new Promise(function(resolve, reject){ + let xhr = new XMLHttpRequest(); + + xhr.open('GET', url); + xhr.onreadystatechange = handler; + xhr.responseType = 'json'; + xhr.setRequestHeader('Accept', 'application/json'); + xhr.send(); + + function handler() { + if (this.readyState === this.DONE) { + if (this.status === 200) { + resolve(this.response); + } else { + reject(new Error('getJSON: `' + url + '` failed with status: [' + this.status + ']')); + } + } + }; + }); + } + + getJSON('/posts.json').then(function(json) { + // on fulfillment + }, function(reason) { + // on rejection + }); + ``` + + Unlike callbacks, promises are great composable primitives. + + ```js + Promise.all([ + getJSON('/posts'), + getJSON('/comments') + ]).then(function(values){ + values[0] // => postsJSON + values[1] // => commentsJSON + + return values; + }); + ``` + + @class Promise + @param {function} resolver + Useful for tooling. + @constructor +*/ +function Promise(resolver) { + this[PROMISE_ID] = nextId(); + this._result = this._state = undefined; + this._subscribers = []; + + if (noop !== resolver) { + typeof resolver !== 'function' && needsResolver(); + this instanceof Promise ? initializePromise(this, resolver) : needsNew(); + } +} + +Promise.all = all; +Promise.race = race; +Promise.resolve = resolve; +Promise.reject = reject; +Promise._setScheduler = setScheduler; +Promise._setAsap = setAsap; +Promise._asap = asap; + +Promise.prototype = { + constructor: Promise, + + /** + The primary way of interacting with a promise is through its `then` method, + which registers callbacks to receive either a promise's eventual value or the + reason why the promise cannot be fulfilled. + + ```js + findUser().then(function(user){ + // user is available + }, function(reason){ + // user is unavailable, and you are given the reason why + }); + ``` + + Chaining + -------- + + The return value of `then` is itself a promise. This second, 'downstream' + promise is resolved with the return value of the first promise's fulfillment + or rejection handler, or rejected if the handler throws an exception. + + ```js + findUser().then(function (user) { + return user.name; + }, function (reason) { + return 'default name'; + }).then(function (userName) { + // If `findUser` fulfilled, `userName` will be the user's name, otherwise it + // will be `'default name'` + }); + + findUser().then(function (user) { + throw new Error('Found user, but still unhappy'); + }, function (reason) { + throw new Error('`findUser` rejected and we're unhappy'); + }).then(function (value) { + // never reached + }, function (reason) { + // if `findUser` fulfilled, `reason` will be 'Found user, but still unhappy'. + // If `findUser` rejected, `reason` will be '`findUser` rejected and we're unhappy'. + }); + ``` + If the downstream promise does not specify a rejection handler, rejection reasons will be propagated further downstream. + + ```js + findUser().then(function (user) { + throw new PedagogicalException('Upstream error'); + }).then(function (value) { + // never reached + }).then(function (value) { + // never reached + }, function (reason) { + // The `PedgagocialException` is propagated all the way down to here + }); + ``` + + Assimilation + ------------ + + Sometimes the value you want to propagate to a downstream promise can only be + retrieved asynchronously. This can be achieved by returning a promise in the + fulfillment or rejection handler. The downstream promise will then be pending + until the returned promise is settled. This is called *assimilation*. + + ```js + findUser().then(function (user) { + return findCommentsByAuthor(user); + }).then(function (comments) { + // The user's comments are now available + }); + ``` + + If the assimliated promise rejects, then the downstream promise will also reject. + + ```js + findUser().then(function (user) { + return findCommentsByAuthor(user); + }).then(function (comments) { + // If `findCommentsByAuthor` fulfills, we'll have the value here + }, function (reason) { + // If `findCommentsByAuthor` rejects, we'll have the reason here + }); + ``` + + Simple Example + -------------- + + Synchronous Example + + ```javascript + let result; + + try { + result = findResult(); + // success + } catch(reason) { + // failure + } + ``` + + Errback Example + + ```js + findResult(function(result, err){ + if (err) { + // failure + } else { + // success + } + }); + ``` + + Promise Example; + + ```javascript + findResult().then(function(result){ + // success + }, function(reason){ + // failure + }); + ``` + + Advanced Example + -------------- + + Synchronous Example + + ```javascript + let author, books; + + try { + author = findAuthor(); + books = findBooksByAuthor(author); + // success + } catch(reason) { + // failure + } + ``` + + Errback Example + + ```js + + function foundBooks(books) { + + } + + function failure(reason) { + + } + + findAuthor(function(author, err){ + if (err) { + failure(err); + // failure + } else { + try { + findBoooksByAuthor(author, function(books, err) { + if (err) { + failure(err); + } else { + try { + foundBooks(books); + } catch(reason) { + failure(reason); + } + } + }); + } catch(error) { + failure(err); + } + // success + } + }); + ``` + + Promise Example; + + ```javascript + findAuthor(). + then(findBooksByAuthor). + then(function(books){ + // found books + }).catch(function(reason){ + // something went wrong + }); + ``` + + @method then + @param {Function} onFulfilled + @param {Function} onRejected + Useful for tooling. + @return {Promise} + */ + then: then, + + /** + `catch` is simply sugar for `then(undefined, onRejection)` which makes it the same + as the catch block of a try/catch statement. + + ```js + function findAuthor(){ + throw new Error('couldn't find that author'); + } + + // synchronous + try { + findAuthor(); + } catch(reason) { + // something went wrong + } + + // async with promises + findAuthor().catch(function(reason){ + // something went wrong + }); + ``` + + @method catch + @param {Function} onRejection + Useful for tooling. + @return {Promise} + */ + 'catch': function _catch(onRejection) { + return this.then(null, onRejection); + } +}; + +function polyfill() { + var local = undefined; + + if (typeof global !== 'undefined') { + local = global; + } else if (typeof self !== 'undefined') { + local = self; + } else { + try { + local = Function('return this')(); + } catch (e) { + throw new Error('polyfill failed because global object is unavailable in this environment'); + } + } + + var P = local.Promise; + + if (P) { + var promiseToString = null; + try { + promiseToString = Object.prototype.toString.call(P.resolve()); + } catch (e) { + // silently ignored + } + + if (promiseToString === '[object Promise]' && !P.cast) { + return; + } + } + + local.Promise = Promise; +} + +// Strange compat.. +Promise.polyfill = polyfill; +Promise.Promise = Promise; + +return Promise; + +}))); + +ES6Promise.polyfill(); +//# sourceMappingURL=es6-promise.auto.map \ No newline at end of file diff --git a/test/vendor/es6-promise.min.js b/test/vendor/es6-promise.min.js new file mode 100644 index 0000000..68f5a2a --- /dev/null +++ b/test/vendor/es6-promise.min.js @@ -0,0 +1 @@ +!function(t,e){"object"==typeof exports&&"undefined"!=typeof module?module.exports=e():"function"==typeof define&&define.amd?define(e):t.ES6Promise=e()}(this,function(){"use strict";function t(t){return"function"==typeof t||"object"==typeof t&&null!==t}function e(t){return"function"==typeof t}function n(t){I=t}function r(t){J=t}function o(){return function(){return process.nextTick(a)}}function i(){return"undefined"!=typeof H?function(){H(a)}:c()}function s(){var t=0,e=new V(a),n=document.createTextNode("");return e.observe(n,{characterData:!0}),function(){n.data=t=++t%2}}function u(){var t=new MessageChannel;return t.port1.onmessage=a,function(){return t.port2.postMessage(0)}}function c(){var t=setTimeout;return function(){return t(a,1)}}function a(){for(var t=0;t"']/g,Y=RegExp(G.source),H=RegExp(J.source),Q=/<%-([\s\S]+?)%>/g,X=/<%([\s\S]+?)%>/g,tt=/<%=([\s\S]+?)%>/g,nt=/\.|\[(?:[^[\]]*|(["'])(?:(?!\1)[^\\]|\\.)*?\1)\]/,rt=/^\w*$/,et=/^\./,ut=/[^.[\]]+|\[(?:(-?\d+(?:\.\d+)?)|(["'])((?:(?!\2)[^\\]|\\.)*?)\2)\]|(?=(?:\.|\[\])(?:\.|\[\]|$))/g,it=/[\\^$.*+?()[\]{}|]/g,ot=RegExp(it.source),ft=/^\s+|\s+$/g,ct=/^\s+/,at=/\s+$/,lt=/\{(?:\n\/\* \[wrapped with .+\] \*\/)?\n?/,st=/\{\n\/\* \[wrapped with (.+)\] \*/,ht=/,? & /,pt=/[^\x00-\x2f\x3a-\x40\x5b-\x60\x7b-\x7f]+/g,_t=/\\(\\)?/g,vt=/\$\{([^\\}]*(?:\\.[^\\}]*)*)\}/g,gt=/\w*$/,dt=/^[-+]0x[0-9a-f]+$/i,yt=/^0b[01]+$/i,bt=/^\[object .+?Constructor\]$/,xt=/^0o[0-7]+$/i,jt=/^(?:0|[1-9]\d*)$/,wt=/[\xc0-\xd6\xd8-\xf6\xf8-\xff\u0100-\u017f]/g,mt=/($^)/,At=/['\n\r\u2028\u2029\\]/g,kt="[\\ufe0e\\ufe0f]?(?:[\\u0300-\\u036f\\ufe20-\\ufe23\\u20d0-\\u20f0]|\\ud83c[\\udffb-\\udfff])?(?:\\u200d(?:[^\\ud800-\\udfff]|(?:\\ud83c[\\udde6-\\uddff]){2}|[\\ud800-\\udbff][\\udc00-\\udfff])[\\ufe0e\\ufe0f]?(?:[\\u0300-\\u036f\\ufe20-\\ufe23\\u20d0-\\u20f0]|\\ud83c[\\udffb-\\udfff])?)*",Et="(?:[\\u2700-\\u27bf]|(?:\\ud83c[\\udde6-\\uddff]){2}|[\\ud800-\\udbff][\\udc00-\\udfff])"+kt,Ot="(?:[^\\ud800-\\udfff][\\u0300-\\u036f\\ufe20-\\ufe23\\u20d0-\\u20f0]?|[\\u0300-\\u036f\\ufe20-\\ufe23\\u20d0-\\u20f0]|(?:\\ud83c[\\udde6-\\uddff]){2}|[\\ud800-\\udbff][\\udc00-\\udfff]|[\\ud800-\\udfff])",St=RegExp("['\u2019]","g"),It=RegExp("[\\u0300-\\u036f\\ufe20-\\ufe23\\u20d0-\\u20f0]","g"),Rt=RegExp("\\ud83c[\\udffb-\\udfff](?=\\ud83c[\\udffb-\\udfff])|"+Ot+kt,"g"),zt=RegExp(["[A-Z\\xc0-\\xd6\\xd8-\\xde]?[a-z\\xdf-\\xf6\\xf8-\\xff]+(?:['\u2019](?:d|ll|m|re|s|t|ve))?(?=[\\xac\\xb1\\xd7\\xf7\\x00-\\x2f\\x3a-\\x40\\x5b-\\x60\\x7b-\\xbf\\u2000-\\u206f \\t\\x0b\\f\\xa0\\ufeff\\n\\r\\u2028\\u2029\\u1680\\u180e\\u2000\\u2001\\u2002\\u2003\\u2004\\u2005\\u2006\\u2007\\u2008\\u2009\\u200a\\u202f\\u205f\\u3000]|[A-Z\\xc0-\\xd6\\xd8-\\xde]|$)|(?:[A-Z\\xc0-\\xd6\\xd8-\\xde]|[^\\ud800-\\udfff\\xac\\xb1\\xd7\\xf7\\x00-\\x2f\\x3a-\\x40\\x5b-\\x60\\x7b-\\xbf\\u2000-\\u206f \\t\\x0b\\f\\xa0\\ufeff\\n\\r\\u2028\\u2029\\u1680\\u180e\\u2000\\u2001\\u2002\\u2003\\u2004\\u2005\\u2006\\u2007\\u2008\\u2009\\u200a\\u202f\\u205f\\u3000\\d+\\u2700-\\u27bfa-z\\xdf-\\xf6\\xf8-\\xffA-Z\\xc0-\\xd6\\xd8-\\xde])+(?:['\u2019](?:D|LL|M|RE|S|T|VE))?(?=[\\xac\\xb1\\xd7\\xf7\\x00-\\x2f\\x3a-\\x40\\x5b-\\x60\\x7b-\\xbf\\u2000-\\u206f \\t\\x0b\\f\\xa0\\ufeff\\n\\r\\u2028\\u2029\\u1680\\u180e\\u2000\\u2001\\u2002\\u2003\\u2004\\u2005\\u2006\\u2007\\u2008\\u2009\\u200a\\u202f\\u205f\\u3000]|[A-Z\\xc0-\\xd6\\xd8-\\xde](?:[a-z\\xdf-\\xf6\\xf8-\\xff]|[^\\ud800-\\udfff\\xac\\xb1\\xd7\\xf7\\x00-\\x2f\\x3a-\\x40\\x5b-\\x60\\x7b-\\xbf\\u2000-\\u206f \\t\\x0b\\f\\xa0\\ufeff\\n\\r\\u2028\\u2029\\u1680\\u180e\\u2000\\u2001\\u2002\\u2003\\u2004\\u2005\\u2006\\u2007\\u2008\\u2009\\u200a\\u202f\\u205f\\u3000\\d+\\u2700-\\u27bfa-z\\xdf-\\xf6\\xf8-\\xffA-Z\\xc0-\\xd6\\xd8-\\xde])|$)|[A-Z\\xc0-\\xd6\\xd8-\\xde]?(?:[a-z\\xdf-\\xf6\\xf8-\\xff]|[^\\ud800-\\udfff\\xac\\xb1\\xd7\\xf7\\x00-\\x2f\\x3a-\\x40\\x5b-\\x60\\x7b-\\xbf\\u2000-\\u206f \\t\\x0b\\f\\xa0\\ufeff\\n\\r\\u2028\\u2029\\u1680\\u180e\\u2000\\u2001\\u2002\\u2003\\u2004\\u2005\\u2006\\u2007\\u2008\\u2009\\u200a\\u202f\\u205f\\u3000\\d+\\u2700-\\u27bfa-z\\xdf-\\xf6\\xf8-\\xffA-Z\\xc0-\\xd6\\xd8-\\xde])+(?:['\u2019](?:d|ll|m|re|s|t|ve))?|[A-Z\\xc0-\\xd6\\xd8-\\xde]+(?:['\u2019](?:D|LL|M|RE|S|T|VE))?|\\d+",Et].join("|"),"g"),Wt=RegExp("[\\u200d\\ud800-\\udfff\\u0300-\\u036f\\ufe20-\\ufe23\\u20d0-\\u20f0\\ufe0e\\ufe0f]"),Bt=/[a-z][A-Z]|[A-Z]{2,}[a-z]|[0-9][a-zA-Z]|[a-zA-Z][0-9]|[^a-zA-Z0-9 ]/,Lt="Array Buffer DataView Date Error Float32Array Float64Array Function Int8Array Int16Array Int32Array Map Math Object Promise RegExp Set String Symbol TypeError Uint8Array Uint8ClampedArray Uint16Array Uint32Array WeakMap _ clearTimeout isFinite parseInt setTimeout".split(" "),Ut={}; +Ut["[object Float32Array]"]=Ut["[object Float64Array]"]=Ut["[object Int8Array]"]=Ut["[object Int16Array]"]=Ut["[object Int32Array]"]=Ut["[object Uint8Array]"]=Ut["[object Uint8ClampedArray]"]=Ut["[object Uint16Array]"]=Ut["[object Uint32Array]"]=true,Ut["[object Arguments]"]=Ut["[object Array]"]=Ut["[object ArrayBuffer]"]=Ut["[object Boolean]"]=Ut["[object DataView]"]=Ut["[object Date]"]=Ut["[object Error]"]=Ut["[object Function]"]=Ut["[object Map]"]=Ut["[object Number]"]=Ut["[object Object]"]=Ut["[object RegExp]"]=Ut["[object Set]"]=Ut["[object String]"]=Ut["[object WeakMap]"]=false; +var Ct={};Ct["[object Arguments]"]=Ct["[object Array]"]=Ct["[object ArrayBuffer]"]=Ct["[object DataView]"]=Ct["[object Boolean]"]=Ct["[object Date]"]=Ct["[object Float32Array]"]=Ct["[object Float64Array]"]=Ct["[object Int8Array]"]=Ct["[object Int16Array]"]=Ct["[object Int32Array]"]=Ct["[object Map]"]=Ct["[object Number]"]=Ct["[object Object]"]=Ct["[object RegExp]"]=Ct["[object Set]"]=Ct["[object String]"]=Ct["[object Symbol]"]=Ct["[object Uint8Array]"]=Ct["[object Uint8ClampedArray]"]=Ct["[object Uint16Array]"]=Ct["[object Uint32Array]"]=true, +Ct["[object Error]"]=Ct["[object Function]"]=Ct["[object WeakMap]"]=false;var Mt,Dt={"\\":"\\","'":"'","\n":"n","\r":"r","\u2028":"u2028","\u2029":"u2029"},Tt=parseFloat,$t=parseInt,Ft=typeof global=="object"&&global&&global.Object===Object&&global,Nt=typeof self=="object"&&self&&self.Object===Object&&self,Pt=Ft||Nt||Function("return this")(),Zt=typeof exports=="object"&&exports&&!exports.nodeType&&exports,qt=Zt&&typeof module=="object"&&module&&!module.nodeType&&module,Vt=qt&&qt.exports===Zt,Kt=Vt&&Ft.h; +t:{try{Mt=Kt&&Kt.g("util");break t}catch(t){}Mt=void 0}var Gt=Mt&&Mt.isArrayBuffer,Jt=Mt&&Mt.isDate,Yt=Mt&&Mt.isMap,Ht=Mt&&Mt.isRegExp,Qt=Mt&&Mt.isSet,Xt=Mt&&Mt.isTypedArray,tn=j("length"),nn=w({"\xc0":"A","\xc1":"A","\xc2":"A","\xc3":"A","\xc4":"A","\xc5":"A","\xe0":"a","\xe1":"a","\xe2":"a","\xe3":"a","\xe4":"a","\xe5":"a","\xc7":"C","\xe7":"c","\xd0":"D","\xf0":"d","\xc8":"E","\xc9":"E","\xca":"E","\xcb":"E","\xe8":"e","\xe9":"e","\xea":"e","\xeb":"e","\xcc":"I","\xcd":"I","\xce":"I","\xcf":"I", +"\xec":"i","\xed":"i","\xee":"i","\xef":"i","\xd1":"N","\xf1":"n","\xd2":"O","\xd3":"O","\xd4":"O","\xd5":"O","\xd6":"O","\xd8":"O","\xf2":"o","\xf3":"o","\xf4":"o","\xf5":"o","\xf6":"o","\xf8":"o","\xd9":"U","\xda":"U","\xdb":"U","\xdc":"U","\xf9":"u","\xfa":"u","\xfb":"u","\xfc":"u","\xdd":"Y","\xfd":"y","\xff":"y","\xc6":"Ae","\xe6":"ae","\xde":"Th","\xfe":"th","\xdf":"ss","\u0100":"A","\u0102":"A","\u0104":"A","\u0101":"a","\u0103":"a","\u0105":"a","\u0106":"C","\u0108":"C","\u010a":"C","\u010c":"C", +"\u0107":"c","\u0109":"c","\u010b":"c","\u010d":"c","\u010e":"D","\u0110":"D","\u010f":"d","\u0111":"d","\u0112":"E","\u0114":"E","\u0116":"E","\u0118":"E","\u011a":"E","\u0113":"e","\u0115":"e","\u0117":"e","\u0119":"e","\u011b":"e","\u011c":"G","\u011e":"G","\u0120":"G","\u0122":"G","\u011d":"g","\u011f":"g","\u0121":"g","\u0123":"g","\u0124":"H","\u0126":"H","\u0125":"h","\u0127":"h","\u0128":"I","\u012a":"I","\u012c":"I","\u012e":"I","\u0130":"I","\u0129":"i","\u012b":"i","\u012d":"i","\u012f":"i", +"\u0131":"i","\u0134":"J","\u0135":"j","\u0136":"K","\u0137":"k","\u0138":"k","\u0139":"L","\u013b":"L","\u013d":"L","\u013f":"L","\u0141":"L","\u013a":"l","\u013c":"l","\u013e":"l","\u0140":"l","\u0142":"l","\u0143":"N","\u0145":"N","\u0147":"N","\u014a":"N","\u0144":"n","\u0146":"n","\u0148":"n","\u014b":"n","\u014c":"O","\u014e":"O","\u0150":"O","\u014d":"o","\u014f":"o","\u0151":"o","\u0154":"R","\u0156":"R","\u0158":"R","\u0155":"r","\u0157":"r","\u0159":"r","\u015a":"S","\u015c":"S","\u015e":"S", +"\u0160":"S","\u015b":"s","\u015d":"s","\u015f":"s","\u0161":"s","\u0162":"T","\u0164":"T","\u0166":"T","\u0163":"t","\u0165":"t","\u0167":"t","\u0168":"U","\u016a":"U","\u016c":"U","\u016e":"U","\u0170":"U","\u0172":"U","\u0169":"u","\u016b":"u","\u016d":"u","\u016f":"u","\u0171":"u","\u0173":"u","\u0174":"W","\u0175":"w","\u0176":"Y","\u0177":"y","\u0178":"Y","\u0179":"Z","\u017b":"Z","\u017d":"Z","\u017a":"z","\u017c":"z","\u017e":"z","\u0132":"IJ","\u0133":"ij","\u0152":"Oe","\u0153":"oe","\u0149":"'n", +"\u017f":"s"}),rn=w({"&":"&","<":"<",">":">",'"':""","'":"'"}),en=w({"&":"&","<":"<",">":">",""":'"',"'":"'"}),un=function w(kt){function Et(t){return fi.call(t)}function Ot(t){if(vu(t)&&!nf(t)&&!(t instanceof Dt)){if(t instanceof Mt)return t;if(ui.call(t,"__wrapped__"))return De(t)}return new Mt(t)}function Rt(){}function Mt(t,n){this.__wrapped__=t,this.__actions__=[],this.__chain__=!!n,this.__index__=0,this.__values__=F}function Dt(t){this.__wrapped__=t,this.__actions__=[], +this.__dir__=1,this.__filtered__=false,this.__iteratees__=[],this.__takeCount__=4294967295,this.__views__=[]}function Ft(t){var n=-1,r=t?t.length:0;for(this.clear();++n=n?t:n)),t}function yn(t,n,r,e,i,o,f){var c;if(e&&(c=o?e(t,i,o,f):e(t)),c!==F)return c;if(!_u(t))return t;if(i=nf(t)){if(c=be(t),!n)return Cr(t,c)}else{var a=Et(t),l="[object Function]"==a||"[object GeneratorFunction]"==a;if(ef(t))return Rr(t,n);if("[object Object]"==a||"[object Arguments]"==a||l&&!o){if(c=xe(l?{}:t),!n)return Dr(t,_n(c,t))}else{if(!Ct[a])return o?t:{};c=je(t,a,yn,n)}}if(f||(f=new Kt),o=f.get(t))return o;f.set(t,c); +var s=i?F:(r?se:Iu)(t);return u(s||t,function(u,i){s&&(i=u,u=t[i]),sn(c,i,yn(u,n,r,e,i,t,f))}),c}function bn(t){var n=Iu(t);return function(r){return xn(r,t,n)}}function xn(t,n,r){var e=r.length;if(null==t)return!e;for(t=Ju(t);e--;){var u=r[e],i=n[u],o=t[u];if(o===F&&!(u in t)||!i(o))return false}return true}function jn(t,n,r){if(typeof t!="function")throw new Qu("Expected a function");return po(function(){t.apply(F,r)},n)}function wn(t,n,r,e){var u=-1,i=c,o=true,f=t.length,s=[],h=n.length;if(!f)return s;r&&(n=l(n,S(r))), +e?(i=a,o=false):200<=n.length&&(i=R,o=false,n=new qt(n));t:for(;++un}function Bn(t,n){return null!=t&&ui.call(t,n)}function Ln(t,n){ +return null!=t&&n in Ju(t)}function Un(t,n,r){for(var e=r?a:c,u=t[0].length,i=t.length,o=i,f=Zu(i),s=1/0,h=[];o--;){var p=t[o];o&&n&&(p=l(p,S(n))),s=Wi(p.length,s),f[o]=!r&&(n||120<=u&&120<=p.length)?new qt(o&&p):F}var p=t[0],_=-1,v=f[0];t:for(;++_n?r:0,me(n,r)?t[n]:F}function rr(t,n,r){var e=-1;return n=l(n.length?n:[Mu],S(_e())),t=Hn(t,function(t){return{a:l(n,function(n){return n(t)}),b:++e,c:t}}),A(t,function(t,n){var e;t:{e=-1;for(var u=t.a,i=n.a,o=u.length,f=r.length;++e=f?c:c*("desc"==r[e]?-1:1);break t}}e=t.b-n.b}return e})}function er(t,n){return t=Ju(t),ur(t,n,function(n,r){return r in t})}function ur(t,n,r){for(var e=-1,u=n.length,i={};++en||9007199254740991n&&(n=-n>u?0:u+n),r=r>u?u:r,0>r&&(r+=u),u=n>r?0:r-n>>>0,n>>>=0,r=Zu(u);++e=u){for(;e>>1,o=t[i];null!==o&&!bu(o)&&(r?o<=n:o=e?t:vr(t,n,r)}function Rr(t,n){if(n)return t.slice();var r=t.length,r=pi?pi(r):new t.constructor(r); +return t.copy(r),r}function zr(t){var n=new t.constructor(t.byteLength);return new hi(n).set(new hi(t)),n}function Wr(t,n){return new t.constructor(n?zr(t.buffer):t.buffer,t.byteOffset,t.length)}function Br(t,n){if(t!==n){var r=t!==F,e=null===t,u=t===t,i=bu(t),o=n!==F,f=null===n,c=n===n,a=bu(n);if(!f&&!a&&!i&&t>n||i&&o&&c&&!f&&!a||e&&o&&c||!r&&c||!u)return 1;if(!e&&!i&&!a&&tu?F:i,u=1),n=Ju(n);++eo&&f[0]!==a&&f[o-1]!==a?[]:C(f,a),o-=c.length,or?r?ar(n,t):n:(r=ar(n,Ai(t/T(n))),Wt.test(n)?Ir($(r),0,t).join(""):r.slice(0,t))}function ne(t,n,e,u){function i(){for(var n=-1,c=arguments.length,a=-1,l=u.length,s=Zu(l+c),h=this&&this!==Pt&&this instanceof i?f:t;++an||e)&&(1&t&&(i[2]=h[2],n|=1&r?0:4),(r=h[3])&&(e=i[3],i[3]=e?Lr(e,r,h[4]):r,i[4]=e?C(i[3],"__lodash_placeholder__"):h[4]),(r=h[5])&&(e=i[5],i[5]=e?Ur(e,r,h[6]):r,i[6]=e?C(i[5],"__lodash_placeholder__"):h[6]),(r=h[7])&&(i[7]=r),128&t&&(i[8]=null==i[8]?h[8]:Wi(i[8],h[8])), +null==i[9]&&(i[9]=h[9]),i[0]=h[0],i[1]=n),t=i[0],n=i[1],r=i[2],e=i[3],u=i[4],f=i[9]=null==i[9]?c?0:t.length:zi(i[9]-a,0),!f&&24&n&&(n&=-25),We((h?uo:ho)(n&&1!=n?8==n||16==n?Kr(t,n,f):32!=n&&33!=n||u.length?Yr.apply(F,i):ne(t,n,r,e):Pr(t,n,r),i),t,n)}function ce(t,n,r,e,u,i){var o=2&u,f=t.length,c=n.length;if(f!=c&&!(o&&c>f))return false;if((c=i.get(t))&&i.get(n))return c==n;var c=-1,a=true,l=1&u?new qt:F;for(i.set(t,n),i.set(n,t);++cr&&(r=zi(e+r,0)),g(t,_e(n,3),r)):-1}function $e(t,n,r){var e=t?t.length:0;if(!e)return-1;var u=e-1;return r!==F&&(u=wu(r),u=0>r?zi(e+u,0):Wi(u,e-1)),g(t,_e(n,3),u,true); +}function Fe(t){return t&&t.length?En(t,1):[]}function Ne(t){return t&&t.length?t[0]:F}function Pe(t){var n=t?t.length:0;return n?t[n-1]:F}function Ze(t,n){return t&&t.length&&n&&n.length?or(t,n):t}function qe(t){return t?Ci.call(t):t}function Ve(t){if(!t||!t.length)return[];var n=0;return t=f(t,function(t){if(au(t))return n=zi(t.length,n),true}),E(n,function(n){return l(t,j(n))})}function Ke(t,n){if(!t||!t.length)return[];var e=Ve(t);return null==n?e:l(e,function(t){return r(n,F,t)})}function Ge(t){ +return t=Ot(t),t.__chain__=true,t}function Je(t,n){return n(t)}function Ye(){return this}function He(t,n){return(nf(t)?u:to)(t,_e(n,3))}function Qe(t,n){return(nf(t)?i:no)(t,_e(n,3))}function Xe(t,n){return(nf(t)?l:Hn)(t,_e(n,3))}function tu(t,n,r){return n=r?F:n,n=t&&null==n?t.length:n,fe(t,128,F,F,F,F,n)}function nu(t,n){var r;if(typeof n!="function")throw new Qu("Expected a function");return t=wu(t),function(){return 0<--t&&(r=n.apply(this,arguments)),1>=t&&(n=F),r}}function ru(t,n,r){return n=r?F:n, +t=fe(t,8,F,F,F,F,F,n),t.placeholder=ru.placeholder,t}function eu(t,n,r){return n=r?F:n,t=fe(t,16,F,F,F,F,F,n),t.placeholder=eu.placeholder,t}function uu(t,n,r){function e(n){var r=c,e=a;return c=a=F,_=n,s=t.apply(e,r)}function u(t){var r=t-p;return t-=_,p===F||r>=n||0>r||g&&t>=l}function i(){var t=Po();if(u(t))return o(t);var r,e=po;r=t-_,t=n-(t-p),r=g?Wi(t,l-r):t,h=e(i,r)}function o(t){return h=F,d&&c?e(t):(c=a=F,s)}function f(){var t=Po(),r=u(t);if(c=arguments,a=this,p=t,r){if(h===F)return _=t=p, +h=po(i,n),v?e(t):s;if(g)return h=po(i,n),e(p)}return h===F&&(h=po(i,n)),s}var c,a,l,s,h,p,_=0,v=false,g=false,d=true;if(typeof t!="function")throw new Qu("Expected a function");return n=Au(n)||0,_u(r)&&(v=!!r.leading,l=(g="maxWait"in r)?zi(Au(r.maxWait)||0,n):l,d="trailing"in r?!!r.trailing:d),f.cancel=function(){h!==F&&oo(h),_=0,c=p=a=h=F},f.flush=function(){return h===F?s:o(Po())},f}function iu(t,n){function r(){var e=arguments,u=n?n.apply(this,e):e[0],i=r.cache;return i.has(u)?i.get(u):(e=t.apply(this,e), +r.cache=i.set(u,e)||i,e)}if(typeof t!="function"||n&&typeof n!="function")throw new Qu("Expected a function");return r.cache=new(iu.Cache||Zt),r}function ou(t){if(typeof t!="function")throw new Qu("Expected a function");return function(){var n=arguments;switch(n.length){case 0:return!t.call(this);case 1:return!t.call(this,n[0]);case 2:return!t.call(this,n[0],n[1]);case 3:return!t.call(this,n[0],n[1],n[2])}return!t.apply(this,n)}}function fu(t,n){return t===n||t!==t&&n!==n}function cu(t){return null!=t&&pu(t.length)&&!su(t); +}function au(t){return vu(t)&&cu(t)}function lu(t){return!!vu(t)&&("[object Error]"==fi.call(t)||typeof t.message=="string"&&typeof t.name=="string")}function su(t){return t=_u(t)?fi.call(t):"","[object Function]"==t||"[object GeneratorFunction]"==t||"[object Proxy]"==t}function hu(t){return typeof t=="number"&&t==wu(t)}function pu(t){return typeof t=="number"&&-1=t}function _u(t){var n=typeof t;return null!=t&&("object"==n||"function"==n)}function vu(t){return null!=t&&typeof t=="object"; +}function gu(t){return typeof t=="number"||vu(t)&&"[object Number]"==fi.call(t)}function du(t){return!(!vu(t)||"[object Object]"!=fi.call(t))&&(t=_i(t),null===t||(t=ui.call(t,"constructor")&&t.constructor,typeof t=="function"&&t instanceof t&&ei.call(t)==oi))}function yu(t){return typeof t=="string"||!nf(t)&&vu(t)&&"[object String]"==fi.call(t)}function bu(t){return typeof t=="symbol"||vu(t)&&"[object Symbol]"==fi.call(t)}function xu(t){if(!t)return[];if(cu(t))return yu(t)?$(t):Cr(t);if(vi&&t[vi]){t=t[vi](); +for(var n,r=[];!(n=t.next()).done;)r.push(n.value);return r}return n=Et(t),("[object Map]"==n?L:"[object Set]"==n?M:Wu)(t)}function ju(t){return t?(t=Au(t),t===N||t===-N?1.7976931348623157e308*(0>t?-1:1):t===t?t:0):0===t?t:0}function wu(t){t=ju(t);var n=t%1;return t===t?n?t-n:t:0}function mu(t){return t?dn(wu(t),0,4294967295):0}function Au(t){if(typeof t=="number")return t;if(bu(t))return P;if(_u(t)&&(t=typeof t.valueOf=="function"?t.valueOf():t,t=_u(t)?t+"":t),typeof t!="string")return 0===t?t:+t; +t=t.replace(ft,"");var n=yt.test(t);return n||xt.test(t)?$t(t.slice(2),n?2:8):dt.test(t)?P:+t}function ku(t){return Mr(t,Ru(t))}function Eu(t){return null==t?"":jr(t)}function Ou(t,n,r){return t=null==t?F:Rn(t,n),t===F?r:t}function Su(t,n){return null!=t&&ye(t,n,Ln)}function Iu(t){return cu(t)?tn(t):Jn(t)}function Ru(t){if(cu(t))t=tn(t,true);else if(_u(t)){var n,r=Oe(t),e=[];for(n in t)("constructor"!=n||!r&&ui.call(t,n))&&e.push(n);t=e}else{if(n=[],null!=t)for(r in Ju(t))n.push(r);t=n}return t}function zu(t,n){ +return null==t?{}:ur(t,zn(t,Ru,lo),_e(n))}function Wu(t){return t?I(t,Iu(t)):[]}function Bu(t){return Uf(Eu(t).toLowerCase())}function Lu(t){return(t=Eu(t))&&t.replace(wt,nn).replace(It,"")}function Uu(t,n,r){return t=Eu(t),n=r?F:n,n===F?Bt.test(t)?t.match(zt)||[]:t.match(pt)||[]:t.match(n)||[]}function Cu(t){return function(){return t}}function Mu(t){return t}function Du(t){return Gn(typeof t=="function"?t:yn(t,true))}function Tu(t,n,r){var e=Iu(n),i=In(n,e);null!=r||_u(n)&&(i.length||!e.length)||(r=n, +n=t,t=this,i=In(n,Iu(n)));var o=!(_u(r)&&"chain"in r&&!r.chain),f=su(t);return u(i,function(r){var e=n[r];t[r]=e,f&&(t.prototype[r]=function(){var n=this.__chain__;if(o||n){var r=t(this.__wrapped__);return(r.__actions__=Cr(this.__actions__)).push({func:e,args:arguments,thisArg:t}),r.__chain__=n,r}return e.apply(t,s([this.value()],arguments))})}),t}function $u(){}function Fu(t){return ke(t)?j(Ue(t)):ir(t)}function Nu(){return[]}function Pu(){return false}kt=kt?un.defaults(Pt.Object(),kt,un.pick(Pt,Lt)):Pt; +var Zu=kt.Array,qu=kt.Date,Vu=kt.Error,Ku=kt.Function,Gu=kt.Math,Ju=kt.Object,Yu=kt.RegExp,Hu=kt.String,Qu=kt.TypeError,Xu=Zu.prototype,ti=Ju.prototype,ni=kt["__core-js_shared__"],ri=function(){var t=/[^.]+$/.exec(ni&&ni.keys&&ni.keys.IE_PROTO||"");return t?"Symbol(src)_1."+t:""}(),ei=Ku.prototype.toString,ui=ti.hasOwnProperty,ii=0,oi=ei.call(Ju),fi=ti.toString,ci=Pt._,ai=Yu("^"+ei.call(ui).replace(it,"\\$&").replace(/hasOwnProperty|(function).*?(?=\\\()| for .+?(?=\\\])/g,"$1.*?")+"$"),li=Vt?kt.Buffer:F,si=kt.Symbol,hi=kt.Uint8Array,pi=li?li.f:F,_i=U(Ju.getPrototypeOf,Ju),vi=si?si.iterator:F,gi=Ju.create,di=ti.propertyIsEnumerable,yi=Xu.splice,bi=si?si.isConcatSpreadable:F,xi=function(){ +try{var t=de(Ju,"defineProperty");return t({},"",{}),t}catch(t){}}(),ji=kt.clearTimeout!==Pt.clearTimeout&&kt.clearTimeout,wi=qu&&qu.now!==Pt.Date.now&&qu.now,mi=kt.setTimeout!==Pt.setTimeout&&kt.setTimeout,Ai=Gu.ceil,ki=Gu.floor,Ei=Ju.getOwnPropertySymbols,Oi=li?li.isBuffer:F,Si=kt.isFinite,Ii=Xu.join,Ri=U(Ju.keys,Ju),zi=Gu.max,Wi=Gu.min,Bi=qu.now,Li=kt.parseInt,Ui=Gu.random,Ci=Xu.reverse,Mi=de(kt,"DataView"),Di=de(kt,"Map"),Ti=de(kt,"Promise"),$i=de(kt,"Set"),Fi=de(kt,"WeakMap"),Ni=de(Ju,"create"),Pi=Fi&&new Fi,Zi={},qi=Ce(Mi),Vi=Ce(Di),Ki=Ce(Ti),Gi=Ce($i),Ji=Ce(Fi),Yi=si?si.prototype:F,Hi=Yi?Yi.valueOf:F,Qi=Yi?Yi.toString:F,Xi=function(){ +function t(){}return function(n){return _u(n)?gi?gi(n):(t.prototype=n,n=new t,t.prototype=F,n):{}}}();Ot.templateSettings={escape:Q,evaluate:X,interpolate:tt,variable:"",imports:{_:Ot}},Ot.prototype=Rt.prototype,Ot.prototype.constructor=Ot,Mt.prototype=Xi(Rt.prototype),Mt.prototype.constructor=Mt,Dt.prototype=Xi(Rt.prototype),Dt.prototype.constructor=Dt,Ft.prototype.clear=function(){this.__data__=Ni?Ni(null):{},this.size=0},Ft.prototype.delete=function(t){return t=this.has(t)&&delete this.__data__[t], +this.size-=t?1:0,t},Ft.prototype.get=function(t){var n=this.__data__;return Ni?(t=n[t],"__lodash_hash_undefined__"===t?F:t):ui.call(n,t)?n[t]:F},Ft.prototype.has=function(t){var n=this.__data__;return Ni?n[t]!==F:ui.call(n,t)},Ft.prototype.set=function(t,n){var r=this.__data__;return this.size+=this.has(t)?0:1,r[t]=Ni&&n===F?"__lodash_hash_undefined__":n,this},Nt.prototype.clear=function(){this.__data__=[],this.size=0},Nt.prototype.delete=function(t){var n=this.__data__;return t=hn(n,t),!(0>t)&&(t==n.length-1?n.pop():yi.call(n,t,1), +--this.size,true)},Nt.prototype.get=function(t){var n=this.__data__;return t=hn(n,t),0>t?F:n[t][1]},Nt.prototype.has=function(t){return-1e?(++this.size,r.push([t,n])):r[e][1]=n,this},Zt.prototype.clear=function(){this.size=0,this.__data__={hash:new Ft,map:new(Di||Nt),string:new Ft}},Zt.prototype.delete=function(t){return t=ve(this,t).delete(t),this.size-=t?1:0,t},Zt.prototype.get=function(t){return ve(this,t).get(t); +},Zt.prototype.has=function(t){return ve(this,t).has(t)},Zt.prototype.set=function(t,n){var r=ve(this,t),e=r.size;return r.set(t,n),this.size+=r.size==e?0:1,this},qt.prototype.add=qt.prototype.push=function(t){return this.__data__.set(t,"__lodash_hash_undefined__"),this},qt.prototype.has=function(t){return this.__data__.has(t)},Kt.prototype.clear=function(){this.__data__=new Nt,this.size=0},Kt.prototype.delete=function(t){var n=this.__data__;return t=n.delete(t),this.size=n.size,t},Kt.prototype.get=function(t){ +return this.__data__.get(t)},Kt.prototype.has=function(t){return this.__data__.has(t)},Kt.prototype.set=function(t,n){var r=this.__data__;if(r instanceof Nt){var e=r.__data__;if(!Di||199>e.length)return e.push([t,n]),this.size=++r.size,this;r=this.__data__=new Zt(e)}return r.set(t,n),this.size=r.size,this};var to=Fr(On),no=Fr(Sn,true),ro=Nr(),eo=Nr(true),uo=Pi?function(t,n){return Pi.set(t,n),t}:Mu,io=xi?function(t,n){return xi(t,"toString",{configurable:true,enumerable:false,value:Cu(n),writable:true})}:Mu,oo=ji||function(t){ +return Pt.clearTimeout(t)},fo=$i&&1/M(new $i([,-0]))[1]==N?function(t){return new $i(t)}:$u,co=Pi?function(t){return Pi.get(t)}:$u,ao=Ei?U(Ei,Ju):Nu,lo=Ei?function(t){for(var n=[];t;)s(n,ao(t)),t=_i(t);return n}:Nu;(Mi&&"[object DataView]"!=Et(new Mi(new ArrayBuffer(1)))||Di&&"[object Map]"!=Et(new Di)||Ti&&"[object Promise]"!=Et(Ti.resolve())||$i&&"[object Set]"!=Et(new $i)||Fi&&"[object WeakMap]"!=Et(new Fi))&&(Et=function(t){var n=fi.call(t);if(t=(t="[object Object]"==n?t.constructor:F)?Ce(t):F)switch(t){ +case qi:return"[object DataView]";case Vi:return"[object Map]";case Ki:return"[object Promise]";case Gi:return"[object Set]";case Ji:return"[object WeakMap]"}return n});var so=ni?su:Pu,ho=Be(uo),po=mi||function(t,n){return Pt.setTimeout(t,n)},_o=Be(io),vo=function(t){t=iu(t,function(t){return 500===n.size&&n.clear(),t});var n=t.cache;return t}(function(t){t=Eu(t);var n=[];return et.test(t)&&n.push(""),t.replace(ut,function(t,r,e,u){n.push(e?u.replace(_t,"$1"):r||t)}),n}),go=lr(function(t,n){return au(t)?wn(t,En(n,1,au,true)):[]; +}),yo=lr(function(t,n){var r=Pe(n);return au(r)&&(r=F),au(t)?wn(t,En(n,1,au,true),_e(r,2)):[]}),bo=lr(function(t,n){var r=Pe(n);return au(r)&&(r=F),au(t)?wn(t,En(n,1,au,true),F,r):[]}),xo=lr(function(t){var n=l(t,Or);return n.length&&n[0]===t[0]?Un(n):[]}),jo=lr(function(t){var n=Pe(t),r=l(t,Or);return n===Pe(r)?n=F:r.pop(),r.length&&r[0]===t[0]?Un(r,_e(n,2)):[]}),wo=lr(function(t){var n=Pe(t),r=l(t,Or);return n===Pe(r)?n=F:r.pop(),r.length&&r[0]===t[0]?Un(r,F,n):[]}),mo=lr(Ze),Ao=le(function(t,n){var r=t?t.length:0,e=gn(t,n); +return fr(t,l(n,function(t){return me(t,r)?+t:t}).sort(Br)),e}),ko=lr(function(t){return wr(En(t,1,au,true))}),Eo=lr(function(t){var n=Pe(t);return au(n)&&(n=F),wr(En(t,1,au,true),_e(n,2))}),Oo=lr(function(t){var n=Pe(t);return au(n)&&(n=F),wr(En(t,1,au,true),F,n)}),So=lr(function(t,n){return au(t)?wn(t,n):[]}),Io=lr(function(t){return kr(f(t,au))}),Ro=lr(function(t){var n=Pe(t);return au(n)&&(n=F),kr(f(t,au),_e(n,2))}),zo=lr(function(t){var n=Pe(t);return au(n)&&(n=F),kr(f(t,au),F,n)}),Wo=lr(Ve),Bo=lr(function(t){ +var n=t.length,n=1=n}),tf=Dn(function(){return arguments}())?Dn:function(t){return vu(t)&&ui.call(t,"callee")&&!di.call(t,"callee")},nf=Zu.isArray,rf=Gt?S(Gt):Tn,ef=Oi||Pu,uf=Jt?S(Jt):$n,of=Yt?S(Yt):Nn,ff=Ht?S(Ht):qn,cf=Qt?S(Qt):Vn,af=Xt?S(Xt):Kn,lf=ee(Yn),sf=ee(function(t,n){return t<=n}),hf=$r(function(t,n){if(Oe(n)||cu(n))Mr(n,Iu(n),t);else for(var r in n)ui.call(n,r)&&sn(t,r,n[r]); +}),pf=$r(function(t,n){Mr(n,Ru(n),t)}),_f=$r(function(t,n,r,e){Mr(n,Ru(n),t,e)}),vf=$r(function(t,n,r,e){Mr(n,Iu(n),t,e)}),gf=le(gn),df=lr(function(t){return t.push(F,an),r(_f,F,t)}),yf=lr(function(t){return t.push(F,Ie),r(mf,F,t)}),bf=Hr(function(t,n,r){t[n]=r},Cu(Mu)),xf=Hr(function(t,n,r){ui.call(t,n)?t[n].push(r):t[n]=[r]},_e),jf=lr(Mn),wf=$r(function(t,n,r){tr(t,n,r)}),mf=$r(function(t,n,r,e){tr(t,n,r,e)}),Af=le(function(t,n){return null==t?{}:(n=l(n,Ue),er(t,wn(zn(t,Ru,lo),n)))}),kf=le(function(t,n){ +return null==t?{}:er(t,l(n,Ue))}),Ef=oe(Iu),Of=oe(Ru),Sf=qr(function(t,n,r){return n=n.toLowerCase(),t+(r?Bu(n):n)}),If=qr(function(t,n,r){return t+(r?"-":"")+n.toLowerCase()}),Rf=qr(function(t,n,r){return t+(r?" ":"")+n.toLowerCase()}),zf=Zr("toLowerCase"),Wf=qr(function(t,n,r){return t+(r?"_":"")+n.toLowerCase()}),Bf=qr(function(t,n,r){return t+(r?" ":"")+Uf(n)}),Lf=qr(function(t,n,r){return t+(r?" ":"")+n.toUpperCase()}),Uf=Zr("toUpperCase"),Cf=lr(function(t,n){try{return r(t,F,n)}catch(t){return lu(t)?t:new Vu(t); +}}),Mf=le(function(t,n){return u(n,function(n){n=Ue(n),vn(t,n,Zo(t[n],t))}),t}),Df=Jr(),Tf=Jr(true),$f=lr(function(t,n){return function(r){return Mn(r,t,n)}}),Ff=lr(function(t,n){return function(r){return Mn(t,r,n)}}),Nf=Xr(l),Pf=Xr(o),Zf=Xr(_),qf=re(),Vf=re(true),Kf=Qr(function(t,n){return t+n},0),Gf=ie("ceil"),Jf=Qr(function(t,n){return t/n},1),Yf=ie("floor"),Hf=Qr(function(t,n){return t*n},1),Qf=ie("round"),Xf=Qr(function(t,n){return t-n},0);return Ot.after=function(t,n){if(typeof n!="function")throw new Qu("Expected a function"); +return t=wu(t),function(){if(1>--t)return n.apply(this,arguments)}},Ot.ary=tu,Ot.assign=hf,Ot.assignIn=pf,Ot.assignInWith=_f,Ot.assignWith=vf,Ot.at=gf,Ot.before=nu,Ot.bind=Zo,Ot.bindAll=Mf,Ot.bindKey=qo,Ot.castArray=function(){if(!arguments.length)return[];var t=arguments[0];return nf(t)?t:[t]},Ot.chain=Ge,Ot.chunk=function(t,n,r){if(n=(r?Ae(t,n,r):n===F)?1:zi(wu(n),0),r=t?t.length:0,!r||1>n)return[];for(var e=0,u=0,i=Zu(Ai(r/n));en?0:n,e)):[]},Ot.dropRight=function(t,n,r){var e=t?t.length:0;return e?(n=r||n===F?1:wu(n),n=e-n,vr(t,0,0>n?0:n)):[]},Ot.dropRightWhile=function(t,n){return t&&t.length?mr(t,_e(n,3),true,true):[]},Ot.dropWhile=function(t,n){ +return t&&t.length?mr(t,_e(n,3),true):[]},Ot.fill=function(t,n,r,e){var u=t?t.length:0;if(!u)return[];for(r&&typeof r!="number"&&Ae(t,n,r)&&(r=0,e=u),u=t.length,r=wu(r),0>r&&(r=-r>u?0:u+r),e=e===F||e>u?u:wu(e),0>e&&(e+=u),e=r>e?0:mu(e);r>>0,r?(t=Eu(t))&&(typeof n=="string"||null!=n&&!ff(n))&&(n=jr(n),!n&&Wt.test(t))?Ir($(t),0,r):t.split(n,r):[]},Ot.spread=function(t,n){if(typeof t!="function")throw new Qu("Expected a function");return n=n===F?0:zi(wu(n),0),lr(function(e){var u=e[n];return e=Ir(e,0,n),u&&s(e,u),r(t,this,e)})},Ot.tail=function(t){ +var n=t?t.length:0;return n?vr(t,1,n):[]},Ot.take=function(t,n,r){return t&&t.length?(n=r||n===F?1:wu(n),vr(t,0,0>n?0:n)):[]},Ot.takeRight=function(t,n,r){var e=t?t.length:0;return e?(n=r||n===F?1:wu(n),n=e-n,vr(t,0>n?0:n,e)):[]},Ot.takeRightWhile=function(t,n){return t&&t.length?mr(t,_e(n,3),false,true):[]},Ot.takeWhile=function(t,n){return t&&t.length?mr(t,_e(n,3)):[]},Ot.tap=function(t,n){return n(t),t},Ot.throttle=function(t,n,r){var e=true,u=true;if(typeof t!="function")throw new Qu("Expected a function"); +return _u(r)&&(e="leading"in r?!!r.leading:e,u="trailing"in r?!!r.trailing:u),uu(t,n,{leading:e,maxWait:n,trailing:u})},Ot.thru=Je,Ot.toArray=xu,Ot.toPairs=Ef,Ot.toPairsIn=Of,Ot.toPath=function(t){return nf(t)?l(t,Ue):bu(t)?[t]:Cr(vo(t))},Ot.toPlainObject=ku,Ot.transform=function(t,n,r){var e=nf(t),i=e||ef(t)||af(t);if(n=_e(n,4),null==r){var o=t&&t.constructor;r=i?e?new o:[]:_u(t)&&su(o)?Xi(_i(t)):{}}return(i?u:On)(t,function(t,e,u){return n(r,t,e,u)}),r},Ot.unary=function(t){return tu(t,1)},Ot.union=ko, +Ot.unionBy=Eo,Ot.unionWith=Oo,Ot.uniq=function(t){return t&&t.length?wr(t):[]},Ot.uniqBy=function(t,n){return t&&t.length?wr(t,_e(n,2)):[]},Ot.uniqWith=function(t,n){return t&&t.length?wr(t,F,n):[]},Ot.unset=function(t,n){var r;if(null==t)r=true;else{r=t;var e=n,e=ke(e,r)?[e]:Sr(e);r=ze(r,e),e=Ue(Pe(e)),r=!(null!=r&&ui.call(r,e))||delete r[e]}return r},Ot.unzip=Ve,Ot.unzipWith=Ke,Ot.update=function(t,n,r){return null==t?t:pr(t,n,(typeof r=="function"?r:Mu)(Rn(t,n)),void 0)},Ot.updateWith=function(t,n,r,e){ +return e=typeof e=="function"?e:F,null!=t&&(t=pr(t,n,(typeof r=="function"?r:Mu)(Rn(t,n)),e)),t},Ot.values=Wu,Ot.valuesIn=function(t){return null==t?[]:I(t,Ru(t))},Ot.without=So,Ot.words=Uu,Ot.wrap=function(t,n){return n=null==n?Mu:n,Jo(n,t)},Ot.xor=Io,Ot.xorBy=Ro,Ot.xorWith=zo,Ot.zip=Wo,Ot.zipObject=function(t,n){return Er(t||[],n||[],sn)},Ot.zipObjectDeep=function(t,n){return Er(t||[],n||[],pr)},Ot.zipWith=Bo,Ot.entries=Ef,Ot.entriesIn=Of,Ot.extend=pf,Ot.extendWith=_f,Tu(Ot,Ot),Ot.add=Kf,Ot.attempt=Cf, +Ot.camelCase=Sf,Ot.capitalize=Bu,Ot.ceil=Gf,Ot.clamp=function(t,n,r){return r===F&&(r=n,n=F),r!==F&&(r=Au(r),r=r===r?r:0),n!==F&&(n=Au(n),n=n===n?n:0),dn(Au(t),n,r)},Ot.clone=function(t){return yn(t,false,true)},Ot.cloneDeep=function(t){return yn(t,true,true)},Ot.cloneDeepWith=function(t,n){return yn(t,true,true,n)},Ot.cloneWith=function(t,n){return yn(t,false,true,n)},Ot.conformsTo=function(t,n){return null==n||xn(t,n,Iu(n))},Ot.deburr=Lu,Ot.defaultTo=function(t,n){return null==t||t!==t?n:t},Ot.divide=Jf,Ot.endsWith=function(t,n,r){ +t=Eu(t),n=jr(n);var e=t.length,e=r=r===F?e:dn(wu(r),0,e);return r-=n.length,0<=r&&t.slice(r,e)==n},Ot.eq=fu,Ot.escape=function(t){return(t=Eu(t))&&H.test(t)?t.replace(J,rn):t},Ot.escapeRegExp=function(t){return(t=Eu(t))&&ot.test(t)?t.replace(it,"\\$&"):t},Ot.every=function(t,n,r){var e=nf(t)?o:mn;return r&&Ae(t,n,r)&&(n=F),e(t,_e(n,3))},Ot.find=Co,Ot.findIndex=Te,Ot.findKey=function(t,n){return v(t,_e(n,3),On)},Ot.findLast=Mo,Ot.findLastIndex=$e,Ot.findLastKey=function(t,n){return v(t,_e(n,3),Sn); +},Ot.floor=Yf,Ot.forEach=He,Ot.forEachRight=Qe,Ot.forIn=function(t,n){return null==t?t:ro(t,_e(n,3),Ru)},Ot.forInRight=function(t,n){return null==t?t:eo(t,_e(n,3),Ru)},Ot.forOwn=function(t,n){return t&&On(t,_e(n,3))},Ot.forOwnRight=function(t,n){return t&&Sn(t,_e(n,3))},Ot.get=Ou,Ot.gt=Qo,Ot.gte=Xo,Ot.has=function(t,n){return null!=t&&ye(t,n,Bn)},Ot.hasIn=Su,Ot.head=Ne,Ot.identity=Mu,Ot.includes=function(t,n,r,e){return t=cu(t)?t:Wu(t),r=r&&!e?wu(r):0,e=t.length,0>r&&(r=zi(e+r,0)),yu(t)?r<=e&&-1r&&(r=zi(e+r,0)),d(t,n,r)):-1},Ot.inRange=function(t,n,r){return n=ju(n),r===F?(r=n,n=0):r=ju(r),t=Au(t),t>=Wi(n,r)&&t=t; +},Ot.isSet=cf,Ot.isString=yu,Ot.isSymbol=bu,Ot.isTypedArray=af,Ot.isUndefined=function(t){return t===F},Ot.isWeakMap=function(t){return vu(t)&&"[object WeakMap]"==Et(t)},Ot.isWeakSet=function(t){return vu(t)&&"[object WeakSet]"==fi.call(t)},Ot.join=function(t,n){return t?Ii.call(t,n):""},Ot.kebabCase=If,Ot.last=Pe,Ot.lastIndexOf=function(t,n,r){var e=t?t.length:0;if(!e)return-1;var u=e;if(r!==F&&(u=wu(r),u=0>u?zi(e+u,0):Wi(u,e-1)),n===n){for(r=u+1;r--&&t[r]!==n;);t=r}else t=g(t,b,u,true);return t}, +Ot.lowerCase=Rf,Ot.lowerFirst=zf,Ot.lt=lf,Ot.lte=sf,Ot.max=function(t){return t&&t.length?An(t,Mu,Wn):F},Ot.maxBy=function(t,n){return t&&t.length?An(t,_e(n,2),Wn):F},Ot.mean=function(t){return x(t,Mu)},Ot.meanBy=function(t,n){return x(t,_e(n,2))},Ot.min=function(t){return t&&t.length?An(t,Mu,Yn):F},Ot.minBy=function(t,n){return t&&t.length?An(t,_e(n,2),Yn):F},Ot.stubArray=Nu,Ot.stubFalse=Pu,Ot.stubObject=function(){return{}},Ot.stubString=function(){return""},Ot.stubTrue=function(){return true},Ot.multiply=Hf, +Ot.nth=function(t,n){return t&&t.length?nr(t,wu(n)):F},Ot.noConflict=function(){return Pt._===this&&(Pt._=ci),this},Ot.noop=$u,Ot.now=Po,Ot.pad=function(t,n,r){t=Eu(t);var e=(n=wu(n))?T(t):0;return!n||e>=n?t:(n=(n-e)/2,te(ki(n),r)+t+te(Ai(n),r))},Ot.padEnd=function(t,n,r){t=Eu(t);var e=(n=wu(n))?T(t):0;return n&&en){var e=t;t=n,n=e}return r||t%1||n%1?(r=Ui(),Wi(t+r*(n-t+Tt("1e-"+((r+"").length-1))),n)):cr(t,n)},Ot.reduce=function(t,n,r){var e=nf(t)?h:m,u=3>arguments.length;return e(t,_e(n,4),r,u,to)},Ot.reduceRight=function(t,n,r){var e=nf(t)?p:m,u=3>arguments.length;return e(t,_e(n,4),r,u,no)},Ot.repeat=function(t,n,r){ +return n=(r?Ae(t,n,r):n===F)?1:wu(n),ar(Eu(t),n)},Ot.replace=function(){var t=arguments,n=Eu(t[0]);return 3>t.length?n:n.replace(t[1],t[2])},Ot.result=function(t,n,r){n=ke(n,t)?[n]:Sr(n);var e=-1,u=n.length;for(u||(t=F,u=1);++et||9007199254740991=i)return t;if(i=r-T(e),1>i)return e;if(r=o?Ir(o,0,i).join(""):t.slice(0,i),u===F)return r+e;if(o&&(i+=r.length-i),ff(u)){if(t.slice(i).search(u)){var f=r;for(u.global||(u=Yu(u.source,Eu(gt.exec(u))+"g")),u.lastIndex=0;o=u.exec(f);)var c=o.index;r=r.slice(0,c===F?i:c)}}else t.indexOf(jr(u),i)!=i&&(u=r.lastIndexOf(u),-1u.__dir__?"Right":"")}),u},Dt.prototype[t+"Right"]=function(n){return this.reverse()[t](n).reverse()}}),u(["filter","map","takeWhile"],function(t,n){var r=n+1,e=1==r||3==r;Dt.prototype[t]=function(t){var n=this.clone();return n.__iteratees__.push({iteratee:_e(t,3),type:r}),n.__filtered__=n.__filtered__||e,n}}),u(["head","last"],function(t,n){var r="take"+(n?"Right":"");Dt.prototype[t]=function(){return this[r](1).value()[0]}}),u(["initial","tail"],function(t,n){var r="drop"+(n?"":"Right"); +Dt.prototype[t]=function(){return this.__filtered__?new Dt(this):this[r](1)}}),Dt.prototype.compact=function(){return this.filter(Mu)},Dt.prototype.find=function(t){return this.filter(t).head()},Dt.prototype.findLast=function(t){return this.reverse().find(t)},Dt.prototype.invokeMap=lr(function(t,n){return typeof t=="function"?new Dt(this):this.map(function(r){return Mn(r,t,n)})}),Dt.prototype.reject=function(t){return this.filter(ou(_e(t)))},Dt.prototype.slice=function(t,n){t=wu(t);var r=this;return r.__filtered__&&(0n)?new Dt(r):(0>t?r=r.takeRight(-t):t&&(r=r.drop(t)), +n!==F&&(n=wu(n),r=0>n?r.dropRight(-n):r.take(n-t)),r)},Dt.prototype.takeRightWhile=function(t){return this.reverse().takeWhile(t).reverse()},Dt.prototype.toArray=function(){return this.take(4294967295)},On(Dt.prototype,function(t,n){var r=/^(?:filter|find|map|reject)|While$/.test(n),e=/^(?:head|last)$/.test(n),u=Ot[e?"take"+("last"==n?"Right":""):n],i=e||/^find/.test(n);u&&(Ot.prototype[n]=function(){function n(t){return t=u.apply(Ot,s([t],f)),e&&h?t[0]:t}var o=this.__wrapped__,f=e?[1]:arguments,c=o instanceof Dt,a=f[0],l=c||nf(o); +l&&r&&typeof a=="function"&&1!=a.length&&(c=l=false);var h=this.__chain__,p=!!this.__actions__.length,a=i&&!h,c=c&&!p;return!i&&l?(o=c?o:new Dt(this),o=t.apply(o,f),o.__actions__.push({func:Je,args:[n],thisArg:F}),new Mt(o,h)):a&&c?t.apply(this,f):(o=this.thru(n),a?e?o.value()[0]:o.value():o)})}),u("pop push shift sort splice unshift".split(" "),function(t){var n=Xu[t],r=/^(?:push|sort|unshift)$/.test(t)?"tap":"thru",e=/^(?:pop|shift)$/.test(t);Ot.prototype[t]=function(){var t=arguments;if(e&&!this.__chain__){ +var u=this.value();return n.apply(nf(u)?u:[],t)}return this[r](function(r){return n.apply(nf(r)?r:[],t)})}}),On(Dt.prototype,function(t,n){var r=Ot[n];if(r){var e=r.name+"";(Zi[e]||(Zi[e]=[])).push({name:n,func:r})}}),Zi[Yr(F,2).name]=[{name:"wrapper",func:F}],Dt.prototype.clone=function(){var t=new Dt(this.__wrapped__);return t.__actions__=Cr(this.__actions__),t.__dir__=this.__dir__,t.__filtered__=this.__filtered__,t.__iteratees__=Cr(this.__iteratees__),t.__takeCount__=this.__takeCount__,t.__views__=Cr(this.__views__), +t},Dt.prototype.reverse=function(){if(this.__filtered__){var t=new Dt(this);t.__dir__=-1,t.__filtered__=true}else t=this.clone(),t.__dir__*=-1;return t},Dt.prototype.value=function(){var t,n=this.__wrapped__.value(),r=this.__dir__,e=nf(n),u=0>r,i=e?n.length:0;t=i;for(var o=this.__views__,f=0,c=-1,a=o.length;++ci||i==t&&a==t)return Ar(n,this.__actions__);e=[];t:for(;t--&&c=this.__values__.length;return{done:t,value:t?F:this.__values__[this.__index__++]}},Ot.prototype.plant=function(t){for(var n,r=this;r instanceof Rt;){var e=De(r);e.__index__=0,e.__values__=F,n?u.__wrapped__=e:n=e;var u=e,r=r.__wrapped__}return u.__wrapped__=t,n},Ot.prototype.reverse=function(){var t=this.__wrapped__;return t instanceof Dt?(this.__actions__.length&&(t=new Dt(this)),t=t.reverse(),t.__actions__.push({func:Je,args:[qe],thisArg:F}),new Mt(t,this.__chain__)):this.thru(qe); +},Ot.prototype.toJSON=Ot.prototype.valueOf=Ot.prototype.value=function(){return Ar(this.__wrapped__,this.__actions__)},Ot.prototype.first=Ot.prototype.head,vi&&(Ot.prototype[vi]=Ye),Ot}();typeof define=="function"&&typeof define.amd=="object"&&define.amd?(Pt._=un, define(function(){return un})):qt?((qt.exports=un)._=un,Zt._=un):Pt._=un}).call(this); diff --git a/test/vendor/mocha.css b/test/vendor/mocha.css old mode 100755 new mode 100644 index 724ac3c..759a6c8 --- a/test/vendor/mocha.css +++ b/test/vendor/mocha.css @@ -1,10 +1,16 @@ -@charset "UTF-8"; +@charset "utf-8"; + body { + margin:0; +} + +#mocha { font: 20px/1.5 "Helvetica Neue", Helvetica, Arial, sans-serif; - padding: 60px 50px; + margin: 60px 50px; } -#mocha ul, #mocha li { +#mocha ul, +#mocha li { margin: 0; padding: 0; } @@ -13,7 +19,8 @@ body { list-style: none; } -#mocha h1, #mocha h2 { +#mocha h1, +#mocha h2 { margin: 0; } @@ -37,7 +44,7 @@ body { font-size: .8em; } -.hidden { +#mocha .hidden { display: none; } @@ -53,19 +60,20 @@ body { #mocha .test { margin-left: 15px; + overflow: hidden; } #mocha .test.pending:hover h2::after { content: '(pending)'; - font-family: arial; + font-family: arial, sans-serif; } #mocha .test.pass.medium .duration { - background: #C09853; + background: #c09853; } #mocha .test.pass.slow .duration { - background: #B94A48; + background: #b94a48; } #mocha .test.pass::before { @@ -81,7 +89,7 @@ body { font-size: 9px; margin-left: 5px; padding: 2px 5px; - color: white; + color: #fff; -webkit-box-shadow: inset 0 1px 1px rgba(0,0,0,.2); -moz-box-shadow: inset 0 1px 1px rgba(0,0,0,.2); box-shadow: inset 0 1px 1px rgba(0,0,0,.2); @@ -128,17 +136,63 @@ body { overflow: auto; } +#mocha .test .html-error { + overflow: auto; + color: black; + line-height: 1.5; + display: block; + float: left; + clear: left; + font: 12px/1.5 monaco, monospace; + margin: 5px; + padding: 15px; + border: 1px solid #eee; + max-width: 85%; /*(1)*/ + max-width: calc(100% - 42px); /*(2)*/ + max-height: 300px; + word-wrap: break-word; + border-bottom-color: #ddd; + -webkit-border-radius: 3px; + -webkit-box-shadow: 0 1px 3px #eee; + -moz-border-radius: 3px; + -moz-box-shadow: 0 1px 3px #eee; + border-radius: 3px; +} + +#mocha .test .html-error pre.error { + border: none; + -webkit-border-radius: none; + -webkit-box-shadow: none; + -moz-border-radius: none; + -moz-box-shadow: none; + padding: 0; + margin: 0; + margin-top: 18px; + max-height: none; +} + +/** + * (1): approximate for browsers not supporting calc + * (2): 42 = 2*15 + 2*10 + 2*1 (padding + margin + border) + * ^^ seriously + */ #mocha .test pre { - display: inline-block; + display: block; + float: left; + clear: left; font: 12px/1.5 monaco, monospace; margin: 5px; padding: 15px; border: 1px solid #eee; + max-width: 85%; /*(1)*/ + max-width: calc(100% - 42px); /*(2)*/ + word-wrap: break-word; border-bottom-color: #ddd; -webkit-border-radius: 3px; -webkit-box-shadow: 0 1px 3px #eee; -moz-border-radius: 3px; -moz-box-shadow: 0 1px 3px #eee; + border-radius: 3px; } #mocha .test h2 { @@ -148,7 +202,7 @@ body { #mocha .test a.replay { position: absolute; top: 3px; - right: -20px; + right: 0; text-decoration: none; vertical-align: middle; display: block; @@ -163,7 +217,7 @@ body { -webkit-transition: opacity 200ms; -moz-transition: opacity 200ms; transition: opacity 200ms; - opacity: 0.2; + opacity: 0.3; color: #888; } @@ -171,57 +225,90 @@ body { opacity: 1; } -#report.pass .test.fail { +#mocha-report.pass .test.fail { display: none; } -#report.fail .test.pass { +#mocha-report.fail .test.pass { display: none; } -#error { +#mocha-report.pending .test.pass, +#mocha-report.pending .test.fail { + display: none; +} +#mocha-report.pending .test.pass.pending { + display: block; +} + +#mocha-error { color: #c00; - font-size: 1.5 em; + font-size: 1.5em; font-weight: 100; letter-spacing: 1px; } -#stats { +#mocha-stats { position: fixed; top: 15px; right: 10px; font-size: 12px; margin: 0; color: #888; + z-index: 1; } -#stats .progress { +#mocha-stats .progress { float: right; padding-top: 0; -} - -#stats em { + + /** + * Set safe initial values, so mochas .progress does not inherit these + * properties from Bootstrap .progress (which causes .progress height to + * equal line height set in Bootstrap). + */ + height: auto; + box-shadow: none; + background-color: initial; +} + +#mocha-stats em { color: black; } -#stats a { +#mocha-stats a { text-decoration: none; color: inherit; } -#stats a:hover { +#mocha-stats a:hover { border-bottom: 1px solid #eee; } -#stats li { +#mocha-stats li { display: inline-block; margin: 0 5px; list-style: none; padding-top: 11px; } -code .comment { color: #ddd } -code .init { color: #2F6FAD } -code .string { color: #5890AD } -code .keyword { color: #8A6343 } -code .number { color: #2F6FAD } +#mocha-stats canvas { + width: 40px; + height: 40px; +} + +#mocha code .comment { color: #ddd; } +#mocha code .init { color: #2f6fad; } +#mocha code .string { color: #5890ad; } +#mocha code .keyword { color: #8a6343; } +#mocha code .number { color: #2f6fad; } + +@media screen and (max-device-width: 480px) { + #mocha { + margin: 60px 0px; + } + + #mocha #stats { + position: absolute; + } +} diff --git a/test/vendor/mocha.js b/test/vendor/mocha.js old mode 100755 new mode 100644 index 6e42dc2..af90ada --- a/test/vendor/mocha.js +++ b/test/vendor/mocha.js @@ -1,68 +1,180 @@ -;(function(){ +(function e(t,n,r){function s(o,u){if(!n[o]){if(!t[o]){var a=typeof require=="function"&&require;if(!u&&a)return a(o,!0);if(i)return i(o,!0);var f=new Error("Cannot find module '"+o+"'");throw f.code="MODULE_NOT_FOUND",f}var l=n[o]={exports:{}};t[o][0].call(l.exports,function(e){var n=t[o][1][e];return s(n?n:e)},l,l.exports,e,t,n,r)}return n[o].exports}var i=typeof require=="function"&&require;for(var o=0;o 1) { + suites.shift(); + } + var suite = Suite.create(suites[0], title); + suite.file = file; + suites.unshift(suite); + return suite; }; /** - * Execute after running tests. + * Exclusive test-case. */ - context.after = function(fn){ - suites[0].afterAll(fn); + context.suite.only = function(title, fn) { + var suite = context.suite(title, fn); + mocha.grep(suite.fullTitle()); }; /** - * Execute before each test case. + * Describe a specification or test-case + * with the given `title` and callback `fn` + * acting as a thunk. */ - context.beforeEach = function(fn){ - suites[0].beforeEach(fn); + context.test = function(title, fn) { + var test = new Test(title, fn); + test.file = file; + suites[0].addTest(test); + return test; }; /** - * Execute after each test case. + * Exclusive test-case. */ - context.afterEach = function(fn){ - suites[0].afterEach(fn); - }; - - /** - * Describe a "suite" with the given `title`. - */ - - context.suite = function(title){ - if (suites.length > 1) suites.shift(); - var suite = Suite.create(suites[0], title); - suites.unshift(suite); + context.test.only = function(title, fn) { + var test = context.test(title, fn); + var reString = '^' + escapeRe(test.fullTitle()) + '$'; + mocha.grep(new RegExp(reString)); }; - /** - * Describe a specification or test-case - * with the given `title` and callback `fn` - * acting as a thunk. - */ - - context.test = function(title, fn){ - suites[0].addTest(new Test(title, fn)); - }; + context.test.skip = common.test.skip; + context.test.retries = common.test.retries; }); }; -}); // module: interfaces/qunit.js - -require.register("interfaces/tdd.js", function(module, exports, require){ - +},{"../suite":37,"../test":38,"./common":9,"escape-string-regexp":49}],13:[function(require,module,exports){ /** * Module dependencies. */ -var Suite = require('../suite') - , Test = require('../test'); +var Suite = require('../suite'); +var Test = require('../test'); +var escapeRe = require('escape-string-regexp'); /** * TDD-style interface: * - * suite('Array', function(){ - * suite('#indexOf()', function(){ - * suiteSetup(function(){ + * suite('Array', function() { + * suite('#indexOf()', function() { + * suiteSetup(function() { * * }); - * - * test('should return -1 when not present', function(){ + * + * test('should return -1 when not present', function() { * * }); * - * test('should return the index when present', function(){ + * test('should return the index when present', function() { * * }); * - * suiteTeardown(function(){ + * suiteTeardown(function() { * * }); * }); * }); * + * @param {Suite} suite Root suite. */ - -module.exports = function(suite){ +module.exports = function(suite) { var suites = [suite]; - suite.on('pre-require', function(context, file, mocha){ - - /** - * Execute before each test case. - */ - - context.setup = function(fn){ - suites[0].beforeEach(fn); - }; - - /** - * Execute after each test case. - */ - - context.teardown = function(fn){ - suites[0].afterEach(fn); - }; - - /** - * Execute before the suite. - */ + suite.on('pre-require', function(context, file, mocha) { + var common = require('./common')(suites, context); - context.suiteSetup = function(fn){ - suites[0].beforeAll(fn); - }; + context.setup = common.beforeEach; + context.teardown = common.afterEach; + context.suiteSetup = common.before; + context.suiteTeardown = common.after; + context.run = mocha.options.delay && common.runWithSuite(suite); /** - * Execute after the suite. + * Describe a "suite" with the given `title` and callback `fn` containing + * nested suites and/or tests. */ - - context.suiteTeardown = function(fn){ - suites[0].afterAll(fn); + context.suite = function(title, fn) { + var suite = Suite.create(suites[0], title); + suite.file = file; + suites.unshift(suite); + fn.call(suite); + suites.shift(); + return suite; }; /** - * Describe a "suite" with the given `title` - * and callback `fn` containing nested suites - * and/or tests. + * Pending suite. */ - - context.suite = function(title, fn){ + context.suite.skip = function(title, fn) { var suite = Suite.create(suites[0], title); + suite.pending = true; suites.unshift(suite); fn.call(suite); suites.shift(); - return suite; }; /** * Exclusive test-case. */ - - context.suite.only = function(title, fn){ + context.suite.only = function(title, fn) { var suite = context.suite(title, fn); mocha.grep(suite.fullTitle()); }; /** - * Describe a specification or test-case - * with the given `title` and callback `fn` - * acting as a thunk. + * Describe a specification or test-case with the given `title` and + * callback `fn` acting as a thunk. */ - - context.test = function(title, fn){ + context.test = function(title, fn) { + var suite = suites[0]; + if (suite.isPending()) { + fn = null; + } var test = new Test(title, fn); - suites[0].addTest(test); + test.file = file; + suite.addTest(test); return test; }; @@ -933,16 +1125,19 @@ module.exports = function(suite){ * Exclusive test-case. */ - context.test.only = function(title, fn){ + context.test.only = function(title, fn) { var test = context.test(title, fn); - mocha.grep(test.fullTitle()); + var reString = '^' + escapeRe(test.fullTitle()) + '$'; + mocha.grep(new RegExp(reString)); }; + + context.test.skip = common.test.skip; + context.test.retries = common.test.retries; }); }; -}); // module: interfaces/tdd.js - -require.register("mocha.js", function(module, exports, require){ +},{"../suite":37,"../test":38,"./common":9,"escape-string-regexp":49}],14:[function(require,module,exports){ +(function (process,global,__dirname){ /*! * mocha * Copyright(c) 2011 TJ Holowaychuk @@ -953,8 +1148,10 @@ require.register("mocha.js", function(module, exports, require){ * Module dependencies. */ -var path = require('browser/path') - , utils = require('./utils'); +var escapeRe = require('escape-string-regexp'); +var path = require('path'); +var reporters = require('./reporters'); +var utils = require('./utils'); /** * Expose `Mocha`. @@ -962,13 +1159,22 @@ var path = require('browser/path') exports = module.exports = Mocha; +/** + * To require local UIs and reporters when running in node. + */ + +if (!process.browser) { + var cwd = process.cwd(); + module.paths.push(cwd, path.join(cwd, 'node_modules')); +} + /** * Expose internals. */ exports.utils = utils; exports.interfaces = require('./interfaces'); -exports.reporters = require('./reporters'); +exports.reporters = reporters; exports.Runnable = require('./runnable'); exports.Context = require('./context'); exports.Runner = require('./runner'); @@ -979,90 +1185,164 @@ exports.Test = require('./test'); /** * Return image `name` path. * - * @param {String} name - * @return {String} * @api private + * @param {string} name + * @return {string} */ - function image(name) { - return __dirname + '/../images/' + name + '.png'; + return path.join(__dirname, '../images', name + '.png'); } /** - * Setup mocha with `options`. + * Set up mocha with `options`. * * Options: * * - `ui` name "bdd", "tdd", "exports" etc - * - `reporter` reporter instance, defaults to `mocha.reporters.Dot` + * - `reporter` reporter instance, defaults to `mocha.reporters.spec` * - `globals` array of accepted globals * - `timeout` timeout in milliseconds + * - `retries` number of times to retry failed tests + * - `bail` bail on the first test failure * - `slow` milliseconds to wait before considering a test slow * - `ignoreLeaks` ignore global leaks + * - `fullTrace` display the full stack-trace on failing * - `grep` string or regexp to filter tests with * * @param {Object} options * @api public */ - function Mocha(options) { options = options || {}; this.files = []; this.options = options; - this.grep(options.grep); - this.suite = new exports.Suite('', new exports.Context); + if (options.grep) { + this.grep(new RegExp(options.grep)); + } + if (options.fgrep) { + this.grep(options.fgrep); + } + this.suite = new exports.Suite('', new exports.Context()); this.ui(options.ui); - this.reporter(options.reporter); - if (options.timeout) this.timeout(options.timeout); - if (options.slow) this.slow(options.slow); + this.bail(options.bail); + this.reporter(options.reporter, options.reporterOptions); + if (typeof options.timeout !== 'undefined' && options.timeout !== null) { + this.timeout(options.timeout); + } + if (typeof options.retries !== 'undefined' && options.retries !== null) { + this.retries(options.retries); + } + this.useColors(options.useColors); + if (options.enableTimeouts !== null) { + this.enableTimeouts(options.enableTimeouts); + } + if (options.slow) { + this.slow(options.slow); + } } /** - * Add test `file`. + * Enable or disable bailing on the first failure. * - * @param {String} file * @api public + * @param {boolean} [bail] */ +Mocha.prototype.bail = function(bail) { + if (!arguments.length) { + bail = true; + } + this.suite.bail(bail); + return this; +}; -Mocha.prototype.addFile = function(file){ +/** + * Add test `file`. + * + * @api public + * @param {string} file + */ +Mocha.prototype.addFile = function(file) { this.files.push(file); return this; }; /** - * Set reporter to `reporter`, defaults to "dot". + * Set reporter to `reporter`, defaults to "spec". * - * @param {String|Function} reporter name of a reporter or a reporter constructor + * @param {String|Function} reporter name or constructor + * @param {Object} reporterOptions optional options * @api public + * @param {string|Function} reporter name or constructor + * @param {Object} reporterOptions optional options */ - -Mocha.prototype.reporter = function(reporter){ - if ('function' == typeof reporter) { +Mocha.prototype.reporter = function(reporter, reporterOptions) { + if (typeof reporter === 'function') { this._reporter = reporter; } else { - reporter = reporter || 'dot'; - try { - this._reporter = require('./reporters/' + reporter); - } catch (err) { - this._reporter = require(reporter); + reporter = reporter || 'spec'; + var _reporter; + // Try to load a built-in reporter. + if (reporters[reporter]) { + _reporter = reporters[reporter]; + } + // Try to load reporters from process.cwd() and node_modules + if (!_reporter) { + try { + _reporter = require(reporter); + } catch (err) { + err.message.indexOf('Cannot find module') !== -1 + ? console.warn('"' + reporter + '" reporter not found') + : console.warn('"' + reporter + '" reporter blew up with error:\n' + err.stack); + } } - if (!this._reporter) throw new Error('invalid reporter "' + reporter + '"'); + if (!_reporter && reporter === 'teamcity') { + console.warn('The Teamcity reporter was moved to a package named ' + + 'mocha-teamcity-reporter ' + + '(https://npmjs.org/package/mocha-teamcity-reporter).'); + } + if (!_reporter) { + throw new Error('invalid reporter "' + reporter + '"'); + } + this._reporter = _reporter; } + this.options.reporterOptions = reporterOptions; return this; }; /** * Set test UI `name`, defaults to "bdd". * - * @param {String} bdd * @api public + * @param {string} bdd */ - -Mocha.prototype.ui = function(name){ +Mocha.prototype.ui = function(name) { name = name || 'bdd'; this._ui = exports.interfaces[name]; - if (!this._ui) throw new Error('invalid interface "' + name + '"'); + if (!this._ui) { + try { + this._ui = require(name); + } catch (err) { + throw new Error('invalid interface "' + name + '"'); + } + } this._ui = this._ui(this.suite); + + this.suite.on('pre-require', function(context) { + exports.afterEach = context.afterEach || context.teardown; + exports.after = context.after || context.suiteTeardown; + exports.beforeEach = context.beforeEach || context.setup; + exports.before = context.before || context.suiteSetup; + exports.describe = context.describe || context.suite; + exports.it = context.it || context.test; + exports.setup = context.setup || context.beforeEach; + exports.suiteSetup = context.suiteSetup || context.before; + exports.suiteTeardown = context.suiteTeardown || context.after; + exports.suite = context.suite || context.describe; + exports.teardown = context.teardown || context.afterEach; + exports.test = context.test || context.it; + exports.run = context.run; + }); + return this; }; @@ -1071,18 +1351,16 @@ Mocha.prototype.ui = function(name){ * * @api private */ - -Mocha.prototype.loadFiles = function(fn){ +Mocha.prototype.loadFiles = function(fn) { var self = this; var suite = this.suite; - var pending = this.files.length; - this.files.forEach(function(file){ + this.files.forEach(function(file) { file = path.resolve(file); suite.emit('pre-require', global, file, self); suite.emit('require', require(file), file, self); suite.emit('post-require', global, file, self); - --pending || (fn && fn()); }); + fn && fn(); }; /** @@ -1090,20 +1368,19 @@ Mocha.prototype.loadFiles = function(fn){ * * @api private */ - Mocha.prototype._growl = function(runner, reporter) { var notify = require('growl'); - runner.on('end', function(){ + runner.on('end', function() { var stats = reporter.stats; if (stats.failures) { var msg = stats.failures + ' of ' + runner.total + ' tests failed'; notify(msg, { name: 'mocha', title: 'Failed', image: image('error') }); } else { notify(stats.passes + ' tests passed in ' + stats.duration + 'ms', { - name: 'mocha' - , title: 'Passed' - , image: image('ok') + name: 'mocha', + title: 'Passed', + image: image('ok') }); } }); @@ -1115,12 +1392,11 @@ Mocha.prototype._growl = function(runner, reporter) { * @param {RegExp|String} re * @return {Mocha} * @api public + * @param {RegExp|string} re + * @return {Mocha} */ - -Mocha.prototype.grep = function(re){ - this.options.grep = 'string' == typeof re - ? new RegExp(utils.escapeRegexp(re)) - : re; +Mocha.prototype.grep = function(re) { + this.options.grep = typeof re === 'string' ? new RegExp(escapeRe(re)) : re; return this; }; @@ -1130,8 +1406,7 @@ Mocha.prototype.grep = function(re){ * @return {Mocha} * @api public */ - -Mocha.prototype.invert = function(){ +Mocha.prototype.invert = function() { this.options.invert = true; return this; }; @@ -1139,12 +1414,14 @@ Mocha.prototype.invert = function(){ /** * Ignore global leaks. * + * @param {Boolean} ignore * @return {Mocha} * @api public + * @param {boolean} ignore + * @return {Mocha} */ - -Mocha.prototype.ignoreLeaks = function(){ - this.options.ignoreLeaks = true; +Mocha.prototype.ignoreLeaks = function(ignore) { + this.options.ignoreLeaks = Boolean(ignore); return this; }; @@ -1154,20 +1431,29 @@ Mocha.prototype.ignoreLeaks = function(){ * @return {Mocha} * @api public */ - -Mocha.prototype.checkLeaks = function(){ +Mocha.prototype.checkLeaks = function() { this.options.ignoreLeaks = false; return this; }; /** - * Enable growl support. + * Display long stack-trace on failing * * @return {Mocha} * @api public */ +Mocha.prototype.fullTrace = function() { + this.options.fullStackTrace = true; + return this; +}; -Mocha.prototype.growl = function(){ +/** + * Enable growl support. + * + * @return {Mocha} + * @api public + */ +Mocha.prototype.growl = function() { this.options.growl = true; return this; }; @@ -1178,64 +1464,186 @@ Mocha.prototype.growl = function(){ * @param {Array|String} globals * @return {Mocha} * @api public + * @param {Array|string} globals + * @return {Mocha} */ - -Mocha.prototype.globals = function(globals){ +Mocha.prototype.globals = function(globals) { this.options.globals = (this.options.globals || []).concat(globals); return this; }; +/** + * Emit color output. + * + * @param {Boolean} colors + * @return {Mocha} + * @api public + * @param {boolean} colors + * @return {Mocha} + */ +Mocha.prototype.useColors = function(colors) { + if (colors !== undefined) { + this.options.useColors = colors; + } + return this; +}; + +/** + * Use inline diffs rather than +/-. + * + * @param {Boolean} inlineDiffs + * @return {Mocha} + * @api public + * @param {boolean} inlineDiffs + * @return {Mocha} + */ +Mocha.prototype.useInlineDiffs = function(inlineDiffs) { + this.options.useInlineDiffs = inlineDiffs !== undefined && inlineDiffs; + return this; +}; + /** * Set the timeout in milliseconds. * * @param {Number} timeout * @return {Mocha} * @api public + * @param {number} timeout + * @return {Mocha} */ - -Mocha.prototype.timeout = function(timeout){ +Mocha.prototype.timeout = function(timeout) { this.suite.timeout(timeout); return this; }; +/** + * Set the number of times to retry failed tests. + * + * @param {Number} retry times + * @return {Mocha} + * @api public + */ +Mocha.prototype.retries = function(n) { + this.suite.retries(n); + return this; +}; + /** * Set slowness threshold in milliseconds. * * @param {Number} slow * @return {Mocha} * @api public + * @param {number} slow + * @return {Mocha} */ - -Mocha.prototype.slow = function(slow){ +Mocha.prototype.slow = function(slow) { this.suite.slow(slow); return this; }; +/** + * Enable timeouts. + * + * @param {Boolean} enabled + * @return {Mocha} + * @api public + * @param {boolean} enabled + * @return {Mocha} + */ +Mocha.prototype.enableTimeouts = function(enabled) { + this.suite.enableTimeouts(arguments.length && enabled !== undefined ? enabled : true); + return this; +}; + +/** + * Makes all tests async (accepting a callback) + * + * @return {Mocha} + * @api public + */ +Mocha.prototype.asyncOnly = function() { + this.options.asyncOnly = true; + return this; +}; + +/** + * Disable syntax highlighting (in browser). + * + * @api public + */ +Mocha.prototype.noHighlighting = function() { + this.options.noHighlighting = true; + return this; +}; + +/** + * Enable uncaught errors to propagate (in browser). + * + * @return {Mocha} + * @api public + */ +Mocha.prototype.allowUncaught = function() { + this.options.allowUncaught = true; + return this; +}; + +/** + * Delay root suite execution. + * @returns {Mocha} + */ +Mocha.prototype.delay = function delay() { + this.options.delay = true; + return this; +}; + /** * Run tests and invoke `fn()` when complete. * + * @api public * @param {Function} fn * @return {Runner} - * @api public */ - -Mocha.prototype.run = function(fn){ - if (this.files.length) this.loadFiles(); +Mocha.prototype.run = function(fn) { + if (this.files.length) { + this.loadFiles(); + } var suite = this.suite; var options = this.options; - var runner = new exports.Runner(suite); - var reporter = new this._reporter(runner); - runner.ignoreLeaks = options.ignoreLeaks; - if (options.grep) runner.grep(options.grep, options.invert); - if (options.globals) runner.globals(options.globals); - if (options.growl) this._growl(runner, reporter); - return runner.run(fn); -}; + options.files = this.files; + var runner = new exports.Runner(suite, options.delay); + var reporter = new this._reporter(runner, options); + runner.ignoreLeaks = options.ignoreLeaks !== false; + runner.fullStackTrace = options.fullStackTrace; + runner.asyncOnly = options.asyncOnly; + runner.allowUncaught = options.allowUncaught; + if (options.grep) { + runner.grep(options.grep, options.invert); + } + if (options.globals) { + runner.globals(options.globals); + } + if (options.growl) { + this._growl(runner, reporter); + } + if (options.useColors !== undefined) { + exports.reporters.Base.useColors = options.useColors; + } + exports.reporters.Base.inlineDiffs = options.useInlineDiffs; -}); // module: mocha.js + function done(failures) { + if (reporter.done) { + reporter.done(failures, fn); + } else { + fn && fn(failures); + } + } -require.register("ms.js", function(module, exports, require){ + return runner.run(done); +}; +}).call(this,require('_process'),typeof global !== "undefined" ? global : typeof self !== "undefined" ? self : typeof window !== "undefined" ? window : {},"/lib") +},{"./context":6,"./hook":7,"./interfaces":11,"./reporters":22,"./runnable":35,"./runner":36,"./suite":37,"./test":38,"./utils":39,"_process":58,"escape-string-regexp":49,"growl":51,"path":43}],15:[function(require,module,exports){ /** * Helpers. */ @@ -1244,99 +1652,174 @@ var s = 1000; var m = s * 60; var h = m * 60; var d = h * 24; +var y = d * 365.25; /** * Parse or format the given `val`. * - * @param {String|Number} val - * @return {String|Number} + * Options: + * + * - `long` verbose formatting [false] + * * @api public + * @param {string|number} val + * @param {Object} options + * @return {string|number} */ - -module.exports = function(val){ - if ('string' == typeof val) return parse(val); - return format(val); -} +module.exports = function(val, options) { + options = options || {}; + if (typeof val === 'string') { + return parse(val); + } + // https://github.com/mochajs/mocha/pull/1035 + return options['long'] ? longFormat(val) : shortFormat(val); +}; /** * Parse the given `str` and return milliseconds. * - * @param {String} str - * @return {Number} * @api private + * @param {string} str + * @return {number} */ - function parse(str) { - var m = /^((?:\d+)?\.?\d+) *(ms|seconds?|s|minutes?|m|hours?|h|days?|d|years?|y)?$/i.exec(str); - if (!m) return; - var n = parseFloat(m[1]); - var type = (m[2] || 'ms').toLowerCase(); + var match = (/^((?:\d+)?\.?\d+) *(ms|seconds?|s|minutes?|m|hours?|h|days?|d|years?|y)?$/i).exec(str); + if (!match) { + return; + } + var n = parseFloat(match[1]); + var type = (match[2] || 'ms').toLowerCase(); switch (type) { case 'years': case 'year': case 'y': - return n * 31557600000; + return n * y; case 'days': case 'day': case 'd': - return n * 86400000; + return n * d; case 'hours': case 'hour': case 'h': - return n * 3600000; + return n * h; case 'minutes': case 'minute': case 'm': - return n * 60000; + return n * m; case 'seconds': case 'second': case 's': - return n * 1000; + return n * s; case 'ms': return n; + default: + // No default case } } /** - * Format the given `ms`. + * Short format for `ms`. * - * @param {Number} ms - * @return {String} - * @api public + * @api private + * @param {number} ms + * @return {string} */ +function shortFormat(ms) { + if (ms >= d) { + return Math.round(ms / d) + 'd'; + } + if (ms >= h) { + return Math.round(ms / h) + 'h'; + } + if (ms >= m) { + return Math.round(ms / m) + 'm'; + } + if (ms >= s) { + return Math.round(ms / s) + 's'; + } + return ms + 'ms'; +} -function format(ms) { - if (ms == d) return (ms / d) + ' day'; - if (ms > d) return (ms / d) + ' days'; - if (ms == h) return (ms / h) + ' hour'; - if (ms > h) return (ms / h) + ' hours'; - if (ms == m) return (ms / m) + ' minute'; - if (ms > m) return (ms / m) + ' minutes'; - if (ms == s) return (ms / s) + ' second'; - if (ms > s) return (ms / s) + ' seconds'; - return ms + ' ms'; +/** + * Long format for `ms`. + * + * @api private + * @param {number} ms + * @return {string} + */ +function longFormat(ms) { + return plural(ms, d, 'day') + || plural(ms, h, 'hour') + || plural(ms, m, 'minute') + || plural(ms, s, 'second') + || ms + ' ms'; +} + +/** + * Pluralization helper. + * + * @api private + * @param {number} ms + * @param {number} n + * @param {string} name + */ +function plural(ms, n, name) { + if (ms < n) { + return; + } + if (ms < n * 1.5) { + return Math.floor(ms / n) + ' ' + name; + } + return Math.ceil(ms / n) + ' ' + name + 's'; } -}); // module: ms.js -require.register("reporters/base.js", function(module, exports, require){ +},{}],16:[function(require,module,exports){ + +/** + * Expose `Pending`. + */ + +module.exports = Pending; +/** + * Initialize a new `Pending` error with the given message. + * + * @param {string} message + */ +function Pending(message) { + this.message = message; +} + +},{}],17:[function(require,module,exports){ +(function (process,global){ /** * Module dependencies. */ -var tty = require('browser/tty') - , diff = require('browser/diff') - , ms = require('../ms'); +var tty = require('tty'); +var diff = require('diff'); +var ms = require('../ms'); +var utils = require('../utils'); +var supportsColor = process.browser ? null : require('supports-color'); /** - * Save timer references to avoid Sinon interfering (see GH-237). + * Expose `Base`. + */ + +exports = module.exports = Base; + +/** + * Save timer references to avoid Sinon interfering. + * See: https://github.com/mochajs/mocha/issues/237 */ -var Date = global.Date - , setTimeout = global.setTimeout - , setInterval = global.setInterval - , clearTimeout = global.clearTimeout - , clearInterval = global.clearInterval; +/* eslint-disable no-unused-vars, no-native-reassign */ +var Date = global.Date; +var setTimeout = global.setTimeout; +var setInterval = global.setInterval; +var clearTimeout = global.clearTimeout; +var clearInterval = global.clearInterval; +/* eslint-enable no-unused-vars, no-native-reassign */ /** * Check if both stdio streams are associated with a tty. @@ -1345,98 +1828,120 @@ var Date = global.Date var isatty = tty.isatty(1) && tty.isatty(2); /** - * Expose `Base`. + * Enable coloring by default, except in the browser interface. */ -exports = module.exports = Base; +exports.useColors = !process.browser && (supportsColor || (process.env.MOCHA_COLORS !== undefined)); /** - * Enable coloring by default. + * Inline diffs instead of +/- */ -exports.useColors = isatty; +exports.inlineDiffs = false; /** * Default color map. */ exports.colors = { - 'pass': 90 - , 'fail': 31 - , 'bright pass': 92 - , 'bright fail': 91 - , 'bright yellow': 93 - , 'pending': 36 - , 'suite': 0 - , 'error title': 0 - , 'error message': 31 - , 'error stack': 90 - , 'checkmark': 32 - , 'fast': 90 - , 'medium': 33 - , 'slow': 31 - , 'green': 32 - , 'light': 90 - , 'diff gutter': 90 - , 'diff added': 42 - , 'diff removed': 41 + pass: 90, + fail: 31, + 'bright pass': 92, + 'bright fail': 91, + 'bright yellow': 93, + pending: 36, + suite: 0, + 'error title': 0, + 'error message': 31, + 'error stack': 90, + checkmark: 32, + fast: 90, + medium: 33, + slow: 31, + green: 32, + light: 90, + 'diff gutter': 90, + 'diff added': 32, + 'diff removed': 31 }; /** - * Color `str` with the given `type`, - * allowing colors to be disabled, + * Default symbol map. + */ + +exports.symbols = { + ok: '✓', + err: '✖', + dot: '․' +}; + +// With node.js on Windows: use symbols available in terminal default fonts +if (process.platform === 'win32') { + exports.symbols.ok = '\u221A'; + exports.symbols.err = '\u00D7'; + exports.symbols.dot = '.'; +} + +/** + * Color `str` with the given `type`, + * allowing colors to be disabled, * as well as user-defined color * schemes. * - * @param {String} type - * @param {String} str - * @return {String} + * @param {string} type + * @param {string} str + * @return {string} * @api private */ - var color = exports.color = function(type, str) { - if (!exports.useColors) return str; + if (!exports.useColors) { + return String(str); + } return '\u001b[' + exports.colors[type] + 'm' + str + '\u001b[0m'; }; /** - * Expose term window size, with some - * defaults for when stderr is not a tty. + * Expose term window size, with some defaults for when stderr is not a tty. */ exports.window = { - width: isatty - ? process.stdout.getWindowSize - ? process.stdout.getWindowSize(1)[0] - : tty.getWindowSize()[1] - : 75 + width: 75 }; +if (isatty) { + exports.window.width = process.stdout.getWindowSize + ? process.stdout.getWindowSize(1)[0] + : tty.getWindowSize()[1]; +} + /** - * Expose some basic cursor interactions - * that are common among reporters. + * Expose some basic cursor interactions that are common among reporters. */ exports.cursor = { - hide: function(){ - process.stdout.write('\u001b[?25l'); + hide: function() { + isatty && process.stdout.write('\u001b[?25l'); }, - show: function(){ - process.stdout.write('\u001b[?25h'); + show: function() { + isatty && process.stdout.write('\u001b[?25h'); }, - deleteLine: function(){ - process.stdout.write('\u001b[2K'); + deleteLine: function() { + isatty && process.stdout.write('\u001b[2K'); }, - beginningOfLine: function(){ - process.stdout.write('\u001b[0G'); + beginningOfLine: function() { + isatty && process.stdout.write('\u001b[0G'); }, - CR: function(){ - exports.cursor.deleteLine(); - exports.cursor.beginningOfLine(); + CR: function() { + if (isatty) { + exports.cursor.deleteLine(); + exports.cursor.beginningOfLine(); + } else { + process.stdout.write('\r'); + } } }; @@ -1447,68 +1952,67 @@ exports.cursor = { * @api public */ -exports.list = function(failures){ - console.error(); - failures.forEach(function(test, i){ +exports.list = function(failures) { + console.log(); + failures.forEach(function(test, i) { // format var fmt = color('error title', ' %s) %s:\n') + color('error message', ' %s') + color('error stack', '\n%s\n'); // msg - var err = test.err - , message = err.message || '' - , stack = err.stack || message - , index = stack.indexOf(message) + message.length - , msg = stack.slice(0, index) - , actual = err.actual - , expected = err.expected - , escape = true; + var msg; + var err = test.err; + var message; + if (err.message && typeof err.message.toString === 'function') { + message = err.message + ''; + } else if (typeof err.inspect === 'function') { + message = err.inspect() + ''; + } else { + message = ''; + } + var stack = err.stack || message; + var index = stack.indexOf(message); + var actual = err.actual; + var expected = err.expected; + var escape = true; + + if (index === -1) { + msg = message; + } else { + index += message.length; + msg = stack.slice(0, index); + // remove msg from stack + stack = stack.slice(index + 1); + } + // uncaught + if (err.uncaught) { + msg = 'Uncaught ' + msg; + } // explicitly show diff - if (err.showDiff) { + if (err.showDiff !== false && sameType(actual, expected) && expected !== undefined) { escape = false; - err.actual = actual = JSON.stringify(actual, null, 2); - err.expected = expected = JSON.stringify(expected, null, 2); - } - - // actual / expected diff - if ('string' == typeof actual && 'string' == typeof expected) { - var len = Math.max(actual.length, expected.length); - - if (len < 20) msg = errorDiff(err, 'Chars', escape); - else msg = errorDiff(err, 'Words', escape); - - // linenos - var lines = msg.split('\n'); - if (lines.length > 4) { - var width = String(lines.length).length; - msg = lines.map(function(str, i){ - return pad(++i, width) + ' |' + ' ' + str; - }).join('\n'); + if (!(utils.isString(actual) && utils.isString(expected))) { + err.actual = actual = utils.stringify(actual); + err.expected = expected = utils.stringify(expected); } - // legend - msg = '\n' - + color('diff removed', 'actual') - + ' ' - + color('diff added', 'expected') - + '\n\n' - + msg - + '\n'; - - // indent - msg = msg.replace(/^/gm, ' '); + fmt = color('error title', ' %s) %s:\n%s') + color('error stack', '\n%s\n'); + var match = message.match(/^([^:]+): expected/); + msg = '\n ' + color('error message', match ? match[1] : msg); - fmt = color('error title', ' %s) %s:\n%s') - + color('error stack', '\n%s\n'); + if (exports.inlineDiffs) { + msg += inlineDiff(err, escape); + } else { + msg += unifiedDiff(err, escape); + } } - // indent stack trace without msg - stack = stack.slice(index ? index + 1 : index) - .replace(/^/gm, ' '); + // indent stack trace + stack = stack.replace(/^/gm, ' '); - console.error(fmt, (i + 1), test.fullTitle(), msg, stack); + console.log(fmt, (i + 1), test.fullTitle(), msg, stack); }); }; @@ -1525,55 +2029,57 @@ exports.list = function(failures){ */ function Base(runner) { - var self = this - , stats = this.stats = { suites: 0, tests: 0, passes: 0, pending: 0, failures: 0 } - , failures = this.failures = []; + var stats = this.stats = { suites: 0, tests: 0, passes: 0, pending: 0, failures: 0 }; + var failures = this.failures = []; - if (!runner) return; + if (!runner) { + return; + } this.runner = runner; runner.stats = stats; - runner.on('start', function(){ - stats.start = new Date; + runner.on('start', function() { + stats.start = new Date(); }); - runner.on('suite', function(suite){ + runner.on('suite', function(suite) { stats.suites = stats.suites || 0; suite.root || stats.suites++; }); - runner.on('test end', function(test){ + runner.on('test end', function() { stats.tests = stats.tests || 0; stats.tests++; }); - runner.on('pass', function(test){ + runner.on('pass', function(test) { stats.passes = stats.passes || 0; - var medium = test.slow() / 2; - test.speed = test.duration > test.slow() - ? 'slow' - : test.duration > medium - ? 'medium' - : 'fast'; + if (test.duration > test.slow()) { + test.speed = 'slow'; + } else if (test.duration > test.slow() / 2) { + test.speed = 'medium'; + } else { + test.speed = 'fast'; + } stats.passes++; }); - runner.on('fail', function(test, err){ + runner.on('fail', function(test, err) { stats.failures = stats.failures || 0; stats.failures++; test.err = err; failures.push(test); }); - runner.on('end', function(){ - stats.end = new Date; - stats.duration = new Date - stats.start; + runner.on('end', function() { + stats.end = new Date(); + stats.duration = new Date() - stats.start; }); - runner.on('pending', function(){ + runner.on('pending', function() { stats.pending++; }); } @@ -1584,50 +2090,37 @@ function Base(runner) { * * @api public */ - -Base.prototype.epilogue = function(){ - var stats = this.stats - , fmt - , tests; +Base.prototype.epilogue = function() { + var stats = this.stats; + var fmt; console.log(); - function pluralize(n) { - return 1 == n ? 'test' : 'tests'; - } - - // failure - if (stats.failures) { - fmt = color('bright fail', ' ✖') - + color('fail', ' %d of %d %s failed') - + color('light', ':') - - console.error(fmt, - stats.failures, - this.runner.total, - pluralize(this.runner.total)); - - Base.list(this.failures); - console.error(); - return; - } - - // pass - fmt = color('bright pass', ' ✔') - + color('green', ' %d %s complete') + // passes + fmt = color('bright pass', ' ') + + color('green', ' %d passing') + color('light', ' (%s)'); console.log(fmt, - stats.tests || 0, - pluralize(stats.tests), + stats.passes || 0, ms(stats.duration)); // pending if (stats.pending) { - fmt = color('pending', ' •') - + color('pending', ' %d %s pending'); + fmt = color('pending', ' ') + + color('pending', ' %d pending'); + + console.log(fmt, stats.pending); + } - console.log(fmt, stats.pending, pluralize(stats.pending)); + // failures + if (stats.failures) { + fmt = color('fail', ' %d failing'); + + console.log(fmt, stats.failures); + + Base.list(this.failures); + console.log(); } console.log(); @@ -1636,64 +2129,165 @@ Base.prototype.epilogue = function(){ /** * Pad the given `str` to `len`. * - * @param {String} str - * @param {String} len - * @return {String} * @api private + * @param {string} str + * @param {string} len + * @return {string} */ - function pad(str, len) { str = String(str); return Array(len - str.length + 1).join(' ') + str; } /** - * Return a character diff for `err`. + * Returns an inline diff between 2 strings with coloured ANSI output + * + * @api private + * @param {Error} err with actual/expected + * @param {boolean} escape + * @return {string} Diff + */ +function inlineDiff(err, escape) { + var msg = errorDiff(err, 'WordsWithSpace', escape); + + // linenos + var lines = msg.split('\n'); + if (lines.length > 4) { + var width = String(lines.length).length; + msg = lines.map(function(str, i) { + return pad(++i, width) + ' |' + ' ' + str; + }).join('\n'); + } + + // legend + msg = '\n' + + color('diff removed', 'actual') + + ' ' + + color('diff added', 'expected') + + '\n\n' + + msg + + '\n'; + + // indent + msg = msg.replace(/^/gm, ' '); + return msg; +} + +/** + * Returns a unified diff between two strings. * - * @param {Error} err - * @return {String} * @api private + * @param {Error} err with actual/expected + * @param {boolean} escape + * @return {string} The diff. */ +function unifiedDiff(err, escape) { + var indent = ' '; + function cleanUp(line) { + if (escape) { + line = escapeInvisibles(line); + } + if (line[0] === '+') { + return indent + colorLines('diff added', line); + } + if (line[0] === '-') { + return indent + colorLines('diff removed', line); + } + if (line.match(/\@\@/)) { + return null; + } + if (line.match(/\\ No newline/)) { + return null; + } + return indent + line; + } + function notBlank(line) { + return typeof line !== 'undefined' && line !== null; + } + var msg = diff.createPatch('string', err.actual, err.expected); + var lines = msg.split('\n').splice(4); + return '\n ' + + colorLines('diff added', '+ expected') + ' ' + + colorLines('diff removed', '- actual') + + '\n\n' + + lines.map(cleanUp).filter(notBlank).join('\n'); +} +/** + * Return a character diff for `err`. + * + * @api private + * @param {Error} err + * @param {string} type + * @param {boolean} escape + * @return {string} + */ function errorDiff(err, type, escape) { - return diff['diff' + type](err.actual, err.expected).map(function(str){ - if (escape) { - str.value = str.value - .replace(/\t/g, '') - .replace(/\r/g, '') - .replace(/\n/g, '\n'); + var actual = escape ? escapeInvisibles(err.actual) : err.actual; + var expected = escape ? escapeInvisibles(err.expected) : err.expected; + return diff['diff' + type](actual, expected).map(function(str) { + if (str.added) { + return colorLines('diff added', str.value); + } + if (str.removed) { + return colorLines('diff removed', str.value); } - if (str.added) return colorLines('diff added', str.value); - if (str.removed) return colorLines('diff removed', str.value); return str.value; }).join(''); } /** - * Color lines for `str`, using the color `name`. + * Returns a string with all invisible characters in plain text * - * @param {String} name - * @param {String} str - * @return {String} * @api private + * @param {string} line + * @return {string} */ +function escapeInvisibles(line) { + return line.replace(/\t/g, '') + .replace(/\r/g, '') + .replace(/\n/g, '\n'); +} +/** + * Color lines for `str`, using the color `name`. + * + * @api private + * @param {string} name + * @param {string} str + * @return {string} + */ function colorLines(name, str) { - return str.split('\n').map(function(str){ + return str.split('\n').map(function(str) { return color(name, str); }).join('\n'); } -}); // module: reporters/base.js +/** + * Object#toString reference. + */ +var objToString = Object.prototype.toString; -require.register("reporters/doc.js", function(module, exports, require){ +/** + * Check that a / b have the same type. + * + * @api private + * @param {Object} a + * @param {Object} b + * @return {boolean} + */ +function sameType(a, b) { + return objToString.call(a) === objToString.call(b); +} +}).call(this,require('_process'),typeof global !== "undefined" ? global : typeof self !== "undefined" ? self : typeof window !== "undefined" ? window : {}) +},{"../ms":15,"../utils":39,"_process":58,"diff":48,"supports-color":43,"tty":5}],18:[function(require,module,exports){ /** * Module dependencies. */ -var Base = require('./base') - , utils = require('../utils'); +var Base = require('./base'); +var utils = require('../utils'); /** * Expose `Doc`. @@ -1707,21 +2301,19 @@ exports = module.exports = Doc; * @param {Runner} runner * @api public */ - function Doc(runner) { Base.call(this, runner); - var self = this - , stats = this.stats - , total = runner.total - , indents = 2; + var indents = 2; function indent() { return Array(indents).join(' '); } - runner.on('suite', function(suite){ - if (suite.root) return; + runner.on('suite', function(suite) { + if (suite.root) { + return; + } ++indents; console.log('%s
', indent()); ++indents; @@ -1729,31 +2321,39 @@ function Doc(runner) { console.log('%s
', indent()); }); - runner.on('suite end', function(suite){ - if (suite.root) return; + runner.on('suite end', function(suite) { + if (suite.root) { + return; + } console.log('%s
', indent()); --indents; console.log('%s
', indent()); --indents; }); - runner.on('pass', function(test){ + runner.on('pass', function(test) { console.log('%s
%s
', indent(), utils.escape(test.title)); - var code = utils.escape(utils.clean(test.fn.toString())); + var code = utils.escape(utils.clean(test.body)); console.log('%s
%s
', indent(), code); }); -} - -}); // module: reporters/doc.js -require.register("reporters/dot.js", function(module, exports, require){ + runner.on('fail', function(test, err) { + console.log('%s
%s
', indent(), utils.escape(test.title)); + var code = utils.escape(utils.clean(test.fn.body)); + console.log('%s
%s
', indent(), code); + console.log('%s
%s
', indent(), utils.escape(err)); + }); +} +},{"../utils":39,"./base":17}],19:[function(require,module,exports){ +(function (process){ /** * Module dependencies. */ -var Base = require('./base') - , color = Base.color; +var Base = require('./base'); +var inherits = require('../utils').inherits; +var color = Base.color; /** * Expose `Dot`. @@ -1764,42 +2364,46 @@ exports = module.exports = Dot; /** * Initialize a new `Dot` matrix test reporter. * - * @param {Runner} runner * @api public + * @param {Runner} runner */ - function Dot(runner) { Base.call(this, runner); - var self = this - , stats = this.stats - , width = Base.window.width * .75 | 0 - , c = '․' - , n = 0; + var self = this; + var width = Base.window.width * .75 | 0; + var n = -1; - runner.on('start', function(){ - process.stdout.write('\n '); + runner.on('start', function() { + process.stdout.write('\n'); }); - runner.on('pending', function(test){ - process.stdout.write(color('pending', c)); + runner.on('pending', function() { + if (++n % width === 0) { + process.stdout.write('\n '); + } + process.stdout.write(color('pending', Base.symbols.dot)); }); - runner.on('pass', function(test){ - if (++n % width == 0) process.stdout.write('\n '); - if ('slow' == test.speed) { - process.stdout.write(color('bright yellow', c)); + runner.on('pass', function(test) { + if (++n % width === 0) { + process.stdout.write('\n '); + } + if (test.speed === 'slow') { + process.stdout.write(color('bright yellow', Base.symbols.dot)); } else { - process.stdout.write(color(test.speed, c)); + process.stdout.write(color(test.speed, Base.symbols.dot)); } }); - runner.on('fail', function(test, err){ - if (++n % width == 0) process.stdout.write('\n '); - process.stdout.write(color('fail', c)); + runner.on('fail', function() { + if (++n % width === 0) { + process.stdout.write('\n '); + } + process.stdout.write(color('fail', Base.symbols.dot)); }); - runner.on('end', function(){ + runner.on('end', function() { console.log(); self.epilogue(); }); @@ -1808,20 +2412,18 @@ function Dot(runner) { /** * Inherit from `Base.prototype`. */ +inherits(Dot, Base); -Dot.prototype = new Base; -Dot.prototype.constructor = Dot; - -}); // module: reporters/dot.js - -require.register("reporters/html-cov.js", function(module, exports, require){ - +}).call(this,require('_process')) +},{"../utils":39,"./base":17,"_process":58}],20:[function(require,module,exports){ +(function (process,__dirname){ /** * Module dependencies. */ -var JSONCov = require('./json-cov') - , fs = require('browser/fs'); +var JSONCov = require('./json-cov'); +var readFileSync = require('fs').readFileSync; +var join = require('path').join; /** * Expose `HTMLCov`. @@ -1832,65 +2434,75 @@ exports = module.exports = HTMLCov; /** * Initialize a new `JsCoverage` reporter. * - * @param {Runner} runner * @api public + * @param {Runner} runner */ - function HTMLCov(runner) { - var jade = require('jade') - , file = __dirname + '/templates/coverage.jade' - , str = fs.readFileSync(file, 'utf8') - , fn = jade.compile(str, { filename: file }) - , self = this; + var jade = require('jade'); + var file = join(__dirname, '/templates/coverage.jade'); + var str = readFileSync(file, 'utf8'); + var fn = jade.compile(str, { filename: file }); + var self = this; JSONCov.call(this, runner, false); - runner.on('end', function(){ + runner.on('end', function() { process.stdout.write(fn({ - cov: self.cov - , coverageClass: coverageClass + cov: self.cov, + coverageClass: coverageClass })); }); } /** - * Return coverage class for `n`. + * Return coverage class for a given coverage percentage. * - * @return {String} * @api private + * @param {number} coveragePctg + * @return {string} */ - -function coverageClass(n) { - if (n >= 75) return 'high'; - if (n >= 50) return 'medium'; - if (n >= 25) return 'low'; +function coverageClass(coveragePctg) { + if (coveragePctg >= 75) { + return 'high'; + } + if (coveragePctg >= 50) { + return 'medium'; + } + if (coveragePctg >= 25) { + return 'low'; + } return 'terrible'; } -}); // module: reporters/html-cov.js -require.register("reporters/html.js", function(module, exports, require){ +}).call(this,require('_process'),"/lib/reporters") +},{"./json-cov":23,"_process":58,"fs":43,"jade":43,"path":43}],21:[function(require,module,exports){ +(function (global){ +/* eslint-env browser */ /** * Module dependencies. */ -var Base = require('./base') - , utils = require('../utils') - , Progress = require('../browser/progress') - , escape = utils.escape; +var Base = require('./base'); +var utils = require('../utils'); +var Progress = require('../browser/progress'); +var escapeRe = require('escape-string-regexp'); +var escape = utils.escape; /** * Save timer references to avoid Sinon interfering (see GH-237). */ -var Date = global.Date - , setTimeout = global.setTimeout - , setInterval = global.setInterval - , clearTimeout = global.clearTimeout - , clearInterval = global.clearInterval; +/* eslint-disable no-unused-vars, no-native-reassign */ +var Date = global.Date; +var setTimeout = global.setTimeout; +var setInterval = global.setInterval; +var clearTimeout = global.clearTimeout; +var clearInterval = global.clearInterval; +/* eslint-enable no-unused-vars, no-native-reassign */ /** - * Expose `Doc`. + * Expose `HTML`. */ exports = module.exports = HTML; @@ -1899,40 +2511,37 @@ exports = module.exports = HTML; * Stats template. */ -var statsTemplate = '
    ' +var statsTemplate = ''; /** - * Initialize a new `Doc` reporter. + * Initialize a new `HTML` reporter. * - * @param {Runner} runner * @api public + * @param {Runner} runner */ - -function HTML(runner, root) { +function HTML(runner) { Base.call(this, runner); - var self = this - , stats = this.stats - , total = runner.total - , stat = fragment(statsTemplate) - , items = stat.getElementsByTagName('li') - , passes = items[1].getElementsByTagName('em')[0] - , passesLink = items[1].getElementsByTagName('a')[0] - , failures = items[2].getElementsByTagName('em')[0] - , failuresLink = items[2].getElementsByTagName('a')[0] - , duration = items[3].getElementsByTagName('em')[0] - , canvas = stat.getElementsByTagName('canvas')[0] - , report = fragment('
      ') - , stack = [report] - , progress - , ctx - - root = root || document.getElementById('mocha'); + var self = this; + var stats = this.stats; + var stat = fragment(statsTemplate); + var items = stat.getElementsByTagName('li'); + var passes = items[1].getElementsByTagName('em')[0]; + var passesLink = items[1].getElementsByTagName('a')[0]; + var failures = items[2].getElementsByTagName('em')[0]; + var failuresLink = items[2].getElementsByTagName('a')[0]; + var duration = items[3].getElementsByTagName('em')[0]; + var canvas = stat.getElementsByTagName('canvas')[0]; + var report = fragment('
        '); + var stack = [report]; + var progress; + var ctx; + var root = document.getElementById('mocha'); if (canvas.getContext) { var ratio = window.devicePixelRatio || 1; @@ -1942,37 +2551,49 @@ function HTML(runner, root) { canvas.height *= ratio; ctx = canvas.getContext('2d'); ctx.scale(ratio, ratio); - progress = new Progress; + progress = new Progress(); } - if (!root) return error('#mocha div missing, add it to your document'); + if (!root) { + return error('#mocha div missing, add it to your document'); + } // pass toggle - on(passesLink, 'click', function(){ + on(passesLink, 'click', function(evt) { + evt.preventDefault(); unhide(); - var name = /pass/.test(report.className) ? '' : ' pass'; + var name = (/pass/).test(report.className) ? '' : ' pass'; report.className = report.className.replace(/fail|pass/g, '') + name; - if (report.className.trim()) hideSuitesWithout('test pass'); + if (report.className.trim()) { + hideSuitesWithout('test pass'); + } }); // failure toggle - on(failuresLink, 'click', function(){ + on(failuresLink, 'click', function(evt) { + evt.preventDefault(); unhide(); - var name = /fail/.test(report.className) ? '' : ' fail'; + var name = (/fail/).test(report.className) ? '' : ' fail'; report.className = report.className.replace(/fail|pass/g, '') + name; - if (report.className.trim()) hideSuitesWithout('test fail'); + if (report.className.trim()) { + hideSuitesWithout('test fail'); + } }); root.appendChild(stat); root.appendChild(report); - if (progress) progress.size(40); + if (progress) { + progress.size(40); + } - runner.on('suite', function(suite){ - if (suite.root) return; + runner.on('suite', function(suite) { + if (suite.root) { + return; + } // suite - var url = '?grep=' + encodeURIComponent(suite.fullTitle()); + var url = self.suiteURL(suite); var el = fragment('
      • %s

      • ', url, escape(suite.title)); // container @@ -1981,95 +2602,168 @@ function HTML(runner, root) { el.appendChild(stack[0]); }); - runner.on('suite end', function(suite){ - if (suite.root) return; + runner.on('suite end', function(suite) { + if (suite.root) { + return; + } stack.shift(); }); - runner.on('fail', function(test, err){ - if ('hook' == test.type || err.uncaught) runner.emit('test end', test); + runner.on('pass', function(test) { + var url = self.testURL(test); + var markup = '
      • %e%ems ' + + '‣

      • '; + var el = fragment(markup, test.speed, test.title, test.duration, url); + self.addCodeToggle(el, test.body); + appendToStack(el); + updateStats(); + }); + + runner.on('fail', function(test) { + var el = fragment('
      • %e ‣

      • ', + test.title, self.testURL(test)); + var stackString; // Note: Includes leading newline + var message = test.err.toString(); + + // <=IE7 stringifies to [Object Error]. Since it can be overloaded, we + // check for the result of the stringifying. + if (message === '[object Error]') { + message = test.err.message; + } + + if (test.err.stack) { + var indexOfMessage = test.err.stack.indexOf(test.err.message); + if (indexOfMessage === -1) { + stackString = test.err.stack; + } else { + stackString = test.err.stack.substr(test.err.message.length + indexOfMessage); + } + } else if (test.err.sourceURL && test.err.line !== undefined) { + // Safari doesn't give you a stack. Let's at least provide a source line. + stackString = '\n(' + test.err.sourceURL + ':' + test.err.line + ')'; + } + + stackString = stackString || ''; + + if (test.err.htmlMessage && stackString) { + el.appendChild(fragment('
        %s\n
        %e
        ', + test.err.htmlMessage, stackString)); + } else if (test.err.htmlMessage) { + el.appendChild(fragment('
        %s
        ', test.err.htmlMessage)); + } else { + el.appendChild(fragment('
        %e%e
        ', message, stackString)); + } + + self.addCodeToggle(el, test.body); + appendToStack(el); + updateStats(); + }); + + runner.on('pending', function(test) { + var el = fragment('
      • %e

      • ', test.title); + appendToStack(el); + updateStats(); }); - runner.on('test end', function(test){ - window.scrollTo(0, document.body.scrollHeight); + function appendToStack(el) { + // Don't call .appendChild if #mocha-report was already .shift()'ed off the stack. + if (stack[0]) { + stack[0].appendChild(el); + } + } + function updateStats() { // TODO: add to stats - var percent = stats.tests / total * 100 | 0; - if (progress) progress.update(percent).draw(ctx); + var percent = stats.tests / this.total * 100 | 0; + if (progress) { + progress.update(percent).draw(ctx); + } // update stats - var ms = new Date - stats.start; + var ms = new Date() - stats.start; text(passes, stats.passes); text(failures, stats.failures); text(duration, (ms / 1000).toFixed(2)); + } +} - // test - if ('passed' == test.state) { - var el = fragment('
      • %e%ems ‣

      • ', test.speed, test.title, test.duration, test.fullTitle()); - } else if (test.pending) { - var el = fragment('
      • %e

      • ', test.title); - } else { - var el = fragment('
      • %e ‣

      • ', test.title, test.fullTitle()); - var str = test.err.stack || test.err.toString(); - - // FF / Opera do not add the message - if (!~str.indexOf(test.err.message)) { - str = test.err.message + '\n' + str; - } - - // <=IE7 stringifies to [Object Error]. Since it can be overloaded, we - // check for the result of the stringifying. - if ('[object Error]' == str) str = test.err.message; +/** + * Makes a URL, preserving querystring ("search") parameters. + * + * @param {string} s + * @return {string} A new URL. + */ +function makeUrl(s) { + var search = window.location.search; - // Safari doesn't give you a stack. Let's at least provide a source line. - if (!test.err.stack && test.err.sourceURL && test.err.line !== undefined) { - str += "\n(" + test.err.sourceURL + ":" + test.err.line + ")"; - } + // Remove previous grep query parameter if present + if (search) { + search = search.replace(/[?&]grep=[^&\s]*/g, '').replace(/^&/, '?'); + } - el.appendChild(fragment('
        %e
        ', str)); - } + return window.location.pathname + (search ? search + '&' : '?') + 'grep=' + encodeURIComponent(escapeRe(s)); +} - // toggle code - // TODO: defer - if (!test.pending) { - var h2 = el.getElementsByTagName('h2')[0]; +/** + * Provide suite URL. + * + * @param {Object} [suite] + */ +HTML.prototype.suiteURL = function(suite) { + return makeUrl(suite.fullTitle()); +}; - on(h2, 'click', function(){ - pre.style.display = 'none' == pre.style.display - ? 'inline-block' - : 'none'; - }); +/** + * Provide test URL. + * + * @param {Object} [test] + */ +HTML.prototype.testURL = function(test) { + return makeUrl(test.fullTitle()); +}; - var pre = fragment('
        %e
        ', utils.clean(test.fn.toString())); - el.appendChild(pre); - pre.style.display = 'none'; - } +/** + * Adds code toggle functionality for the provided test's list element. + * + * @param {HTMLLIElement} el + * @param {string} contents + */ +HTML.prototype.addCodeToggle = function(el, contents) { + var h2 = el.getElementsByTagName('h2')[0]; - stack[0].appendChild(el); + on(h2, 'click', function() { + pre.style.display = pre.style.display === 'none' ? 'block' : 'none'; }); -} + + var pre = fragment('
        %e
        ', utils.clean(contents)); + el.appendChild(pre); + pre.style.display = 'none'; +}; /** * Display error `msg`. + * + * @param {string} msg */ - function error(msg) { - document.body.appendChild(fragment('
        %s
        ', msg)); + document.body.appendChild(fragment('
        %s
        ', msg)); } /** * Return a DOM fragment from `html`. + * + * @param {string} html */ - function fragment(html) { - var args = arguments - , div = document.createElement('div') - , i = 1; + var args = arguments; + var div = document.createElement('div'); + var i = 1; - div.innerHTML = html.replace(/%([se])/g, function(_, type){ + div.innerHTML = html.replace(/%([se])/g, function(_, type) { switch (type) { case 's': return String(args[i++]); case 'e': return escape(args[i++]); + // no default } }); @@ -2079,20 +2773,22 @@ function fragment(html) { /** * Check for suites that do not have elements * with `classname`, and hide them. + * + * @param {text} classname */ - function hideSuitesWithout(classname) { var suites = document.getElementsByClassName('suite'); for (var i = 0; i < suites.length; i++) { var els = suites[i].getElementsByClassName(classname); - if (0 == els.length) suites[i].className += ' hidden'; + if (!els.length) { + suites[i].className += ' hidden'; + } } } /** * Unhide .hidden suites. */ - function unhide() { var els = document.getElementsByClassName('suite hidden'); for (var i = 0; i < els.length; ++i) { @@ -2101,21 +2797,22 @@ function unhide() { } /** - * Set `el` text to `str`. + * Set an element's text contents. + * + * @param {HTMLElement} el + * @param {string} contents */ - -function text(el, str) { +function text(el, contents) { if (el.textContent) { - el.textContent = str; + el.textContent = contents; } else { - el.innerText = str; + el.innerText = contents; } } /** * Listen on `event` with callback `fn`. */ - function on(el, event, fn) { if (el.addEventListener) { el.addEventListener(event, fn, false); @@ -2124,33 +2821,30 @@ function on(el, event, fn) { } } -}); // module: reporters/html.js - -require.register("reporters/index.js", function(module, exports, require){ - -exports.Base = require('./base'); -exports.Dot = require('./dot'); -exports.Doc = require('./doc'); -exports.TAP = require('./tap'); -exports.JSON = require('./json'); -exports.HTML = require('./html'); -exports.List = require('./list'); -exports.Min = require('./min'); -exports.Spec = require('./spec'); -exports.Nyan = require('./nyan'); -exports.XUnit = require('./xunit'); -exports.Markdown = require('./markdown'); -exports.Progress = require('./progress'); -exports.Landing = require('./landing'); -exports.JSONCov = require('./json-cov'); -exports.HTMLCov = require('./html-cov'); -exports.JSONStream = require('./json-stream'); -exports.Teamcity = require('./teamcity'); - -}); // module: reporters/index.js - -require.register("reporters/json-cov.js", function(module, exports, require){ - +}).call(this,typeof global !== "undefined" ? global : typeof self !== "undefined" ? self : typeof window !== "undefined" ? window : {}) +},{"../browser/progress":4,"../utils":39,"./base":17,"escape-string-regexp":49}],22:[function(require,module,exports){ +// Alias exports to a their normalized format Mocha#reporter to prevent a need +// for dynamic (try/catch) requires, which Browserify doesn't handle. +exports.Base = exports.base = require('./base'); +exports.Dot = exports.dot = require('./dot'); +exports.Doc = exports.doc = require('./doc'); +exports.TAP = exports.tap = require('./tap'); +exports.JSON = exports.json = require('./json'); +exports.HTML = exports.html = require('./html'); +exports.List = exports.list = require('./list'); +exports.Min = exports.min = require('./min'); +exports.Spec = exports.spec = require('./spec'); +exports.Nyan = exports.nyan = require('./nyan'); +exports.XUnit = exports.xunit = require('./xunit'); +exports.Markdown = exports.markdown = require('./markdown'); +exports.Progress = exports.progress = require('./progress'); +exports.Landing = exports.landing = require('./landing'); +exports.JSONCov = exports['json-cov'] = require('./json-cov'); +exports.HTMLCov = exports['html-cov'] = require('./html-cov'); +exports.JSONStream = exports['json-stream'] = require('./json-stream'); + +},{"./base":17,"./doc":18,"./dot":19,"./html":21,"./html-cov":20,"./json":25,"./json-cov":23,"./json-stream":24,"./landing":26,"./list":27,"./markdown":28,"./min":29,"./nyan":30,"./progress":31,"./spec":32,"./tap":33,"./xunit":34}],23:[function(require,module,exports){ +(function (process,global){ /** * Module dependencies. */ @@ -2166,42 +2860,42 @@ exports = module.exports = JSONCov; /** * Initialize a new `JsCoverage` reporter. * - * @param {Runner} runner - * @param {Boolean} output * @api public + * @param {Runner} runner + * @param {boolean} output */ - function JSONCov(runner, output) { - var self = this - , output = 1 == arguments.length ? true : output; - Base.call(this, runner); - var tests = [] - , failures = [] - , passes = []; + output = arguments.length === 1 || output; + var self = this; + var tests = []; + var failures = []; + var passes = []; - runner.on('test end', function(test){ + runner.on('test end', function(test) { tests.push(test); }); - runner.on('pass', function(test){ + runner.on('pass', function(test) { passes.push(test); }); - runner.on('fail', function(test){ + runner.on('fail', function(test) { failures.push(test); }); - runner.on('end', function(){ + runner.on('end', function() { var cov = global._$jscoverage || {}; var result = self.cov = map(cov); result.stats = self.stats; result.tests = tests.map(clean); result.failures = failures.map(clean); result.passes = passes.map(clean); - if (!output) return; - process.stdout.write(JSON.stringify(result, null, 2 )); + if (!output) { + return; + } + process.stdout.write(JSON.stringify(result, null, 2)); }); } @@ -2209,46 +2903,51 @@ function JSONCov(runner, output) { * Map jscoverage data to a JSON structure * suitable for reporting. * + * @api private * @param {Object} cov * @return {Object} - * @api private */ function map(cov) { var ret = { - instrumentation: 'node-jscoverage' - , sloc: 0 - , hits: 0 - , misses: 0 - , coverage: 0 - , files: [] + instrumentation: 'node-jscoverage', + sloc: 0, + hits: 0, + misses: 0, + coverage: 0, + files: [] }; for (var filename in cov) { - var data = coverage(filename, cov[filename]); - ret.files.push(data); - ret.hits += data.hits; - ret.misses += data.misses; - ret.sloc += data.sloc; + if (Object.prototype.hasOwnProperty.call(cov, filename)) { + var data = coverage(filename, cov[filename]); + ret.files.push(data); + ret.hits += data.hits; + ret.misses += data.misses; + ret.sloc += data.sloc; + } } + ret.files.sort(function(a, b) { + return a.filename.localeCompare(b.filename); + }); + if (ret.sloc > 0) { ret.coverage = (ret.hits / ret.sloc) * 100; } return ret; -}; +} /** * Map jscoverage data for a single source file * to a JSON structure suitable for reporting. * - * @param {String} filename name of the source file + * @api private + * @param {string} filename name of the source file * @param {Object} data jscoverage coverage data * @return {Object} - * @api private */ - function coverage(filename, data) { var ret = { filename: filename, @@ -2259,7 +2958,7 @@ function coverage(filename, data) { source: {} }; - data.source.forEach(function(line, num){ + data.source.forEach(function(line, num) { num++; if (data[num] === 0) { @@ -2271,10 +2970,8 @@ function coverage(filename, data) { } ret.source[num] = { - source: line - , coverage: data[num] === undefined - ? '' - : data[num] + source: line, + coverage: data[num] === undefined ? '' : data[num] }; }); @@ -2287,29 +2984,27 @@ function coverage(filename, data) { * Return a plain-object representation of `test` * free of cyclic properties etc. * + * @api private * @param {Object} test * @return {Object} - * @api private */ - function clean(test) { return { - title: test.title - , fullTitle: test.fullTitle() - , duration: test.duration - } + duration: test.duration, + currentRetry: test.currentRetry(), + fullTitle: test.fullTitle(), + title: test.title + }; } -}); // module: reporters/json-cov.js - -require.register("reporters/json-stream.js", function(module, exports, require){ - +}).call(this,require('_process'),typeof global !== "undefined" ? global : typeof self !== "undefined" ? self : typeof window !== "undefined" ? window : {}) +},{"./base":17,"_process":58}],24:[function(require,module,exports){ +(function (process){ /** * Module dependencies. */ -var Base = require('./base') - , color = Base.color; +var Base = require('./base'); /** * Expose `List`. @@ -2320,30 +3015,31 @@ exports = module.exports = List; /** * Initialize a new `List` test reporter. * - * @param {Runner} runner * @api public + * @param {Runner} runner */ - function List(runner) { Base.call(this, runner); - var self = this - , stats = this.stats - , total = runner.total; + var self = this; + var total = runner.total; - runner.on('start', function(){ + runner.on('start', function() { console.log(JSON.stringify(['start', { total: total }])); }); - runner.on('pass', function(test){ + runner.on('pass', function(test) { console.log(JSON.stringify(['pass', clean(test)])); }); - runner.on('fail', function(test, err){ - console.log(JSON.stringify(['fail', clean(test)])); + runner.on('fail', function(test, err) { + test = clean(test); + test.err = err.message; + test.stack = err.stack || null; + console.log(JSON.stringify(['fail', test])); }); - runner.on('end', function(){ + runner.on('end', function() { process.stdout.write(JSON.stringify(['end', self.stats])); }); } @@ -2352,29 +3048,27 @@ function List(runner) { * Return a plain-object representation of `test` * free of cyclic properties etc. * + * @api private * @param {Object} test * @return {Object} - * @api private */ - function clean(test) { return { - title: test.title - , fullTitle: test.fullTitle() - , duration: test.duration - } + title: test.title, + fullTitle: test.fullTitle(), + duration: test.duration, + currentRetry: test.currentRetry() + }; } -}); // module: reporters/json-stream.js - -require.register("reporters/json.js", function(module, exports, require){ +}).call(this,require('_process')) +},{"./base":17,"_process":58}],25:[function(require,module,exports){ +(function (process){ /** * Module dependencies. */ -var Base = require('./base') - , cursor = Base.cursor - , color = Base.color; +var Base = require('./base'); /** * Expose `JSON`. @@ -2385,38 +3079,45 @@ exports = module.exports = JSONReporter; /** * Initialize a new `JSON` reporter. * - * @param {Runner} runner * @api public + * @param {Runner} runner */ - function JSONReporter(runner) { - var self = this; Base.call(this, runner); - var tests = [] - , failures = [] - , passes = []; + var self = this; + var tests = []; + var pending = []; + var failures = []; + var passes = []; - runner.on('test end', function(test){ + runner.on('test end', function(test) { tests.push(test); }); - runner.on('pass', function(test){ + runner.on('pass', function(test) { passes.push(test); }); - runner.on('fail', function(test){ + runner.on('fail', function(test) { failures.push(test); }); - runner.on('end', function(){ + runner.on('pending', function(test) { + pending.push(test); + }); + + runner.on('end', function() { var obj = { - stats: self.stats - , tests: tests.map(clean) - , failures: failures.map(clean) - , passes: passes.map(clean) + stats: self.stats, + tests: tests.map(clean), + pending: pending.map(clean), + failures: failures.map(clean), + passes: passes.map(clean) }; + runner.testResults = obj; + process.stdout.write(JSON.stringify(obj, null, 2)); }); } @@ -2425,29 +3126,46 @@ function JSONReporter(runner) { * Return a plain-object representation of `test` * free of cyclic properties etc. * + * @api private * @param {Object} test * @return {Object} - * @api private */ - function clean(test) { return { - title: test.title - , fullTitle: test.fullTitle() - , duration: test.duration - } + title: test.title, + fullTitle: test.fullTitle(), + duration: test.duration, + currentRetry: test.currentRetry(), + err: errorJSON(test.err || {}) + }; } -}); // module: reporters/json.js -require.register("reporters/landing.js", function(module, exports, require){ +/** + * Transform `error` into a JSON object. + * + * @api private + * @param {Error} err + * @return {Object} + */ +function errorJSON(err) { + var res = {}; + Object.getOwnPropertyNames(err).forEach(function(key) { + res[key] = err[key]; + }, err); + return res; +} +}).call(this,require('_process')) +},{"./base":17,"_process":58}],26:[function(require,module,exports){ +(function (process){ /** * Module dependencies. */ -var Base = require('./base') - , cursor = Base.cursor - , color = Base.color; +var Base = require('./base'); +var inherits = require('../utils').inherits; +var cursor = Base.cursor; +var color = Base.color; /** * Expose `Landing`. @@ -2476,56 +3194,52 @@ Base.colors.runway = 90; /** * Initialize a new `Landing` reporter. * - * @param {Runner} runner * @api public + * @param {Runner} runner */ - function Landing(runner) { Base.call(this, runner); - var self = this - , stats = this.stats - , width = Base.window.width * .75 | 0 - , total = runner.total - , stream = process.stdout - , plane = color('plane', '✈') - , crashed = -1 - , n = 0; + var self = this; + var width = Base.window.width * .75 | 0; + var total = runner.total; + var stream = process.stdout; + var plane = color('plane', '✈'); + var crashed = -1; + var n = 0; function runway() { var buf = Array(width).join('-'); return ' ' + color('runway', buf); } - runner.on('start', function(){ - stream.write('\n '); + runner.on('start', function() { + stream.write('\n\n\n '); cursor.hide(); }); - runner.on('test end', function(test){ + runner.on('test end', function(test) { // check if the plane crashed - var col = -1 == crashed - ? width * ++n / total | 0 - : crashed; + var col = crashed === -1 ? width * ++n / total | 0 : crashed; // show the crash - if ('failed' == test.state) { + if (test.state === 'failed') { plane = color('plane crash', '✈'); crashed = col; } // render landing strip - stream.write('\u001b[4F\n\n'); + stream.write('\u001b[' + (width + 1) + 'D\u001b[2A'); stream.write(runway()); stream.write('\n '); stream.write(color('runway', Array(col).join('⋅'))); - stream.write(plane) + stream.write(plane); stream.write(color('runway', Array(width - col).join('⋅') + '\n')); stream.write(runway()); stream.write('\u001b[0m'); }); - runner.on('end', function(){ + runner.on('end', function() { cursor.show(); console.log(); self.epilogue(); @@ -2535,21 +3249,19 @@ function Landing(runner) { /** * Inherit from `Base.prototype`. */ +inherits(Landing, Base); -Landing.prototype = new Base; -Landing.prototype.constructor = Landing; - -}); // module: reporters/landing.js - -require.register("reporters/list.js", function(module, exports, require){ - +}).call(this,require('_process')) +},{"../utils":39,"./base":17,"_process":58}],27:[function(require,module,exports){ +(function (process){ /** * Module dependencies. */ -var Base = require('./base') - , cursor = Base.cursor - , color = Base.color; +var Base = require('./base'); +var inherits = require('../utils').inherits; +var color = Base.color; +var cursor = Base.cursor; /** * Expose `List`. @@ -2560,40 +3272,38 @@ exports = module.exports = List; /** * Initialize a new `List` test reporter. * - * @param {Runner} runner * @api public + * @param {Runner} runner */ - function List(runner) { Base.call(this, runner); - var self = this - , stats = this.stats - , n = 0; + var self = this; + var n = 0; - runner.on('start', function(){ + runner.on('start', function() { console.log(); }); - runner.on('test', function(test){ + runner.on('test', function(test) { process.stdout.write(color('pass', ' ' + test.fullTitle() + ': ')); }); - runner.on('pending', function(test){ + runner.on('pending', function(test) { var fmt = color('checkmark', ' -') + color('pending', ' %s'); console.log(fmt, test.fullTitle()); }); - runner.on('pass', function(test){ - var fmt = color('checkmark', ' ✓') + runner.on('pass', function(test) { + var fmt = color('checkmark', ' ' + Base.symbols.dot) + color('pass', ' %s: ') + color(test.speed, '%dms'); cursor.CR(); console.log(fmt, test.fullTitle(), test.duration); }); - runner.on('fail', function(test, err){ + runner.on('fail', function(test) { cursor.CR(); console.log(color('fail', ' %d) %s'), ++n, test.fullTitle()); }); @@ -2604,20 +3314,23 @@ function List(runner) { /** * Inherit from `Base.prototype`. */ +inherits(List, Base); -List.prototype = new Base; -List.prototype.constructor = List; - +}).call(this,require('_process')) +},{"../utils":39,"./base":17,"_process":58}],28:[function(require,module,exports){ +(function (process){ +/** + * Module dependencies. + */ -}); // module: reporters/list.js +var Base = require('./base'); +var utils = require('../utils'); -require.register("reporters/markdown.js", function(module, exports, require){ /** - * Module dependencies. + * Constants */ -var Base = require('./base') - , utils = require('../utils'); +var SUITE_PREFIX = '$'; /** * Expose `Markdown`. @@ -2628,33 +3341,28 @@ exports = module.exports = Markdown; /** * Initialize a new `Markdown` reporter. * - * @param {Runner} runner * @api public + * @param {Runner} runner */ - function Markdown(runner) { Base.call(this, runner); - var self = this - , stats = this.stats - , total = runner.total - , level = 0 - , buf = ''; + var level = 0; + var buf = ''; function title(str) { return Array(level).join('#') + ' ' + str; } - function indent() { - return Array(level).join(' '); - } - function mapTOC(suite, obj) { var ret = obj; - obj = obj[suite.title] = obj[suite.title] || { suite: suite }; - suite.suites.forEach(function(suite){ + var key = SUITE_PREFIX + suite.title; + + obj = obj[key] = obj[key] || { suite: suite }; + suite.suites.forEach(function(suite) { mapTOC(suite, obj); }); + return ret; } @@ -2663,12 +3371,16 @@ function Markdown(runner) { var buf = ''; var link; for (var key in obj) { - if ('suite' == key) continue; - if (key) link = ' - [' + key + '](#' + utils.slug(obj[key].suite.fullTitle()) + ')\n'; - if (key) buf += Array(level).join(' ') + link; + if (key === 'suite') { + continue; + } + if (key !== SUITE_PREFIX) { + link = ' - [' + key.substring(1) + ']'; + link += '(#' + utils.slug(obj[key].suite.fullTitle()) + ')\n'; + buf += Array(level).join(' ') + link; + } buf += stringifyTOC(obj[key], level); } - --level; return buf; } @@ -2679,40 +3391,41 @@ function Markdown(runner) { generateTOC(runner.suite); - runner.on('suite', function(suite){ + runner.on('suite', function(suite) { ++level; var slug = utils.slug(suite.fullTitle()); - buf += '' + '\n'; + buf += '' + '\n'; buf += title(suite.title) + '\n'; }); - runner.on('suite end', function(suite){ + runner.on('suite end', function() { --level; }); - runner.on('pass', function(test){ - var code = utils.clean(test.fn.toString()); + runner.on('pass', function(test) { + var code = utils.clean(test.body); buf += test.title + '.\n'; buf += '\n```js\n'; buf += code + '\n'; buf += '```\n\n'; }); - runner.on('end', function(){ + runner.on('end', function() { process.stdout.write('# TOC\n'); process.stdout.write(generateTOC(runner.suite)); process.stdout.write(buf); }); } -}); // module: reporters/markdown.js - -require.register("reporters/min.js", function(module, exports, require){ +}).call(this,require('_process')) +},{"../utils":39,"./base":17,"_process":58}],29:[function(require,module,exports){ +(function (process){ /** * Module dependencies. */ var Base = require('./base'); +var inherits = require('../utils').inherits; /** * Expose `Min`. @@ -2723,14 +3436,13 @@ exports = module.exports = Min; /** * Initialize a new `Min` minimal test reporter (best used with --watch). * - * @param {Runner} runner * @api public + * @param {Runner} runner */ - function Min(runner) { Base.call(this, runner); - - runner.on('start', function(){ + + runner.on('start', function() { // clear screen process.stdout.write('\u001b[2J'); // set cursor position @@ -2743,20 +3455,17 @@ function Min(runner) { /** * Inherit from `Base.prototype`. */ +inherits(Min, Base); -Min.prototype = new Base; -Min.prototype.constructor = Min; - -}); // module: reporters/min.js - -require.register("reporters/nyan.js", function(module, exports, require){ - +}).call(this,require('_process')) +},{"../utils":39,"./base":17,"_process":58}],30:[function(require,module,exports){ +(function (process){ /** * Module dependencies. */ -var Base = require('./base') - , color = Base.color; +var Base = require('./base'); +var inherits = require('../utils').inherits; /** * Expose `Dot`. @@ -2774,55 +3483,60 @@ exports = module.exports = NyanCat; function NyanCat(runner) { Base.call(this, runner); - var self = this - , stats = this.stats - , width = Base.window.width * .75 | 0 - , rainbowColors = this.rainbowColors = self.generateColors() - , colorIndex = this.colorIndex = 0 - , numerOfLines = this.numberOfLines = 4 - , trajectories = this.trajectories = [[], [], [], []] - , nyanCatWidth = this.nyanCatWidth = 11 - , trajectoryWidthMax = this.trajectoryWidthMax = (width - nyanCatWidth) - , scoreboardWidth = this.scoreboardWidth = 5 - , tick = this.tick = 0 - , n = 0; - - runner.on('start', function(){ + var self = this; + var width = Base.window.width * .75 | 0; + var nyanCatWidth = this.nyanCatWidth = 11; + + this.colorIndex = 0; + this.numberOfLines = 4; + this.rainbowColors = self.generateColors(); + this.scoreboardWidth = 5; + this.tick = 0; + this.trajectories = [[], [], [], []]; + this.trajectoryWidthMax = (width - nyanCatWidth); + + runner.on('start', function() { Base.cursor.hide(); - self.draw('start'); + self.draw(); }); - runner.on('pending', function(test){ - self.draw('pending'); + runner.on('pending', function() { + self.draw(); }); - runner.on('pass', function(test){ - self.draw('pass'); + runner.on('pass', function() { + self.draw(); }); - runner.on('fail', function(test, err){ - self.draw('fail'); + runner.on('fail', function() { + self.draw(); }); - runner.on('end', function(){ + runner.on('end', function() { Base.cursor.show(); - for (var i = 0; i < self.numberOfLines; i++) write('\n'); + for (var i = 0; i < self.numberOfLines; i++) { + write('\n'); + } self.epilogue(); }); } /** - * Draw the nyan cat with runner `status`. + * Inherit from `Base.prototype`. + */ +inherits(NyanCat, Base); + +/** + * Draw the nyan cat * - * @param {String} status * @api private */ -NyanCat.prototype.draw = function(status){ +NyanCat.prototype.draw = function() { this.appendRainbow(); this.drawScoreboard(); this.drawRainbow(); - this.drawNyanCat(status); + this.drawNyanCat(); this.tick = !this.tick; }; @@ -2833,19 +3547,18 @@ NyanCat.prototype.draw = function(status){ * @api private */ -NyanCat.prototype.drawScoreboard = function(){ +NyanCat.prototype.drawScoreboard = function() { var stats = this.stats; - var colors = Base.colors; - function draw(color, n) { + function draw(type, n) { write(' '); - write('\u001b[' + color + 'm' + n + '\u001b[0m'); + write(Base.color(type, n)); write('\n'); } - draw(colors.green, stats.passes); - draw(colors.fail, stats.failures); - draw(colors.pending, stats.pending); + draw('green', stats.passes); + draw('fail', stats.failures); + draw('pending', stats.pending); write('\n'); this.cursorUp(this.numberOfLines); @@ -2857,13 +3570,15 @@ NyanCat.prototype.drawScoreboard = function(){ * @api private */ -NyanCat.prototype.appendRainbow = function(){ +NyanCat.prototype.appendRainbow = function() { var segment = this.tick ? '_' : '-'; var rainbowified = this.rainbowify(segment); for (var index = 0; index < this.numberOfLines; index++) { var trajectory = this.trajectories[index]; - if (trajectory.length >= this.trajectoryWidthMax) trajectory.shift(); + if (trajectory.length >= this.trajectoryWidthMax) { + trajectory.shift(); + } trajectory.push(rainbowified); } }; @@ -2874,10 +3589,10 @@ NyanCat.prototype.appendRainbow = function(){ * @api private */ -NyanCat.prototype.drawRainbow = function(){ +NyanCat.prototype.drawRainbow = function() { var self = this; - this.trajectories.forEach(function(line, index) { + this.trajectories.forEach(function(line) { write('\u001b[' + self.scoreboardWidth + 'C'); write(line.join('')); write('\n'); @@ -2887,62 +3602,63 @@ NyanCat.prototype.drawRainbow = function(){ }; /** - * Draw the nyan cat with `status`. + * Draw the nyan cat * - * @param {String} status * @api private */ - -NyanCat.prototype.drawNyanCat = function(status) { +NyanCat.prototype.drawNyanCat = function() { var self = this; var startWidth = this.scoreboardWidth + this.trajectories[0].length; + var dist = '\u001b[' + startWidth + 'C'; + var padding = ''; - [0, 1, 2, 3].forEach(function(index) { - write('\u001b[' + startWidth + 'C'); + write(dist); + write('_,------,'); + write('\n'); - switch (index) { - case 0: - write('_,------,'); - write('\n'); - break; - case 1: - var padding = self.tick ? ' ' : ' '; - write('_|' + padding + '/\\_/\\ '); - write('\n'); - break; - case 2: - var padding = self.tick ? '_' : '__'; - var tail = self.tick ? '~' : '^'; - var face; - switch (status) { - case 'pass': - face = '( ^ .^)'; - break; - case 'fail': - face = '( o .o)'; - break; - default: - face = '( - .-)'; - } - write(tail + '|' + padding + face + ' '); - write('\n'); - break; - case 3: - var padding = self.tick ? ' ' : ' '; - write(padding + '"" "" '); - write('\n'); - break; - } - }); + write(dist); + padding = self.tick ? ' ' : ' '; + write('_|' + padding + '/\\_/\\ '); + write('\n'); + + write(dist); + padding = self.tick ? '_' : '__'; + var tail = self.tick ? '~' : '^'; + write(tail + '|' + padding + this.face() + ' '); + write('\n'); + + write(dist); + padding = self.tick ? ' ' : ' '; + write(padding + '"" "" '); + write('\n'); this.cursorUp(this.numberOfLines); }; +/** + * Draw nyan cat face. + * + * @api private + * @return {string} + */ + +NyanCat.prototype.face = function() { + var stats = this.stats; + if (stats.failures) { + return '( x .x)'; + } else if (stats.pending) { + return '( o .o)'; + } else if (stats.passes) { + return '( ^ .^)'; + } + return '( - .-)'; +}; + /** * Move cursor up `n`. * - * @param {Number} n * @api private + * @param {number} n */ NyanCat.prototype.cursorUp = function(n) { @@ -2952,8 +3668,8 @@ NyanCat.prototype.cursorUp = function(n) { /** * Move cursor down `n`. * - * @param {Number} n * @api private + * @param {number} n */ NyanCat.prototype.cursorDown = function(n) { @@ -2963,11 +3679,10 @@ NyanCat.prototype.cursorDown = function(n) { /** * Generate rainbow colors. * - * @return {Array} * @api private + * @return {Array} */ - -NyanCat.prototype.generateColors = function(){ +NyanCat.prototype.generateColors = function() { var colors = []; for (var i = 0; i < (6 * 7); i++) { @@ -2985,12 +3700,14 @@ NyanCat.prototype.generateColors = function(){ /** * Apply rainbow to the given `str`. * - * @param {String} str - * @return {String} * @api private + * @param {string} str + * @return {string} */ - -NyanCat.prototype.rainbowify = function(str){ +NyanCat.prototype.rainbowify = function(str) { + if (!Base.useColors) { + return str; + } var color = this.rainbowColors[this.colorIndex % this.rainbowColors.length]; this.colorIndex += 1; return '\u001b[38;5;' + color + 'm' + str + '\u001b[0m'; @@ -2998,31 +3715,24 @@ NyanCat.prototype.rainbowify = function(str){ /** * Stdout helper. + * + * @param {string} string A message to write to stdout. */ - function write(string) { process.stdout.write(string); } -/** - * Inherit from `Base.prototype`. - */ - -NyanCat.prototype = new Base; -NyanCat.prototype.constructor = NyanCat; - - -}); // module: reporters/nyan.js - -require.register("reporters/progress.js", function(module, exports, require){ - +}).call(this,require('_process')) +},{"../utils":39,"./base":17,"_process":58}],31:[function(require,module,exports){ +(function (process){ /** * Module dependencies. */ -var Base = require('./base') - , cursor = Base.cursor - , color = Base.color; +var Base = require('./base'); +var inherits = require('../utils').inherits; +var color = Base.color; +var cursor = Base.cursor; /** * Expose `Progress`. @@ -3039,42 +3749,46 @@ Base.colors.progress = 90; /** * Initialize a new `Progress` bar test reporter. * + * @api public * @param {Runner} runner * @param {Object} options - * @api public */ - function Progress(runner, options) { Base.call(this, runner); - var self = this - , options = options || {} - , stats = this.stats - , width = Base.window.width * .50 | 0 - , total = runner.total - , complete = 0 - , max = Math.max; + var self = this; + var width = Base.window.width * .50 | 0; + var total = runner.total; + var complete = 0; + var lastN = -1; // default chars + options = options || {}; options.open = options.open || '['; options.complete = options.complete || '▬'; - options.incomplete = options.incomplete || '⋅'; + options.incomplete = options.incomplete || Base.symbols.dot; options.close = options.close || ']'; options.verbose = false; // tests started - runner.on('start', function(){ + runner.on('start', function() { console.log(); cursor.hide(); }); // tests complete - runner.on('test end', function(){ + runner.on('test end', function() { complete++; - var incomplete = total - complete - , percent = complete / total - , n = width * percent | 0 - , i = width - n; + + var percent = complete / total; + var n = width * percent | 0; + var i = width - n; + + if (n === lastN && !options.verbose) { + // Don't re-render the line if it hasn't changed + return; + } + lastN = n; cursor.CR(); process.stdout.write('\u001b[J'); @@ -3089,7 +3803,7 @@ function Progress(runner, options) { // tests are complete, output some stats // and the failures if any - runner.on('end', function(){ + runner.on('end', function() { cursor.show(); console.log(); self.epilogue(); @@ -3099,22 +3813,18 @@ function Progress(runner, options) { /** * Inherit from `Base.prototype`. */ +inherits(Progress, Base); -Progress.prototype = new Base; -Progress.prototype.constructor = Progress; - - -}); // module: reporters/progress.js - -require.register("reporters/spec.js", function(module, exports, require){ - +}).call(this,require('_process')) +},{"../utils":39,"./base":17,"_process":58}],32:[function(require,module,exports){ /** * Module dependencies. */ -var Base = require('./base') - , cursor = Base.cursor - , color = Base.color; +var Base = require('./base'); +var inherits = require('../utils').inherits; +var color = Base.color; +var cursor = Base.cursor; /** * Expose `Spec`. @@ -3125,63 +3835,60 @@ exports = module.exports = Spec; /** * Initialize a new `Spec` test reporter. * - * @param {Runner} runner * @api public + * @param {Runner} runner */ - function Spec(runner) { Base.call(this, runner); - var self = this - , stats = this.stats - , indents = 0 - , n = 0; + var self = this; + var indents = 0; + var n = 0; function indent() { - return Array(indents).join(' ') + return Array(indents).join(' '); } - runner.on('start', function(){ + runner.on('start', function() { console.log(); }); - runner.on('suite', function(suite){ + runner.on('suite', function(suite) { ++indents; console.log(color('suite', '%s%s'), indent(), suite.title); }); - runner.on('suite end', function(suite){ + runner.on('suite end', function() { --indents; - if (1 == indents) console.log(); - }); - - runner.on('test', function(test){ - process.stdout.write(indent() + color('pass', ' ◦ ' + test.title + ': ')); + if (indents === 1) { + console.log(); + } }); - runner.on('pending', function(test){ + runner.on('pending', function(test) { var fmt = indent() + color('pending', ' - %s'); console.log(fmt, test.title); }); - runner.on('pass', function(test){ - if ('fast' == test.speed) { - var fmt = indent() - + color('checkmark', ' ✓') - + color('pass', ' %s '); + runner.on('pass', function(test) { + var fmt; + if (test.speed === 'fast') { + fmt = indent() + + color('checkmark', ' ' + Base.symbols.ok) + + color('pass', ' %s'); cursor.CR(); console.log(fmt, test.title); } else { - var fmt = indent() - + color('checkmark', ' ✓') - + color('pass', ' %s ') - + color(test.speed, '(%dms)'); + fmt = indent() + + color('checkmark', ' ' + Base.symbols.ok) + + color('pass', ' %s') + + color(test.speed, ' (%dms)'); cursor.CR(); console.log(fmt, test.title, test.duration); } }); - runner.on('fail', function(test, err){ + runner.on('fail', function(test) { cursor.CR(); console.log(indent() + color('fail', ' %d) %s'), ++n, test.title); }); @@ -3192,22 +3899,14 @@ function Spec(runner) { /** * Inherit from `Base.prototype`. */ +inherits(Spec, Base); -Spec.prototype = new Base; -Spec.prototype.constructor = Spec; - - -}); // module: reporters/spec.js - -require.register("reporters/tap.js", function(module, exports, require){ - +},{"../utils":39,"./base":17}],33:[function(require,module,exports){ /** * Module dependencies. */ -var Base = require('./base') - , cursor = Base.cursor - , color = Base.color; +var Base = require('./base'); /** * Expose `TAP`. @@ -3218,263 +3917,260 @@ exports = module.exports = TAP; /** * Initialize a new `TAP` reporter. * - * @param {Runner} runner * @api public + * @param {Runner} runner */ - function TAP(runner) { Base.call(this, runner); - var self = this - , stats = this.stats - , n = 1; + var n = 1; + var passes = 0; + var failures = 0; - runner.on('start', function(){ + runner.on('start', function() { var total = runner.grepTotal(runner.suite); console.log('%d..%d', 1, total); }); - runner.on('test end', function(){ + runner.on('test end', function() { ++n; }); - runner.on('pending', function(test){ + runner.on('pending', function(test) { console.log('ok %d %s # SKIP -', n, title(test)); }); - runner.on('pass', function(test){ + runner.on('pass', function(test) { + passes++; console.log('ok %d %s', n, title(test)); }); - runner.on('fail', function(test, err){ + runner.on('fail', function(test, err) { + failures++; console.log('not ok %d %s', n, title(test)); - console.log(err.stack.replace(/^/gm, ' ')); + if (err.stack) { + console.log(err.stack.replace(/^/gm, ' ')); + } + }); + + runner.on('end', function() { + console.log('# tests ' + (passes + failures)); + console.log('# pass ' + passes); + console.log('# fail ' + failures); }); } /** * Return a TAP-safe title of `test` * + * @api private * @param {Object} test * @return {String} - * @api private */ - function title(test) { return test.fullTitle().replace(/#/g, ''); } -}); // module: reporters/tap.js - -require.register("reporters/teamcity.js", function(module, exports, require){ - +},{"./base":17}],34:[function(require,module,exports){ +(function (process,global){ /** * Module dependencies. */ var Base = require('./base'); +var utils = require('../utils'); +var inherits = utils.inherits; +var fs = require('fs'); +var escape = utils.escape; +var mkdirp = require('mkdirp'); +var path = require('path'); + +/** + * Save timer references to avoid Sinon interfering (see GH-237). + */ + +/* eslint-disable no-unused-vars, no-native-reassign */ +var Date = global.Date; +var setTimeout = global.setTimeout; +var setInterval = global.setInterval; +var clearTimeout = global.clearTimeout; +var clearInterval = global.clearInterval; +/* eslint-enable no-unused-vars, no-native-reassign */ /** - * Expose `Teamcity`. + * Expose `XUnit`. */ -exports = module.exports = Teamcity; +exports = module.exports = XUnit; /** - * Initialize a new `Teamcity` reporter. + * Initialize a new `XUnit` reporter. * - * @param {Runner} runner * @api public + * @param {Runner} runner */ - -function Teamcity(runner) { +function XUnit(runner, options) { Base.call(this, runner); - var stats = this.stats; - runner.on('start', function() { - console.log("##teamcity[testSuiteStarted name='mocha.suite']"); - }); + var stats = this.stats; + var tests = []; + var self = this; - runner.on('test', function(test) { - console.log("##teamcity[testStarted name='" + escape(test.fullTitle()) + "']"); - }); + if (options.reporterOptions && options.reporterOptions.output) { + if (!fs.createWriteStream) { + throw new Error('file output not supported in browser'); + } + mkdirp.sync(path.dirname(options.reporterOptions.output)); + self.fileStream = fs.createWriteStream(options.reporterOptions.output); + } - runner.on('fail', function(test, err) { - console.log("##teamcity[testFailed name='" + escape(test.fullTitle()) + "' message='" + escape(err.message) + "']"); + runner.on('pending', function(test) { + tests.push(test); }); - runner.on('pending', function(test) { - console.log("##teamcity[testIgnored name='" + escape(test.fullTitle()) + "' message='pending']"); + runner.on('pass', function(test) { + tests.push(test); }); - runner.on('test end', function(test) { - console.log("##teamcity[testFinished name='" + escape(test.fullTitle()) + "' duration='" + test.duration + "']"); + runner.on('fail', function(test) { + tests.push(test); }); runner.on('end', function() { - console.log("##teamcity[testSuiteFinished name='mocha.suite' duration='" + stats.duration + "']"); + self.write(tag('testsuite', { + name: 'Mocha Tests', + tests: stats.tests, + failures: stats.failures, + errors: stats.failures, + skipped: stats.tests - stats.failures - stats.passes, + timestamp: (new Date()).toUTCString(), + time: (stats.duration / 1000) || 0 + }, false)); + + tests.forEach(function(t) { + self.test(t); + }); + + self.write(''); }); } /** - * Escape the given `str`. + * Inherit from `Base.prototype`. */ +inherits(XUnit, Base); -function escape(str) { - return str - .replace(/\|/g, "||") - .replace(/\n/g, "|n") - .replace(/\r/g, "|r") - .replace(/\[/g, "|[") - .replace(/\]/g, "|]") - .replace(/\u0085/g, "|x") - .replace(/\u2028/g, "|l") - .replace(/\u2029/g, "|p") - .replace(/'/g, "|'"); -} +/** + * Override done to close the stream (if it's a file). + * + * @param failures + * @param {Function} fn + */ +XUnit.prototype.done = function(failures, fn) { + if (this.fileStream) { + this.fileStream.end(function() { + fn(failures); + }); + } else { + fn(failures); + } +}; + +/** + * Write out the given line. + * + * @param {string} line + */ +XUnit.prototype.write = function(line) { + if (this.fileStream) { + this.fileStream.write(line + '\n'); + } else if (typeof process === 'object' && process.stdout) { + process.stdout.write(line + '\n'); + } else { + console.log(line); + } +}; + +/** + * Output tag for the given `test.` + * + * @param {Test} test + */ +XUnit.prototype.test = function(test) { + var attrs = { + classname: test.parent.fullTitle(), + name: test.title, + time: (test.duration / 1000) || 0 + }; + + if (test.state === 'failed') { + var err = test.err; + this.write(tag('testcase', attrs, false, tag('failure', {}, false, escape(err.message) + '\n' + escape(err.stack)))); + } else if (test.isPending()) { + this.write(tag('testcase', attrs, false, tag('skipped', {}, true))); + } else { + this.write(tag('testcase', attrs, true)); + } +}; -}); // module: reporters/teamcity.js +/** + * HTML tag helper. + * + * @param name + * @param attrs + * @param close + * @param content + * @return {string} + */ +function tag(name, attrs, close, content) { + var end = close ? '/>' : '>'; + var pairs = []; + var tag; + + for (var key in attrs) { + if (Object.prototype.hasOwnProperty.call(attrs, key)) { + pairs.push(key + '="' + escape(attrs[key]) + '"'); + } + } -require.register("reporters/xunit.js", function(module, exports, require){ + tag = '<' + name + (pairs.length ? ' ' + pairs.join(' ') : '') + end; + if (content) { + tag += content + ''); - }); -} - -/** - * Inherit from `Base.prototype`. - */ - -XUnit.prototype = new Base; -XUnit.prototype.constructor = XUnit; - - -/** - * Output tag for the given `test.` - */ - -function test(test) { - var attrs = { - classname: test.parent.fullTitle() - , name: test.title - , time: test.duration / 1000 - }; - - if ('failed' == test.state) { - var err = test.err; - attrs.message = escape(err.message); - console.log(tag('testcase', attrs, false, tag('failure', attrs, false, cdata(err.stack)))); - } else if (test.pending) { - console.log(tag('testcase', attrs, false, tag('skipped', {}, true))); - } else { - console.log(tag('testcase', attrs, true) ); - } -} - -/** - * HTML tag helper. - */ - -function tag(name, attrs, close, content) { - var end = close ? '/>' : '>' - , pairs = [] - , tag; - - for (var key in attrs) { - pairs.push(key + '="' + escape(attrs[key]) + '"'); - } - - tag = '<' + name + (pairs.length ? ' ' + pairs.join(' ') : '') + end; - if (content) tag += content + ''; -} - -}); // module: reporters/xunit.js - -require.register("runnable.js", function(module, exports, require){ - -/** - * Module dependencies. - */ - -var EventEmitter = require('browser/events').EventEmitter - , debug = require('browser/debug')('mocha:runnable') - , milliseconds = require('./ms'); - -/** - * Save timer references to avoid Sinon interfering (see GH-237). - */ - -var Date = global.Date - , setTimeout = global.setTimeout - , setInterval = global.setInterval - , clearTimeout = global.clearTimeout - , clearInterval = global.clearInterval; +var toString = Object.prototype.toString; /** * Expose `Runnable`. @@ -3488,68 +4184,140 @@ module.exports = Runnable; * @param {String} title * @param {Function} fn * @api private + * @param {string} title + * @param {Function} fn */ - function Runnable(title, fn) { this.title = title; this.fn = fn; + this.body = (fn || '').toString(); this.async = fn && fn.length; - this.sync = ! this.async; + this.sync = !this.async; this._timeout = 2000; this._slow = 75; + this._enableTimeouts = true; this.timedOut = false; + this._trace = new Error('done() called multiple times'); + this._retries = -1; + this._currentRetry = 0; + this.pending = false; } /** * Inherit from `EventEmitter.prototype`. */ - -Runnable.prototype = new EventEmitter; -Runnable.prototype.constructor = Runnable; - +inherits(Runnable, EventEmitter); /** * Set & get timeout `ms`. * - * @param {Number|String} ms - * @return {Runnable|Number} ms or self * @api private + * @param {number|string} ms + * @return {Runnable|number} ms or Runnable instance. */ - -Runnable.prototype.timeout = function(ms){ - if (0 == arguments.length) return this._timeout; - if ('string' == typeof ms) ms = milliseconds(ms); +Runnable.prototype.timeout = function(ms) { + if (!arguments.length) { + return this._timeout; + } + if (ms === 0) { + this._enableTimeouts = false; + } + if (typeof ms === 'string') { + ms = milliseconds(ms); + } debug('timeout %d', ms); this._timeout = ms; - if (this.timer) this.resetTimeout(); + if (this.timer) { + this.resetTimeout(); + } return this; }; /** * Set & get slow `ms`. * - * @param {Number|String} ms - * @return {Runnable|Number} ms or self * @api private + * @param {number|string} ms + * @return {Runnable|number} ms or Runnable instance. */ - -Runnable.prototype.slow = function(ms){ - if (0 === arguments.length) return this._slow; - if ('string' == typeof ms) ms = milliseconds(ms); +Runnable.prototype.slow = function(ms) { + if (!arguments.length) { + return this._slow; + } + if (typeof ms === 'string') { + ms = milliseconds(ms); + } debug('timeout %d', ms); this._slow = ms; return this; }; /** - * Return the full title generated by recursively - * concatenating the parent's full title. + * Set and get whether timeout is `enabled`. + * + * @api private + * @param {boolean} enabled + * @return {Runnable|boolean} enabled or Runnable instance. + */ +Runnable.prototype.enableTimeouts = function(enabled) { + if (!arguments.length) { + return this._enableTimeouts; + } + debug('enableTimeouts %s', enabled); + this._enableTimeouts = enabled; + return this; +}; + +/** + * Halt and mark as pending. * - * @return {String} * @api public */ +Runnable.prototype.skip = function() { + throw new Pending(); +}; + +/** + * Check if this runnable or its parent suite is marked as pending. + * + * @api private + */ +Runnable.prototype.isPending = function() { + return this.pending || (this.parent && this.parent.isPending()); +}; + +/** + * Set number of retries. + * + * @api private + */ +Runnable.prototype.retries = function(n) { + if (!arguments.length) { + return this._retries; + } + this._retries = n; +}; + +/** + * Get current retry + * + * @api private + */ +Runnable.prototype.currentRetry = function(n) { + if (!arguments.length) { + return this._currentRetry; + } + this._currentRetry = n; +}; -Runnable.prototype.fullTitle = function(){ +/** + * Return the full title generated by recursively concatenating the parent's + * full title. + * + * @api public + * @return {string} + */ +Runnable.prototype.fullTitle = function() { return this.parent.fullTitle() + ' ' + this.title; }; @@ -3558,23 +4326,27 @@ Runnable.prototype.fullTitle = function(){ * * @api private */ - -Runnable.prototype.clearTimeout = function(){ +Runnable.prototype.clearTimeout = function() { clearTimeout(this.timer); }; /** * Inspect the runnable void of private properties. * - * @return {String} * @api private + * @return {string} */ - -Runnable.prototype.inspect = function(){ - return JSON.stringify(this, function(key, val){ - if ('_' == key[0]) return; - if ('parent' == key) return '#'; - if ('ctx' == key) return '#'; +Runnable.prototype.inspect = function() { + return JSON.stringify(this, function(key, val) { + if (key[0] === '_') { + return; + } + if (key === 'parent') { + return '#'; + } + if (key === 'ctx') { + return '#'; + } return val; }, 2); }; @@ -3584,18 +4356,34 @@ Runnable.prototype.inspect = function(){ * * @api private */ +Runnable.prototype.resetTimeout = function() { + var self = this; + var ms = this.timeout() || 1e9; -Runnable.prototype.resetTimeout = function(){ - var self = this - , ms = this.timeout(); - + if (!this._enableTimeouts) { + return; + } this.clearTimeout(); - if (ms) { - this.timer = setTimeout(function(){ - self.callback(new Error('timeout of ' + ms + 'ms exceeded')); - self.timedOut = true; - }, ms); + this.timer = setTimeout(function() { + if (!self._enableTimeouts) { + return; + } + self.callback(new Error('timeout of ' + ms + 'ms exceeded. Ensure the done() callback is being called in this test.')); + self.timedOut = true; + }, ms); +}; + +/** + * Whitelist a list of globals for this test run. + * + * @api private + * @param {string[]} globals + */ +Runnable.prototype.globals = function(globals) { + if (!arguments.length) { + return this._allowedGlobals; } + this._allowedGlobals = globals; }; /** @@ -3604,86 +4392,157 @@ Runnable.prototype.resetTimeout = function(){ * @param {Function} fn * @api private */ - -Runnable.prototype.run = function(fn){ - var self = this - , ms = this.timeout() - , start = new Date - , ctx = this.ctx - , finished - , emitted; - - if (ctx) ctx.runnable(this); - - // timeout - if (this.async) { - if (ms) { - this.timer = setTimeout(function(){ - done(new Error('timeout of ' + ms + 'ms exceeded')); - self.timedOut = true; - }, ms); - } +Runnable.prototype.run = function(fn) { + var self = this; + var start = new Date(); + var ctx = this.ctx; + var finished; + var emitted; + + // Sometimes the ctx exists, but it is not runnable + if (ctx && ctx.runnable) { + ctx.runnable(this); } // called multiple times function multiple(err) { - if (emitted) return; + if (emitted) { + return; + } emitted = true; - self.emit('error', err || new Error('done() called multiple times')); + self.emit('error', err || new Error('done() called multiple times; stacktrace may be inaccurate')); } // finished function done(err) { - if (self.timedOut) return; - if (finished) return multiple(err); + var ms = self.timeout(); + if (self.timedOut) { + return; + } + if (finished) { + return multiple(err || self._trace); + } + self.clearTimeout(); - self.duration = new Date - start; + self.duration = new Date() - start; finished = true; + if (!err && self.duration > ms && self._enableTimeouts) { + err = new Error('timeout of ' + ms + 'ms exceeded. Ensure the done() callback is being called in this test.'); + } fn(err); } // for .resetTimeout() this.callback = done; - // async + // explicit async with `done` argument if (this.async) { + this.resetTimeout(); + + if (this.allowUncaught) { + return callFnAsync(this.fn); + } try { - this.fn.call(ctx, function(err){ - if (err instanceof Error) return done(err); - if (null != err) return done(new Error('done() invoked with non-Error: ' + err)); - done(); - }); + callFnAsync(this.fn); } catch (err) { - done(err); + done(utils.getError(err)); } return; } - - // sync + + if (this.allowUncaught) { + callFn(this.fn); + done(); + return; + } + + // sync or promise-returning try { - if (!this.pending) this.fn.call(ctx); - this.duration = new Date - start; - fn(); + if (this.isPending()) { + done(); + } else { + callFn(this.fn); + } } catch (err) { - fn(err); + done(utils.getError(err)); } -}; -}); // module: runnable.js + function callFn(fn) { + var result = fn.call(ctx); + if (result && typeof result.then === 'function') { + self.resetTimeout(); + result + .then(function() { + done(); + // Return null so libraries like bluebird do not warn about + // subsequently constructed Promises. + return null; + }, + function(reason) { + done(reason || new Error('Promise rejected with no or falsy reason')); + }); + } else { + if (self.asyncOnly) { + return done(new Error('--async-only option in use without declaring `done()` or returning a promise')); + } + + done(); + } + } -require.register("runner.js", function(module, exports, require){ + function callFnAsync(fn) { + fn.call(ctx, function(err) { + if (err instanceof Error || toString.call(err) === '[object Error]') { + return done(err); + } + if (err) { + if (Object.prototype.toString.call(err) === '[object Object]') { + return done(new Error('done() invoked with non-Error: ' + + JSON.stringify(err))); + } + return done(new Error('done() invoked with non-Error: ' + err)); + } + done(); + }); + } +}; +}).call(this,typeof global !== "undefined" ? global : typeof self !== "undefined" ? self : typeof window !== "undefined" ? window : {}) +},{"./ms":15,"./pending":16,"./utils":39,"debug":2,"events":3}],36:[function(require,module,exports){ +(function (process,global){ /** * Module dependencies. */ -var EventEmitter = require('browser/events').EventEmitter - , debug = require('browser/debug')('mocha:runner') - , Test = require('./test') - , utils = require('./utils') - , filter = utils.filter - , keys = utils.keys - , noop = function(){}; +var EventEmitter = require('events').EventEmitter; +var Pending = require('./pending'); +var utils = require('./utils'); +var inherits = utils.inherits; +var debug = require('debug')('mocha:runner'); +var Runnable = require('./runnable'); +var filter = utils.filter; +var indexOf = utils.indexOf; +var keys = utils.keys; +var stackFilter = utils.stackTraceFilter(); +var stringify = utils.stringify; +var type = utils.type; +var undefinedError = utils.undefinedError; +var isArray = utils.isArray; + +/** + * Non-enumerable globals. + */ + +var globals = [ + 'setTimeout', + 'clearTimeout', + 'setInterval', + 'clearInterval', + 'XMLHttpRequest', + 'Date', + 'setImmediate', + 'clearImmediate' +]; /** * Expose `Runner`. @@ -3706,29 +4565,45 @@ module.exports = Runner; * - `hook end` (hook) hook complete * - `pass` (test) test passed * - `fail` (test, err) test failed + * - `pending` (test) test pending * * @api public + * @param {Suite} suite Root suite + * @param {boolean} [delay] Whether or not to delay execution of root suite + * until ready. */ - -function Runner(suite) { +function Runner(suite, delay) { var self = this; this._globals = []; + this._abort = false; + this._delay = delay; this.suite = suite; + this.started = false; this.total = suite.total(); this.failures = 0; - this.on('test end', function(test){ self.checkGlobals(test); }); - this.on('hook end', function(hook){ self.checkGlobals(hook); }); - this.grep(/.*/); - this.globals(utils.keys(global).concat(['errno'])); + this.on('test end', function(test) { + self.checkGlobals(test); + }); + this.on('hook end', function(hook) { + self.checkGlobals(hook); + }); + this._defaultGrep = /.*/; + this.grep(this._defaultGrep); + this.globals(this.globalProps().concat(extraGlobals())); } /** - * Inherit from `EventEmitter.prototype`. + * Wrapper for setImmediate, process.nextTick, or browser polyfill. + * + * @param {Function} fn + * @api private */ +Runner.immediately = global.setImmediate || process.nextTick; -Runner.prototype = new EventEmitter; -Runner.prototype.constructor = Runner; - +/** + * Inherit from `EventEmitter.prototype`. + */ +inherits(Runner, EventEmitter); /** * Run tests with full titles matching `re`. Updates runner.total @@ -3738,9 +4613,11 @@ Runner.prototype.constructor = Runner; * @param {Boolean} invert * @return {Runner} for chaining * @api public + * @param {RegExp} re + * @param {boolean} invert + * @return {Runner} Runner instance. */ - -Runner.prototype.grep = function(re, invert){ +Runner.prototype.grep = function(re, invert) { debug('grep %s', re); this._grep = re; this._invert = invert; @@ -3755,35 +4632,61 @@ Runner.prototype.grep = function(re, invert){ * @param {Suite} suite * @return {Number} * @api public + * @param {Suite} suite + * @return {number} */ - Runner.prototype.grepTotal = function(suite) { var self = this; var total = 0; - suite.eachTest(function(test){ + suite.eachTest(function(test) { var match = self._grep.test(test.fullTitle()); - if (self._invert) match = !match; - if (match) total++; + if (self._invert) { + match = !match; + } + if (match) { + total++; + } }); return total; }; +/** + * Return a list of global properties. + * + * @return {Array} + * @api private + */ +Runner.prototype.globalProps = function() { + var props = keys(global); + + // non-enumerables + for (var i = 0; i < globals.length; ++i) { + if (~indexOf(props, globals[i])) { + continue; + } + props.push(globals[i]); + } + + return props; +}; + /** * Allow the given `arr` of globals. * * @param {Array} arr * @return {Runner} for chaining * @api public + * @param {Array} arr + * @return {Runner} Runner instance. */ - -Runner.prototype.globals = function(arr){ - if (0 == arguments.length) return this._globals; +Runner.prototype.globals = function(arr) { + if (!arguments.length) { + return this._globals; + } debug('globals %j', arr); - utils.forEach(arr, function(arr){ - this._globals.push(arr); - }, this); + this._globals = this._globals.concat(arr); return this; }; @@ -3792,17 +4695,23 @@ Runner.prototype.globals = function(arr){ * * @api private */ - -Runner.prototype.checkGlobals = function(test){ - if (this.ignoreLeaks) return; +Runner.prototype.checkGlobals = function(test) { + if (this.ignoreLeaks) { + return; + } var ok = this._globals; - var globals = keys(global); - var isNode = process.kill; + + var globals = this.globalProps(); var leaks; - // check length - 2 ('errno' and 'location' globals) - if (isNode && 1 == ok.length - globals.length) return - else if (2 == ok.length - globals.length) return; + if (test) { + ok = ok.concat(test._allowedGlobals || []); + } + + if (this.prevGlobalsLength === globals.length) { + return; + } + this.prevGlobalsLength = globals.length; leaks = filterLeaks(ok, globals); this._globals = this._globals.concat(leaks); @@ -3817,91 +4726,125 @@ Runner.prototype.checkGlobals = function(test){ /** * Fail the given `test`. * + * @api private * @param {Test} test * @param {Error} err - * @api private */ - -Runner.prototype.fail = function(test, err){ +Runner.prototype.fail = function(test, err) { ++this.failures; test.state = 'failed'; - if ('string' == typeof err) { - err = new Error('the string "' + err + '" was thrown, throw an Error :)'); + + if (!(err instanceof Error || err && typeof err.message === 'string')) { + err = new Error('the ' + type(err) + ' ' + stringify(err) + ' was thrown, throw an Error :)'); } + + err.stack = (this.fullStackTrace || !err.stack) + ? err.stack + : stackFilter(err.stack); + this.emit('fail', test, err); }; /** * Fail the given `hook` with `err`. * - * Hook failures (currently) hard-end due - * to that fact that a failing hook will - * surely cause subsequent tests to fail, - * causing jumbled reporting. + * Hook failures work in the following pattern: + * - If bail, then exit + * - Failed `before` hook skips all tests in a suite and subsuites, + * but jumps to corresponding `after` hook + * - Failed `before each` hook skips remaining tests in a + * suite and jumps to corresponding `after each` hook, + * which is run only once + * - Failed `after` hook does not alter + * execution order + * - Failed `after each` hook skips remaining tests in a + * suite and subsuites, but executes other `after each` + * hooks * + * @api private * @param {Hook} hook * @param {Error} err - * @api private */ +Runner.prototype.failHook = function(hook, err) { + if (hook.ctx && hook.ctx.currentTest) { + hook.originalTitle = hook.originalTitle || hook.title; + hook.title = hook.originalTitle + ' for "' + hook.ctx.currentTest.title + '"'; + } -Runner.prototype.failHook = function(hook, err){ this.fail(hook, err); - this.emit('end'); + if (this.suite.bail()) { + this.emit('end'); + } }; /** * Run hook `name` callbacks and then invoke `fn()`. * - * @param {String} name - * @param {Function} function * @api private + * @param {string} name + * @param {Function} fn */ -Runner.prototype.hook = function(name, fn){ - var suite = this.suite - , hooks = suite['_' + name] - , self = this - , timer; +Runner.prototype.hook = function(name, fn) { + var suite = this.suite; + var hooks = suite['_' + name]; + var self = this; function next(i) { var hook = hooks[i]; - if (!hook) return fn(); + if (!hook) { + return fn(); + } self.currentRunnable = hook; + hook.ctx.currentTest = self.test; + self.emit('hook', hook); - hook.on('error', function(err){ - self.failHook(hook, err); - }); + if (!hook.listeners('error').length) { + hook.on('error', function(err) { + self.failHook(hook, err); + }); + } - hook.run(function(err){ - hook.removeAllListeners('error'); + hook.run(function(err) { var testError = hook.error(); - if (testError) self.fail(self.test, testError); - if (err) return self.failHook(hook, err); + if (testError) { + self.fail(self.test, testError); + } + if (err) { + if (err instanceof Pending) { + suite.pending = true; + } else { + self.failHook(hook, err); + + // stop executing hooks, notify callee of hook err + return fn(err); + } + } self.emit('hook end', hook); + delete hook.ctx.currentTest; next(++i); }); } - process.nextTick(function(){ + Runner.immediately(function() { next(0); }); }; /** * Run hook `name` for the given array of `suites` - * in order, and callback `fn(err)`. + * in order, and callback `fn(err, errSuite)`. * - * @param {String} name + * @api private + * @param {string} name * @param {Array} suites * @param {Function} fn - * @api private */ - -Runner.prototype.hooks = function(name, suites, fn){ - var self = this - , orig = this.suite; +Runner.prototype.hooks = function(name, suites, fn) { + var self = this; + var orig = this.suite; function next(suite) { self.suite = suite; @@ -3911,10 +4854,11 @@ Runner.prototype.hooks = function(name, suites, fn){ return fn(); } - self.hook(name, function(err){ + self.hook(name, function(err) { if (err) { + var errSuite = self.suite; self.suite = orig; - return fn(err); + return fn(err, errSuite); } next(suites.pop()); @@ -3931,8 +4875,7 @@ Runner.prototype.hooks = function(name, suites, fn){ * @param {Function} fn * @api private */ - -Runner.prototype.hookUp = function(name, fn){ +Runner.prototype.hookUp = function(name, fn) { var suites = [this.suite].concat(this.parents()).reverse(); this.hooks(name, suites, fn); }; @@ -3944,8 +4887,7 @@ Runner.prototype.hookUp = function(name, fn){ * @param {Function} fn * @api private */ - -Runner.prototype.hookDown = function(name, fn){ +Runner.prototype.hookDown = function(name, fn) { var suites = [this.suite].concat(this.parents()); this.hooks(name, suites, fn); }; @@ -3957,11 +4899,13 @@ Runner.prototype.hookDown = function(name, fn){ * @return {Array} * @api private */ - -Runner.prototype.parents = function(){ - var suite = this.suite - , suites = []; - while (suite = suite.parent) suites.push(suite); +Runner.prototype.parents = function() { + var suite = this.suite; + var suites = []; + while (suite.parent) { + suite = suite.parent; + suites.push(suite); + } return suites; }; @@ -3971,13 +4915,20 @@ Runner.prototype.parents = function(){ * @param {Function} fn * @api private */ +Runner.prototype.runTest = function(fn) { + var self = this; + var test = this.test; -Runner.prototype.runTest = function(fn){ - var test = this.test - , self = this; + if (this.asyncOnly) { + test.asyncOnly = true; + } + if (this.allowUncaught) { + test.allowUncaught = true; + return test.run(fn); + } try { - test.on('error', function(err){ + test.on('error', function(err) { self.fail(test, err); }); test.run(fn); @@ -3987,36 +4938,88 @@ Runner.prototype.runTest = function(fn){ }; /** - * Run tests in the given `suite` and invoke - * the callback `fn()` when complete. + * Run tests in the given `suite` and invoke the callback `fn()` when complete. * + * @api private * @param {Suite} suite * @param {Function} fn - * @api private */ +Runner.prototype.runTests = function(suite, fn) { + var self = this; + var tests = suite.tests.slice(); + var test; -Runner.prototype.runTests = function(suite, fn){ - var self = this - , tests = suite.tests.slice() - , test; - - function next(err) { - // if we bail after first err - if (self.failures && suite._bail) return fn(); + function hookErr(_, errSuite, after) { + // before/after Each hook for errSuite failed: + var orig = self.suite; - // next test - test = tests.shift(); + // for failed 'after each' hook start from errSuite parent, + // otherwise start from errSuite itself + self.suite = after ? errSuite.parent : errSuite; - // all done - if (!test) return fn(); + if (self.suite) { + // call hookUp afterEach + self.hookUp('afterEach', function(err2, errSuite2) { + self.suite = orig; + // some hooks may fail even now + if (err2) { + return hookErr(err2, errSuite2, true); + } + // report error suite + fn(errSuite); + }); + } else { + // there is no need calling other 'after each' hooks + self.suite = orig; + fn(errSuite); + } + } + + function next(err, errSuite) { + // if we bail after first err + if (self.failures && suite._bail) { + return fn(); + } + + if (self._abort) { + return fn(); + } + + if (err) { + return hookErr(err, errSuite, true); + } + + // next test + test = tests.shift(); + + // all done + if (!test) { + return fn(); + } // grep var match = self._grep.test(test.fullTitle()); - if (self._invert) match = !match; - if (!match) return next(); + if (self._invert) { + match = !match; + } + if (!match) { + // Run immediately only if we have defined a grep. When we + // define a grep — It can cause maximum callstack error if + // the grep is doing a large recursive loop by neglecting + // all tests. The run immediately function also comes with + // a performance cost. So we don't want to run immediately + // if we run the whole test suite, because running the whole + // test suite don't do any immediate recursive loops. Thus, + // allowing a JS runtime to breathe. + if (self._grep !== self._defaultGrep) { + Runner.immediately(next); + } else { + next(); + } + return; + } - // pending - if (test.pending) { + if (test.isPending()) { self.emit('pending', test); self.emit('test end', test); return next(); @@ -4024,14 +5027,40 @@ Runner.prototype.runTests = function(suite, fn){ // execute test and hook(s) self.emit('test', self.test = test); - self.hookDown('beforeEach', function(){ + self.hookDown('beforeEach', function(err, errSuite) { + if (suite.isPending()) { + self.emit('pending', test); + self.emit('test end', test); + return next(); + } + if (err) { + return hookErr(err, errSuite, false); + } self.currentRunnable = self.test; - self.runTest(function(err){ + self.runTest(function(err) { test = self.test; - if (err) { - self.fail(test, err); + var retry = test.currentRetry(); + if (err instanceof Pending) { + test.pending = true; + self.emit('pending', test); + } else if (retry < test.retries()) { + var clonedTest = test.clone(); + clonedTest.currentRetry(retry + 1); + tests.unshift(clonedTest); + + // Early return + hook trigger so that it doesn't + // increment the count wrong + return self.hookUp('afterEach', next); + } else { + self.fail(test, err); + } self.emit('test end', test); + + if (err instanceof Pending) { + return next(); + } + return self.hookUp('afterEach', next); } @@ -4044,44 +5073,92 @@ Runner.prototype.runTests = function(suite, fn){ } this.next = next; + this.hookErr = hookErr; next(); }; /** - * Run the given `suite` and invoke the - * callback `fn()` when complete. + * Run the given `suite` and invoke the callback `fn()` when complete. * + * @api private * @param {Suite} suite * @param {Function} fn - * @api private */ - -Runner.prototype.runSuite = function(suite, fn){ - var total = this.grepTotal(suite) - , self = this - , i = 0; +Runner.prototype.runSuite = function(suite, fn) { + var i = 0; + var self = this; + var total = this.grepTotal(suite); + var afterAllHookCalled = false; debug('run suite %s', suite.fullTitle()); - if (!total) return fn(); + if (!total || (self.failures && suite._bail)) { + return fn(); + } this.emit('suite', this.suite = suite); - function next() { + function next(errSuite) { + if (errSuite) { + // current suite failed on a hook from errSuite + if (errSuite === suite) { + // if errSuite is current suite + // continue to the next sibling suite + return done(); + } + // errSuite is among the parents of current suite + // stop execution of errSuite and all sub-suites + return done(errSuite); + } + + if (self._abort) { + return done(); + } + var curr = suite.suites[i++]; - if (!curr) return done(); - self.runSuite(curr, next); + if (!curr) { + return done(); + } + + // Avoid grep neglecting large number of tests causing a + // huge recursive loop and thus a maximum call stack error. + // See comment in `this.runTests()` for more information. + if (self._grep !== self._defaultGrep) { + Runner.immediately(function() { + self.runSuite(curr, next); + }); + } else { + self.runSuite(curr, next); + } } - function done() { + function done(errSuite) { self.suite = suite; - self.hook('afterAll', function(){ - self.emit('suite end', suite); - fn(); - }); + self.nextSuite = next; + + if (afterAllHookCalled) { + fn(errSuite); + } else { + // mark that the afterAll block has been called once + // and so can be skipped if there is an error in it. + afterAllHookCalled = true; + + // remove reference to test + delete self.test; + + self.hook('afterAll', function() { + self.emit('suite end', suite); + fn(errSuite); + }); + } } - this.hook('beforeAll', function(){ + this.nextSuite = next; + + this.hook('beforeAll', function(err) { + if (err) { + return done(); + } self.runTests(suite, next); }); }; @@ -4092,26 +5169,107 @@ Runner.prototype.runSuite = function(suite, fn){ * @param {Error} err * @api private */ +Runner.prototype.uncaught = function(err) { + if (err) { + debug('uncaught exception %s', err !== function() { + return this; + }.call(err) ? err : (err.message || err)); + } else { + debug('uncaught undefined exception'); + err = undefinedError(); + } + err.uncaught = true; -Runner.prototype.uncaught = function(err){ - debug('uncaught exception %s', err.message); var runnable = this.currentRunnable; - if (!runnable || 'failed' == runnable.state) return; + + if (!runnable) { + runnable = new Runnable('Uncaught error outside test suite'); + runnable.parent = this.suite; + + if (this.started) { + this.fail(runnable, err); + } else { + // Can't recover from this failure + this.emit('start'); + this.fail(runnable, err); + this.emit('end'); + } + + return; + } + runnable.clearTimeout(); - err.uncaught = true; + + // Ignore errors if complete + if (runnable.state) { + return; + } this.fail(runnable, err); // recover from test - if ('test' == runnable.type) { + if (runnable.type === 'test') { this.emit('test end', runnable); this.hookUp('afterEach', this.next); return; } - // bail on hooks + // recover from hooks + if (runnable.type === 'hook') { + var errSuite = this.suite; + // if hook failure is in afterEach block + if (runnable.fullTitle().indexOf('after each') > -1) { + return this.hookErr(err, errSuite, true); + } + // if hook failure is in beforeEach block + if (runnable.fullTitle().indexOf('before each') > -1) { + return this.hookErr(err, errSuite, false); + } + // if hook failure is in after or before blocks + return this.nextSuite(errSuite); + } + + // bail this.emit('end'); }; +/** + * Cleans up the references to all the deferred functions + * (before/after/beforeEach/afterEach) and tests of a Suite. + * These must be deleted otherwise a memory leak can happen, + * as those functions may reference variables from closures, + * thus those variables can never be garbage collected as long + * as the deferred functions exist. + * + * @param {Suite} suite + */ +function cleanSuiteReferences(suite) { + function cleanArrReferences(arr) { + for (var i = 0; i < arr.length; i++) { + delete arr[i].fn; + } + } + + if (isArray(suite._beforeAll)) { + cleanArrReferences(suite._beforeAll); + } + + if (isArray(suite._beforeEach)) { + cleanArrReferences(suite._beforeEach); + } + + if (isArray(suite._afterAll)) { + cleanArrReferences(suite._afterAll); + } + + if (isArray(suite._afterEach)) { + cleanArrReferences(suite._afterEach); + } + + for (var i = 0; i < suite.tests.length; i++) { + delete suite.tests[i].fn; + } +} + /** * Run the root suite and invoke `fn(failures)` * on completion. @@ -4119,71 +5277,146 @@ Runner.prototype.uncaught = function(err){ * @param {Function} fn * @return {Runner} for chaining * @api public + * @param {Function} fn + * @return {Runner} Runner instance. */ +Runner.prototype.run = function(fn) { + var self = this; + var rootSuite = this.suite; -Runner.prototype.run = function(fn){ - var self = this - , fn = fn || function(){}; - - debug('start'); + fn = fn || function() {}; - // uncaught callback function uncaught(err) { self.uncaught(err); } + function start() { + self.started = true; + self.emit('start'); + self.runSuite(rootSuite, function() { + debug('finished running'); + self.emit('end'); + }); + } + + debug('start'); + + // references cleanup to avoid memory leaks + this.on('suite end', cleanSuiteReferences); + // callback - this.on('end', function(){ + this.on('end', function() { debug('end'); process.removeListener('uncaughtException', uncaught); fn(self.failures); }); - // run suites - this.emit('start'); - this.runSuite(this.suite, function(){ - debug('finished running'); - self.emit('end'); - }); - // uncaught exception process.on('uncaughtException', uncaught); + if (this._delay) { + // for reporters, I guess. + // might be nice to debounce some dots while we wait. + this.emit('waiting', rootSuite); + rootSuite.once('run', start); + } else { + start(); + } + + return this; +}; + +/** + * Cleanly abort execution. + * + * @api public + * @return {Runner} Runner instance. + */ +Runner.prototype.abort = function() { + debug('aborting'); + this._abort = true; + return this; }; /** * Filter leaks with the given globals flagged as `ok`. * + * @api private * @param {Array} ok * @param {Array} globals * @return {Array} - * @api private */ - function filterLeaks(ok, globals) { - return filter(globals, function(key){ - var matched = filter(ok, function(ok){ - if (~ok.indexOf('*')) return 0 == key.indexOf(ok.split('*')[0]); - return key == ok; + return filter(globals, function(key) { + // Firefox and Chrome exposes iframes as index inside the window object + if (/^d+/.test(key)) { + return false; + } + + // in firefox + // if runner runs in an iframe, this iframe's window.getInterface method not init at first + // it is assigned in some seconds + if (global.navigator && (/^getInterface/).test(key)) { + return false; + } + + // an iframe could be approached by window[iframeIndex] + // in ie6,7,8 and opera, iframeIndex is enumerable, this could cause leak + if (global.navigator && (/^\d+/).test(key)) { + return false; + } + + // Opera and IE expose global variables for HTML element IDs (issue #243) + if (/^mocha-/.test(key)) { + return false; + } + + var matched = filter(ok, function(ok) { + if (~ok.indexOf('*')) { + return key.indexOf(ok.split('*')[0]) === 0; + } + return key === ok; }); - return matched.length == 0 && (!global.navigator || 'onerror' !== key); + return !matched.length && (!global.navigator || key !== 'onerror'); }); } -}); // module: runner.js +/** + * Array of globals dependent on the environment. + * + * @return {Array} + * @api private + */ +function extraGlobals() { + if (typeof process === 'object' && typeof process.version === 'string') { + var parts = process.version.split('.'); + var nodeVersion = utils.reduce(parts, function(a, v) { + return a << 8 | v; + }); + + // 'errno' was renamed to process._errno in v0.9.11. + + if (nodeVersion < 0x00090B) { + return ['errno']; + } + } -require.register("suite.js", function(module, exports, require){ + return []; +} +}).call(this,require('_process'),typeof global !== "undefined" ? global : typeof self !== "undefined" ? self : typeof window !== "undefined" ? window : {}) +},{"./pending":16,"./runnable":35,"./utils":39,"_process":58,"debug":2,"events":3}],37:[function(require,module,exports){ /** * Module dependencies. */ -var EventEmitter = require('browser/events').EventEmitter - , debug = require('browser/debug')('mocha:suite') - , milliseconds = require('./ms') - , utils = require('./utils') - , Hook = require('./hook'); +var EventEmitter = require('events').EventEmitter; +var Hook = require('./hook'); +var utils = require('./utils'); +var inherits = utils.inherits; +var debug = require('debug')('mocha:suite'); +var milliseconds = require('./ms'); /** * Expose `Suite`. @@ -4192,39 +5425,35 @@ var EventEmitter = require('browser/events').EventEmitter exports = module.exports = Suite; /** - * Create a new `Suite` with the given `title` - * and parent `Suite`. When a suite with the - * same title is already present, that suite - * is returned to provide nicer reporter - * and more flexible meta-testing. + * Create a new `Suite` with the given `title` and parent `Suite`. When a suite + * with the same title is already present, that suite is returned to provide + * nicer reporter and more flexible meta-testing. * + * @api public * @param {Suite} parent - * @param {String} title + * @param {string} title * @return {Suite} - * @api public */ - -exports.create = function(parent, title){ +exports.create = function(parent, title) { var suite = new Suite(title, parent.ctx); suite.parent = parent; - if (parent.pending) suite.pending = true; title = suite.fullTitle(); parent.addSuite(suite); return suite; }; /** - * Initialize a new `Suite` with the given - * `title` and `ctx`. + * Initialize a new `Suite` with the given `title` and `ctx`. * - * @param {String} title - * @param {Context} ctx * @api private + * @param {string} title + * @param {Context} parentContext */ - -function Suite(title, ctx) { +function Suite(title, parentContext) { this.title = title; - this.ctx = ctx; + function Context() {} + Context.prototype = parentContext; + this.ctx = new Context(); this.suites = []; this.tests = []; this.pending = false; @@ -4234,30 +5463,31 @@ function Suite(title, ctx) { this._afterAll = []; this.root = !title; this._timeout = 2000; + this._enableTimeouts = true; this._slow = 75; this._bail = false; + this._retries = -1; + this.delayed = false; } /** * Inherit from `EventEmitter.prototype`. */ - -Suite.prototype = new EventEmitter; -Suite.prototype.constructor = Suite; - +inherits(Suite, EventEmitter); /** * Return a clone of this `Suite`. * - * @return {Suite} * @api private + * @return {Suite} */ - -Suite.prototype.clone = function(){ +Suite.prototype.clone = function() { var suite = new Suite(this.title); debug('clone'); suite.ctx = this.ctx; suite.timeout(this.timeout()); + suite.retries(this.retries()); + suite.enableTimeouts(this.enableTimeouts()); suite.slow(this.slow()); suite.bail(this.bail()); return suite; @@ -4266,30 +5496,71 @@ Suite.prototype.clone = function(){ /** * Set timeout `ms` or short-hand such as "2s". * - * @param {Number|String} ms - * @return {Suite|Number} for chaining * @api private + * @param {number|string} ms + * @return {Suite|number} for chaining */ - -Suite.prototype.timeout = function(ms){ - if (0 == arguments.length) return this._timeout; - if ('string' == typeof ms) ms = milliseconds(ms); +Suite.prototype.timeout = function(ms) { + if (!arguments.length) { + return this._timeout; + } + if (ms.toString() === '0') { + this._enableTimeouts = false; + } + if (typeof ms === 'string') { + ms = milliseconds(ms); + } debug('timeout %d', ms); this._timeout = parseInt(ms, 10); return this; }; /** - * Set slow `ms` or short-hand such as "2s". + * Set number of times to retry a failed test. * - * @param {Number|String} ms - * @return {Suite|Number} for chaining * @api private + * @param {number|string} n + * @return {Suite|number} for chaining */ +Suite.prototype.retries = function(n) { + if (!arguments.length) { + return this._retries; + } + debug('retries %d', n); + this._retries = parseInt(n, 10) || 0; + return this; +}; + +/** + * Set timeout to `enabled`. + * + * @api private + * @param {boolean} enabled + * @return {Suite|boolean} self or enabled + */ +Suite.prototype.enableTimeouts = function(enabled) { + if (!arguments.length) { + return this._enableTimeouts; + } + debug('enableTimeouts %s', enabled); + this._enableTimeouts = enabled; + return this; +}; -Suite.prototype.slow = function(ms){ - if (0 === arguments.length) return this._slow; - if ('string' == typeof ms) ms = milliseconds(ms); +/** + * Set slow `ms` or short-hand such as "2s". + * + * @api private + * @param {number|string} ms + * @return {Suite|number} for chaining + */ +Suite.prototype.slow = function(ms) { + if (!arguments.length) { + return this._slow; + } + if (typeof ms === 'string') { + ms = milliseconds(ms); + } debug('slow %d', ms); this._slow = ms; return this; @@ -4298,31 +5569,51 @@ Suite.prototype.slow = function(ms){ /** * Sets whether to bail after first error. * - * @parma {Boolean} bail - * @return {Suite|Number} for chaining * @api private + * @param {boolean} bail + * @return {Suite|number} for chaining */ - -Suite.prototype.bail = function(bail){ - if (0 == arguments.length) return this._bail; +Suite.prototype.bail = function(bail) { + if (!arguments.length) { + return this._bail; + } debug('bail %s', bail); this._bail = bail; return this; }; +/** + * Check if this suite or its parent suite is marked as pending. + * + * @api private + */ +Suite.prototype.isPending = function() { + return this.pending || (this.parent && this.parent.isPending()); +}; + /** * Run `fn(test[, done])` before running tests. * + * @api private + * @param {string} title * @param {Function} fn * @return {Suite} for chaining - * @api private */ +Suite.prototype.beforeAll = function(title, fn) { + if (this.isPending()) { + return this; + } + if (typeof title === 'function') { + fn = title; + title = fn.name; + } + title = '"before all" hook' + (title ? ': ' + title : ''); -Suite.prototype.beforeAll = function(fn){ - if (this.pending) return this; - var hook = new Hook('"before all" hook', fn); + var hook = new Hook(title, fn); hook.parent = this; hook.timeout(this.timeout()); + hook.retries(this.retries()); + hook.enableTimeouts(this.enableTimeouts()); hook.slow(this.slow()); hook.ctx = this.ctx; this._beforeAll.push(hook); @@ -4333,16 +5624,26 @@ Suite.prototype.beforeAll = function(fn){ /** * Run `fn(test[, done])` after running tests. * + * @api private + * @param {string} title * @param {Function} fn * @return {Suite} for chaining - * @api private */ +Suite.prototype.afterAll = function(title, fn) { + if (this.isPending()) { + return this; + } + if (typeof title === 'function') { + fn = title; + title = fn.name; + } + title = '"after all" hook' + (title ? ': ' + title : ''); -Suite.prototype.afterAll = function(fn){ - if (this.pending) return this; - var hook = new Hook('"after all" hook', fn); + var hook = new Hook(title, fn); hook.parent = this; hook.timeout(this.timeout()); + hook.retries(this.retries()); + hook.enableTimeouts(this.enableTimeouts()); hook.slow(this.slow()); hook.ctx = this.ctx; this._afterAll.push(hook); @@ -4353,16 +5654,26 @@ Suite.prototype.afterAll = function(fn){ /** * Run `fn(test[, done])` before each test case. * + * @api private + * @param {string} title * @param {Function} fn * @return {Suite} for chaining - * @api private */ +Suite.prototype.beforeEach = function(title, fn) { + if (this.isPending()) { + return this; + } + if (typeof title === 'function') { + fn = title; + title = fn.name; + } + title = '"before each" hook' + (title ? ': ' + title : ''); -Suite.prototype.beforeEach = function(fn){ - if (this.pending) return this; - var hook = new Hook('"before each" hook', fn); + var hook = new Hook(title, fn); hook.parent = this; hook.timeout(this.timeout()); + hook.retries(this.retries()); + hook.enableTimeouts(this.enableTimeouts()); hook.slow(this.slow()); hook.ctx = this.ctx; this._beforeEach.push(hook); @@ -4373,16 +5684,26 @@ Suite.prototype.beforeEach = function(fn){ /** * Run `fn(test[, done])` after each test case. * + * @api private + * @param {string} title * @param {Function} fn * @return {Suite} for chaining - * @api private */ +Suite.prototype.afterEach = function(title, fn) { + if (this.isPending()) { + return this; + } + if (typeof title === 'function') { + fn = title; + title = fn.name; + } + title = '"after each" hook' + (title ? ': ' + title : ''); -Suite.prototype.afterEach = function(fn){ - if (this.pending) return this; - var hook = new Hook('"after each" hook', fn); + var hook = new Hook(title, fn); hook.parent = this; hook.timeout(this.timeout()); + hook.retries(this.retries()); + hook.enableTimeouts(this.enableTimeouts()); hook.slow(this.slow()); hook.ctx = this.ctx; this._afterEach.push(hook); @@ -4393,14 +5714,15 @@ Suite.prototype.afterEach = function(fn){ /** * Add a test `suite`. * + * @api private * @param {Suite} suite * @return {Suite} for chaining - * @api private */ - -Suite.prototype.addSuite = function(suite){ +Suite.prototype.addSuite = function(suite) { suite.parent = this; suite.timeout(this.timeout()); + suite.retries(this.retries()); + suite.enableTimeouts(this.enableTimeouts()); suite.slow(this.slow()); suite.bail(this.bail()); this.suites.push(suite); @@ -4411,14 +5733,15 @@ Suite.prototype.addSuite = function(suite){ /** * Add a `test` to this suite. * + * @api private * @param {Test} test * @return {Suite} for chaining - * @api private */ - -Suite.prototype.addTest = function(test){ +Suite.prototype.addTest = function(test) { test.parent = this; test.timeout(this.timeout()); + test.retries(this.retries()); + test.enableTimeouts(this.enableTimeouts()); test.slow(this.slow()); test.ctx = this.ctx; this.tests.push(test); @@ -4427,17 +5750,18 @@ Suite.prototype.addTest = function(test){ }; /** - * Return the full title generated by recursively - * concatenating the parent's full title. + * Return the full title generated by recursively concatenating the parent's + * full title. * - * @return {String} * @api public + * @return {string} */ - -Suite.prototype.fullTitle = function(){ +Suite.prototype.fullTitle = function() { if (this.parent) { var full = this.parent.fullTitle(); - if (full) return full + ' ' + this.title; + if (full) { + return full + ' ' + this.title; + } } return this.title; }; @@ -4445,43 +5769,47 @@ Suite.prototype.fullTitle = function(){ /** * Return the total number of tests. * - * @return {Number} * @api public + * @return {number} */ - -Suite.prototype.total = function(){ - return utils.reduce(this.suites, function(sum, suite){ +Suite.prototype.total = function() { + return utils.reduce(this.suites, function(sum, suite) { return sum + suite.total(); }, 0) + this.tests.length; }; /** - * Iterates through each suite recursively to find - * all tests. Applies a function in the format - * `fn(test)`. + * Iterates through each suite recursively to find all tests. Applies a + * function in the format `fn(test)`. * + * @api private * @param {Function} fn * @return {Suite} - * @api private */ - -Suite.prototype.eachTest = function(fn){ +Suite.prototype.eachTest = function(fn) { utils.forEach(this.tests, fn); - utils.forEach(this.suites, function(suite){ + utils.forEach(this.suites, function(suite) { suite.eachTest(fn); }); return this; }; -}); // module: suite.js - -require.register("test.js", function(module, exports, require){ +/** + * This will run the root suite if we happen to be running in delayed mode. + */ +Suite.prototype.run = function run() { + if (this.root) { + this.emit('run'); + } +}; +},{"./hook":7,"./ms":15,"./utils":39,"debug":2,"events":3}],38:[function(require,module,exports){ /** * Module dependencies. */ var Runnable = require('./runnable'); +var inherits = require('./utils').inherits; /** * Expose `Test`. @@ -4492,11 +5820,10 @@ module.exports = Test; /** * Initialize a new `Test` with the given `title` and callback `fn`. * + * @api private * @param {String} title * @param {Function} fn - * @api private */ - function Test(title, fn) { Runnable.call(this, title, fn); this.pending = !fn; @@ -4506,23 +5833,39 @@ function Test(title, fn) { /** * Inherit from `Runnable.prototype`. */ +inherits(Test, Runnable); -Test.prototype = new Runnable; -Test.prototype.constructor = Test; - - -}); // module: test.js +Test.prototype.clone = function() { + var test = new Test(this.title, this.fn); + test.timeout(this.timeout()); + test.slow(this.slow()); + test.enableTimeouts(this.enableTimeouts()); + test.retries(this.retries()); + test.currentRetry(this.currentRetry()); + test.globals(this.globals()); + test.parent = this.parent; + test.file = this.file; + test.ctx = this.ctx; + return test; +}; -require.register("utils.js", function(module, exports, require){ +},{"./runnable":35,"./utils":39}],39:[function(require,module,exports){ +(function (process,Buffer){ +/* eslint-env browser */ /** * Module dependencies. */ -var fs = require('browser/fs') - , path = require('browser/path') - , join = path.join - , debug = require('browser/debug')('mocha:watch'); +var basename = require('path').basename; +var debug = require('debug')('mocha:watch'); +var exists = require('fs').existsSync || require('path').existsSync; +var glob = require('glob'); +var join = require('path').join; +var readdirSync = require('fs').readdirSync; +var statSync = require('fs').statSync; +var watchFile = require('fs').watchFile; +var toISOString = require('to-iso-string'); /** * Ignored directories. @@ -4530,15 +5873,16 @@ var fs = require('browser/fs') var ignore = ['node_modules', '.git']; +exports.inherits = require('util').inherits; + /** * Escape special characters in the given string of html. * - * @param {String} html - * @return {String} * @api private + * @param {string} html + * @return {string} */ - -exports.escape = function(html){ +exports.escape = function(html) { return String(html) .replace(/&/g, '&') .replace(/"/g, '"') @@ -4549,46 +5893,75 @@ exports.escape = function(html){ /** * Array#forEach (<=IE8) * - * @param {Array} array + * @api private + * @param {Array} arr * @param {Function} fn * @param {Object} scope - * @api private */ - -exports.forEach = function(arr, fn, scope){ - for (var i = 0, l = arr.length; i < l; i++) +exports.forEach = function(arr, fn, scope) { + for (var i = 0, l = arr.length; i < l; i++) { fn.call(scope, arr[i], i); + } }; /** - * Array#indexOf (<=IE8) + * Test if the given obj is type of string. * - * @parma {Array} arr - * @param {Object} obj to find index of - * @param {Number} start * @api private + * @param {Object} obj + * @return {boolean} */ - -exports.indexOf = function(arr, obj, start){ - for (var i = start || 0, l = arr.length; i < l; i++) { - if (arr[i] === obj) - return i; - } - return -1; +exports.isString = function(obj) { + return typeof obj === 'string'; }; /** - * Array#reduce (<=IE8) - * - * @param {Array} array - * @param {Function} fn - * @param {Object} initial value + * Array#map (<=IE8) + * * @api private + * @param {Array} arr + * @param {Function} fn + * @param {Object} scope + * @return {Array} */ - -exports.reduce = function(arr, fn, val){ - var rval = val; - +exports.map = function(arr, fn, scope) { + var result = []; + for (var i = 0, l = arr.length; i < l; i++) { + result.push(fn.call(scope, arr[i], i, arr)); + } + return result; +}; + +/** + * Array#indexOf (<=IE8) + * + * @api private + * @param {Array} arr + * @param {Object} obj to find index of + * @param {number} start + * @return {number} + */ +exports.indexOf = function(arr, obj, start) { + for (var i = start || 0, l = arr.length; i < l; i++) { + if (arr[i] === obj) { + return i; + } + } + return -1; +}; + +/** + * Array#reduce (<=IE8) + * + * @api private + * @param {Array} arr + * @param {Function} fn + * @param {Object} val Initial value. + * @return {*} + */ +exports.reduce = function(arr, fn, val) { + var rval = val; + for (var i = 0, l = arr.length; i < l; i++) { rval = fn(rval, arr[i], i, arr); } @@ -4599,17 +5972,19 @@ exports.reduce = function(arr, fn, val){ /** * Array#filter (<=IE8) * - * @param {Array} array - * @param {Function} fn * @api private + * @param {Array} arr + * @param {Function} fn + * @return {Array} */ - -exports.filter = function(arr, fn){ +exports.filter = function(arr, fn) { var ret = []; for (var i = 0, l = arr.length; i < l; i++) { var val = arr[i]; - if (fn(val, i, arr)) ret.push(val); + if (fn(val, i, arr)) { + ret.push(val); + } } return ret; @@ -4618,14 +5993,13 @@ exports.filter = function(arr, fn){ /** * Object.keys (<=IE8) * + * @api private * @param {Object} obj * @return {Array} keys - * @api private */ - -exports.keys = Object.keys || function(obj) { - var keys = [] - , has = Object.prototype.hasOwnProperty // for `window` on <=IE8 +exports.keys = typeof Object.keys === 'function' ? Object.keys : function(obj) { + var keys = []; + var has = Object.prototype.hasOwnProperty; // for `window` on <=IE8 for (var key in obj) { if (has.call(obj, key)) { @@ -4640,49 +6014,82 @@ exports.keys = Object.keys || function(obj) { * Watch the given `files` for changes * and invoke `fn(file)` on modification. * + * @api private * @param {Array} files * @param {Function} fn - * @api private */ - -exports.watch = function(files, fn){ +exports.watch = function(files, fn) { var options = { interval: 100 }; - files.forEach(function(file){ + files.forEach(function(file) { debug('file %s', file); - fs.watchFile(file, options, function(curr, prev){ - if (prev.mtime < curr.mtime) fn(file); + watchFile(file, options, function(curr, prev) { + if (prev.mtime < curr.mtime) { + fn(file); + } }); }); }; /** - * Ignored files. + * Array.isArray (<=IE8) + * + * @api private + * @param {Object} obj + * @return {Boolean} + */ +var isArray = typeof Array.isArray === 'function' ? Array.isArray : function(obj) { + return Object.prototype.toString.call(obj) === '[object Array]'; +}; + +exports.isArray = isArray; + +/** + * Buffer.prototype.toJSON polyfill. + * + * @type {Function} */ +if (typeof Buffer !== 'undefined' && Buffer.prototype) { + Buffer.prototype.toJSON = Buffer.prototype.toJSON || function() { + return Array.prototype.slice.call(this, 0); + }; +} -function ignored(path){ +/** + * Ignored files. + * + * @api private + * @param {string} path + * @return {boolean} + */ +function ignored(path) { return !~ignore.indexOf(path); } /** * Lookup files in the given `dir`. * - * @return {Array} * @api private + * @param {string} dir + * @param {string[]} [ext=['.js']] + * @param {Array} [ret=[]] + * @return {Array} */ - -exports.files = function(dir, ret){ +exports.files = function(dir, ext, ret) { ret = ret || []; - - fs.readdirSync(dir) - .filter(ignored) - .forEach(function(path){ - path = join(dir, path); - if (fs.statSync(path).isDirectory()) { - exports.files(path, ret); - } else if (path.match(/\.(js|coffee)$/)) { - ret.push(path); - } - }); + ext = ext || ['js']; + + var re = new RegExp('\\.(' + ext.join('|') + ')$'); + + readdirSync(dir) + .filter(ignored) + .forEach(function(path) { + path = join(dir, path); + if (statSync(path).isDirectory()) { + exports.files(path, ext, ret); + } else if (path.match(re)) { + ret.push(path); + } + }); return ret; }; @@ -4690,12 +6097,11 @@ exports.files = function(dir, ret){ /** * Compute a slug from the given `str`. * - * @param {String} str - * @return {String} * @api private + * @param {string} str + * @return {string} */ - -exports.slug = function(str){ +exports.slug = function(str) { return str .toLowerCase() .replace(/ +/g, '-') @@ -4703,60 +6109,49 @@ exports.slug = function(str){ }; /** - * Strip the function definition from `str`, - * and re-indent for pre whitespace. + * Strip the function definition from `str`, and re-indent for pre whitespace. + * + * @param {string} str + * @return {string} */ - exports.clean = function(str) { str = str - .replace(/^function *\(.*\) *{/, '') + .replace(/\r\n?|[\n\u2028\u2029]/g, '\n').replace(/^\uFEFF/, '') + .replace(/^function *\(.*\)\s*\{|\(.*\) *=> *\{?/, '') .replace(/\s+\}$/, ''); - var spaces = str.match(/^\n?( *)/)[1].length - , re = new RegExp('^ {' + spaces + '}', 'gm'); + var spaces = str.match(/^\n?( *)/)[1].length; + var tabs = str.match(/^\n?(\t*)/)[1].length; + var re = new RegExp('^\n?' + (tabs ? '\t' : ' ') + '{' + (tabs ? tabs : spaces) + '}', 'gm'); str = str.replace(re, ''); return exports.trim(str); }; -/** - * Escape regular expression characters in `str`. - * - * @param {String} str - * @return {String} - * @api private - */ - -exports.escapeRegexp = function(str){ - return str.replace(/[-\\^$*+?.()|[\]{}]/g, "\\$&"); -}; - /** * Trim the given `str`. * - * @param {String} str - * @return {String} * @api private + * @param {string} str + * @return {string} */ - -exports.trim = function(str){ +exports.trim = function(str) { return str.replace(/^\s+|\s+$/g, ''); }; /** * Parse the given `qs`. * - * @param {String} qs - * @return {Object} * @api private + * @param {string} qs + * @return {Object} */ - -exports.parseQuery = function(qs){ - return exports.reduce(qs.replace('?', '').split('&'), function(obj, pair){ - var i = pair.indexOf('=') - , key = pair.slice(0, i) - , val = pair.slice(++i); +exports.parseQuery = function(qs) { + return exports.reduce(qs.replace('?', '').split('&'), function(obj, pair) { + var i = pair.indexOf('='); + var key = pair.slice(0, i); + var val = pair.slice(++i); obj[key] = decodeURIComponent(val); return obj; @@ -4766,11 +6161,10 @@ exports.parseQuery = function(qs){ /** * Highlight the given string of `js`. * - * @param {String} js - * @return {String} * @api private + * @param {string} js + * @return {string} */ - function highlight(js) { return js .replace(/$1') .replace(/(\d+\.\d+)/gm, '$1') .replace(/(\d+)/gm, '$1') - .replace(/\bnew *(\w+)/gm, 'new $1') - .replace(/\b(function|new|throw|return|var|if|else)\b/gm, '$1') + .replace(/\bnew[ \t]+(\w+)/gm, 'new $1') + .replace(/\b(function|new|throw|return|var|if|else)\b/gm, '$1'); } /** * Highlight the contents of tag `name`. * - * @param {String} name * @api private + * @param {string} name */ - exports.highlightTags = function(name) { - var code = document.getElementsByTagName(name); + var code = document.getElementById('mocha').getElementsByTagName(name); for (var i = 0, len = code.length; i < len; ++i) { code[i].innerHTML = highlight(code[i].innerHTML); } }; -}); // module: utils.js /** - * Node shims. + * If a value could have properties, and has none, this function is called, + * which returns a string representation of the empty value. * - * These are meant only to allow - * mocha.js to run untouched, not - * to allow running node code in - * the browser. + * Functions w/ no properties return `'[Function]'` + * Arrays w/ length === 0 return `'[]'` + * Objects w/ no properties return `'{}'` + * All else: return result of `value.toString()` + * + * @api private + * @param {*} value The value to inspect. + * @param {string} [type] The type of the value, if known. + * @returns {string} */ +function emptyRepresentation(value, type) { + type = type || exports.type(value); -process = {}; -process.exit = function(status){}; -process.stdout = {}; -global = window; + switch (type) { + case 'function': + return '[Function]'; + case 'object': + return '{}'; + case 'array': + return '[]'; + default: + return value.toString(); + } +} + +/** + * Takes some variable and asks `Object.prototype.toString()` what it thinks it + * is. + * + * @api private + * @see https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object/toString + * @param {*} value The value to test. + * @returns {string} + * @example + * type({}) // 'object' + * type([]) // 'array' + * type(1) // 'number' + * type(false) // 'boolean' + * type(Infinity) // 'number' + * type(null) // 'null' + * type(new Date()) // 'date' + * type(/foo/) // 'regexp' + * type('type') // 'string' + * type(global) // 'global' + */ +exports.type = function type(value) { + if (value === undefined) { + return 'undefined'; + } else if (value === null) { + return 'null'; + } else if (typeof Buffer !== 'undefined' && Buffer.isBuffer(value)) { + return 'buffer'; + } + return Object.prototype.toString.call(value) + .replace(/^\[.+\s(.+?)\]$/, '$1') + .toLowerCase(); +}; /** - * next tick implementation. + * Stringify `value`. Different behavior depending on type of value: + * + * - If `value` is undefined or null, return `'[undefined]'` or `'[null]'`, respectively. + * - If `value` is not an object, function or array, return result of `value.toString()` wrapped in double-quotes. + * - If `value` is an *empty* object, function, or array, return result of function + * {@link emptyRepresentation}. + * - If `value` has properties, call {@link exports.canonicalize} on it, then return result of + * JSON.stringify(). + * + * @api private + * @see exports.type + * @param {*} value + * @return {string} */ +exports.stringify = function(value) { + var type = exports.type(value); + + if (!~exports.indexOf(['object', 'array', 'function'], type)) { + if (type !== 'buffer') { + return jsonStringify(value); + } + var json = value.toJSON(); + // Based on the toJSON result + return jsonStringify(json.data && json.type ? json.data : json, 2) + .replace(/,(\n|$)/g, '$1'); + } + + for (var prop in value) { + if (Object.prototype.hasOwnProperty.call(value, prop)) { + return jsonStringify(exports.canonicalize(value), 2).replace(/,(\n|$)/g, '$1'); + } + } + + return emptyRepresentation(value, type); +}; -process.nextTick = (function(){ - // postMessage behaves badly on IE8 - if (window.ActiveXObject || !window.postMessage) { - return function(fn){ fn() }; +/** + * like JSON.stringify but more sense. + * + * @api private + * @param {Object} object + * @param {number=} spaces + * @param {number=} depth + * @returns {*} + */ +function jsonStringify(object, spaces, depth) { + if (typeof spaces === 'undefined') { + // primitive types + return _stringify(object); } - // based on setZeroTimeout by David Baron - // - http://dbaron.org/log/20100309-faster-timeouts - var timeouts = [] - , name = 'mocha-zero-timeout' + depth = depth || 1; + var space = spaces * depth; + var str = isArray(object) ? '[' : '{'; + var end = isArray(object) ? ']' : '}'; + var length = typeof object.length === 'number' ? object.length : exports.keys(object).length; + // `.repeat()` polyfill + function repeat(s, n) { + return new Array(n).join(s); + } - window.addEventListener('message', function(e){ - if (e.source == window && e.data == name) { - if (e.stopPropagation) e.stopPropagation(); - if (timeouts.length) timeouts.shift()(); + function _stringify(val) { + switch (exports.type(val)) { + case 'null': + case 'undefined': + val = '[' + val + ']'; + break; + case 'array': + case 'object': + val = jsonStringify(val, spaces, depth + 1); + break; + case 'boolean': + case 'regexp': + case 'symbol': + case 'number': + val = val === 0 && (1 / val) === -Infinity // `-0` + ? '-0' + : val.toString(); + break; + case 'date': + var sDate; + if (isNaN(val.getTime())) { // Invalid date + sDate = val.toString(); + } else { + sDate = val.toISOString ? val.toISOString() : toISOString(val); + } + val = '[Date: ' + sDate + ']'; + break; + case 'buffer': + var json = val.toJSON(); + // Based on the toJSON result + json = json.data && json.type ? json.data : json; + val = '[Buffer: ' + jsonStringify(json, 2, depth + 1) + ']'; + break; + default: + val = (val === '[Function]' || val === '[Circular]') + ? val + : JSON.stringify(val); // string } - }, true); + return val; + } - return function(fn){ - timeouts.push(fn); - window.postMessage(name, '*'); + for (var i in object) { + if (!Object.prototype.hasOwnProperty.call(object, i)) { + continue; // not my business + } + --length; + str += '\n ' + repeat(' ', space) + + (isArray(object) ? '' : '"' + i + '": ') // key + + _stringify(object[i]) // value + + (length ? ',' : ''); // comma } -})(); + + return str + // [], {} + + (str.length !== 1 ? '\n' + repeat(' ', --space) + end : end); +} /** - * Remove uncaughtException listener. + * Test if a value is a buffer. + * + * @api private + * @param {*} value The value to test. + * @return {boolean} True if `value` is a buffer, otherwise false */ +exports.isBuffer = function(value) { + return typeof Buffer !== 'undefined' && Buffer.isBuffer(value); +}; -process.removeListener = function(e){ - if ('uncaughtException' == e) { - window.onerror = null; +/** + * Return a new Thing that has the keys in sorted order. Recursive. + * + * If the Thing... + * - has already been seen, return string `'[Circular]'` + * - is `undefined`, return string `'[undefined]'` + * - is `null`, return value `null` + * - is some other primitive, return the value + * - is not a primitive or an `Array`, `Object`, or `Function`, return the value of the Thing's `toString()` method + * - is a non-empty `Array`, `Object`, or `Function`, return the result of calling this function again. + * - is an empty `Array`, `Object`, or `Function`, return the result of calling `emptyRepresentation()` + * + * @api private + * @see {@link exports.stringify} + * @param {*} value Thing to inspect. May or may not have properties. + * @param {Array} [stack=[]] Stack of seen values + * @return {(Object|Array|Function|string|undefined)} + */ +exports.canonicalize = function(value, stack) { + var canonicalizedObj; + /* eslint-disable no-unused-vars */ + var prop; + /* eslint-enable no-unused-vars */ + var type = exports.type(value); + function withStack(value, fn) { + stack.push(value); + fn(); + stack.pop(); + } + + stack = stack || []; + + if (exports.indexOf(stack, value) !== -1) { + return '[Circular]'; + } + + switch (type) { + case 'undefined': + case 'buffer': + case 'null': + canonicalizedObj = value; + break; + case 'array': + withStack(value, function() { + canonicalizedObj = exports.map(value, function(item) { + return exports.canonicalize(item, stack); + }); + }); + break; + case 'function': + /* eslint-disable guard-for-in */ + for (prop in value) { + canonicalizedObj = {}; + break; + } + /* eslint-enable guard-for-in */ + if (!canonicalizedObj) { + canonicalizedObj = emptyRepresentation(value, type); + break; + } + /* falls through */ + case 'object': + canonicalizedObj = canonicalizedObj || {}; + withStack(value, function() { + exports.forEach(exports.keys(value).sort(), function(key) { + canonicalizedObj[key] = exports.canonicalize(value[key], stack); + }); + }); + break; + case 'date': + case 'number': + case 'regexp': + case 'boolean': + case 'symbol': + canonicalizedObj = value; + break; + default: + canonicalizedObj = value + ''; } + + return canonicalizedObj; }; /** - * Implements uncaughtException listener. - */ + * Lookup file names at the given `path`. + * + * @api public + * @param {string} path Base path to start searching from. + * @param {string[]} extensions File extensions to look for. + * @param {boolean} recursive Whether or not to recurse into subdirectories. + * @return {string[]} An array of paths. + */ +exports.lookupFiles = function lookupFiles(path, extensions, recursive) { + var files = []; + var re = new RegExp('\\.(' + extensions.join('|') + ')$'); + + if (!exists(path)) { + if (exists(path + '.js')) { + path += '.js'; + } else { + files = glob.sync(path); + if (!files.length) { + throw new Error("cannot resolve path (or pattern) '" + path + "'"); + } + return files; + } + } -process.on = function(e, fn){ - if ('uncaughtException' == e) { - window.onerror = fn; + try { + var stat = statSync(path); + if (stat.isFile()) { + return path; + } + } catch (err) { + // ignore error + return; } + + readdirSync(path).forEach(function(file) { + file = join(path, file); + try { + var stat = statSync(file); + if (stat.isDirectory()) { + if (recursive) { + files = files.concat(lookupFiles(file, extensions, recursive)); + } + return; + } + } catch (err) { + // ignore error + return; + } + if (!stat.isFile() || !re.test(file) || basename(file)[0] === '.') { + return; + } + files.push(file); + }); + + return files; }; -// boot -;(function(){ +/** + * Generate an undefined error with a message warning the user. + * + * @return {Error} + */ + +exports.undefinedError = function() { + return new Error('Caught undefined error, did you throw without specifying what?'); +}; - /** - * Expose mocha. - */ +/** + * Generate an undefined error if `err` is not defined. + * + * @param {Error} err + * @return {Error} + */ - var Mocha = window.Mocha = require('mocha'), - mocha = window.mocha = new Mocha({ reporter: 'html' }); +exports.getError = function(err) { + return err || exports.undefinedError(); +}; - /** - * Override ui to ensure that the ui functions are initialized. - * Normally this would happen in Mocha.prototype.loadFiles. - */ +/** + * @summary + * This Filter based on `mocha-clean` module.(see: `github.com/rstacruz/mocha-clean`) + * @description + * When invoking this function you get a filter function that get the Error.stack as an input, + * and return a prettify output. + * (i.e: strip Mocha and internal node functions from stack trace). + * @returns {Function} + */ +exports.stackTraceFilter = function() { + // TODO: Replace with `process.browser` + var slash = '/'; + var is = typeof document === 'undefined' ? { node: true } : { browser: true }; + var cwd = is.node + ? process.cwd() + slash + : (typeof location === 'undefined' ? window.location : location).href.replace(/\/[^\/]*$/, '/'); + + function isMochaInternal(line) { + return (~line.indexOf('node_modules' + slash + 'mocha' + slash)) + || (~line.indexOf('components' + slash + 'mochajs' + slash)) + || (~line.indexOf('components' + slash + 'mocha' + slash)) + || (~line.indexOf(slash + 'mocha.js')); + } - mocha.ui = function(ui){ - Mocha.prototype.ui.call(this, ui); - this.suite.emit('pre-require', window, null, this); - return this; - }; + function isNodeInternal(line) { + return (~line.indexOf('(timers.js:')) + || (~line.indexOf('(events.js:')) + || (~line.indexOf('(node.js:')) + || (~line.indexOf('(module.js:')) + || (~line.indexOf('GeneratorFunctionPrototype.next (native)')) + || false; + } - /** - * Setup mocha with the given setting options. - */ + return function(stack) { + stack = stack.split('\n'); - mocha.setup = function(opts){ - if ('string' == typeof opts) opts = { ui: opts }; - for (var opt in opts) this[opt](opts[opt]); - return this; - }; + stack = exports.reduce(stack, function(list, line) { + if (isMochaInternal(line)) { + return list; + } - /** - * Run mocha, returning the Runner. - */ + if (is.node && isNodeInternal(line)) { + return list; + } - mocha.run = function(fn){ - var options = mocha.options; - mocha.globals('location'); + // Clean up cwd(absolute) + if (/\(?.+:\d+:\d+\)?$/.test(line)) { + line = line.replace(cwd, ''); + } - var query = Mocha.utils.parseQuery(window.location.search || ''); - if (query.grep) mocha.grep(query.grep); + list.push(line); + return list; + }, []); - return Mocha.prototype.run.call(mocha, function(){ - Mocha.utils.highlightTags('code'); - if (fn) fn(); - }); + return stack.join('\n'); }; -})(); -})(); +}; + +}).call(this,require('_process'),require("buffer").Buffer) +},{"_process":58,"buffer":45,"debug":2,"fs":43,"glob":43,"path":43,"to-iso-string":72,"util":75}],40:[function(require,module,exports){ +'use strict' + +exports.toByteArray = toByteArray +exports.fromByteArray = fromByteArray + +var lookup = [] +var revLookup = [] +var Arr = typeof Uint8Array !== 'undefined' ? Uint8Array : Array + +function init () { + var code = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/' + for (var i = 0, len = code.length; i < len; ++i) { + lookup[i] = code[i] + revLookup[code.charCodeAt(i)] = i + } + + revLookup['-'.charCodeAt(0)] = 62 + revLookup['_'.charCodeAt(0)] = 63 +} + +init() + +function toByteArray (b64) { + var i, j, l, tmp, placeHolders, arr + var len = b64.length + + if (len % 4 > 0) { + throw new Error('Invalid string. Length must be a multiple of 4') + } + + // the number of equal signs (place holders) + // if there are two placeholders, than the two characters before it + // represent one byte + // if there is only one, then the three characters before it represent 2 bytes + // this is just a cheap hack to not do indexOf twice + placeHolders = b64[len - 2] === '=' ? 2 : b64[len - 1] === '=' ? 1 : 0 + + // base64 is 4/3 + up to two characters of the original data + arr = new Arr(len * 3 / 4 - placeHolders) + + // if there are placeholders, only get up to the last complete 4 chars + l = placeHolders > 0 ? len - 4 : len + + var L = 0 + + for (i = 0, j = 0; i < l; i += 4, j += 3) { + tmp = (revLookup[b64.charCodeAt(i)] << 18) | (revLookup[b64.charCodeAt(i + 1)] << 12) | (revLookup[b64.charCodeAt(i + 2)] << 6) | revLookup[b64.charCodeAt(i + 3)] + arr[L++] = (tmp >> 16) & 0xFF + arr[L++] = (tmp >> 8) & 0xFF + arr[L++] = tmp & 0xFF + } + + if (placeHolders === 2) { + tmp = (revLookup[b64.charCodeAt(i)] << 2) | (revLookup[b64.charCodeAt(i + 1)] >> 4) + arr[L++] = tmp & 0xFF + } else if (placeHolders === 1) { + tmp = (revLookup[b64.charCodeAt(i)] << 10) | (revLookup[b64.charCodeAt(i + 1)] << 4) | (revLookup[b64.charCodeAt(i + 2)] >> 2) + arr[L++] = (tmp >> 8) & 0xFF + arr[L++] = tmp & 0xFF + } + + return arr +} + +function tripletToBase64 (num) { + return lookup[num >> 18 & 0x3F] + lookup[num >> 12 & 0x3F] + lookup[num >> 6 & 0x3F] + lookup[num & 0x3F] +} + +function encodeChunk (uint8, start, end) { + var tmp + var output = [] + for (var i = start; i < end; i += 3) { + tmp = (uint8[i] << 16) + (uint8[i + 1] << 8) + (uint8[i + 2]) + output.push(tripletToBase64(tmp)) + } + return output.join('') +} + +function fromByteArray (uint8) { + var tmp + var len = uint8.length + var extraBytes = len % 3 // if we have 1 byte left, pad 2 bytes + var output = '' + var parts = [] + var maxChunkLength = 16383 // must be multiple of 3 + + // go through the array every three bytes, we'll deal with trailing stuff later + for (var i = 0, len2 = len - extraBytes; i < len2; i += maxChunkLength) { + parts.push(encodeChunk(uint8, i, (i + maxChunkLength) > len2 ? len2 : (i + maxChunkLength))) + } + + // pad the end with zeros, but make sure to not forget the extra bytes + if (extraBytes === 1) { + tmp = uint8[len - 1] + output += lookup[tmp >> 2] + output += lookup[(tmp << 4) & 0x3F] + output += '==' + } else if (extraBytes === 2) { + tmp = (uint8[len - 2] << 8) + (uint8[len - 1]) + output += lookup[tmp >> 10] + output += lookup[(tmp >> 4) & 0x3F] + output += lookup[(tmp << 2) & 0x3F] + output += '=' + } + + parts.push(output) + + return parts.join('') +} + +},{}],41:[function(require,module,exports){ + +},{}],42:[function(require,module,exports){ +(function (process){ +var WritableStream = require('stream').Writable +var inherits = require('util').inherits + +module.exports = BrowserStdout + + +inherits(BrowserStdout, WritableStream) + +function BrowserStdout(opts) { + if (!(this instanceof BrowserStdout)) return new BrowserStdout(opts) + + opts = opts || {} + WritableStream.call(this, opts) + this.label = (opts.label !== undefined) ? opts.label : 'stdout' +} + +BrowserStdout.prototype._write = function(chunks, encoding, cb) { + var output = chunks.toString ? chunks.toString() : chunks + if (this.label === false) { + console.log(output) + } else { + console.log(this.label+':', output) + } + process.nextTick(cb) +} + +}).call(this,require('_process')) +},{"_process":58,"stream":59,"util":75}],43:[function(require,module,exports){ +arguments[4][41][0].apply(exports,arguments) +},{"dup":41}],44:[function(require,module,exports){ +(function (global){ +'use strict'; + +var buffer = require('buffer'); +var Buffer = buffer.Buffer; +var SlowBuffer = buffer.SlowBuffer; +var MAX_LEN = buffer.kMaxLength || 2147483647; +exports.alloc = function alloc(size, fill, encoding) { + if (typeof Buffer.alloc === 'function') { + return Buffer.alloc(size, fill, encoding); + } + if (typeof encoding === 'number') { + throw new TypeError('encoding must not be number'); + } + if (typeof size !== 'number') { + throw new TypeError('size must be a number'); + } + if (size > MAX_LEN) { + throw new RangeError('size is too large'); + } + var enc = encoding; + var _fill = fill; + if (_fill === undefined) { + enc = undefined; + _fill = 0; + } + var buf = new Buffer(size); + if (typeof _fill === 'string') { + var fillBuf = new Buffer(_fill, enc); + var flen = fillBuf.length; + var i = -1; + while (++i < size) { + buf[i] = fillBuf[i % flen]; + } + } else { + buf.fill(_fill); + } + return buf; +} +exports.allocUnsafe = function allocUnsafe(size) { + if (typeof Buffer.allocUnsafe === 'function') { + return Buffer.allocUnsafe(size); + } + if (typeof size !== 'number') { + throw new TypeError('size must be a number'); + } + if (size > MAX_LEN) { + throw new RangeError('size is too large'); + } + return new Buffer(size); +} +exports.from = function from(value, encodingOrOffset, length) { + if (typeof Buffer.from === 'function' && (!global.Uint8Array || Uint8Array.from !== Buffer.from)) { + return Buffer.from(value, encodingOrOffset, length); + } + if (typeof value === 'number') { + throw new TypeError('"value" argument must not be a number'); + } + if (typeof value === 'string') { + return new Buffer(value, encodingOrOffset); + } + if (typeof ArrayBuffer !== 'undefined' && value instanceof ArrayBuffer) { + var offset = encodingOrOffset; + if (arguments.length === 1) { + return new Buffer(value); + } + if (typeof offset === 'undefined') { + offset = 0; + } + var len = length; + if (typeof len === 'undefined') { + len = value.byteLength - offset; + } + if (offset >= value.byteLength) { + throw new RangeError('\'offset\' is out of bounds'); + } + if (len > value.byteLength - offset) { + throw new RangeError('\'length\' is out of bounds'); + } + return new Buffer(value.slice(offset, offset + len)); + } + if (Buffer.isBuffer(value)) { + var out = new Buffer(value.length); + value.copy(out, 0, 0, value.length); + return out; + } + if (value) { + if (Array.isArray(value) || (typeof ArrayBuffer !== 'undefined' && value.buffer instanceof ArrayBuffer) || 'length' in value) { + return new Buffer(value); + } + if (value.type === 'Buffer' && Array.isArray(value.data)) { + return new Buffer(value.data); + } + } + + throw new TypeError('First argument must be a string, Buffer, ' + 'ArrayBuffer, Array, or array-like object.'); +} +exports.allocUnsafeSlow = function allocUnsafeSlow(size) { + if (typeof Buffer.allocUnsafeSlow === 'function') { + return Buffer.allocUnsafeSlow(size); + } + if (typeof size !== 'number') { + throw new TypeError('size must be a number'); + } + if (size >= MAX_LEN) { + throw new RangeError('size is too large'); + } + return new SlowBuffer(size); +} + +}).call(this,typeof global !== "undefined" ? global : typeof self !== "undefined" ? self : typeof window !== "undefined" ? window : {}) +},{"buffer":45}],45:[function(require,module,exports){ +(function (global){ +/*! + * The buffer module from node.js, for the browser. + * + * @author Feross Aboukhadijeh + * @license MIT + */ +/* eslint-disable no-proto */ + +'use strict' + +var base64 = require('base64-js') +var ieee754 = require('ieee754') +var isArray = require('isarray') + +exports.Buffer = Buffer +exports.SlowBuffer = SlowBuffer +exports.INSPECT_MAX_BYTES = 50 + +/** + * If `Buffer.TYPED_ARRAY_SUPPORT`: + * === true Use Uint8Array implementation (fastest) + * === false Use Object implementation (most compatible, even IE6) + * + * Browsers that support typed arrays are IE 10+, Firefox 4+, Chrome 7+, Safari 5.1+, + * Opera 11.6+, iOS 4.2+. + * + * Due to various browser bugs, sometimes the Object implementation will be used even + * when the browser supports typed arrays. + * + * Note: + * + * - Firefox 4-29 lacks support for adding new properties to `Uint8Array` instances, + * See: https://bugzilla.mozilla.org/show_bug.cgi?id=695438. + * + * - Chrome 9-10 is missing the `TypedArray.prototype.subarray` function. + * + * - IE10 has a broken `TypedArray.prototype.subarray` function which returns arrays of + * incorrect length in some situations. + + * We detect these buggy browsers and set `Buffer.TYPED_ARRAY_SUPPORT` to `false` so they + * get the Object implementation, which is slower but behaves correctly. + */ +Buffer.TYPED_ARRAY_SUPPORT = global.TYPED_ARRAY_SUPPORT !== undefined + ? global.TYPED_ARRAY_SUPPORT + : typedArraySupport() + +/* + * Export kMaxLength after typed array support is determined. + */ +exports.kMaxLength = kMaxLength() + +function typedArraySupport () { + try { + var arr = new Uint8Array(1) + arr.foo = function () { return 42 } + return arr.foo() === 42 && // typed array instances can be augmented + typeof arr.subarray === 'function' && // chrome 9-10 lack `subarray` + arr.subarray(1, 1).byteLength === 0 // ie10 has broken `subarray` + } catch (e) { + return false + } +} + +function kMaxLength () { + return Buffer.TYPED_ARRAY_SUPPORT + ? 0x7fffffff + : 0x3fffffff +} + +function createBuffer (that, length) { + if (kMaxLength() < length) { + throw new RangeError('Invalid typed array length') + } + if (Buffer.TYPED_ARRAY_SUPPORT) { + // Return an augmented `Uint8Array` instance, for best performance + that = new Uint8Array(length) + that.__proto__ = Buffer.prototype + } else { + // Fallback: Return an object instance of the Buffer class + if (that === null) { + that = new Buffer(length) + } + that.length = length + } + + return that +} + +/** + * The Buffer constructor returns instances of `Uint8Array` that have their + * prototype changed to `Buffer.prototype`. Furthermore, `Buffer` is a subclass of + * `Uint8Array`, so the returned instances will have all the node `Buffer` methods + * and the `Uint8Array` methods. Square bracket notation works as expected -- it + * returns a single octet. + * + * The `Uint8Array` prototype remains unmodified. + */ + +function Buffer (arg, encodingOrOffset, length) { + if (!Buffer.TYPED_ARRAY_SUPPORT && !(this instanceof Buffer)) { + return new Buffer(arg, encodingOrOffset, length) + } + + // Common case. + if (typeof arg === 'number') { + if (typeof encodingOrOffset === 'string') { + throw new Error( + 'If encoding is specified then the first argument must be a string' + ) + } + return allocUnsafe(this, arg) + } + return from(this, arg, encodingOrOffset, length) +} + +Buffer.poolSize = 8192 // not used by this implementation + +// TODO: Legacy, not needed anymore. Remove in next major version. +Buffer._augment = function (arr) { + arr.__proto__ = Buffer.prototype + return arr +} + +function from (that, value, encodingOrOffset, length) { + if (typeof value === 'number') { + throw new TypeError('"value" argument must not be a number') + } + + if (typeof ArrayBuffer !== 'undefined' && value instanceof ArrayBuffer) { + return fromArrayBuffer(that, value, encodingOrOffset, length) + } + + if (typeof value === 'string') { + return fromString(that, value, encodingOrOffset) + } + + return fromObject(that, value) +} + +/** + * Functionally equivalent to Buffer(arg, encoding) but throws a TypeError + * if value is a number. + * Buffer.from(str[, encoding]) + * Buffer.from(array) + * Buffer.from(buffer) + * Buffer.from(arrayBuffer[, byteOffset[, length]]) + **/ +Buffer.from = function (value, encodingOrOffset, length) { + return from(null, value, encodingOrOffset, length) +} + +if (Buffer.TYPED_ARRAY_SUPPORT) { + Buffer.prototype.__proto__ = Uint8Array.prototype + Buffer.__proto__ = Uint8Array + if (typeof Symbol !== 'undefined' && Symbol.species && + Buffer[Symbol.species] === Buffer) { + // Fix subarray() in ES2016. See: https://github.com/feross/buffer/pull/97 + Object.defineProperty(Buffer, Symbol.species, { + value: null, + configurable: true + }) + } +} + +function assertSize (size) { + if (typeof size !== 'number') { + throw new TypeError('"size" argument must be a number') + } +} + +function alloc (that, size, fill, encoding) { + assertSize(size) + if (size <= 0) { + return createBuffer(that, size) + } + if (fill !== undefined) { + // Only pay attention to encoding if it's a string. This + // prevents accidentally sending in a number that would + // be interpretted as a start offset. + return typeof encoding === 'string' + ? createBuffer(that, size).fill(fill, encoding) + : createBuffer(that, size).fill(fill) + } + return createBuffer(that, size) +} + +/** + * Creates a new filled Buffer instance. + * alloc(size[, fill[, encoding]]) + **/ +Buffer.alloc = function (size, fill, encoding) { + return alloc(null, size, fill, encoding) +} + +function allocUnsafe (that, size) { + assertSize(size) + that = createBuffer(that, size < 0 ? 0 : checked(size) | 0) + if (!Buffer.TYPED_ARRAY_SUPPORT) { + for (var i = 0; i < size; i++) { + that[i] = 0 + } + } + return that +} + +/** + * Equivalent to Buffer(num), by default creates a non-zero-filled Buffer instance. + * */ +Buffer.allocUnsafe = function (size) { + return allocUnsafe(null, size) +} +/** + * Equivalent to SlowBuffer(num), by default creates a non-zero-filled Buffer instance. + */ +Buffer.allocUnsafeSlow = function (size) { + return allocUnsafe(null, size) +} + +function fromString (that, string, encoding) { + if (typeof encoding !== 'string' || encoding === '') { + encoding = 'utf8' + } + + if (!Buffer.isEncoding(encoding)) { + throw new TypeError('"encoding" must be a valid string encoding') + } + + var length = byteLength(string, encoding) | 0 + that = createBuffer(that, length) + + that.write(string, encoding) + return that +} + +function fromArrayLike (that, array) { + var length = checked(array.length) | 0 + that = createBuffer(that, length) + for (var i = 0; i < length; i += 1) { + that[i] = array[i] & 255 + } + return that +} + +function fromArrayBuffer (that, array, byteOffset, length) { + array.byteLength // this throws if `array` is not a valid ArrayBuffer + + if (byteOffset < 0 || array.byteLength < byteOffset) { + throw new RangeError('\'offset\' is out of bounds') + } + + if (array.byteLength < byteOffset + (length || 0)) { + throw new RangeError('\'length\' is out of bounds') + } + + if (length === undefined) { + array = new Uint8Array(array, byteOffset) + } else { + array = new Uint8Array(array, byteOffset, length) + } + + if (Buffer.TYPED_ARRAY_SUPPORT) { + // Return an augmented `Uint8Array` instance, for best performance + that = array + that.__proto__ = Buffer.prototype + } else { + // Fallback: Return an object instance of the Buffer class + that = fromArrayLike(that, array) + } + return that +} + +function fromObject (that, obj) { + if (Buffer.isBuffer(obj)) { + var len = checked(obj.length) | 0 + that = createBuffer(that, len) + + if (that.length === 0) { + return that + } + + obj.copy(that, 0, 0, len) + return that + } + + if (obj) { + if ((typeof ArrayBuffer !== 'undefined' && + obj.buffer instanceof ArrayBuffer) || 'length' in obj) { + if (typeof obj.length !== 'number' || isnan(obj.length)) { + return createBuffer(that, 0) + } + return fromArrayLike(that, obj) + } + + if (obj.type === 'Buffer' && isArray(obj.data)) { + return fromArrayLike(that, obj.data) + } + } + + throw new TypeError('First argument must be a string, Buffer, ArrayBuffer, Array, or array-like object.') +} + +function checked (length) { + // Note: cannot use `length < kMaxLength` here because that fails when + // length is NaN (which is otherwise coerced to zero.) + if (length >= kMaxLength()) { + throw new RangeError('Attempt to allocate Buffer larger than maximum ' + + 'size: 0x' + kMaxLength().toString(16) + ' bytes') + } + return length | 0 +} + +function SlowBuffer (length) { + if (+length != length) { // eslint-disable-line eqeqeq + length = 0 + } + return Buffer.alloc(+length) +} + +Buffer.isBuffer = function isBuffer (b) { + return !!(b != null && b._isBuffer) +} + +Buffer.compare = function compare (a, b) { + if (!Buffer.isBuffer(a) || !Buffer.isBuffer(b)) { + throw new TypeError('Arguments must be Buffers') + } + + if (a === b) return 0 + + var x = a.length + var y = b.length + + for (var i = 0, len = Math.min(x, y); i < len; ++i) { + if (a[i] !== b[i]) { + x = a[i] + y = b[i] + break + } + } + + if (x < y) return -1 + if (y < x) return 1 + return 0 +} + +Buffer.isEncoding = function isEncoding (encoding) { + switch (String(encoding).toLowerCase()) { + case 'hex': + case 'utf8': + case 'utf-8': + case 'ascii': + case 'binary': + case 'base64': + case 'raw': + case 'ucs2': + case 'ucs-2': + case 'utf16le': + case 'utf-16le': + return true + default: + return false + } +} + +Buffer.concat = function concat (list, length) { + if (!isArray(list)) { + throw new TypeError('"list" argument must be an Array of Buffers') + } + + if (list.length === 0) { + return Buffer.alloc(0) + } + + var i + if (length === undefined) { + length = 0 + for (i = 0; i < list.length; i++) { + length += list[i].length + } + } + + var buffer = Buffer.allocUnsafe(length) + var pos = 0 + for (i = 0; i < list.length; i++) { + var buf = list[i] + if (!Buffer.isBuffer(buf)) { + throw new TypeError('"list" argument must be an Array of Buffers') + } + buf.copy(buffer, pos) + pos += buf.length + } + return buffer +} + +function byteLength (string, encoding) { + if (Buffer.isBuffer(string)) { + return string.length + } + if (typeof ArrayBuffer !== 'undefined' && typeof ArrayBuffer.isView === 'function' && + (ArrayBuffer.isView(string) || string instanceof ArrayBuffer)) { + return string.byteLength + } + if (typeof string !== 'string') { + string = '' + string + } + + var len = string.length + if (len === 0) return 0 + + // Use a for loop to avoid recursion + var loweredCase = false + for (;;) { + switch (encoding) { + case 'ascii': + case 'binary': + // Deprecated + case 'raw': + case 'raws': + return len + case 'utf8': + case 'utf-8': + case undefined: + return utf8ToBytes(string).length + case 'ucs2': + case 'ucs-2': + case 'utf16le': + case 'utf-16le': + return len * 2 + case 'hex': + return len >>> 1 + case 'base64': + return base64ToBytes(string).length + default: + if (loweredCase) return utf8ToBytes(string).length // assume utf8 + encoding = ('' + encoding).toLowerCase() + loweredCase = true + } + } +} +Buffer.byteLength = byteLength + +function slowToString (encoding, start, end) { + var loweredCase = false + + // No need to verify that "this.length <= MAX_UINT32" since it's a read-only + // property of a typed array. + + // This behaves neither like String nor Uint8Array in that we set start/end + // to their upper/lower bounds if the value passed is out of range. + // undefined is handled specially as per ECMA-262 6th Edition, + // Section 13.3.3.7 Runtime Semantics: KeyedBindingInitialization. + if (start === undefined || start < 0) { + start = 0 + } + // Return early if start > this.length. Done here to prevent potential uint32 + // coercion fail below. + if (start > this.length) { + return '' + } + + if (end === undefined || end > this.length) { + end = this.length + } + + if (end <= 0) { + return '' + } + + // Force coersion to uint32. This will also coerce falsey/NaN values to 0. + end >>>= 0 + start >>>= 0 + + if (end <= start) { + return '' + } + + if (!encoding) encoding = 'utf8' + + while (true) { + switch (encoding) { + case 'hex': + return hexSlice(this, start, end) + + case 'utf8': + case 'utf-8': + return utf8Slice(this, start, end) + + case 'ascii': + return asciiSlice(this, start, end) + + case 'binary': + return binarySlice(this, start, end) + + case 'base64': + return base64Slice(this, start, end) + + case 'ucs2': + case 'ucs-2': + case 'utf16le': + case 'utf-16le': + return utf16leSlice(this, start, end) + + default: + if (loweredCase) throw new TypeError('Unknown encoding: ' + encoding) + encoding = (encoding + '').toLowerCase() + loweredCase = true + } + } +} + +// The property is used by `Buffer.isBuffer` and `is-buffer` (in Safari 5-7) to detect +// Buffer instances. +Buffer.prototype._isBuffer = true + +function swap (b, n, m) { + var i = b[n] + b[n] = b[m] + b[m] = i +} + +Buffer.prototype.swap16 = function swap16 () { + var len = this.length + if (len % 2 !== 0) { + throw new RangeError('Buffer size must be a multiple of 16-bits') + } + for (var i = 0; i < len; i += 2) { + swap(this, i, i + 1) + } + return this +} + +Buffer.prototype.swap32 = function swap32 () { + var len = this.length + if (len % 4 !== 0) { + throw new RangeError('Buffer size must be a multiple of 32-bits') + } + for (var i = 0; i < len; i += 4) { + swap(this, i, i + 3) + swap(this, i + 1, i + 2) + } + return this +} + +Buffer.prototype.toString = function toString () { + var length = this.length | 0 + if (length === 0) return '' + if (arguments.length === 0) return utf8Slice(this, 0, length) + return slowToString.apply(this, arguments) +} + +Buffer.prototype.equals = function equals (b) { + if (!Buffer.isBuffer(b)) throw new TypeError('Argument must be a Buffer') + if (this === b) return true + return Buffer.compare(this, b) === 0 +} + +Buffer.prototype.inspect = function inspect () { + var str = '' + var max = exports.INSPECT_MAX_BYTES + if (this.length > 0) { + str = this.toString('hex', 0, max).match(/.{2}/g).join(' ') + if (this.length > max) str += ' ... ' + } + return '' +} + +Buffer.prototype.compare = function compare (target, start, end, thisStart, thisEnd) { + if (!Buffer.isBuffer(target)) { + throw new TypeError('Argument must be a Buffer') + } + + if (start === undefined) { + start = 0 + } + if (end === undefined) { + end = target ? target.length : 0 + } + if (thisStart === undefined) { + thisStart = 0 + } + if (thisEnd === undefined) { + thisEnd = this.length + } + + if (start < 0 || end > target.length || thisStart < 0 || thisEnd > this.length) { + throw new RangeError('out of range index') + } + + if (thisStart >= thisEnd && start >= end) { + return 0 + } + if (thisStart >= thisEnd) { + return -1 + } + if (start >= end) { + return 1 + } + + start >>>= 0 + end >>>= 0 + thisStart >>>= 0 + thisEnd >>>= 0 + + if (this === target) return 0 + + var x = thisEnd - thisStart + var y = end - start + var len = Math.min(x, y) + + var thisCopy = this.slice(thisStart, thisEnd) + var targetCopy = target.slice(start, end) + + for (var i = 0; i < len; ++i) { + if (thisCopy[i] !== targetCopy[i]) { + x = thisCopy[i] + y = targetCopy[i] + break + } + } + + if (x < y) return -1 + if (y < x) return 1 + return 0 +} + +function arrayIndexOf (arr, val, byteOffset, encoding) { + var indexSize = 1 + var arrLength = arr.length + var valLength = val.length + + if (encoding !== undefined) { + encoding = String(encoding).toLowerCase() + if (encoding === 'ucs2' || encoding === 'ucs-2' || + encoding === 'utf16le' || encoding === 'utf-16le') { + if (arr.length < 2 || val.length < 2) { + return -1 + } + indexSize = 2 + arrLength /= 2 + valLength /= 2 + byteOffset /= 2 + } + } + + function read (buf, i) { + if (indexSize === 1) { + return buf[i] + } else { + return buf.readUInt16BE(i * indexSize) + } + } + + var foundIndex = -1 + for (var i = 0; byteOffset + i < arrLength; i++) { + if (read(arr, byteOffset + i) === read(val, foundIndex === -1 ? 0 : i - foundIndex)) { + if (foundIndex === -1) foundIndex = i + if (i - foundIndex + 1 === valLength) return (byteOffset + foundIndex) * indexSize + } else { + if (foundIndex !== -1) i -= i - foundIndex + foundIndex = -1 + } + } + return -1 +} + +Buffer.prototype.indexOf = function indexOf (val, byteOffset, encoding) { + if (typeof byteOffset === 'string') { + encoding = byteOffset + byteOffset = 0 + } else if (byteOffset > 0x7fffffff) { + byteOffset = 0x7fffffff + } else if (byteOffset < -0x80000000) { + byteOffset = -0x80000000 + } + byteOffset >>= 0 + + if (this.length === 0) return -1 + if (byteOffset >= this.length) return -1 + + // Negative offsets start from the end of the buffer + if (byteOffset < 0) byteOffset = Math.max(this.length + byteOffset, 0) + + if (typeof val === 'string') { + val = Buffer.from(val, encoding) + } + + if (Buffer.isBuffer(val)) { + // special case: looking for empty string/buffer always fails + if (val.length === 0) { + return -1 + } + return arrayIndexOf(this, val, byteOffset, encoding) + } + if (typeof val === 'number') { + if (Buffer.TYPED_ARRAY_SUPPORT && Uint8Array.prototype.indexOf === 'function') { + return Uint8Array.prototype.indexOf.call(this, val, byteOffset) + } + return arrayIndexOf(this, [ val ], byteOffset, encoding) + } + + throw new TypeError('val must be string, number or Buffer') +} + +Buffer.prototype.includes = function includes (val, byteOffset, encoding) { + return this.indexOf(val, byteOffset, encoding) !== -1 +} + +function hexWrite (buf, string, offset, length) { + offset = Number(offset) || 0 + var remaining = buf.length - offset + if (!length) { + length = remaining + } else { + length = Number(length) + if (length > remaining) { + length = remaining + } + } + + // must be an even number of digits + var strLen = string.length + if (strLen % 2 !== 0) throw new Error('Invalid hex string') + + if (length > strLen / 2) { + length = strLen / 2 + } + for (var i = 0; i < length; i++) { + var parsed = parseInt(string.substr(i * 2, 2), 16) + if (isNaN(parsed)) return i + buf[offset + i] = parsed + } + return i +} + +function utf8Write (buf, string, offset, length) { + return blitBuffer(utf8ToBytes(string, buf.length - offset), buf, offset, length) +} + +function asciiWrite (buf, string, offset, length) { + return blitBuffer(asciiToBytes(string), buf, offset, length) +} + +function binaryWrite (buf, string, offset, length) { + return asciiWrite(buf, string, offset, length) +} + +function base64Write (buf, string, offset, length) { + return blitBuffer(base64ToBytes(string), buf, offset, length) +} + +function ucs2Write (buf, string, offset, length) { + return blitBuffer(utf16leToBytes(string, buf.length - offset), buf, offset, length) +} + +Buffer.prototype.write = function write (string, offset, length, encoding) { + // Buffer#write(string) + if (offset === undefined) { + encoding = 'utf8' + length = this.length + offset = 0 + // Buffer#write(string, encoding) + } else if (length === undefined && typeof offset === 'string') { + encoding = offset + length = this.length + offset = 0 + // Buffer#write(string, offset[, length][, encoding]) + } else if (isFinite(offset)) { + offset = offset | 0 + if (isFinite(length)) { + length = length | 0 + if (encoding === undefined) encoding = 'utf8' + } else { + encoding = length + length = undefined + } + // legacy write(string, encoding, offset, length) - remove in v0.13 + } else { + throw new Error( + 'Buffer.write(string, encoding, offset[, length]) is no longer supported' + ) + } + + var remaining = this.length - offset + if (length === undefined || length > remaining) length = remaining + + if ((string.length > 0 && (length < 0 || offset < 0)) || offset > this.length) { + throw new RangeError('Attempt to write outside buffer bounds') + } + + if (!encoding) encoding = 'utf8' + + var loweredCase = false + for (;;) { + switch (encoding) { + case 'hex': + return hexWrite(this, string, offset, length) + + case 'utf8': + case 'utf-8': + return utf8Write(this, string, offset, length) + + case 'ascii': + return asciiWrite(this, string, offset, length) + + case 'binary': + return binaryWrite(this, string, offset, length) + + case 'base64': + // Warning: maxLength not taken into account in base64Write + return base64Write(this, string, offset, length) + + case 'ucs2': + case 'ucs-2': + case 'utf16le': + case 'utf-16le': + return ucs2Write(this, string, offset, length) + + default: + if (loweredCase) throw new TypeError('Unknown encoding: ' + encoding) + encoding = ('' + encoding).toLowerCase() + loweredCase = true + } + } +} + +Buffer.prototype.toJSON = function toJSON () { + return { + type: 'Buffer', + data: Array.prototype.slice.call(this._arr || this, 0) + } +} + +function base64Slice (buf, start, end) { + if (start === 0 && end === buf.length) { + return base64.fromByteArray(buf) + } else { + return base64.fromByteArray(buf.slice(start, end)) + } +} + +function utf8Slice (buf, start, end) { + end = Math.min(buf.length, end) + var res = [] + + var i = start + while (i < end) { + var firstByte = buf[i] + var codePoint = null + var bytesPerSequence = (firstByte > 0xEF) ? 4 + : (firstByte > 0xDF) ? 3 + : (firstByte > 0xBF) ? 2 + : 1 + + if (i + bytesPerSequence <= end) { + var secondByte, thirdByte, fourthByte, tempCodePoint + + switch (bytesPerSequence) { + case 1: + if (firstByte < 0x80) { + codePoint = firstByte + } + break + case 2: + secondByte = buf[i + 1] + if ((secondByte & 0xC0) === 0x80) { + tempCodePoint = (firstByte & 0x1F) << 0x6 | (secondByte & 0x3F) + if (tempCodePoint > 0x7F) { + codePoint = tempCodePoint + } + } + break + case 3: + secondByte = buf[i + 1] + thirdByte = buf[i + 2] + if ((secondByte & 0xC0) === 0x80 && (thirdByte & 0xC0) === 0x80) { + tempCodePoint = (firstByte & 0xF) << 0xC | (secondByte & 0x3F) << 0x6 | (thirdByte & 0x3F) + if (tempCodePoint > 0x7FF && (tempCodePoint < 0xD800 || tempCodePoint > 0xDFFF)) { + codePoint = tempCodePoint + } + } + break + case 4: + secondByte = buf[i + 1] + thirdByte = buf[i + 2] + fourthByte = buf[i + 3] + if ((secondByte & 0xC0) === 0x80 && (thirdByte & 0xC0) === 0x80 && (fourthByte & 0xC0) === 0x80) { + tempCodePoint = (firstByte & 0xF) << 0x12 | (secondByte & 0x3F) << 0xC | (thirdByte & 0x3F) << 0x6 | (fourthByte & 0x3F) + if (tempCodePoint > 0xFFFF && tempCodePoint < 0x110000) { + codePoint = tempCodePoint + } + } + } + } + + if (codePoint === null) { + // we did not generate a valid codePoint so insert a + // replacement char (U+FFFD) and advance only 1 byte + codePoint = 0xFFFD + bytesPerSequence = 1 + } else if (codePoint > 0xFFFF) { + // encode to utf16 (surrogate pair dance) + codePoint -= 0x10000 + res.push(codePoint >>> 10 & 0x3FF | 0xD800) + codePoint = 0xDC00 | codePoint & 0x3FF + } + + res.push(codePoint) + i += bytesPerSequence + } + + return decodeCodePointsArray(res) +} + +// Based on http://stackoverflow.com/a/22747272/680742, the browser with +// the lowest limit is Chrome, with 0x10000 args. +// We go 1 magnitude less, for safety +var MAX_ARGUMENTS_LENGTH = 0x1000 + +function decodeCodePointsArray (codePoints) { + var len = codePoints.length + if (len <= MAX_ARGUMENTS_LENGTH) { + return String.fromCharCode.apply(String, codePoints) // avoid extra slice() + } + + // Decode in chunks to avoid "call stack size exceeded". + var res = '' + var i = 0 + while (i < len) { + res += String.fromCharCode.apply( + String, + codePoints.slice(i, i += MAX_ARGUMENTS_LENGTH) + ) + } + return res +} + +function asciiSlice (buf, start, end) { + var ret = '' + end = Math.min(buf.length, end) + + for (var i = start; i < end; i++) { + ret += String.fromCharCode(buf[i] & 0x7F) + } + return ret +} + +function binarySlice (buf, start, end) { + var ret = '' + end = Math.min(buf.length, end) + + for (var i = start; i < end; i++) { + ret += String.fromCharCode(buf[i]) + } + return ret +} + +function hexSlice (buf, start, end) { + var len = buf.length + + if (!start || start < 0) start = 0 + if (!end || end < 0 || end > len) end = len + + var out = '' + for (var i = start; i < end; i++) { + out += toHex(buf[i]) + } + return out +} + +function utf16leSlice (buf, start, end) { + var bytes = buf.slice(start, end) + var res = '' + for (var i = 0; i < bytes.length; i += 2) { + res += String.fromCharCode(bytes[i] + bytes[i + 1] * 256) + } + return res +} + +Buffer.prototype.slice = function slice (start, end) { + var len = this.length + start = ~~start + end = end === undefined ? len : ~~end + + if (start < 0) { + start += len + if (start < 0) start = 0 + } else if (start > len) { + start = len + } + + if (end < 0) { + end += len + if (end < 0) end = 0 + } else if (end > len) { + end = len + } + + if (end < start) end = start + + var newBuf + if (Buffer.TYPED_ARRAY_SUPPORT) { + newBuf = this.subarray(start, end) + newBuf.__proto__ = Buffer.prototype + } else { + var sliceLen = end - start + newBuf = new Buffer(sliceLen, undefined) + for (var i = 0; i < sliceLen; i++) { + newBuf[i] = this[i + start] + } + } + + return newBuf +} + +/* + * Need to make sure that buffer isn't trying to write out of bounds. + */ +function checkOffset (offset, ext, length) { + if ((offset % 1) !== 0 || offset < 0) throw new RangeError('offset is not uint') + if (offset + ext > length) throw new RangeError('Trying to access beyond buffer length') +} + +Buffer.prototype.readUIntLE = function readUIntLE (offset, byteLength, noAssert) { + offset = offset | 0 + byteLength = byteLength | 0 + if (!noAssert) checkOffset(offset, byteLength, this.length) + + var val = this[offset] + var mul = 1 + var i = 0 + while (++i < byteLength && (mul *= 0x100)) { + val += this[offset + i] * mul + } + + return val +} + +Buffer.prototype.readUIntBE = function readUIntBE (offset, byteLength, noAssert) { + offset = offset | 0 + byteLength = byteLength | 0 + if (!noAssert) { + checkOffset(offset, byteLength, this.length) + } + + var val = this[offset + --byteLength] + var mul = 1 + while (byteLength > 0 && (mul *= 0x100)) { + val += this[offset + --byteLength] * mul + } + + return val +} + +Buffer.prototype.readUInt8 = function readUInt8 (offset, noAssert) { + if (!noAssert) checkOffset(offset, 1, this.length) + return this[offset] +} + +Buffer.prototype.readUInt16LE = function readUInt16LE (offset, noAssert) { + if (!noAssert) checkOffset(offset, 2, this.length) + return this[offset] | (this[offset + 1] << 8) +} + +Buffer.prototype.readUInt16BE = function readUInt16BE (offset, noAssert) { + if (!noAssert) checkOffset(offset, 2, this.length) + return (this[offset] << 8) | this[offset + 1] +} + +Buffer.prototype.readUInt32LE = function readUInt32LE (offset, noAssert) { + if (!noAssert) checkOffset(offset, 4, this.length) + + return ((this[offset]) | + (this[offset + 1] << 8) | + (this[offset + 2] << 16)) + + (this[offset + 3] * 0x1000000) +} + +Buffer.prototype.readUInt32BE = function readUInt32BE (offset, noAssert) { + if (!noAssert) checkOffset(offset, 4, this.length) + + return (this[offset] * 0x1000000) + + ((this[offset + 1] << 16) | + (this[offset + 2] << 8) | + this[offset + 3]) +} + +Buffer.prototype.readIntLE = function readIntLE (offset, byteLength, noAssert) { + offset = offset | 0 + byteLength = byteLength | 0 + if (!noAssert) checkOffset(offset, byteLength, this.length) + + var val = this[offset] + var mul = 1 + var i = 0 + while (++i < byteLength && (mul *= 0x100)) { + val += this[offset + i] * mul + } + mul *= 0x80 + + if (val >= mul) val -= Math.pow(2, 8 * byteLength) + + return val +} + +Buffer.prototype.readIntBE = function readIntBE (offset, byteLength, noAssert) { + offset = offset | 0 + byteLength = byteLength | 0 + if (!noAssert) checkOffset(offset, byteLength, this.length) + + var i = byteLength + var mul = 1 + var val = this[offset + --i] + while (i > 0 && (mul *= 0x100)) { + val += this[offset + --i] * mul + } + mul *= 0x80 + + if (val >= mul) val -= Math.pow(2, 8 * byteLength) + + return val +} + +Buffer.prototype.readInt8 = function readInt8 (offset, noAssert) { + if (!noAssert) checkOffset(offset, 1, this.length) + if (!(this[offset] & 0x80)) return (this[offset]) + return ((0xff - this[offset] + 1) * -1) +} + +Buffer.prototype.readInt16LE = function readInt16LE (offset, noAssert) { + if (!noAssert) checkOffset(offset, 2, this.length) + var val = this[offset] | (this[offset + 1] << 8) + return (val & 0x8000) ? val | 0xFFFF0000 : val +} + +Buffer.prototype.readInt16BE = function readInt16BE (offset, noAssert) { + if (!noAssert) checkOffset(offset, 2, this.length) + var val = this[offset + 1] | (this[offset] << 8) + return (val & 0x8000) ? val | 0xFFFF0000 : val +} + +Buffer.prototype.readInt32LE = function readInt32LE (offset, noAssert) { + if (!noAssert) checkOffset(offset, 4, this.length) + + return (this[offset]) | + (this[offset + 1] << 8) | + (this[offset + 2] << 16) | + (this[offset + 3] << 24) +} + +Buffer.prototype.readInt32BE = function readInt32BE (offset, noAssert) { + if (!noAssert) checkOffset(offset, 4, this.length) + + return (this[offset] << 24) | + (this[offset + 1] << 16) | + (this[offset + 2] << 8) | + (this[offset + 3]) +} + +Buffer.prototype.readFloatLE = function readFloatLE (offset, noAssert) { + if (!noAssert) checkOffset(offset, 4, this.length) + return ieee754.read(this, offset, true, 23, 4) +} + +Buffer.prototype.readFloatBE = function readFloatBE (offset, noAssert) { + if (!noAssert) checkOffset(offset, 4, this.length) + return ieee754.read(this, offset, false, 23, 4) +} + +Buffer.prototype.readDoubleLE = function readDoubleLE (offset, noAssert) { + if (!noAssert) checkOffset(offset, 8, this.length) + return ieee754.read(this, offset, true, 52, 8) +} + +Buffer.prototype.readDoubleBE = function readDoubleBE (offset, noAssert) { + if (!noAssert) checkOffset(offset, 8, this.length) + return ieee754.read(this, offset, false, 52, 8) +} + +function checkInt (buf, value, offset, ext, max, min) { + if (!Buffer.isBuffer(buf)) throw new TypeError('"buffer" argument must be a Buffer instance') + if (value > max || value < min) throw new RangeError('"value" argument is out of bounds') + if (offset + ext > buf.length) throw new RangeError('Index out of range') +} + +Buffer.prototype.writeUIntLE = function writeUIntLE (value, offset, byteLength, noAssert) { + value = +value + offset = offset | 0 + byteLength = byteLength | 0 + if (!noAssert) { + var maxBytes = Math.pow(2, 8 * byteLength) - 1 + checkInt(this, value, offset, byteLength, maxBytes, 0) + } + + var mul = 1 + var i = 0 + this[offset] = value & 0xFF + while (++i < byteLength && (mul *= 0x100)) { + this[offset + i] = (value / mul) & 0xFF + } + + return offset + byteLength +} + +Buffer.prototype.writeUIntBE = function writeUIntBE (value, offset, byteLength, noAssert) { + value = +value + offset = offset | 0 + byteLength = byteLength | 0 + if (!noAssert) { + var maxBytes = Math.pow(2, 8 * byteLength) - 1 + checkInt(this, value, offset, byteLength, maxBytes, 0) + } + + var i = byteLength - 1 + var mul = 1 + this[offset + i] = value & 0xFF + while (--i >= 0 && (mul *= 0x100)) { + this[offset + i] = (value / mul) & 0xFF + } + + return offset + byteLength +} + +Buffer.prototype.writeUInt8 = function writeUInt8 (value, offset, noAssert) { + value = +value + offset = offset | 0 + if (!noAssert) checkInt(this, value, offset, 1, 0xff, 0) + if (!Buffer.TYPED_ARRAY_SUPPORT) value = Math.floor(value) + this[offset] = (value & 0xff) + return offset + 1 +} + +function objectWriteUInt16 (buf, value, offset, littleEndian) { + if (value < 0) value = 0xffff + value + 1 + for (var i = 0, j = Math.min(buf.length - offset, 2); i < j; i++) { + buf[offset + i] = (value & (0xff << (8 * (littleEndian ? i : 1 - i)))) >>> + (littleEndian ? i : 1 - i) * 8 + } +} + +Buffer.prototype.writeUInt16LE = function writeUInt16LE (value, offset, noAssert) { + value = +value + offset = offset | 0 + if (!noAssert) checkInt(this, value, offset, 2, 0xffff, 0) + if (Buffer.TYPED_ARRAY_SUPPORT) { + this[offset] = (value & 0xff) + this[offset + 1] = (value >>> 8) + } else { + objectWriteUInt16(this, value, offset, true) + } + return offset + 2 +} + +Buffer.prototype.writeUInt16BE = function writeUInt16BE (value, offset, noAssert) { + value = +value + offset = offset | 0 + if (!noAssert) checkInt(this, value, offset, 2, 0xffff, 0) + if (Buffer.TYPED_ARRAY_SUPPORT) { + this[offset] = (value >>> 8) + this[offset + 1] = (value & 0xff) + } else { + objectWriteUInt16(this, value, offset, false) + } + return offset + 2 +} + +function objectWriteUInt32 (buf, value, offset, littleEndian) { + if (value < 0) value = 0xffffffff + value + 1 + for (var i = 0, j = Math.min(buf.length - offset, 4); i < j; i++) { + buf[offset + i] = (value >>> (littleEndian ? i : 3 - i) * 8) & 0xff + } +} + +Buffer.prototype.writeUInt32LE = function writeUInt32LE (value, offset, noAssert) { + value = +value + offset = offset | 0 + if (!noAssert) checkInt(this, value, offset, 4, 0xffffffff, 0) + if (Buffer.TYPED_ARRAY_SUPPORT) { + this[offset + 3] = (value >>> 24) + this[offset + 2] = (value >>> 16) + this[offset + 1] = (value >>> 8) + this[offset] = (value & 0xff) + } else { + objectWriteUInt32(this, value, offset, true) + } + return offset + 4 +} + +Buffer.prototype.writeUInt32BE = function writeUInt32BE (value, offset, noAssert) { + value = +value + offset = offset | 0 + if (!noAssert) checkInt(this, value, offset, 4, 0xffffffff, 0) + if (Buffer.TYPED_ARRAY_SUPPORT) { + this[offset] = (value >>> 24) + this[offset + 1] = (value >>> 16) + this[offset + 2] = (value >>> 8) + this[offset + 3] = (value & 0xff) + } else { + objectWriteUInt32(this, value, offset, false) + } + return offset + 4 +} + +Buffer.prototype.writeIntLE = function writeIntLE (value, offset, byteLength, noAssert) { + value = +value + offset = offset | 0 + if (!noAssert) { + var limit = Math.pow(2, 8 * byteLength - 1) + + checkInt(this, value, offset, byteLength, limit - 1, -limit) + } + + var i = 0 + var mul = 1 + var sub = 0 + this[offset] = value & 0xFF + while (++i < byteLength && (mul *= 0x100)) { + if (value < 0 && sub === 0 && this[offset + i - 1] !== 0) { + sub = 1 + } + this[offset + i] = ((value / mul) >> 0) - sub & 0xFF + } + + return offset + byteLength +} + +Buffer.prototype.writeIntBE = function writeIntBE (value, offset, byteLength, noAssert) { + value = +value + offset = offset | 0 + if (!noAssert) { + var limit = Math.pow(2, 8 * byteLength - 1) + + checkInt(this, value, offset, byteLength, limit - 1, -limit) + } + + var i = byteLength - 1 + var mul = 1 + var sub = 0 + this[offset + i] = value & 0xFF + while (--i >= 0 && (mul *= 0x100)) { + if (value < 0 && sub === 0 && this[offset + i + 1] !== 0) { + sub = 1 + } + this[offset + i] = ((value / mul) >> 0) - sub & 0xFF + } + + return offset + byteLength +} + +Buffer.prototype.writeInt8 = function writeInt8 (value, offset, noAssert) { + value = +value + offset = offset | 0 + if (!noAssert) checkInt(this, value, offset, 1, 0x7f, -0x80) + if (!Buffer.TYPED_ARRAY_SUPPORT) value = Math.floor(value) + if (value < 0) value = 0xff + value + 1 + this[offset] = (value & 0xff) + return offset + 1 +} + +Buffer.prototype.writeInt16LE = function writeInt16LE (value, offset, noAssert) { + value = +value + offset = offset | 0 + if (!noAssert) checkInt(this, value, offset, 2, 0x7fff, -0x8000) + if (Buffer.TYPED_ARRAY_SUPPORT) { + this[offset] = (value & 0xff) + this[offset + 1] = (value >>> 8) + } else { + objectWriteUInt16(this, value, offset, true) + } + return offset + 2 +} + +Buffer.prototype.writeInt16BE = function writeInt16BE (value, offset, noAssert) { + value = +value + offset = offset | 0 + if (!noAssert) checkInt(this, value, offset, 2, 0x7fff, -0x8000) + if (Buffer.TYPED_ARRAY_SUPPORT) { + this[offset] = (value >>> 8) + this[offset + 1] = (value & 0xff) + } else { + objectWriteUInt16(this, value, offset, false) + } + return offset + 2 +} + +Buffer.prototype.writeInt32LE = function writeInt32LE (value, offset, noAssert) { + value = +value + offset = offset | 0 + if (!noAssert) checkInt(this, value, offset, 4, 0x7fffffff, -0x80000000) + if (Buffer.TYPED_ARRAY_SUPPORT) { + this[offset] = (value & 0xff) + this[offset + 1] = (value >>> 8) + this[offset + 2] = (value >>> 16) + this[offset + 3] = (value >>> 24) + } else { + objectWriteUInt32(this, value, offset, true) + } + return offset + 4 +} + +Buffer.prototype.writeInt32BE = function writeInt32BE (value, offset, noAssert) { + value = +value + offset = offset | 0 + if (!noAssert) checkInt(this, value, offset, 4, 0x7fffffff, -0x80000000) + if (value < 0) value = 0xffffffff + value + 1 + if (Buffer.TYPED_ARRAY_SUPPORT) { + this[offset] = (value >>> 24) + this[offset + 1] = (value >>> 16) + this[offset + 2] = (value >>> 8) + this[offset + 3] = (value & 0xff) + } else { + objectWriteUInt32(this, value, offset, false) + } + return offset + 4 +} + +function checkIEEE754 (buf, value, offset, ext, max, min) { + if (offset + ext > buf.length) throw new RangeError('Index out of range') + if (offset < 0) throw new RangeError('Index out of range') +} + +function writeFloat (buf, value, offset, littleEndian, noAssert) { + if (!noAssert) { + checkIEEE754(buf, value, offset, 4, 3.4028234663852886e+38, -3.4028234663852886e+38) + } + ieee754.write(buf, value, offset, littleEndian, 23, 4) + return offset + 4 +} + +Buffer.prototype.writeFloatLE = function writeFloatLE (value, offset, noAssert) { + return writeFloat(this, value, offset, true, noAssert) +} + +Buffer.prototype.writeFloatBE = function writeFloatBE (value, offset, noAssert) { + return writeFloat(this, value, offset, false, noAssert) +} + +function writeDouble (buf, value, offset, littleEndian, noAssert) { + if (!noAssert) { + checkIEEE754(buf, value, offset, 8, 1.7976931348623157E+308, -1.7976931348623157E+308) + } + ieee754.write(buf, value, offset, littleEndian, 52, 8) + return offset + 8 +} + +Buffer.prototype.writeDoubleLE = function writeDoubleLE (value, offset, noAssert) { + return writeDouble(this, value, offset, true, noAssert) +} + +Buffer.prototype.writeDoubleBE = function writeDoubleBE (value, offset, noAssert) { + return writeDouble(this, value, offset, false, noAssert) +} + +// copy(targetBuffer, targetStart=0, sourceStart=0, sourceEnd=buffer.length) +Buffer.prototype.copy = function copy (target, targetStart, start, end) { + if (!start) start = 0 + if (!end && end !== 0) end = this.length + if (targetStart >= target.length) targetStart = target.length + if (!targetStart) targetStart = 0 + if (end > 0 && end < start) end = start + + // Copy 0 bytes; we're done + if (end === start) return 0 + if (target.length === 0 || this.length === 0) return 0 + + // Fatal error conditions + if (targetStart < 0) { + throw new RangeError('targetStart out of bounds') + } + if (start < 0 || start >= this.length) throw new RangeError('sourceStart out of bounds') + if (end < 0) throw new RangeError('sourceEnd out of bounds') + + // Are we oob? + if (end > this.length) end = this.length + if (target.length - targetStart < end - start) { + end = target.length - targetStart + start + } + + var len = end - start + var i + + if (this === target && start < targetStart && targetStart < end) { + // descending copy from end + for (i = len - 1; i >= 0; i--) { + target[i + targetStart] = this[i + start] + } + } else if (len < 1000 || !Buffer.TYPED_ARRAY_SUPPORT) { + // ascending copy from start + for (i = 0; i < len; i++) { + target[i + targetStart] = this[i + start] + } + } else { + Uint8Array.prototype.set.call( + target, + this.subarray(start, start + len), + targetStart + ) + } + + return len +} + +// Usage: +// buffer.fill(number[, offset[, end]]) +// buffer.fill(buffer[, offset[, end]]) +// buffer.fill(string[, offset[, end]][, encoding]) +Buffer.prototype.fill = function fill (val, start, end, encoding) { + // Handle string cases: + if (typeof val === 'string') { + if (typeof start === 'string') { + encoding = start + start = 0 + end = this.length + } else if (typeof end === 'string') { + encoding = end + end = this.length + } + if (val.length === 1) { + var code = val.charCodeAt(0) + if (code < 256) { + val = code + } + } + if (encoding !== undefined && typeof encoding !== 'string') { + throw new TypeError('encoding must be a string') + } + if (typeof encoding === 'string' && !Buffer.isEncoding(encoding)) { + throw new TypeError('Unknown encoding: ' + encoding) + } + } else if (typeof val === 'number') { + val = val & 255 + } + + // Invalid ranges are not set to a default, so can range check early. + if (start < 0 || this.length < start || this.length < end) { + throw new RangeError('Out of range index') + } + + if (end <= start) { + return this + } + + start = start >>> 0 + end = end === undefined ? this.length : end >>> 0 + + if (!val) val = 0 + + var i + if (typeof val === 'number') { + for (i = start; i < end; i++) { + this[i] = val + } + } else { + var bytes = Buffer.isBuffer(val) + ? val + : utf8ToBytes(new Buffer(val, encoding).toString()) + var len = bytes.length + for (i = 0; i < end - start; i++) { + this[i + start] = bytes[i % len] + } + } + + return this +} + +// HELPER FUNCTIONS +// ================ + +var INVALID_BASE64_RE = /[^+\/0-9A-Za-z-_]/g + +function base64clean (str) { + // Node strips out invalid characters like \n and \t from the string, base64-js does not + str = stringtrim(str).replace(INVALID_BASE64_RE, '') + // Node converts strings with length < 2 to '' + if (str.length < 2) return '' + // Node allows for non-padded base64 strings (missing trailing ===), base64-js does not + while (str.length % 4 !== 0) { + str = str + '=' + } + return str +} + +function stringtrim (str) { + if (str.trim) return str.trim() + return str.replace(/^\s+|\s+$/g, '') +} + +function toHex (n) { + if (n < 16) return '0' + n.toString(16) + return n.toString(16) +} + +function utf8ToBytes (string, units) { + units = units || Infinity + var codePoint + var length = string.length + var leadSurrogate = null + var bytes = [] + + for (var i = 0; i < length; i++) { + codePoint = string.charCodeAt(i) + + // is surrogate component + if (codePoint > 0xD7FF && codePoint < 0xE000) { + // last char was a lead + if (!leadSurrogate) { + // no lead yet + if (codePoint > 0xDBFF) { + // unexpected trail + if ((units -= 3) > -1) bytes.push(0xEF, 0xBF, 0xBD) + continue + } else if (i + 1 === length) { + // unpaired lead + if ((units -= 3) > -1) bytes.push(0xEF, 0xBF, 0xBD) + continue + } + + // valid lead + leadSurrogate = codePoint + + continue + } + + // 2 leads in a row + if (codePoint < 0xDC00) { + if ((units -= 3) > -1) bytes.push(0xEF, 0xBF, 0xBD) + leadSurrogate = codePoint + continue + } + + // valid surrogate pair + codePoint = (leadSurrogate - 0xD800 << 10 | codePoint - 0xDC00) + 0x10000 + } else if (leadSurrogate) { + // valid bmp char, but last char was a lead + if ((units -= 3) > -1) bytes.push(0xEF, 0xBF, 0xBD) + } + + leadSurrogate = null + + // encode utf8 + if (codePoint < 0x80) { + if ((units -= 1) < 0) break + bytes.push(codePoint) + } else if (codePoint < 0x800) { + if ((units -= 2) < 0) break + bytes.push( + codePoint >> 0x6 | 0xC0, + codePoint & 0x3F | 0x80 + ) + } else if (codePoint < 0x10000) { + if ((units -= 3) < 0) break + bytes.push( + codePoint >> 0xC | 0xE0, + codePoint >> 0x6 & 0x3F | 0x80, + codePoint & 0x3F | 0x80 + ) + } else if (codePoint < 0x110000) { + if ((units -= 4) < 0) break + bytes.push( + codePoint >> 0x12 | 0xF0, + codePoint >> 0xC & 0x3F | 0x80, + codePoint >> 0x6 & 0x3F | 0x80, + codePoint & 0x3F | 0x80 + ) + } else { + throw new Error('Invalid code point') + } + } + + return bytes +} + +function asciiToBytes (str) { + var byteArray = [] + for (var i = 0; i < str.length; i++) { + // Node's code seems to be doing this and not & 0x7F.. + byteArray.push(str.charCodeAt(i) & 0xFF) + } + return byteArray +} + +function utf16leToBytes (str, units) { + var c, hi, lo + var byteArray = [] + for (var i = 0; i < str.length; i++) { + if ((units -= 2) < 0) break + + c = str.charCodeAt(i) + hi = c >> 8 + lo = c % 256 + byteArray.push(lo) + byteArray.push(hi) + } + + return byteArray +} + +function base64ToBytes (str) { + return base64.toByteArray(base64clean(str)) +} + +function blitBuffer (src, dst, offset, length) { + for (var i = 0; i < length; i++) { + if ((i + offset >= dst.length) || (i >= src.length)) break + dst[i + offset] = src[i] + } + return i +} + +function isnan (val) { + return val !== val // eslint-disable-line no-self-compare +} + +}).call(this,typeof global !== "undefined" ? global : typeof self !== "undefined" ? self : typeof window !== "undefined" ? window : {}) +},{"base64-js":40,"ieee754":52,"isarray":46}],46:[function(require,module,exports){ +var toString = {}.toString; + +module.exports = Array.isArray || function (arr) { + return toString.call(arr) == '[object Array]'; +}; + +},{}],47:[function(require,module,exports){ +(function (Buffer){ +// Copyright Joyent, Inc. and other Node contributors. +// +// Permission is hereby granted, free of charge, to any person obtaining a +// copy of this software and associated documentation files (the +// "Software"), to deal in the Software without restriction, including +// without limitation the rights to use, copy, modify, merge, publish, +// distribute, sublicense, and/or sell copies of the Software, and to permit +// persons to whom the Software is furnished to do so, subject to the +// following conditions: +// +// The above copyright notice and this permission notice shall be included +// in all copies or substantial portions of the Software. +// +// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS +// OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF +// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN +// NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, +// DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR +// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE +// USE OR OTHER DEALINGS IN THE SOFTWARE. + +// NOTE: These type checking functions intentionally don't use `instanceof` +// because it is fragile and can be easily faked with `Object.create()`. + +function isArray(arg) { + if (Array.isArray) { + return Array.isArray(arg); + } + return objectToString(arg) === '[object Array]'; +} +exports.isArray = isArray; + +function isBoolean(arg) { + return typeof arg === 'boolean'; +} +exports.isBoolean = isBoolean; + +function isNull(arg) { + return arg === null; +} +exports.isNull = isNull; + +function isNullOrUndefined(arg) { + return arg == null; +} +exports.isNullOrUndefined = isNullOrUndefined; + +function isNumber(arg) { + return typeof arg === 'number'; +} +exports.isNumber = isNumber; + +function isString(arg) { + return typeof arg === 'string'; +} +exports.isString = isString; + +function isSymbol(arg) { + return typeof arg === 'symbol'; +} +exports.isSymbol = isSymbol; + +function isUndefined(arg) { + return arg === void 0; +} +exports.isUndefined = isUndefined; + +function isRegExp(re) { + return objectToString(re) === '[object RegExp]'; +} +exports.isRegExp = isRegExp; + +function isObject(arg) { + return typeof arg === 'object' && arg !== null; +} +exports.isObject = isObject; + +function isDate(d) { + return objectToString(d) === '[object Date]'; +} +exports.isDate = isDate; + +function isError(e) { + return (objectToString(e) === '[object Error]' || e instanceof Error); +} +exports.isError = isError; + +function isFunction(arg) { + return typeof arg === 'function'; +} +exports.isFunction = isFunction; + +function isPrimitive(arg) { + return arg === null || + typeof arg === 'boolean' || + typeof arg === 'number' || + typeof arg === 'string' || + typeof arg === 'symbol' || // ES6 symbol + typeof arg === 'undefined'; +} +exports.isPrimitive = isPrimitive; + +exports.isBuffer = Buffer.isBuffer; + +function objectToString(o) { + return Object.prototype.toString.call(o); +} + +}).call(this,{"isBuffer":require("../../is-buffer/index.js")}) +},{"../../is-buffer/index.js":54}],48:[function(require,module,exports){ +/* See LICENSE file for terms of use */ + +/* + * Text diff implementation. + * + * This library supports the following APIS: + * JsDiff.diffChars: Character by character diff + * JsDiff.diffWords: Word (as defined by \b regex) diff which ignores whitespace + * JsDiff.diffLines: Line based diff + * + * JsDiff.diffCss: Diff targeted at CSS content + * + * These methods are based on the implementation proposed in + * "An O(ND) Difference Algorithm and its Variations" (Myers, 1986). + * http://citeseerx.ist.psu.edu/viewdoc/summary?doi=10.1.1.4.6927 + */ +(function(global, undefined) { + var objectPrototypeToString = Object.prototype.toString; + + /*istanbul ignore next*/ + function map(arr, mapper, that) { + if (Array.prototype.map) { + return Array.prototype.map.call(arr, mapper, that); + } + + var other = new Array(arr.length); + + for (var i = 0, n = arr.length; i < n; i++) { + other[i] = mapper.call(that, arr[i], i, arr); + } + return other; + } + function clonePath(path) { + return { newPos: path.newPos, components: path.components.slice(0) }; + } + function removeEmpty(array) { + var ret = []; + for (var i = 0; i < array.length; i++) { + if (array[i]) { + ret.push(array[i]); + } + } + return ret; + } + function escapeHTML(s) { + var n = s; + n = n.replace(/&/g, '&'); + n = n.replace(//g, '>'); + n = n.replace(/"/g, '"'); + + return n; + } + + // This function handles the presence of circular references by bailing out when encountering an + // object that is already on the "stack" of items being processed. + function canonicalize(obj, stack, replacementStack) { + stack = stack || []; + replacementStack = replacementStack || []; + + var i; + + for (i = 0; i < stack.length; i += 1) { + if (stack[i] === obj) { + return replacementStack[i]; + } + } + + var canonicalizedObj; + + if ('[object Array]' === objectPrototypeToString.call(obj)) { + stack.push(obj); + canonicalizedObj = new Array(obj.length); + replacementStack.push(canonicalizedObj); + for (i = 0; i < obj.length; i += 1) { + canonicalizedObj[i] = canonicalize(obj[i], stack, replacementStack); + } + stack.pop(); + replacementStack.pop(); + } else if (typeof obj === 'object' && obj !== null) { + stack.push(obj); + canonicalizedObj = {}; + replacementStack.push(canonicalizedObj); + var sortedKeys = [], + key; + for (key in obj) { + sortedKeys.push(key); + } + sortedKeys.sort(); + for (i = 0; i < sortedKeys.length; i += 1) { + key = sortedKeys[i]; + canonicalizedObj[key] = canonicalize(obj[key], stack, replacementStack); + } + stack.pop(); + replacementStack.pop(); + } else { + canonicalizedObj = obj; + } + return canonicalizedObj; + } + + function buildValues(components, newString, oldString, useLongestToken) { + var componentPos = 0, + componentLen = components.length, + newPos = 0, + oldPos = 0; + + for (; componentPos < componentLen; componentPos++) { + var component = components[componentPos]; + if (!component.removed) { + if (!component.added && useLongestToken) { + var value = newString.slice(newPos, newPos + component.count); + value = map(value, function(value, i) { + var oldValue = oldString[oldPos + i]; + return oldValue.length > value.length ? oldValue : value; + }); + + component.value = value.join(''); + } else { + component.value = newString.slice(newPos, newPos + component.count).join(''); + } + newPos += component.count; + + // Common case + if (!component.added) { + oldPos += component.count; + } + } else { + component.value = oldString.slice(oldPos, oldPos + component.count).join(''); + oldPos += component.count; + + // Reverse add and remove so removes are output first to match common convention + // The diffing algorithm is tied to add then remove output and this is the simplest + // route to get the desired output with minimal overhead. + if (componentPos && components[componentPos - 1].added) { + var tmp = components[componentPos - 1]; + components[componentPos - 1] = components[componentPos]; + components[componentPos] = tmp; + } + } + } + + return components; + } + + function Diff(ignoreWhitespace) { + this.ignoreWhitespace = ignoreWhitespace; + } + Diff.prototype = { + diff: function(oldString, newString, callback) { + var self = this; + + function done(value) { + if (callback) { + setTimeout(function() { callback(undefined, value); }, 0); + return true; + } else { + return value; + } + } + + // Handle the identity case (this is due to unrolling editLength == 0 + if (newString === oldString) { + return done([{ value: newString }]); + } + if (!newString) { + return done([{ value: oldString, removed: true }]); + } + if (!oldString) { + return done([{ value: newString, added: true }]); + } + + newString = this.tokenize(newString); + oldString = this.tokenize(oldString); + + var newLen = newString.length, oldLen = oldString.length; + var editLength = 1; + var maxEditLength = newLen + oldLen; + var bestPath = [{ newPos: -1, components: [] }]; + + // Seed editLength = 0, i.e. the content starts with the same values + var oldPos = this.extractCommon(bestPath[0], newString, oldString, 0); + if (bestPath[0].newPos + 1 >= newLen && oldPos + 1 >= oldLen) { + // Identity per the equality and tokenizer + return done([{value: newString.join('')}]); + } + + // Main worker method. checks all permutations of a given edit length for acceptance. + function execEditLength() { + for (var diagonalPath = -1 * editLength; diagonalPath <= editLength; diagonalPath += 2) { + var basePath; + var addPath = bestPath[diagonalPath - 1], + removePath = bestPath[diagonalPath + 1], + oldPos = (removePath ? removePath.newPos : 0) - diagonalPath; + if (addPath) { + // No one else is going to attempt to use this value, clear it + bestPath[diagonalPath - 1] = undefined; + } + + var canAdd = addPath && addPath.newPos + 1 < newLen, + canRemove = removePath && 0 <= oldPos && oldPos < oldLen; + if (!canAdd && !canRemove) { + // If this path is a terminal then prune + bestPath[diagonalPath] = undefined; + continue; + } + + // Select the diagonal that we want to branch from. We select the prior + // path whose position in the new string is the farthest from the origin + // and does not pass the bounds of the diff graph + if (!canAdd || (canRemove && addPath.newPos < removePath.newPos)) { + basePath = clonePath(removePath); + self.pushComponent(basePath.components, undefined, true); + } else { + basePath = addPath; // No need to clone, we've pulled it from the list + basePath.newPos++; + self.pushComponent(basePath.components, true, undefined); + } + + oldPos = self.extractCommon(basePath, newString, oldString, diagonalPath); + + // If we have hit the end of both strings, then we are done + if (basePath.newPos + 1 >= newLen && oldPos + 1 >= oldLen) { + return done(buildValues(basePath.components, newString, oldString, self.useLongestToken)); + } else { + // Otherwise track this path as a potential candidate and continue. + bestPath[diagonalPath] = basePath; + } + } + + editLength++; + } + + // Performs the length of edit iteration. Is a bit fugly as this has to support the + // sync and async mode which is never fun. Loops over execEditLength until a value + // is produced. + if (callback) { + (function exec() { + setTimeout(function() { + // This should not happen, but we want to be safe. + /*istanbul ignore next */ + if (editLength > maxEditLength) { + return callback(); + } + + if (!execEditLength()) { + exec(); + } + }, 0); + }()); + } else { + while (editLength <= maxEditLength) { + var ret = execEditLength(); + if (ret) { + return ret; + } + } + } + }, + + pushComponent: function(components, added, removed) { + var last = components[components.length - 1]; + if (last && last.added === added && last.removed === removed) { + // We need to clone here as the component clone operation is just + // as shallow array clone + components[components.length - 1] = {count: last.count + 1, added: added, removed: removed }; + } else { + components.push({count: 1, added: added, removed: removed }); + } + }, + extractCommon: function(basePath, newString, oldString, diagonalPath) { + var newLen = newString.length, + oldLen = oldString.length, + newPos = basePath.newPos, + oldPos = newPos - diagonalPath, + + commonCount = 0; + while (newPos + 1 < newLen && oldPos + 1 < oldLen && this.equals(newString[newPos + 1], oldString[oldPos + 1])) { + newPos++; + oldPos++; + commonCount++; + } + + if (commonCount) { + basePath.components.push({count: commonCount}); + } + + basePath.newPos = newPos; + return oldPos; + }, + + equals: function(left, right) { + var reWhitespace = /\S/; + return left === right || (this.ignoreWhitespace && !reWhitespace.test(left) && !reWhitespace.test(right)); + }, + tokenize: function(value) { + return value.split(''); + } + }; + + var CharDiff = new Diff(); + + var WordDiff = new Diff(true); + var WordWithSpaceDiff = new Diff(); + WordDiff.tokenize = WordWithSpaceDiff.tokenize = function(value) { + return removeEmpty(value.split(/(\s+|\b)/)); + }; + + var CssDiff = new Diff(true); + CssDiff.tokenize = function(value) { + return removeEmpty(value.split(/([{}:;,]|\s+)/)); + }; + + var LineDiff = new Diff(); + + var TrimmedLineDiff = new Diff(); + TrimmedLineDiff.ignoreTrim = true; + + LineDiff.tokenize = TrimmedLineDiff.tokenize = function(value) { + var retLines = [], + lines = value.split(/^/m); + for (var i = 0; i < lines.length; i++) { + var line = lines[i], + lastLine = lines[i - 1], + lastLineLastChar = lastLine && lastLine[lastLine.length - 1]; + + // Merge lines that may contain windows new lines + if (line === '\n' && lastLineLastChar === '\r') { + retLines[retLines.length - 1] = retLines[retLines.length - 1].slice(0, -1) + '\r\n'; + } else { + if (this.ignoreTrim) { + line = line.trim(); + // add a newline unless this is the last line. + if (i < lines.length - 1) { + line += '\n'; + } + } + retLines.push(line); + } + } + + return retLines; + }; + + var PatchDiff = new Diff(); + PatchDiff.tokenize = function(value) { + var ret = [], + linesAndNewlines = value.split(/(\n|\r\n)/); + + // Ignore the final empty token that occurs if the string ends with a new line + if (!linesAndNewlines[linesAndNewlines.length - 1]) { + linesAndNewlines.pop(); + } + + // Merge the content and line separators into single tokens + for (var i = 0; i < linesAndNewlines.length; i++) { + var line = linesAndNewlines[i]; + + if (i % 2) { + ret[ret.length - 1] += line; + } else { + ret.push(line); + } + } + return ret; + }; + + var SentenceDiff = new Diff(); + SentenceDiff.tokenize = function(value) { + return removeEmpty(value.split(/(\S.+?[.!?])(?=\s+|$)/)); + }; + + var JsonDiff = new Diff(); + // Discriminate between two lines of pretty-printed, serialized JSON where one of them has a + // dangling comma and the other doesn't. Turns out including the dangling comma yields the nicest output: + JsonDiff.useLongestToken = true; + JsonDiff.tokenize = LineDiff.tokenize; + JsonDiff.equals = function(left, right) { + return LineDiff.equals(left.replace(/,([\r\n])/g, '$1'), right.replace(/,([\r\n])/g, '$1')); + }; + + var JsDiff = { + Diff: Diff, + + diffChars: function(oldStr, newStr, callback) { return CharDiff.diff(oldStr, newStr, callback); }, + diffWords: function(oldStr, newStr, callback) { return WordDiff.diff(oldStr, newStr, callback); }, + diffWordsWithSpace: function(oldStr, newStr, callback) { return WordWithSpaceDiff.diff(oldStr, newStr, callback); }, + diffLines: function(oldStr, newStr, callback) { return LineDiff.diff(oldStr, newStr, callback); }, + diffTrimmedLines: function(oldStr, newStr, callback) { return TrimmedLineDiff.diff(oldStr, newStr, callback); }, + + diffSentences: function(oldStr, newStr, callback) { return SentenceDiff.diff(oldStr, newStr, callback); }, + + diffCss: function(oldStr, newStr, callback) { return CssDiff.diff(oldStr, newStr, callback); }, + diffJson: function(oldObj, newObj, callback) { + return JsonDiff.diff( + typeof oldObj === 'string' ? oldObj : JSON.stringify(canonicalize(oldObj), undefined, ' '), + typeof newObj === 'string' ? newObj : JSON.stringify(canonicalize(newObj), undefined, ' '), + callback + ); + }, + + createTwoFilesPatch: function(oldFileName, newFileName, oldStr, newStr, oldHeader, newHeader) { + var ret = []; + + if (oldFileName == newFileName) { + ret.push('Index: ' + oldFileName); + } + ret.push('==================================================================='); + ret.push('--- ' + oldFileName + (typeof oldHeader === 'undefined' ? '' : '\t' + oldHeader)); + ret.push('+++ ' + newFileName + (typeof newHeader === 'undefined' ? '' : '\t' + newHeader)); + + var diff = PatchDiff.diff(oldStr, newStr); + diff.push({value: '', lines: []}); // Append an empty value to make cleanup easier + + // Formats a given set of lines for printing as context lines in a patch + function contextLines(lines) { + return map(lines, function(entry) { return ' ' + entry; }); + } + + // Outputs the no newline at end of file warning if needed + function eofNL(curRange, i, current) { + var last = diff[diff.length - 2], + isLast = i === diff.length - 2, + isLastOfType = i === diff.length - 3 && current.added !== last.added; + + // Figure out if this is the last line for the given file and missing NL + if (!(/\n$/.test(current.value)) && (isLast || isLastOfType)) { + curRange.push('\\ No newline at end of file'); + } + } + + var oldRangeStart = 0, newRangeStart = 0, curRange = [], + oldLine = 1, newLine = 1; + for (var i = 0; i < diff.length; i++) { + var current = diff[i], + lines = current.lines || current.value.replace(/\n$/, '').split('\n'); + current.lines = lines; + + if (current.added || current.removed) { + // If we have previous context, start with that + if (!oldRangeStart) { + var prev = diff[i - 1]; + oldRangeStart = oldLine; + newRangeStart = newLine; + + if (prev) { + curRange = contextLines(prev.lines.slice(-4)); + oldRangeStart -= curRange.length; + newRangeStart -= curRange.length; + } + } + + // Output our changes + curRange.push.apply(curRange, map(lines, function(entry) { + return (current.added ? '+' : '-') + entry; + })); + eofNL(curRange, i, current); + + // Track the updated file position + if (current.added) { + newLine += lines.length; + } else { + oldLine += lines.length; + } + } else { + // Identical context lines. Track line changes + if (oldRangeStart) { + // Close out any changes that have been output (or join overlapping) + if (lines.length <= 8 && i < diff.length - 2) { + // Overlapping + curRange.push.apply(curRange, contextLines(lines)); + } else { + // end the range and output + var contextSize = Math.min(lines.length, 4); + ret.push( + '@@ -' + oldRangeStart + ',' + (oldLine - oldRangeStart + contextSize) + + ' +' + newRangeStart + ',' + (newLine - newRangeStart + contextSize) + + ' @@'); + ret.push.apply(ret, curRange); + ret.push.apply(ret, contextLines(lines.slice(0, contextSize))); + if (lines.length <= 4) { + eofNL(ret, i, current); + } + + oldRangeStart = 0; + newRangeStart = 0; + curRange = []; + } + } + oldLine += lines.length; + newLine += lines.length; + } + } + + return ret.join('\n') + '\n'; + }, + + createPatch: function(fileName, oldStr, newStr, oldHeader, newHeader) { + return JsDiff.createTwoFilesPatch(fileName, fileName, oldStr, newStr, oldHeader, newHeader); + }, + + applyPatch: function(oldStr, uniDiff) { + var diffstr = uniDiff.split('\n'), + hunks = [], + i = 0, + remEOFNL = false, + addEOFNL = false; + + // Skip to the first change hunk + while (i < diffstr.length && !(/^@@/.test(diffstr[i]))) { + i++; + } + + // Parse the unified diff + for (; i < diffstr.length; i++) { + if (diffstr[i][0] === '@') { + var chnukHeader = diffstr[i].split(/@@ -(\d+),(\d+) \+(\d+),(\d+) @@/); + hunks.unshift({ + start: chnukHeader[3], + oldlength: +chnukHeader[2], + removed: [], + newlength: chnukHeader[4], + added: [] + }); + } else if (diffstr[i][0] === '+') { + hunks[0].added.push(diffstr[i].substr(1)); + } else if (diffstr[i][0] === '-') { + hunks[0].removed.push(diffstr[i].substr(1)); + } else if (diffstr[i][0] === ' ') { + hunks[0].added.push(diffstr[i].substr(1)); + hunks[0].removed.push(diffstr[i].substr(1)); + } else if (diffstr[i][0] === '\\') { + if (diffstr[i - 1][0] === '+') { + remEOFNL = true; + } else if (diffstr[i - 1][0] === '-') { + addEOFNL = true; + } + } + } + + // Apply the diff to the input + var lines = oldStr.split('\n'); + for (i = hunks.length - 1; i >= 0; i--) { + var hunk = hunks[i]; + // Sanity check the input string. Bail if we don't match. + for (var j = 0; j < hunk.oldlength; j++) { + if (lines[hunk.start - 1 + j] !== hunk.removed[j]) { + return false; + } + } + Array.prototype.splice.apply(lines, [hunk.start - 1, hunk.oldlength].concat(hunk.added)); + } + + // Handle EOFNL insertion/removal + if (remEOFNL) { + while (!lines[lines.length - 1]) { + lines.pop(); + } + } else if (addEOFNL) { + lines.push(''); + } + return lines.join('\n'); + }, + + convertChangesToXML: function(changes) { + var ret = []; + for (var i = 0; i < changes.length; i++) { + var change = changes[i]; + if (change.added) { + ret.push(''); + } else if (change.removed) { + ret.push(''); + } + + ret.push(escapeHTML(change.value)); + + if (change.added) { + ret.push(''); + } else if (change.removed) { + ret.push(''); + } + } + return ret.join(''); + }, + + // See: http://code.google.com/p/google-diff-match-patch/wiki/API + convertChangesToDMP: function(changes) { + var ret = [], + change, + operation; + for (var i = 0; i < changes.length; i++) { + change = changes[i]; + if (change.added) { + operation = 1; + } else if (change.removed) { + operation = -1; + } else { + operation = 0; + } + + ret.push([operation, change.value]); + } + return ret; + }, + + canonicalize: canonicalize + }; + + /*istanbul ignore next */ + /*global module */ + if (typeof module !== 'undefined' && module.exports) { + module.exports = JsDiff; + } else if (typeof define === 'function' && define.amd) { + /*global define */ + define([], function() { return JsDiff; }); + } else if (typeof global.JsDiff === 'undefined') { + global.JsDiff = JsDiff; + } +}(this)); + +},{}],49:[function(require,module,exports){ +'use strict'; + +var matchOperatorsRe = /[|\\{}()[\]^$+*?.]/g; + +module.exports = function (str) { + if (typeof str !== 'string') { + throw new TypeError('Expected a string'); + } + + return str.replace(matchOperatorsRe, '\\$&'); +}; + +},{}],50:[function(require,module,exports){ +// Copyright Joyent, Inc. and other Node contributors. +// +// Permission is hereby granted, free of charge, to any person obtaining a +// copy of this software and associated documentation files (the +// "Software"), to deal in the Software without restriction, including +// without limitation the rights to use, copy, modify, merge, publish, +// distribute, sublicense, and/or sell copies of the Software, and to permit +// persons to whom the Software is furnished to do so, subject to the +// following conditions: +// +// The above copyright notice and this permission notice shall be included +// in all copies or substantial portions of the Software. +// +// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS +// OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF +// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN +// NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, +// DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR +// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE +// USE OR OTHER DEALINGS IN THE SOFTWARE. + +function EventEmitter() { + this._events = this._events || {}; + this._maxListeners = this._maxListeners || undefined; +} +module.exports = EventEmitter; + +// Backwards-compat with node 0.10.x +EventEmitter.EventEmitter = EventEmitter; + +EventEmitter.prototype._events = undefined; +EventEmitter.prototype._maxListeners = undefined; + +// By default EventEmitters will print a warning if more than 10 listeners are +// added to it. This is a useful default which helps finding memory leaks. +EventEmitter.defaultMaxListeners = 10; + +// Obviously not all Emitters should be limited to 10. This function allows +// that to be increased. Set to zero for unlimited. +EventEmitter.prototype.setMaxListeners = function(n) { + if (!isNumber(n) || n < 0 || isNaN(n)) + throw TypeError('n must be a positive number'); + this._maxListeners = n; + return this; +}; + +EventEmitter.prototype.emit = function(type) { + var er, handler, len, args, i, listeners; + + if (!this._events) + this._events = {}; + + // If there is no 'error' event listener then throw. + if (type === 'error') { + if (!this._events.error || + (isObject(this._events.error) && !this._events.error.length)) { + er = arguments[1]; + if (er instanceof Error) { + throw er; // Unhandled 'error' event + } + throw TypeError('Uncaught, unspecified "error" event.'); + } + } + + handler = this._events[type]; + + if (isUndefined(handler)) + return false; + + if (isFunction(handler)) { + switch (arguments.length) { + // fast cases + case 1: + handler.call(this); + break; + case 2: + handler.call(this, arguments[1]); + break; + case 3: + handler.call(this, arguments[1], arguments[2]); + break; + // slower + default: + args = Array.prototype.slice.call(arguments, 1); + handler.apply(this, args); + } + } else if (isObject(handler)) { + args = Array.prototype.slice.call(arguments, 1); + listeners = handler.slice(); + len = listeners.length; + for (i = 0; i < len; i++) + listeners[i].apply(this, args); + } + + return true; +}; + +EventEmitter.prototype.addListener = function(type, listener) { + var m; + + if (!isFunction(listener)) + throw TypeError('listener must be a function'); + + if (!this._events) + this._events = {}; + + // To avoid recursion in the case that type === "newListener"! Before + // adding it to the listeners, first emit "newListener". + if (this._events.newListener) + this.emit('newListener', type, + isFunction(listener.listener) ? + listener.listener : listener); + + if (!this._events[type]) + // Optimize the case of one listener. Don't need the extra array object. + this._events[type] = listener; + else if (isObject(this._events[type])) + // If we've already got an array, just append. + this._events[type].push(listener); + else + // Adding the second element, need to change to array. + this._events[type] = [this._events[type], listener]; + + // Check for listener leak + if (isObject(this._events[type]) && !this._events[type].warned) { + if (!isUndefined(this._maxListeners)) { + m = this._maxListeners; + } else { + m = EventEmitter.defaultMaxListeners; + } + + if (m && m > 0 && this._events[type].length > m) { + this._events[type].warned = true; + console.error('(node) warning: possible EventEmitter memory ' + + 'leak detected. %d listeners added. ' + + 'Use emitter.setMaxListeners() to increase limit.', + this._events[type].length); + if (typeof console.trace === 'function') { + // not supported in IE 10 + console.trace(); + } + } + } + + return this; +}; + +EventEmitter.prototype.on = EventEmitter.prototype.addListener; + +EventEmitter.prototype.once = function(type, listener) { + if (!isFunction(listener)) + throw TypeError('listener must be a function'); + + var fired = false; + + function g() { + this.removeListener(type, g); + + if (!fired) { + fired = true; + listener.apply(this, arguments); + } + } + + g.listener = listener; + this.on(type, g); + + return this; +}; + +// emits a 'removeListener' event iff the listener was removed +EventEmitter.prototype.removeListener = function(type, listener) { + var list, position, length, i; + + if (!isFunction(listener)) + throw TypeError('listener must be a function'); + + if (!this._events || !this._events[type]) + return this; + + list = this._events[type]; + length = list.length; + position = -1; + + if (list === listener || + (isFunction(list.listener) && list.listener === listener)) { + delete this._events[type]; + if (this._events.removeListener) + this.emit('removeListener', type, listener); + + } else if (isObject(list)) { + for (i = length; i-- > 0;) { + if (list[i] === listener || + (list[i].listener && list[i].listener === listener)) { + position = i; + break; + } + } + + if (position < 0) + return this; + + if (list.length === 1) { + list.length = 0; + delete this._events[type]; + } else { + list.splice(position, 1); + } + + if (this._events.removeListener) + this.emit('removeListener', type, listener); + } + + return this; +}; + +EventEmitter.prototype.removeAllListeners = function(type) { + var key, listeners; + + if (!this._events) + return this; + + // not listening for removeListener, no need to emit + if (!this._events.removeListener) { + if (arguments.length === 0) + this._events = {}; + else if (this._events[type]) + delete this._events[type]; + return this; + } + + // emit removeListener for all listeners on all events + if (arguments.length === 0) { + for (key in this._events) { + if (key === 'removeListener') continue; + this.removeAllListeners(key); + } + this.removeAllListeners('removeListener'); + this._events = {}; + return this; + } + + listeners = this._events[type]; + + if (isFunction(listeners)) { + this.removeListener(type, listeners); + } else if (listeners) { + // LIFO order + while (listeners.length) + this.removeListener(type, listeners[listeners.length - 1]); + } + delete this._events[type]; + + return this; +}; + +EventEmitter.prototype.listeners = function(type) { + var ret; + if (!this._events || !this._events[type]) + ret = []; + else if (isFunction(this._events[type])) + ret = [this._events[type]]; + else + ret = this._events[type].slice(); + return ret; +}; + +EventEmitter.prototype.listenerCount = function(type) { + if (this._events) { + var evlistener = this._events[type]; + + if (isFunction(evlistener)) + return 1; + else if (evlistener) + return evlistener.length; + } + return 0; +}; + +EventEmitter.listenerCount = function(emitter, type) { + return emitter.listenerCount(type); +}; + +function isFunction(arg) { + return typeof arg === 'function'; +} + +function isNumber(arg) { + return typeof arg === 'number'; +} + +function isObject(arg) { + return typeof arg === 'object' && arg !== null; +} + +function isUndefined(arg) { + return arg === void 0; +} + +},{}],51:[function(require,module,exports){ +(function (process){ +// Growl - Copyright TJ Holowaychuk (MIT Licensed) + +/** + * Module dependencies. + */ + +var exec = require('child_process').exec + , fs = require('fs') + , path = require('path') + , exists = fs.existsSync || path.existsSync + , os = require('os') + , quote = JSON.stringify + , cmd; + +function which(name) { + var paths = process.env.PATH.split(':'); + var loc; + + for (var i = 0, len = paths.length; i < len; ++i) { + loc = path.join(paths[i], name); + if (exists(loc)) return loc; + } +} + +switch(os.type()) { + case 'Darwin': + if (which('terminal-notifier')) { + cmd = { + type: "Darwin-NotificationCenter" + , pkg: "terminal-notifier" + , msg: '-message' + , title: '-title' + , subtitle: '-subtitle' + , icon: '-appIcon' + , sound: '-sound' + , url: '-open' + , priority: { + cmd: '-execute' + , range: [] + } + }; + } else { + cmd = { + type: "Darwin-Growl" + , pkg: "growlnotify" + , msg: '-m' + , sticky: '--sticky' + , priority: { + cmd: '--priority' + , range: [ + -2 + , -1 + , 0 + , 1 + , 2 + , "Very Low" + , "Moderate" + , "Normal" + , "High" + , "Emergency" + ] + } + }; + } + break; + case 'Linux': + if (which('growl')) { + cmd = { + type: "Linux-Growl" + , pkg: "growl" + , msg: '-m' + , title: '-title' + , subtitle: '-subtitle' + , host: { + cmd: '-H' + , hostname: '192.168.33.1' + } + }; + } else { + cmd = { + type: "Linux" + , pkg: "notify-send" + , msg: '' + , sticky: '-t 0' + , icon: '-i' + , priority: { + cmd: '-u' + , range: [ + "low" + , "normal" + , "critical" + ] + } + }; + } + break; + case 'Windows_NT': + cmd = { + type: "Windows" + , pkg: "growlnotify" + , msg: '' + , sticky: '/s:true' + , title: '/t:' + , icon: '/i:' + , url: '/cu:' + , priority: { + cmd: '/p:' + , range: [ + -2 + , -1 + , 0 + , 1 + , 2 + ] + } + }; + break; +} + +/** + * Expose `growl`. + */ + +exports = module.exports = growl; + +/** + * Node-growl version. + */ + +exports.version = '1.4.1' + +/** + * Send growl notification _msg_ with _options_. + * + * Options: + * + * - title Notification title + * - sticky Make the notification stick (defaults to false) + * - priority Specify an int or named key (default is 0) + * - name Application name (defaults to growlnotify) + * - sound Sound efect ( in OSx defined in preferences -> sound -> effects) * works only in OSX > 10.8x + * - image + * - path to an icon sets --iconpath + * - path to an image sets --image + * - capitalized word sets --appIcon + * - filename uses extname as --icon + * - otherwise treated as --icon + * + * Examples: + * + * growl('New email') + * growl('5 new emails', { title: 'Thunderbird' }) + * growl('5 new emails', { title: 'Thunderbird', sound: 'Purr' }) + * growl('Email sent', function(){ + * // ... notification sent + * }) + * + * @param {string} msg + * @param {object} options + * @param {function} fn + * @api public + */ + +function growl(msg, options, fn) { + var image + , args + , options = options || {} + , fn = fn || function(){}; + + if (options.exec) { + cmd = { + type: "Custom" + , pkg: options.exec + , range: [] + }; + } + + // noop + if (!cmd) return fn(new Error('growl not supported on this platform')); + args = [cmd.pkg]; + + // image + if (image = options.image) { + switch(cmd.type) { + case 'Darwin-Growl': + var flag, ext = path.extname(image).substr(1) + flag = flag || ext == 'icns' && 'iconpath' + flag = flag || /^[A-Z]/.test(image) && 'appIcon' + flag = flag || /^png|gif|jpe?g$/.test(ext) && 'image' + flag = flag || ext && (image = ext) && 'icon' + flag = flag || 'icon' + args.push('--' + flag, quote(image)) + break; + case 'Darwin-NotificationCenter': + args.push(cmd.icon, quote(image)); + break; + case 'Linux': + args.push(cmd.icon, quote(image)); + // libnotify defaults to sticky, set a hint for transient notifications + if (!options.sticky) args.push('--hint=int:transient:1'); + break; + case 'Windows': + args.push(cmd.icon + quote(image)); + break; + } + } + + // sticky + if (options.sticky) args.push(cmd.sticky); + + // priority + if (options.priority) { + var priority = options.priority + ''; + var checkindexOf = cmd.priority.range.indexOf(priority); + if (~cmd.priority.range.indexOf(priority)) { + args.push(cmd.priority, options.priority); + } + } + + //sound + if(options.sound && cmd.type === 'Darwin-NotificationCenter'){ + args.push(cmd.sound, options.sound) + } + + // name + if (options.name && cmd.type === "Darwin-Growl") { + args.push('--name', options.name); + } + + switch(cmd.type) { + case 'Darwin-Growl': + args.push(cmd.msg); + args.push(quote(msg).replace(/\\n/g, '\n')); + if (options.title) args.push(quote(options.title)); + break; + case 'Darwin-NotificationCenter': + args.push(cmd.msg); + var stringifiedMsg = quote(msg); + var escapedMsg = stringifiedMsg.replace(/\\n/g, '\n'); + args.push(escapedMsg); + if (options.title) { + args.push(cmd.title); + args.push(quote(options.title)); + } + if (options.subtitle) { + args.push(cmd.subtitle); + args.push(quote(options.subtitle)); + } + if (options.url) { + args.push(cmd.url); + args.push(quote(options.url)); + } + break; + case 'Linux-Growl': + args.push(cmd.msg); + args.push(quote(msg).replace(/\\n/g, '\n')); + if (options.title) args.push(quote(options.title)); + if (cmd.host) { + args.push(cmd.host.cmd, cmd.host.hostname) + } + break; + case 'Linux': + if (options.title) { + args.push(quote(options.title)); + args.push(cmd.msg); + args.push(quote(msg).replace(/\\n/g, '\n')); + } else { + args.push(quote(msg).replace(/\\n/g, '\n')); + } + break; + case 'Windows': + args.push(quote(msg).replace(/\\n/g, '\n')); + if (options.title) args.push(cmd.title + quote(options.title)); + if (options.url) args.push(cmd.url + quote(options.url)); + break; + case 'Custom': + args[0] = (function(origCommand) { + var message = options.title + ? options.title + ': ' + msg + : msg; + var command = origCommand.replace(/(^|[^%])%s/g, '$1' + quote(message)); + if (command === origCommand) args.push(quote(message)); + return command; + })(args[0]); + break; + } + + // execute + exec(args.join(' '), fn); +}; + +}).call(this,require('_process')) +},{"_process":58,"child_process":43,"fs":43,"os":56,"path":43}],52:[function(require,module,exports){ +exports.read = function (buffer, offset, isLE, mLen, nBytes) { + var e, m + var eLen = nBytes * 8 - mLen - 1 + var eMax = (1 << eLen) - 1 + var eBias = eMax >> 1 + var nBits = -7 + var i = isLE ? (nBytes - 1) : 0 + var d = isLE ? -1 : 1 + var s = buffer[offset + i] + + i += d + + e = s & ((1 << (-nBits)) - 1) + s >>= (-nBits) + nBits += eLen + for (; nBits > 0; e = e * 256 + buffer[offset + i], i += d, nBits -= 8) {} + + m = e & ((1 << (-nBits)) - 1) + e >>= (-nBits) + nBits += mLen + for (; nBits > 0; m = m * 256 + buffer[offset + i], i += d, nBits -= 8) {} + + if (e === 0) { + e = 1 - eBias + } else if (e === eMax) { + return m ? NaN : ((s ? -1 : 1) * Infinity) + } else { + m = m + Math.pow(2, mLen) + e = e - eBias + } + return (s ? -1 : 1) * m * Math.pow(2, e - mLen) +} + +exports.write = function (buffer, value, offset, isLE, mLen, nBytes) { + var e, m, c + var eLen = nBytes * 8 - mLen - 1 + var eMax = (1 << eLen) - 1 + var eBias = eMax >> 1 + var rt = (mLen === 23 ? Math.pow(2, -24) - Math.pow(2, -77) : 0) + var i = isLE ? 0 : (nBytes - 1) + var d = isLE ? 1 : -1 + var s = value < 0 || (value === 0 && 1 / value < 0) ? 1 : 0 + + value = Math.abs(value) + + if (isNaN(value) || value === Infinity) { + m = isNaN(value) ? 1 : 0 + e = eMax + } else { + e = Math.floor(Math.log(value) / Math.LN2) + if (value * (c = Math.pow(2, -e)) < 1) { + e-- + c *= 2 + } + if (e + eBias >= 1) { + value += rt / c + } else { + value += rt * Math.pow(2, 1 - eBias) + } + if (value * c >= 2) { + e++ + c /= 2 + } + + if (e + eBias >= eMax) { + m = 0 + e = eMax + } else if (e + eBias >= 1) { + m = (value * c - 1) * Math.pow(2, mLen) + e = e + eBias + } else { + m = value * Math.pow(2, eBias - 1) * Math.pow(2, mLen) + e = 0 + } + } + + for (; mLen >= 8; buffer[offset + i] = m & 0xff, i += d, m /= 256, mLen -= 8) {} + + e = (e << mLen) | m + eLen += mLen + for (; eLen > 0; buffer[offset + i] = e & 0xff, i += d, e /= 256, eLen -= 8) {} + + buffer[offset + i - d] |= s * 128 +} + +},{}],53:[function(require,module,exports){ +if (typeof Object.create === 'function') { + // implementation from standard node.js 'util' module + module.exports = function inherits(ctor, superCtor) { + ctor.super_ = superCtor + ctor.prototype = Object.create(superCtor.prototype, { + constructor: { + value: ctor, + enumerable: false, + writable: true, + configurable: true + } + }); + }; +} else { + // old school shim for old browsers + module.exports = function inherits(ctor, superCtor) { + ctor.super_ = superCtor + var TempCtor = function () {} + TempCtor.prototype = superCtor.prototype + ctor.prototype = new TempCtor() + ctor.prototype.constructor = ctor + } +} + +},{}],54:[function(require,module,exports){ +/** + * Determine if an object is Buffer + * + * Author: Feross Aboukhadijeh + * License: MIT + * + * `npm install is-buffer` + */ + +module.exports = function (obj) { + return !!(obj != null && + (obj._isBuffer || // For Safari 5-7 (missing Object.prototype.constructor) + (obj.constructor && + typeof obj.constructor.isBuffer === 'function' && + obj.constructor.isBuffer(obj)) + )) +} + +},{}],55:[function(require,module,exports){ +(function (process){ +var path = require('path'); +var fs = require('fs'); +var _0777 = parseInt('0777', 8); + +module.exports = mkdirP.mkdirp = mkdirP.mkdirP = mkdirP; + +function mkdirP (p, opts, f, made) { + if (typeof opts === 'function') { + f = opts; + opts = {}; + } + else if (!opts || typeof opts !== 'object') { + opts = { mode: opts }; + } + + var mode = opts.mode; + var xfs = opts.fs || fs; + + if (mode === undefined) { + mode = _0777 & (~process.umask()); + } + if (!made) made = null; + + var cb = f || function () {}; + p = path.resolve(p); + + xfs.mkdir(p, mode, function (er) { + if (!er) { + made = made || p; + return cb(null, made); + } + switch (er.code) { + case 'ENOENT': + mkdirP(path.dirname(p), opts, function (er, made) { + if (er) cb(er, made); + else mkdirP(p, opts, cb, made); + }); + break; + + // In the case of any other error, just see if there's a dir + // there already. If so, then hooray! If not, then something + // is borked. + default: + xfs.stat(p, function (er2, stat) { + // if the stat fails, then that's super weird. + // let the original error be the failure reason. + if (er2 || !stat.isDirectory()) cb(er, made) + else cb(null, made); + }); + break; + } + }); +} + +mkdirP.sync = function sync (p, opts, made) { + if (!opts || typeof opts !== 'object') { + opts = { mode: opts }; + } + + var mode = opts.mode; + var xfs = opts.fs || fs; + + if (mode === undefined) { + mode = _0777 & (~process.umask()); + } + if (!made) made = null; + + p = path.resolve(p); + + try { + xfs.mkdirSync(p, mode); + made = made || p; + } + catch (err0) { + switch (err0.code) { + case 'ENOENT' : + made = sync(path.dirname(p), opts, made); + sync(p, opts, made); + break; + + // In the case of any other error, just see if there's a dir + // there already. If so, then hooray! If not, then something + // is borked. + default: + var stat; + try { + stat = xfs.statSync(p); + } + catch (err1) { + throw err0; + } + if (!stat.isDirectory()) throw err0; + break; + } + } + + return made; +}; + +}).call(this,require('_process')) +},{"_process":58,"fs":43,"path":43}],56:[function(require,module,exports){ +exports.endianness = function () { return 'LE' }; + +exports.hostname = function () { + if (typeof location !== 'undefined') { + return location.hostname + } + else return ''; +}; + +exports.loadavg = function () { return [] }; + +exports.uptime = function () { return 0 }; + +exports.freemem = function () { + return Number.MAX_VALUE; +}; + +exports.totalmem = function () { + return Number.MAX_VALUE; +}; + +exports.cpus = function () { return [] }; + +exports.type = function () { return 'Browser' }; + +exports.release = function () { + if (typeof navigator !== 'undefined') { + return navigator.appVersion; + } + return ''; +}; + +exports.networkInterfaces += exports.getNetworkInterfaces += function () { return {} }; + +exports.arch = function () { return 'javascript' }; + +exports.platform = function () { return 'browser' }; + +exports.tmpdir = exports.tmpDir = function () { + return '/tmp'; +}; + +exports.EOL = '\n'; + +},{}],57:[function(require,module,exports){ +(function (process){ +'use strict'; + +if (!process.version || + process.version.indexOf('v0.') === 0 || + process.version.indexOf('v1.') === 0 && process.version.indexOf('v1.8.') !== 0) { + module.exports = nextTick; +} else { + module.exports = process.nextTick; +} + +function nextTick(fn, arg1, arg2, arg3) { + if (typeof fn !== 'function') { + throw new TypeError('"callback" argument must be a function'); + } + var len = arguments.length; + var args, i; + switch (len) { + case 0: + case 1: + return process.nextTick(fn); + case 2: + return process.nextTick(function afterTickOne() { + fn.call(null, arg1); + }); + case 3: + return process.nextTick(function afterTickTwo() { + fn.call(null, arg1, arg2); + }); + case 4: + return process.nextTick(function afterTickThree() { + fn.call(null, arg1, arg2, arg3); + }); + default: + args = new Array(len - 1); + i = 0; + while (i < args.length) { + args[i++] = arguments[i]; + } + return process.nextTick(function afterTick() { + fn.apply(null, args); + }); + } +} + +}).call(this,require('_process')) +},{"_process":58}],58:[function(require,module,exports){ +// shim for using process in browser + +var process = module.exports = {}; +var queue = []; +var draining = false; +var currentQueue; +var queueIndex = -1; + +function cleanUpNextTick() { + if (!draining || !currentQueue) { + return; + } + draining = false; + if (currentQueue.length) { + queue = currentQueue.concat(queue); + } else { + queueIndex = -1; + } + if (queue.length) { + drainQueue(); + } +} + +function drainQueue() { + if (draining) { + return; + } + var timeout = setTimeout(cleanUpNextTick); + draining = true; + + var len = queue.length; + while(len) { + currentQueue = queue; + queue = []; + while (++queueIndex < len) { + if (currentQueue) { + currentQueue[queueIndex].run(); + } + } + queueIndex = -1; + len = queue.length; + } + currentQueue = null; + draining = false; + clearTimeout(timeout); +} + +process.nextTick = function (fun) { + var args = new Array(arguments.length - 1); + if (arguments.length > 1) { + for (var i = 1; i < arguments.length; i++) { + args[i - 1] = arguments[i]; + } + } + queue.push(new Item(fun, args)); + if (queue.length === 1 && !draining) { + setTimeout(drainQueue, 0); + } +}; + +// v8 likes predictible objects +function Item(fun, array) { + this.fun = fun; + this.array = array; +} +Item.prototype.run = function () { + this.fun.apply(null, this.array); +}; +process.title = 'browser'; +process.browser = true; +process.env = {}; +process.argv = []; +process.version = ''; // empty string to avoid regexp issues +process.versions = {}; + +function noop() {} + +process.on = noop; +process.addListener = noop; +process.once = noop; +process.off = noop; +process.removeListener = noop; +process.removeAllListeners = noop; +process.emit = noop; + +process.binding = function (name) { + throw new Error('process.binding is not supported'); +}; + +process.cwd = function () { return '/' }; +process.chdir = function (dir) { + throw new Error('process.chdir is not supported'); +}; +process.umask = function() { return 0; }; + +},{}],59:[function(require,module,exports){ +// Copyright Joyent, Inc. and other Node contributors. +// +// Permission is hereby granted, free of charge, to any person obtaining a +// copy of this software and associated documentation files (the +// "Software"), to deal in the Software without restriction, including +// without limitation the rights to use, copy, modify, merge, publish, +// distribute, sublicense, and/or sell copies of the Software, and to permit +// persons to whom the Software is furnished to do so, subject to the +// following conditions: +// +// The above copyright notice and this permission notice shall be included +// in all copies or substantial portions of the Software. +// +// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS +// OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF +// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN +// NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, +// DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR +// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE +// USE OR OTHER DEALINGS IN THE SOFTWARE. + +module.exports = Stream; + +var EE = require('events').EventEmitter; +var inherits = require('inherits'); + +inherits(Stream, EE); +Stream.Readable = require('readable-stream/readable.js'); +Stream.Writable = require('readable-stream/writable.js'); +Stream.Duplex = require('readable-stream/duplex.js'); +Stream.Transform = require('readable-stream/transform.js'); +Stream.PassThrough = require('readable-stream/passthrough.js'); + +// Backwards-compat with node 0.4.x +Stream.Stream = Stream; + + + +// old-style streams. Note that the pipe method (the only relevant +// part of this class) is overridden in the Readable class. + +function Stream() { + EE.call(this); +} + +Stream.prototype.pipe = function(dest, options) { + var source = this; + + function ondata(chunk) { + if (dest.writable) { + if (false === dest.write(chunk) && source.pause) { + source.pause(); + } + } + } + + source.on('data', ondata); + + function ondrain() { + if (source.readable && source.resume) { + source.resume(); + } + } + + dest.on('drain', ondrain); + + // If the 'end' option is not supplied, dest.end() will be called when + // source gets the 'end' or 'close' events. Only dest.end() once. + if (!dest._isStdio && (!options || options.end !== false)) { + source.on('end', onend); + source.on('close', onclose); + } + + var didOnEnd = false; + function onend() { + if (didOnEnd) return; + didOnEnd = true; + + dest.end(); + } + + + function onclose() { + if (didOnEnd) return; + didOnEnd = true; + + if (typeof dest.destroy === 'function') dest.destroy(); + } + + // don't leave dangling pipes when there are errors. + function onerror(er) { + cleanup(); + if (EE.listenerCount(this, 'error') === 0) { + throw er; // Unhandled stream error in pipe. + } + } + + source.on('error', onerror); + dest.on('error', onerror); + + // remove all the event listeners that were added. + function cleanup() { + source.removeListener('data', ondata); + dest.removeListener('drain', ondrain); + + source.removeListener('end', onend); + source.removeListener('close', onclose); + + source.removeListener('error', onerror); + dest.removeListener('error', onerror); + + source.removeListener('end', cleanup); + source.removeListener('close', cleanup); + + dest.removeListener('close', cleanup); + } + + source.on('end', cleanup); + source.on('close', cleanup); + + dest.on('close', cleanup); + + dest.emit('pipe', source); + + // Allow for unix-like usage: A.pipe(B).pipe(C) + return dest; +}; + +},{"events":50,"inherits":53,"readable-stream/duplex.js":61,"readable-stream/passthrough.js":67,"readable-stream/readable.js":68,"readable-stream/transform.js":69,"readable-stream/writable.js":70}],60:[function(require,module,exports){ +arguments[4][46][0].apply(exports,arguments) +},{"dup":46}],61:[function(require,module,exports){ +module.exports = require("./lib/_stream_duplex.js") + +},{"./lib/_stream_duplex.js":62}],62:[function(require,module,exports){ +// a duplex stream is just a stream that is both readable and writable. +// Since JS doesn't have multiple prototypal inheritance, this class +// prototypally inherits from Readable, and then parasitically from +// Writable. + +'use strict'; + +/**/ + +var objectKeys = Object.keys || function (obj) { + var keys = []; + for (var key in obj) { + keys.push(key); + }return keys; +}; +/**/ + +module.exports = Duplex; + +/**/ +var processNextTick = require('process-nextick-args'); +/**/ + +/**/ +var util = require('core-util-is'); +util.inherits = require('inherits'); +/**/ + +var Readable = require('./_stream_readable'); +var Writable = require('./_stream_writable'); + +util.inherits(Duplex, Readable); + +var keys = objectKeys(Writable.prototype); +for (var v = 0; v < keys.length; v++) { + var method = keys[v]; + if (!Duplex.prototype[method]) Duplex.prototype[method] = Writable.prototype[method]; +} + +function Duplex(options) { + if (!(this instanceof Duplex)) return new Duplex(options); + + Readable.call(this, options); + Writable.call(this, options); + + if (options && options.readable === false) this.readable = false; + + if (options && options.writable === false) this.writable = false; + + this.allowHalfOpen = true; + if (options && options.allowHalfOpen === false) this.allowHalfOpen = false; + + this.once('end', onend); +} + +// the no-half-open enforcer +function onend() { + // if we allow half-open state, or if the writable side ended, + // then we're ok. + if (this.allowHalfOpen || this._writableState.ended) return; + + // no more data can be written. + // But allow more writes to happen in this tick. + processNextTick(onEndNT, this); +} + +function onEndNT(self) { + self.end(); +} + +function forEach(xs, f) { + for (var i = 0, l = xs.length; i < l; i++) { + f(xs[i], i); + } +} +},{"./_stream_readable":64,"./_stream_writable":66,"core-util-is":47,"inherits":53,"process-nextick-args":57}],63:[function(require,module,exports){ +// a passthrough stream. +// basically just the most minimal sort of Transform stream. +// Every written chunk gets output as-is. + +'use strict'; + +module.exports = PassThrough; + +var Transform = require('./_stream_transform'); + +/**/ +var util = require('core-util-is'); +util.inherits = require('inherits'); +/**/ + +util.inherits(PassThrough, Transform); + +function PassThrough(options) { + if (!(this instanceof PassThrough)) return new PassThrough(options); + + Transform.call(this, options); +} + +PassThrough.prototype._transform = function (chunk, encoding, cb) { + cb(null, chunk); +}; +},{"./_stream_transform":65,"core-util-is":47,"inherits":53}],64:[function(require,module,exports){ +(function (process){ +'use strict'; + +module.exports = Readable; + +/**/ +var processNextTick = require('process-nextick-args'); +/**/ + +/**/ +var isArray = require('isarray'); +/**/ + +Readable.ReadableState = ReadableState; + +/**/ +var EE = require('events').EventEmitter; + +var EElistenerCount = function (emitter, type) { + return emitter.listeners(type).length; +}; +/**/ + +/**/ +var Stream; +(function () { + try { + Stream = require('st' + 'ream'); + } catch (_) {} finally { + if (!Stream) Stream = require('events').EventEmitter; + } +})(); +/**/ + +var Buffer = require('buffer').Buffer; +/**/ +var bufferShim = require('buffer-shims'); +/**/ + +/**/ +var util = require('core-util-is'); +util.inherits = require('inherits'); +/**/ + +/**/ +var debugUtil = require('util'); +var debug = void 0; +if (debugUtil && debugUtil.debuglog) { + debug = debugUtil.debuglog('stream'); +} else { + debug = function () {}; +} +/**/ + +var StringDecoder; + +util.inherits(Readable, Stream); + +var hasPrependListener = typeof EE.prototype.prependListener === 'function'; + +function prependListener(emitter, event, fn) { + if (hasPrependListener) return emitter.prependListener(event, fn); + + // This is a brutally ugly hack to make sure that our error handler + // is attached before any userland ones. NEVER DO THIS. This is here + // only because this code needs to continue to work with older versions + // of Node.js that do not include the prependListener() method. The goal + // is to eventually remove this hack. + if (!emitter._events || !emitter._events[event]) emitter.on(event, fn);else if (isArray(emitter._events[event])) emitter._events[event].unshift(fn);else emitter._events[event] = [fn, emitter._events[event]]; +} + +var Duplex; +function ReadableState(options, stream) { + Duplex = Duplex || require('./_stream_duplex'); + + options = options || {}; + + // object stream flag. Used to make read(n) ignore n and to + // make all the buffer merging and length checks go away + this.objectMode = !!options.objectMode; + + if (stream instanceof Duplex) this.objectMode = this.objectMode || !!options.readableObjectMode; + + // the point at which it stops calling _read() to fill the buffer + // Note: 0 is a valid value, means "don't call _read preemptively ever" + var hwm = options.highWaterMark; + var defaultHwm = this.objectMode ? 16 : 16 * 1024; + this.highWaterMark = hwm || hwm === 0 ? hwm : defaultHwm; + + // cast to ints. + this.highWaterMark = ~ ~this.highWaterMark; + + this.buffer = []; + this.length = 0; + this.pipes = null; + this.pipesCount = 0; + this.flowing = null; + this.ended = false; + this.endEmitted = false; + this.reading = false; + + // a flag to be able to tell if the onwrite cb is called immediately, + // or on a later tick. We set this to true at first, because any + // actions that shouldn't happen until "later" should generally also + // not happen before the first write call. + this.sync = true; + + // whenever we return null, then we set a flag to say + // that we're awaiting a 'readable' event emission. + this.needReadable = false; + this.emittedReadable = false; + this.readableListening = false; + this.resumeScheduled = false; + + // Crypto is kind of old and crusty. Historically, its default string + // encoding is 'binary' so we have to make this configurable. + // Everything else in the universe uses 'utf8', though. + this.defaultEncoding = options.defaultEncoding || 'utf8'; + + // when piping, we only care about 'readable' events that happen + // after read()ing all the bytes and not getting any pushback. + this.ranOut = false; + + // the number of writers that are awaiting a drain event in .pipe()s + this.awaitDrain = 0; + + // if true, a maybeReadMore has been scheduled + this.readingMore = false; + + this.decoder = null; + this.encoding = null; + if (options.encoding) { + if (!StringDecoder) StringDecoder = require('string_decoder/').StringDecoder; + this.decoder = new StringDecoder(options.encoding); + this.encoding = options.encoding; + } +} + +var Duplex; +function Readable(options) { + Duplex = Duplex || require('./_stream_duplex'); + + if (!(this instanceof Readable)) return new Readable(options); + + this._readableState = new ReadableState(options, this); + + // legacy + this.readable = true; + + if (options && typeof options.read === 'function') this._read = options.read; + + Stream.call(this); +} + +// Manually shove something into the read() buffer. +// This returns true if the highWaterMark has not been hit yet, +// similar to how Writable.write() returns true if you should +// write() some more. +Readable.prototype.push = function (chunk, encoding) { + var state = this._readableState; + + if (!state.objectMode && typeof chunk === 'string') { + encoding = encoding || state.defaultEncoding; + if (encoding !== state.encoding) { + chunk = bufferShim.from(chunk, encoding); + encoding = ''; + } + } + + return readableAddChunk(this, state, chunk, encoding, false); +}; + +// Unshift should *always* be something directly out of read() +Readable.prototype.unshift = function (chunk) { + var state = this._readableState; + return readableAddChunk(this, state, chunk, '', true); +}; + +Readable.prototype.isPaused = function () { + return this._readableState.flowing === false; +}; + +function readableAddChunk(stream, state, chunk, encoding, addToFront) { + var er = chunkInvalid(state, chunk); + if (er) { + stream.emit('error', er); + } else if (chunk === null) { + state.reading = false; + onEofChunk(stream, state); + } else if (state.objectMode || chunk && chunk.length > 0) { + if (state.ended && !addToFront) { + var e = new Error('stream.push() after EOF'); + stream.emit('error', e); + } else if (state.endEmitted && addToFront) { + var _e = new Error('stream.unshift() after end event'); + stream.emit('error', _e); + } else { + var skipAdd; + if (state.decoder && !addToFront && !encoding) { + chunk = state.decoder.write(chunk); + skipAdd = !state.objectMode && chunk.length === 0; + } + + if (!addToFront) state.reading = false; + + // Don't add to the buffer if we've decoded to an empty string chunk and + // we're not in object mode + if (!skipAdd) { + // if we want the data now, just emit it. + if (state.flowing && state.length === 0 && !state.sync) { + stream.emit('data', chunk); + stream.read(0); + } else { + // update the buffer info. + state.length += state.objectMode ? 1 : chunk.length; + if (addToFront) state.buffer.unshift(chunk);else state.buffer.push(chunk); + + if (state.needReadable) emitReadable(stream); + } + } + + maybeReadMore(stream, state); + } + } else if (!addToFront) { + state.reading = false; + } + + return needMoreData(state); +} + +// if it's past the high water mark, we can push in some more. +// Also, if we have no data yet, we can stand some +// more bytes. This is to work around cases where hwm=0, +// such as the repl. Also, if the push() triggered a +// readable event, and the user called read(largeNumber) such that +// needReadable was set, then we ought to push more, so that another +// 'readable' event will be triggered. +function needMoreData(state) { + return !state.ended && (state.needReadable || state.length < state.highWaterMark || state.length === 0); +} + +// backwards compatibility. +Readable.prototype.setEncoding = function (enc) { + if (!StringDecoder) StringDecoder = require('string_decoder/').StringDecoder; + this._readableState.decoder = new StringDecoder(enc); + this._readableState.encoding = enc; + return this; +}; + +// Don't raise the hwm > 8MB +var MAX_HWM = 0x800000; +function computeNewHighWaterMark(n) { + if (n >= MAX_HWM) { + n = MAX_HWM; + } else { + // Get the next highest power of 2 + n--; + n |= n >>> 1; + n |= n >>> 2; + n |= n >>> 4; + n |= n >>> 8; + n |= n >>> 16; + n++; + } + return n; +} + +function howMuchToRead(n, state) { + if (state.length === 0 && state.ended) return 0; + + if (state.objectMode) return n === 0 ? 0 : 1; + + if (n === null || isNaN(n)) { + // only flow one buffer at a time + if (state.flowing && state.buffer.length) return state.buffer[0].length;else return state.length; + } + + if (n <= 0) return 0; + + // If we're asking for more than the target buffer level, + // then raise the water mark. Bump up to the next highest + // power of 2, to prevent increasing it excessively in tiny + // amounts. + if (n > state.highWaterMark) state.highWaterMark = computeNewHighWaterMark(n); + + // don't have that much. return null, unless we've ended. + if (n > state.length) { + if (!state.ended) { + state.needReadable = true; + return 0; + } else { + return state.length; + } + } + + return n; +} + +// you can override either this method, or the async _read(n) below. +Readable.prototype.read = function (n) { + debug('read', n); + var state = this._readableState; + var nOrig = n; + + if (typeof n !== 'number' || n > 0) state.emittedReadable = false; + + // if we're doing read(0) to trigger a readable event, but we + // already have a bunch of data in the buffer, then just trigger + // the 'readable' event and move on. + if (n === 0 && state.needReadable && (state.length >= state.highWaterMark || state.ended)) { + debug('read: emitReadable', state.length, state.ended); + if (state.length === 0 && state.ended) endReadable(this);else emitReadable(this); + return null; + } + + n = howMuchToRead(n, state); + + // if we've ended, and we're now clear, then finish it up. + if (n === 0 && state.ended) { + if (state.length === 0) endReadable(this); + return null; + } + + // All the actual chunk generation logic needs to be + // *below* the call to _read. The reason is that in certain + // synthetic stream cases, such as passthrough streams, _read + // may be a completely synchronous operation which may change + // the state of the read buffer, providing enough data when + // before there was *not* enough. + // + // So, the steps are: + // 1. Figure out what the state of things will be after we do + // a read from the buffer. + // + // 2. If that resulting state will trigger a _read, then call _read. + // Note that this may be asynchronous, or synchronous. Yes, it is + // deeply ugly to write APIs this way, but that still doesn't mean + // that the Readable class should behave improperly, as streams are + // designed to be sync/async agnostic. + // Take note if the _read call is sync or async (ie, if the read call + // has returned yet), so that we know whether or not it's safe to emit + // 'readable' etc. + // + // 3. Actually pull the requested chunks out of the buffer and return. + + // if we need a readable event, then we need to do some reading. + var doRead = state.needReadable; + debug('need readable', doRead); + + // if we currently have less than the highWaterMark, then also read some + if (state.length === 0 || state.length - n < state.highWaterMark) { + doRead = true; + debug('length less than watermark', doRead); + } + + // however, if we've ended, then there's no point, and if we're already + // reading, then it's unnecessary. + if (state.ended || state.reading) { + doRead = false; + debug('reading or ended', doRead); + } + + if (doRead) { + debug('do read'); + state.reading = true; + state.sync = true; + // if the length is currently zero, then we *need* a readable event. + if (state.length === 0) state.needReadable = true; + // call internal read method + this._read(state.highWaterMark); + state.sync = false; + } + + // If _read pushed data synchronously, then `reading` will be false, + // and we need to re-evaluate how much data we can return to the user. + if (doRead && !state.reading) n = howMuchToRead(nOrig, state); + + var ret; + if (n > 0) ret = fromList(n, state);else ret = null; + + if (ret === null) { + state.needReadable = true; + n = 0; + } + + state.length -= n; + + // If we have nothing in the buffer, then we want to know + // as soon as we *do* get something into the buffer. + if (state.length === 0 && !state.ended) state.needReadable = true; + + // If we tried to read() past the EOF, then emit end on the next tick. + if (nOrig !== n && state.ended && state.length === 0) endReadable(this); + + if (ret !== null) this.emit('data', ret); + + return ret; +}; + +function chunkInvalid(state, chunk) { + var er = null; + if (!Buffer.isBuffer(chunk) && typeof chunk !== 'string' && chunk !== null && chunk !== undefined && !state.objectMode) { + er = new TypeError('Invalid non-string/buffer chunk'); + } + return er; +} + +function onEofChunk(stream, state) { + if (state.ended) return; + if (state.decoder) { + var chunk = state.decoder.end(); + if (chunk && chunk.length) { + state.buffer.push(chunk); + state.length += state.objectMode ? 1 : chunk.length; + } + } + state.ended = true; + + // emit 'readable' now to make sure it gets picked up. + emitReadable(stream); +} + +// Don't emit readable right away in sync mode, because this can trigger +// another read() call => stack overflow. This way, it might trigger +// a nextTick recursion warning, but that's not so bad. +function emitReadable(stream) { + var state = stream._readableState; + state.needReadable = false; + if (!state.emittedReadable) { + debug('emitReadable', state.flowing); + state.emittedReadable = true; + if (state.sync) processNextTick(emitReadable_, stream);else emitReadable_(stream); + } +} + +function emitReadable_(stream) { + debug('emit readable'); + stream.emit('readable'); + flow(stream); +} + +// at this point, the user has presumably seen the 'readable' event, +// and called read() to consume some data. that may have triggered +// in turn another _read(n) call, in which case reading = true if +// it's in progress. +// However, if we're not ended, or reading, and the length < hwm, +// then go ahead and try to read some more preemptively. +function maybeReadMore(stream, state) { + if (!state.readingMore) { + state.readingMore = true; + processNextTick(maybeReadMore_, stream, state); + } +} + +function maybeReadMore_(stream, state) { + var len = state.length; + while (!state.reading && !state.flowing && !state.ended && state.length < state.highWaterMark) { + debug('maybeReadMore read 0'); + stream.read(0); + if (len === state.length) + // didn't get any data, stop spinning. + break;else len = state.length; + } + state.readingMore = false; +} + +// abstract method. to be overridden in specific implementation classes. +// call cb(er, data) where data is <= n in length. +// for virtual (non-string, non-buffer) streams, "length" is somewhat +// arbitrary, and perhaps not very meaningful. +Readable.prototype._read = function (n) { + this.emit('error', new Error('not implemented')); +}; + +Readable.prototype.pipe = function (dest, pipeOpts) { + var src = this; + var state = this._readableState; + + switch (state.pipesCount) { + case 0: + state.pipes = dest; + break; + case 1: + state.pipes = [state.pipes, dest]; + break; + default: + state.pipes.push(dest); + break; + } + state.pipesCount += 1; + debug('pipe count=%d opts=%j', state.pipesCount, pipeOpts); + + var doEnd = (!pipeOpts || pipeOpts.end !== false) && dest !== process.stdout && dest !== process.stderr; + + var endFn = doEnd ? onend : cleanup; + if (state.endEmitted) processNextTick(endFn);else src.once('end', endFn); + + dest.on('unpipe', onunpipe); + function onunpipe(readable) { + debug('onunpipe'); + if (readable === src) { + cleanup(); + } + } + + function onend() { + debug('onend'); + dest.end(); + } + + // when the dest drains, it reduces the awaitDrain counter + // on the source. This would be more elegant with a .once() + // handler in flow(), but adding and removing repeatedly is + // too slow. + var ondrain = pipeOnDrain(src); + dest.on('drain', ondrain); + + var cleanedUp = false; + function cleanup() { + debug('cleanup'); + // cleanup event handlers once the pipe is broken + dest.removeListener('close', onclose); + dest.removeListener('finish', onfinish); + dest.removeListener('drain', ondrain); + dest.removeListener('error', onerror); + dest.removeListener('unpipe', onunpipe); + src.removeListener('end', onend); + src.removeListener('end', cleanup); + src.removeListener('data', ondata); + + cleanedUp = true; + + // if the reader is waiting for a drain event from this + // specific writer, then it would cause it to never start + // flowing again. + // So, if this is awaiting a drain, then we just call it now. + // If we don't know, then assume that we are waiting for one. + if (state.awaitDrain && (!dest._writableState || dest._writableState.needDrain)) ondrain(); + } + + src.on('data', ondata); + function ondata(chunk) { + debug('ondata'); + var ret = dest.write(chunk); + if (false === ret) { + // If the user unpiped during `dest.write()`, it is possible + // to get stuck in a permanently paused state if that write + // also returned false. + // => Check whether `dest` is still a piping destination. + if ((state.pipesCount === 1 && state.pipes === dest || state.pipesCount > 1 && indexOf(state.pipes, dest) !== -1) && !cleanedUp) { + debug('false write response, pause', src._readableState.awaitDrain); + src._readableState.awaitDrain++; + } + src.pause(); + } + } + + // if the dest has an error, then stop piping into it. + // however, don't suppress the throwing behavior for this. + function onerror(er) { + debug('onerror', er); + unpipe(); + dest.removeListener('error', onerror); + if (EElistenerCount(dest, 'error') === 0) dest.emit('error', er); + } + + // Make sure our error handler is attached before userland ones. + prependListener(dest, 'error', onerror); + + // Both close and finish should trigger unpipe, but only once. + function onclose() { + dest.removeListener('finish', onfinish); + unpipe(); + } + dest.once('close', onclose); + function onfinish() { + debug('onfinish'); + dest.removeListener('close', onclose); + unpipe(); + } + dest.once('finish', onfinish); + + function unpipe() { + debug('unpipe'); + src.unpipe(dest); + } + + // tell the dest that it's being piped to + dest.emit('pipe', src); + + // start the flow if it hasn't been started already. + if (!state.flowing) { + debug('pipe resume'); + src.resume(); + } + + return dest; +}; + +function pipeOnDrain(src) { + return function () { + var state = src._readableState; + debug('pipeOnDrain', state.awaitDrain); + if (state.awaitDrain) state.awaitDrain--; + if (state.awaitDrain === 0 && EElistenerCount(src, 'data')) { + state.flowing = true; + flow(src); + } + }; +} + +Readable.prototype.unpipe = function (dest) { + var state = this._readableState; + + // if we're not piping anywhere, then do nothing. + if (state.pipesCount === 0) return this; + + // just one destination. most common case. + if (state.pipesCount === 1) { + // passed in one, but it's not the right one. + if (dest && dest !== state.pipes) return this; + + if (!dest) dest = state.pipes; + + // got a match. + state.pipes = null; + state.pipesCount = 0; + state.flowing = false; + if (dest) dest.emit('unpipe', this); + return this; + } + + // slow case. multiple pipe destinations. + + if (!dest) { + // remove all. + var dests = state.pipes; + var len = state.pipesCount; + state.pipes = null; + state.pipesCount = 0; + state.flowing = false; + + for (var _i = 0; _i < len; _i++) { + dests[_i].emit('unpipe', this); + }return this; + } + + // try to find the right one. + var i = indexOf(state.pipes, dest); + if (i === -1) return this; + + state.pipes.splice(i, 1); + state.pipesCount -= 1; + if (state.pipesCount === 1) state.pipes = state.pipes[0]; + + dest.emit('unpipe', this); + + return this; +}; + +// set up data events if they are asked for +// Ensure readable listeners eventually get something +Readable.prototype.on = function (ev, fn) { + var res = Stream.prototype.on.call(this, ev, fn); + + // If listening to data, and it has not explicitly been paused, + // then call resume to start the flow of data on the next tick. + if (ev === 'data' && false !== this._readableState.flowing) { + this.resume(); + } + + if (ev === 'readable' && !this._readableState.endEmitted) { + var state = this._readableState; + if (!state.readableListening) { + state.readableListening = true; + state.emittedReadable = false; + state.needReadable = true; + if (!state.reading) { + processNextTick(nReadingNextTick, this); + } else if (state.length) { + emitReadable(this, state); + } + } + } + + return res; +}; +Readable.prototype.addListener = Readable.prototype.on; + +function nReadingNextTick(self) { + debug('readable nexttick read 0'); + self.read(0); +} + +// pause() and resume() are remnants of the legacy readable stream API +// If the user uses them, then switch into old mode. +Readable.prototype.resume = function () { + var state = this._readableState; + if (!state.flowing) { + debug('resume'); + state.flowing = true; + resume(this, state); + } + return this; +}; + +function resume(stream, state) { + if (!state.resumeScheduled) { + state.resumeScheduled = true; + processNextTick(resume_, stream, state); + } +} + +function resume_(stream, state) { + if (!state.reading) { + debug('resume read 0'); + stream.read(0); + } + + state.resumeScheduled = false; + stream.emit('resume'); + flow(stream); + if (state.flowing && !state.reading) stream.read(0); +} + +Readable.prototype.pause = function () { + debug('call pause flowing=%j', this._readableState.flowing); + if (false !== this._readableState.flowing) { + debug('pause'); + this._readableState.flowing = false; + this.emit('pause'); + } + return this; +}; + +function flow(stream) { + var state = stream._readableState; + debug('flow', state.flowing); + if (state.flowing) { + do { + var chunk = stream.read(); + } while (null !== chunk && state.flowing); + } +} + +// wrap an old-style stream as the async data source. +// This is *not* part of the readable stream interface. +// It is an ugly unfortunate mess of history. +Readable.prototype.wrap = function (stream) { + var state = this._readableState; + var paused = false; + + var self = this; + stream.on('end', function () { + debug('wrapped end'); + if (state.decoder && !state.ended) { + var chunk = state.decoder.end(); + if (chunk && chunk.length) self.push(chunk); + } + + self.push(null); + }); + + stream.on('data', function (chunk) { + debug('wrapped data'); + if (state.decoder) chunk = state.decoder.write(chunk); + + // don't skip over falsy values in objectMode + if (state.objectMode && (chunk === null || chunk === undefined)) return;else if (!state.objectMode && (!chunk || !chunk.length)) return; + + var ret = self.push(chunk); + if (!ret) { + paused = true; + stream.pause(); + } + }); + + // proxy all the other methods. + // important when wrapping filters and duplexes. + for (var i in stream) { + if (this[i] === undefined && typeof stream[i] === 'function') { + this[i] = function (method) { + return function () { + return stream[method].apply(stream, arguments); + }; + }(i); + } + } + + // proxy certain important events. + var events = ['error', 'close', 'destroy', 'pause', 'resume']; + forEach(events, function (ev) { + stream.on(ev, self.emit.bind(self, ev)); + }); + + // when we try to consume some more bytes, simply unpause the + // underlying stream. + self._read = function (n) { + debug('wrapped _read', n); + if (paused) { + paused = false; + stream.resume(); + } + }; + + return self; +}; + +// exposed for testing purposes only. +Readable._fromList = fromList; + +// Pluck off n bytes from an array of buffers. +// Length is the combined lengths of all the buffers in the list. +function fromList(n, state) { + var list = state.buffer; + var length = state.length; + var stringMode = !!state.decoder; + var objectMode = !!state.objectMode; + var ret; + + // nothing in the list, definitely empty. + if (list.length === 0) return null; + + if (length === 0) ret = null;else if (objectMode) ret = list.shift();else if (!n || n >= length) { + // read it all, truncate the array. + if (stringMode) ret = list.join('');else if (list.length === 1) ret = list[0];else ret = Buffer.concat(list, length); + list.length = 0; + } else { + // read just some of it. + if (n < list[0].length) { + // just take a part of the first list item. + // slice is the same for buffers and strings. + var buf = list[0]; + ret = buf.slice(0, n); + list[0] = buf.slice(n); + } else if (n === list[0].length) { + // first list is a perfect match + ret = list.shift(); + } else { + // complex case. + // we have enough to cover it, but it spans past the first buffer. + if (stringMode) ret = '';else ret = bufferShim.allocUnsafe(n); + + var c = 0; + for (var i = 0, l = list.length; i < l && c < n; i++) { + var _buf = list[0]; + var cpy = Math.min(n - c, _buf.length); + + if (stringMode) ret += _buf.slice(0, cpy);else _buf.copy(ret, c, 0, cpy); + + if (cpy < _buf.length) list[0] = _buf.slice(cpy);else list.shift(); + + c += cpy; + } + } + } + + return ret; +} + +function endReadable(stream) { + var state = stream._readableState; + + // If we get here before consuming all the bytes, then that is a + // bug in node. Should never happen. + if (state.length > 0) throw new Error('"endReadable()" called on non-empty stream'); + + if (!state.endEmitted) { + state.ended = true; + processNextTick(endReadableNT, state, stream); + } +} + +function endReadableNT(state, stream) { + // Check that we didn't get one last unshift. + if (!state.endEmitted && state.length === 0) { + state.endEmitted = true; + stream.readable = false; + stream.emit('end'); + } +} + +function forEach(xs, f) { + for (var i = 0, l = xs.length; i < l; i++) { + f(xs[i], i); + } +} + +function indexOf(xs, x) { + for (var i = 0, l = xs.length; i < l; i++) { + if (xs[i] === x) return i; + } + return -1; +} +}).call(this,require('_process')) +},{"./_stream_duplex":62,"_process":58,"buffer":45,"buffer-shims":44,"core-util-is":47,"events":50,"inherits":53,"isarray":60,"process-nextick-args":57,"string_decoder/":71,"util":41}],65:[function(require,module,exports){ +// a transform stream is a readable/writable stream where you do +// something with the data. Sometimes it's called a "filter", +// but that's not a great name for it, since that implies a thing where +// some bits pass through, and others are simply ignored. (That would +// be a valid example of a transform, of course.) +// +// While the output is causally related to the input, it's not a +// necessarily symmetric or synchronous transformation. For example, +// a zlib stream might take multiple plain-text writes(), and then +// emit a single compressed chunk some time in the future. +// +// Here's how this works: +// +// The Transform stream has all the aspects of the readable and writable +// stream classes. When you write(chunk), that calls _write(chunk,cb) +// internally, and returns false if there's a lot of pending writes +// buffered up. When you call read(), that calls _read(n) until +// there's enough pending readable data buffered up. +// +// In a transform stream, the written data is placed in a buffer. When +// _read(n) is called, it transforms the queued up data, calling the +// buffered _write cb's as it consumes chunks. If consuming a single +// written chunk would result in multiple output chunks, then the first +// outputted bit calls the readcb, and subsequent chunks just go into +// the read buffer, and will cause it to emit 'readable' if necessary. +// +// This way, back-pressure is actually determined by the reading side, +// since _read has to be called to start processing a new chunk. However, +// a pathological inflate type of transform can cause excessive buffering +// here. For example, imagine a stream where every byte of input is +// interpreted as an integer from 0-255, and then results in that many +// bytes of output. Writing the 4 bytes {ff,ff,ff,ff} would result in +// 1kb of data being output. In this case, you could write a very small +// amount of input, and end up with a very large amount of output. In +// such a pathological inflating mechanism, there'd be no way to tell +// the system to stop doing the transform. A single 4MB write could +// cause the system to run out of memory. +// +// However, even in such a pathological case, only a single written chunk +// would be consumed, and then the rest would wait (un-transformed) until +// the results of the previous transformed chunk were consumed. + +'use strict'; + +module.exports = Transform; + +var Duplex = require('./_stream_duplex'); + +/**/ +var util = require('core-util-is'); +util.inherits = require('inherits'); +/**/ + +util.inherits(Transform, Duplex); + +function TransformState(stream) { + this.afterTransform = function (er, data) { + return afterTransform(stream, er, data); + }; + + this.needTransform = false; + this.transforming = false; + this.writecb = null; + this.writechunk = null; + this.writeencoding = null; +} + +function afterTransform(stream, er, data) { + var ts = stream._transformState; + ts.transforming = false; + + var cb = ts.writecb; + + if (!cb) return stream.emit('error', new Error('no writecb in Transform class')); + + ts.writechunk = null; + ts.writecb = null; + + if (data !== null && data !== undefined) stream.push(data); + + cb(er); + + var rs = stream._readableState; + rs.reading = false; + if (rs.needReadable || rs.length < rs.highWaterMark) { + stream._read(rs.highWaterMark); + } +} + +function Transform(options) { + if (!(this instanceof Transform)) return new Transform(options); + + Duplex.call(this, options); + + this._transformState = new TransformState(this); + + // when the writable side finishes, then flush out anything remaining. + var stream = this; + + // start out asking for a readable event once data is transformed. + this._readableState.needReadable = true; + + // we have implemented the _read method, and done the other things + // that Readable wants before the first _read call, so unset the + // sync guard flag. + this._readableState.sync = false; + + if (options) { + if (typeof options.transform === 'function') this._transform = options.transform; + + if (typeof options.flush === 'function') this._flush = options.flush; + } + + this.once('prefinish', function () { + if (typeof this._flush === 'function') this._flush(function (er) { + done(stream, er); + });else done(stream); + }); +} + +Transform.prototype.push = function (chunk, encoding) { + this._transformState.needTransform = false; + return Duplex.prototype.push.call(this, chunk, encoding); +}; + +// This is the part where you do stuff! +// override this function in implementation classes. +// 'chunk' is an input chunk. +// +// Call `push(newChunk)` to pass along transformed output +// to the readable side. You may call 'push' zero or more times. +// +// Call `cb(err)` when you are done with this chunk. If you pass +// an error, then that'll put the hurt on the whole operation. If you +// never call cb(), then you'll never get another chunk. +Transform.prototype._transform = function (chunk, encoding, cb) { + throw new Error('Not implemented'); +}; + +Transform.prototype._write = function (chunk, encoding, cb) { + var ts = this._transformState; + ts.writecb = cb; + ts.writechunk = chunk; + ts.writeencoding = encoding; + if (!ts.transforming) { + var rs = this._readableState; + if (ts.needTransform || rs.needReadable || rs.length < rs.highWaterMark) this._read(rs.highWaterMark); + } +}; + +// Doesn't matter what the args are here. +// _transform does all the work. +// That we got here means that the readable side wants more data. +Transform.prototype._read = function (n) { + var ts = this._transformState; + + if (ts.writechunk !== null && ts.writecb && !ts.transforming) { + ts.transforming = true; + this._transform(ts.writechunk, ts.writeencoding, ts.afterTransform); + } else { + // mark that we need a transform, so that any data that comes in + // will get processed, now that we've asked for it. + ts.needTransform = true; + } +}; + +function done(stream, er) { + if (er) return stream.emit('error', er); + + // if there's nothing in the write buffer, then that means + // that nothing more will ever be provided + var ws = stream._writableState; + var ts = stream._transformState; + + if (ws.length) throw new Error('Calling transform done when ws.length != 0'); + + if (ts.transforming) throw new Error('Calling transform done when still transforming'); + + return stream.push(null); +} +},{"./_stream_duplex":62,"core-util-is":47,"inherits":53}],66:[function(require,module,exports){ +(function (process){ +// A bit simpler than readable streams. +// Implement an async ._write(chunk, encoding, cb), and it'll handle all +// the drain event emission and buffering. + +'use strict'; + +module.exports = Writable; + +/**/ +var processNextTick = require('process-nextick-args'); +/**/ + +/**/ +var asyncWrite = !process.browser && ['v0.10', 'v0.9.'].indexOf(process.version.slice(0, 5)) > -1 ? setImmediate : processNextTick; +/**/ + +Writable.WritableState = WritableState; + +/**/ +var util = require('core-util-is'); +util.inherits = require('inherits'); +/**/ + +/**/ +var internalUtil = { + deprecate: require('util-deprecate') +}; +/**/ + +/**/ +var Stream; +(function () { + try { + Stream = require('st' + 'ream'); + } catch (_) {} finally { + if (!Stream) Stream = require('events').EventEmitter; + } +})(); +/**/ + +var Buffer = require('buffer').Buffer; +/**/ +var bufferShim = require('buffer-shims'); +/**/ + +util.inherits(Writable, Stream); + +function nop() {} + +function WriteReq(chunk, encoding, cb) { + this.chunk = chunk; + this.encoding = encoding; + this.callback = cb; + this.next = null; +} + +var Duplex; +function WritableState(options, stream) { + Duplex = Duplex || require('./_stream_duplex'); + + options = options || {}; + + // object stream flag to indicate whether or not this stream + // contains buffers or objects. + this.objectMode = !!options.objectMode; + + if (stream instanceof Duplex) this.objectMode = this.objectMode || !!options.writableObjectMode; + + // the point at which write() starts returning false + // Note: 0 is a valid value, means that we always return false if + // the entire buffer is not flushed immediately on write() + var hwm = options.highWaterMark; + var defaultHwm = this.objectMode ? 16 : 16 * 1024; + this.highWaterMark = hwm || hwm === 0 ? hwm : defaultHwm; + + // cast to ints. + this.highWaterMark = ~ ~this.highWaterMark; + + this.needDrain = false; + // at the start of calling end() + this.ending = false; + // when end() has been called, and returned + this.ended = false; + // when 'finish' is emitted + this.finished = false; + + // should we decode strings into buffers before passing to _write? + // this is here so that some node-core streams can optimize string + // handling at a lower level. + var noDecode = options.decodeStrings === false; + this.decodeStrings = !noDecode; + + // Crypto is kind of old and crusty. Historically, its default string + // encoding is 'binary' so we have to make this configurable. + // Everything else in the universe uses 'utf8', though. + this.defaultEncoding = options.defaultEncoding || 'utf8'; + + // not an actual buffer we keep track of, but a measurement + // of how much we're waiting to get pushed to some underlying + // socket or file. + this.length = 0; + + // a flag to see when we're in the middle of a write. + this.writing = false; + + // when true all writes will be buffered until .uncork() call + this.corked = 0; + + // a flag to be able to tell if the onwrite cb is called immediately, + // or on a later tick. We set this to true at first, because any + // actions that shouldn't happen until "later" should generally also + // not happen before the first write call. + this.sync = true; + + // a flag to know if we're processing previously buffered items, which + // may call the _write() callback in the same tick, so that we don't + // end up in an overlapped onwrite situation. + this.bufferProcessing = false; + + // the callback that's passed to _write(chunk,cb) + this.onwrite = function (er) { + onwrite(stream, er); + }; + + // the callback that the user supplies to write(chunk,encoding,cb) + this.writecb = null; + + // the amount that is being written when _write is called. + this.writelen = 0; + + this.bufferedRequest = null; + this.lastBufferedRequest = null; + + // number of pending user-supplied write callbacks + // this must be 0 before 'finish' can be emitted + this.pendingcb = 0; + + // emit prefinish if the only thing we're waiting for is _write cbs + // This is relevant for synchronous Transform streams + this.prefinished = false; + + // True if the error was already emitted and should not be thrown again + this.errorEmitted = false; + + // count buffered requests + this.bufferedRequestCount = 0; + + // allocate the first CorkedRequest, there is always + // one allocated and free to use, and we maintain at most two + this.corkedRequestsFree = new CorkedRequest(this); +} + +WritableState.prototype.getBuffer = function writableStateGetBuffer() { + var current = this.bufferedRequest; + var out = []; + while (current) { + out.push(current); + current = current.next; + } + return out; +}; + +(function () { + try { + Object.defineProperty(WritableState.prototype, 'buffer', { + get: internalUtil.deprecate(function () { + return this.getBuffer(); + }, '_writableState.buffer is deprecated. Use _writableState.getBuffer ' + 'instead.') + }); + } catch (_) {} +})(); + +var Duplex; +function Writable(options) { + Duplex = Duplex || require('./_stream_duplex'); + + // Writable ctor is applied to Duplexes, though they're not + // instanceof Writable, they're instanceof Readable. + if (!(this instanceof Writable) && !(this instanceof Duplex)) return new Writable(options); + + this._writableState = new WritableState(options, this); + + // legacy. + this.writable = true; + + if (options) { + if (typeof options.write === 'function') this._write = options.write; + + if (typeof options.writev === 'function') this._writev = options.writev; + } + + Stream.call(this); +} + +// Otherwise people can pipe Writable streams, which is just wrong. +Writable.prototype.pipe = function () { + this.emit('error', new Error('Cannot pipe, not readable')); +}; + +function writeAfterEnd(stream, cb) { + var er = new Error('write after end'); + // TODO: defer error events consistently everywhere, not just the cb + stream.emit('error', er); + processNextTick(cb, er); +} + +// If we get something that is not a buffer, string, null, or undefined, +// and we're not in objectMode, then that's an error. +// Otherwise stream chunks are all considered to be of length=1, and the +// watermarks determine how many objects to keep in the buffer, rather than +// how many bytes or characters. +function validChunk(stream, state, chunk, cb) { + var valid = true; + var er = false; + // Always throw error if a null is written + // if we are not in object mode then throw + // if it is not a buffer, string, or undefined. + if (chunk === null) { + er = new TypeError('May not write null values to stream'); + } else if (!Buffer.isBuffer(chunk) && typeof chunk !== 'string' && chunk !== undefined && !state.objectMode) { + er = new TypeError('Invalid non-string/buffer chunk'); + } + if (er) { + stream.emit('error', er); + processNextTick(cb, er); + valid = false; + } + return valid; +} + +Writable.prototype.write = function (chunk, encoding, cb) { + var state = this._writableState; + var ret = false; + + if (typeof encoding === 'function') { + cb = encoding; + encoding = null; + } + + if (Buffer.isBuffer(chunk)) encoding = 'buffer';else if (!encoding) encoding = state.defaultEncoding; + + if (typeof cb !== 'function') cb = nop; + + if (state.ended) writeAfterEnd(this, cb);else if (validChunk(this, state, chunk, cb)) { + state.pendingcb++; + ret = writeOrBuffer(this, state, chunk, encoding, cb); + } + + return ret; +}; + +Writable.prototype.cork = function () { + var state = this._writableState; + + state.corked++; +}; + +Writable.prototype.uncork = function () { + var state = this._writableState; + + if (state.corked) { + state.corked--; + + if (!state.writing && !state.corked && !state.finished && !state.bufferProcessing && state.bufferedRequest) clearBuffer(this, state); + } +}; + +Writable.prototype.setDefaultEncoding = function setDefaultEncoding(encoding) { + // node::ParseEncoding() requires lower case. + if (typeof encoding === 'string') encoding = encoding.toLowerCase(); + if (!(['hex', 'utf8', 'utf-8', 'ascii', 'binary', 'base64', 'ucs2', 'ucs-2', 'utf16le', 'utf-16le', 'raw'].indexOf((encoding + '').toLowerCase()) > -1)) throw new TypeError('Unknown encoding: ' + encoding); + this._writableState.defaultEncoding = encoding; + return this; +}; + +function decodeChunk(state, chunk, encoding) { + if (!state.objectMode && state.decodeStrings !== false && typeof chunk === 'string') { + chunk = bufferShim.from(chunk, encoding); + } + return chunk; +} + +// if we're already writing something, then just put this +// in the queue, and wait our turn. Otherwise, call _write +// If we return false, then we need a drain event, so set that flag. +function writeOrBuffer(stream, state, chunk, encoding, cb) { + chunk = decodeChunk(state, chunk, encoding); + + if (Buffer.isBuffer(chunk)) encoding = 'buffer'; + var len = state.objectMode ? 1 : chunk.length; + + state.length += len; + + var ret = state.length < state.highWaterMark; + // we must ensure that previous needDrain will not be reset to false. + if (!ret) state.needDrain = true; + + if (state.writing || state.corked) { + var last = state.lastBufferedRequest; + state.lastBufferedRequest = new WriteReq(chunk, encoding, cb); + if (last) { + last.next = state.lastBufferedRequest; + } else { + state.bufferedRequest = state.lastBufferedRequest; + } + state.bufferedRequestCount += 1; + } else { + doWrite(stream, state, false, len, chunk, encoding, cb); + } + + return ret; +} + +function doWrite(stream, state, writev, len, chunk, encoding, cb) { + state.writelen = len; + state.writecb = cb; + state.writing = true; + state.sync = true; + if (writev) stream._writev(chunk, state.onwrite);else stream._write(chunk, encoding, state.onwrite); + state.sync = false; +} + +function onwriteError(stream, state, sync, er, cb) { + --state.pendingcb; + if (sync) processNextTick(cb, er);else cb(er); + + stream._writableState.errorEmitted = true; + stream.emit('error', er); +} + +function onwriteStateUpdate(state) { + state.writing = false; + state.writecb = null; + state.length -= state.writelen; + state.writelen = 0; +} + +function onwrite(stream, er) { + var state = stream._writableState; + var sync = state.sync; + var cb = state.writecb; + + onwriteStateUpdate(state); + + if (er) onwriteError(stream, state, sync, er, cb);else { + // Check if we're actually ready to finish, but don't emit yet + var finished = needFinish(state); + + if (!finished && !state.corked && !state.bufferProcessing && state.bufferedRequest) { + clearBuffer(stream, state); + } + + if (sync) { + /**/ + asyncWrite(afterWrite, stream, state, finished, cb); + /**/ + } else { + afterWrite(stream, state, finished, cb); + } + } +} + +function afterWrite(stream, state, finished, cb) { + if (!finished) onwriteDrain(stream, state); + state.pendingcb--; + cb(); + finishMaybe(stream, state); +} + +// Must force callback to be called on nextTick, so that we don't +// emit 'drain' before the write() consumer gets the 'false' return +// value, and has a chance to attach a 'drain' listener. +function onwriteDrain(stream, state) { + if (state.length === 0 && state.needDrain) { + state.needDrain = false; + stream.emit('drain'); + } +} + +// if there's something in the buffer waiting, then process it +function clearBuffer(stream, state) { + state.bufferProcessing = true; + var entry = state.bufferedRequest; + + if (stream._writev && entry && entry.next) { + // Fast case, write everything using _writev() + var l = state.bufferedRequestCount; + var buffer = new Array(l); + var holder = state.corkedRequestsFree; + holder.entry = entry; + + var count = 0; + while (entry) { + buffer[count] = entry; + entry = entry.next; + count += 1; + } + + doWrite(stream, state, true, state.length, buffer, '', holder.finish); + + // doWrite is almost always async, defer these to save a bit of time + // as the hot path ends with doWrite + state.pendingcb++; + state.lastBufferedRequest = null; + if (holder.next) { + state.corkedRequestsFree = holder.next; + holder.next = null; + } else { + state.corkedRequestsFree = new CorkedRequest(state); + } + } else { + // Slow case, write chunks one-by-one + while (entry) { + var chunk = entry.chunk; + var encoding = entry.encoding; + var cb = entry.callback; + var len = state.objectMode ? 1 : chunk.length; + + doWrite(stream, state, false, len, chunk, encoding, cb); + entry = entry.next; + // if we didn't call the onwrite immediately, then + // it means that we need to wait until it does. + // also, that means that the chunk and cb are currently + // being processed, so move the buffer counter past them. + if (state.writing) { + break; + } + } + + if (entry === null) state.lastBufferedRequest = null; + } + + state.bufferedRequestCount = 0; + state.bufferedRequest = entry; + state.bufferProcessing = false; +} + +Writable.prototype._write = function (chunk, encoding, cb) { + cb(new Error('not implemented')); +}; + +Writable.prototype._writev = null; + +Writable.prototype.end = function (chunk, encoding, cb) { + var state = this._writableState; + + if (typeof chunk === 'function') { + cb = chunk; + chunk = null; + encoding = null; + } else if (typeof encoding === 'function') { + cb = encoding; + encoding = null; + } + + if (chunk !== null && chunk !== undefined) this.write(chunk, encoding); + + // .end() fully uncorks + if (state.corked) { + state.corked = 1; + this.uncork(); + } + + // ignore unnecessary end() calls. + if (!state.ending && !state.finished) endWritable(this, state, cb); +}; + +function needFinish(state) { + return state.ending && state.length === 0 && state.bufferedRequest === null && !state.finished && !state.writing; +} + +function prefinish(stream, state) { + if (!state.prefinished) { + state.prefinished = true; + stream.emit('prefinish'); + } +} + +function finishMaybe(stream, state) { + var need = needFinish(state); + if (need) { + if (state.pendingcb === 0) { + prefinish(stream, state); + state.finished = true; + stream.emit('finish'); + } else { + prefinish(stream, state); + } + } + return need; +} + +function endWritable(stream, state, cb) { + state.ending = true; + finishMaybe(stream, state); + if (cb) { + if (state.finished) processNextTick(cb);else stream.once('finish', cb); + } + state.ended = true; + stream.writable = false; +} + +// It seems a linked list but it is not +// there will be only 2 of these for each stream +function CorkedRequest(state) { + var _this = this; + + this.next = null; + this.entry = null; + + this.finish = function (err) { + var entry = _this.entry; + _this.entry = null; + while (entry) { + var cb = entry.callback; + state.pendingcb--; + cb(err); + entry = entry.next; + } + if (state.corkedRequestsFree) { + state.corkedRequestsFree.next = _this; + } else { + state.corkedRequestsFree = _this; + } + }; +} +}).call(this,require('_process')) +},{"./_stream_duplex":62,"_process":58,"buffer":45,"buffer-shims":44,"core-util-is":47,"events":50,"inherits":53,"process-nextick-args":57,"util-deprecate":73}],67:[function(require,module,exports){ +module.exports = require("./lib/_stream_passthrough.js") + +},{"./lib/_stream_passthrough.js":63}],68:[function(require,module,exports){ +(function (process){ +var Stream = (function (){ + try { + return require('st' + 'ream'); // hack to fix a circular dependency issue when used with browserify + } catch(_){} +}()); +exports = module.exports = require('./lib/_stream_readable.js'); +exports.Stream = Stream || exports; +exports.Readable = exports; +exports.Writable = require('./lib/_stream_writable.js'); +exports.Duplex = require('./lib/_stream_duplex.js'); +exports.Transform = require('./lib/_stream_transform.js'); +exports.PassThrough = require('./lib/_stream_passthrough.js'); + +if (!process.browser && process.env.READABLE_STREAM === 'disable' && Stream) { + module.exports = Stream; +} + +}).call(this,require('_process')) +},{"./lib/_stream_duplex.js":62,"./lib/_stream_passthrough.js":63,"./lib/_stream_readable.js":64,"./lib/_stream_transform.js":65,"./lib/_stream_writable.js":66,"_process":58}],69:[function(require,module,exports){ +module.exports = require("./lib/_stream_transform.js") + +},{"./lib/_stream_transform.js":65}],70:[function(require,module,exports){ +module.exports = require("./lib/_stream_writable.js") + +},{"./lib/_stream_writable.js":66}],71:[function(require,module,exports){ +// Copyright Joyent, Inc. and other Node contributors. +// +// Permission is hereby granted, free of charge, to any person obtaining a +// copy of this software and associated documentation files (the +// "Software"), to deal in the Software without restriction, including +// without limitation the rights to use, copy, modify, merge, publish, +// distribute, sublicense, and/or sell copies of the Software, and to permit +// persons to whom the Software is furnished to do so, subject to the +// following conditions: +// +// The above copyright notice and this permission notice shall be included +// in all copies or substantial portions of the Software. +// +// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS +// OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF +// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN +// NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, +// DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR +// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE +// USE OR OTHER DEALINGS IN THE SOFTWARE. + +var Buffer = require('buffer').Buffer; + +var isBufferEncoding = Buffer.isEncoding + || function(encoding) { + switch (encoding && encoding.toLowerCase()) { + case 'hex': case 'utf8': case 'utf-8': case 'ascii': case 'binary': case 'base64': case 'ucs2': case 'ucs-2': case 'utf16le': case 'utf-16le': case 'raw': return true; + default: return false; + } + } + + +function assertEncoding(encoding) { + if (encoding && !isBufferEncoding(encoding)) { + throw new Error('Unknown encoding: ' + encoding); + } +} + +// StringDecoder provides an interface for efficiently splitting a series of +// buffers into a series of JS strings without breaking apart multi-byte +// characters. CESU-8 is handled as part of the UTF-8 encoding. +// +// @TODO Handling all encodings inside a single object makes it very difficult +// to reason about this code, so it should be split up in the future. +// @TODO There should be a utf8-strict encoding that rejects invalid UTF-8 code +// points as used by CESU-8. +var StringDecoder = exports.StringDecoder = function(encoding) { + this.encoding = (encoding || 'utf8').toLowerCase().replace(/[-_]/, ''); + assertEncoding(encoding); + switch (this.encoding) { + case 'utf8': + // CESU-8 represents each of Surrogate Pair by 3-bytes + this.surrogateSize = 3; + break; + case 'ucs2': + case 'utf16le': + // UTF-16 represents each of Surrogate Pair by 2-bytes + this.surrogateSize = 2; + this.detectIncompleteChar = utf16DetectIncompleteChar; + break; + case 'base64': + // Base-64 stores 3 bytes in 4 chars, and pads the remainder. + this.surrogateSize = 3; + this.detectIncompleteChar = base64DetectIncompleteChar; + break; + default: + this.write = passThroughWrite; + return; + } + + // Enough space to store all bytes of a single character. UTF-8 needs 4 + // bytes, but CESU-8 may require up to 6 (3 bytes per surrogate). + this.charBuffer = new Buffer(6); + // Number of bytes received for the current incomplete multi-byte character. + this.charReceived = 0; + // Number of bytes expected for the current incomplete multi-byte character. + this.charLength = 0; +}; + + +// write decodes the given buffer and returns it as JS string that is +// guaranteed to not contain any partial multi-byte characters. Any partial +// character found at the end of the buffer is buffered up, and will be +// returned when calling write again with the remaining bytes. +// +// Note: Converting a Buffer containing an orphan surrogate to a String +// currently works, but converting a String to a Buffer (via `new Buffer`, or +// Buffer#write) will replace incomplete surrogates with the unicode +// replacement character. See https://codereview.chromium.org/121173009/ . +StringDecoder.prototype.write = function(buffer) { + var charStr = ''; + // if our last write ended with an incomplete multibyte character + while (this.charLength) { + // determine how many remaining bytes this buffer has to offer for this char + var available = (buffer.length >= this.charLength - this.charReceived) ? + this.charLength - this.charReceived : + buffer.length; + + // add the new bytes to the char buffer + buffer.copy(this.charBuffer, this.charReceived, 0, available); + this.charReceived += available; + + if (this.charReceived < this.charLength) { + // still not enough chars in this buffer? wait for more ... + return ''; + } + + // remove bytes belonging to the current character from the buffer + buffer = buffer.slice(available, buffer.length); + + // get the character that was split + charStr = this.charBuffer.slice(0, this.charLength).toString(this.encoding); + + // CESU-8: lead surrogate (D800-DBFF) is also the incomplete character + var charCode = charStr.charCodeAt(charStr.length - 1); + if (charCode >= 0xD800 && charCode <= 0xDBFF) { + this.charLength += this.surrogateSize; + charStr = ''; + continue; + } + this.charReceived = this.charLength = 0; + + // if there are no more bytes in this buffer, just emit our char + if (buffer.length === 0) { + return charStr; + } + break; + } + + // determine and set charLength / charReceived + this.detectIncompleteChar(buffer); + + var end = buffer.length; + if (this.charLength) { + // buffer the incomplete character bytes we got + buffer.copy(this.charBuffer, 0, buffer.length - this.charReceived, end); + end -= this.charReceived; + } + + charStr += buffer.toString(this.encoding, 0, end); + + var end = charStr.length - 1; + var charCode = charStr.charCodeAt(end); + // CESU-8: lead surrogate (D800-DBFF) is also the incomplete character + if (charCode >= 0xD800 && charCode <= 0xDBFF) { + var size = this.surrogateSize; + this.charLength += size; + this.charReceived += size; + this.charBuffer.copy(this.charBuffer, size, 0, size); + buffer.copy(this.charBuffer, 0, 0, size); + return charStr.substring(0, end); + } + + // or just emit the charStr + return charStr; +}; + +// detectIncompleteChar determines if there is an incomplete UTF-8 character at +// the end of the given buffer. If so, it sets this.charLength to the byte +// length that character, and sets this.charReceived to the number of bytes +// that are available for this character. +StringDecoder.prototype.detectIncompleteChar = function(buffer) { + // determine how many bytes we have to check at the end of this buffer + var i = (buffer.length >= 3) ? 3 : buffer.length; + + // Figure out if one of the last i bytes of our buffer announces an + // incomplete char. + for (; i > 0; i--) { + var c = buffer[buffer.length - i]; + + // See http://en.wikipedia.org/wiki/UTF-8#Description + + // 110XXXXX + if (i == 1 && c >> 5 == 0x06) { + this.charLength = 2; + break; + } + + // 1110XXXX + if (i <= 2 && c >> 4 == 0x0E) { + this.charLength = 3; + break; + } + + // 11110XXX + if (i <= 3 && c >> 3 == 0x1E) { + this.charLength = 4; + break; + } + } + this.charReceived = i; +}; + +StringDecoder.prototype.end = function(buffer) { + var res = ''; + if (buffer && buffer.length) + res = this.write(buffer); + + if (this.charReceived) { + var cr = this.charReceived; + var buf = this.charBuffer; + var enc = this.encoding; + res += buf.slice(0, cr).toString(enc); + } + + return res; +}; + +function passThroughWrite(buffer) { + return buffer.toString(this.encoding); +} + +function utf16DetectIncompleteChar(buffer) { + this.charReceived = buffer.length % 2; + this.charLength = this.charReceived ? 2 : 0; +} + +function base64DetectIncompleteChar(buffer) { + this.charReceived = buffer.length % 3; + this.charLength = this.charReceived ? 3 : 0; +} + +},{"buffer":45}],72:[function(require,module,exports){ + +/** + * Expose `toIsoString`. + */ + +module.exports = toIsoString; + + +/** + * Turn a `date` into an ISO string. + * + * https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Date/toISOString + * + * @param {Date} date + * @return {String} + */ + +function toIsoString (date) { + return date.getUTCFullYear() + + '-' + pad(date.getUTCMonth() + 1) + + '-' + pad(date.getUTCDate()) + + 'T' + pad(date.getUTCHours()) + + ':' + pad(date.getUTCMinutes()) + + ':' + pad(date.getUTCSeconds()) + + '.' + String((date.getUTCMilliseconds()/1000).toFixed(3)).slice(2, 5) + + 'Z'; +} + + +/** + * Pad a `number` with a ten's place zero. + * + * @param {Number} number + * @return {String} + */ + +function pad (number) { + var n = number.toString(); + return n.length === 1 ? '0' + n : n; +} +},{}],73:[function(require,module,exports){ +(function (global){ + +/** + * Module exports. + */ + +module.exports = deprecate; + +/** + * Mark that a method should not be used. + * Returns a modified function which warns once by default. + * + * If `localStorage.noDeprecation = true` is set, then it is a no-op. + * + * If `localStorage.throwDeprecation = true` is set, then deprecated functions + * will throw an Error when invoked. + * + * If `localStorage.traceDeprecation = true` is set, then deprecated functions + * will invoke `console.trace()` instead of `console.error()`. + * + * @param {Function} fn - the function to deprecate + * @param {String} msg - the string to print to the console when `fn` is invoked + * @returns {Function} a new "deprecated" version of `fn` + * @api public + */ + +function deprecate (fn, msg) { + if (config('noDeprecation')) { + return fn; + } + + var warned = false; + function deprecated() { + if (!warned) { + if (config('throwDeprecation')) { + throw new Error(msg); + } else if (config('traceDeprecation')) { + console.trace(msg); + } else { + console.warn(msg); + } + warned = true; + } + return fn.apply(this, arguments); + } + + return deprecated; +} + +/** + * Checks `localStorage` for boolean values for the given `name`. + * + * @param {String} name + * @returns {Boolean} + * @api private + */ + +function config (name) { + // accessing global.localStorage can trigger a DOMException in sandboxed iframes + try { + if (!global.localStorage) return false; + } catch (_) { + return false; + } + var val = global.localStorage[name]; + if (null == val) return false; + return String(val).toLowerCase() === 'true'; +} + +}).call(this,typeof global !== "undefined" ? global : typeof self !== "undefined" ? self : typeof window !== "undefined" ? window : {}) +},{}],74:[function(require,module,exports){ +module.exports = function isBuffer(arg) { + return arg && typeof arg === 'object' + && typeof arg.copy === 'function' + && typeof arg.fill === 'function' + && typeof arg.readUInt8 === 'function'; +} +},{}],75:[function(require,module,exports){ +(function (process,global){ +// Copyright Joyent, Inc. and other Node contributors. +// +// Permission is hereby granted, free of charge, to any person obtaining a +// copy of this software and associated documentation files (the +// "Software"), to deal in the Software without restriction, including +// without limitation the rights to use, copy, modify, merge, publish, +// distribute, sublicense, and/or sell copies of the Software, and to permit +// persons to whom the Software is furnished to do so, subject to the +// following conditions: +// +// The above copyright notice and this permission notice shall be included +// in all copies or substantial portions of the Software. +// +// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS +// OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF +// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN +// NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, +// DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR +// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE +// USE OR OTHER DEALINGS IN THE SOFTWARE. + +var formatRegExp = /%[sdj%]/g; +exports.format = function(f) { + if (!isString(f)) { + var objects = []; + for (var i = 0; i < arguments.length; i++) { + objects.push(inspect(arguments[i])); + } + return objects.join(' '); + } + + var i = 1; + var args = arguments; + var len = args.length; + var str = String(f).replace(formatRegExp, function(x) { + if (x === '%%') return '%'; + if (i >= len) return x; + switch (x) { + case '%s': return String(args[i++]); + case '%d': return Number(args[i++]); + case '%j': + try { + return JSON.stringify(args[i++]); + } catch (_) { + return '[Circular]'; + } + default: + return x; + } + }); + for (var x = args[i]; i < len; x = args[++i]) { + if (isNull(x) || !isObject(x)) { + str += ' ' + x; + } else { + str += ' ' + inspect(x); + } + } + return str; +}; + + +// Mark that a method should not be used. +// Returns a modified function which warns once by default. +// If --no-deprecation is set, then it is a no-op. +exports.deprecate = function(fn, msg) { + // Allow for deprecating things in the process of starting up. + if (isUndefined(global.process)) { + return function() { + return exports.deprecate(fn, msg).apply(this, arguments); + }; + } + + if (process.noDeprecation === true) { + return fn; + } + + var warned = false; + function deprecated() { + if (!warned) { + if (process.throwDeprecation) { + throw new Error(msg); + } else if (process.traceDeprecation) { + console.trace(msg); + } else { + console.error(msg); + } + warned = true; + } + return fn.apply(this, arguments); + } + + return deprecated; +}; + + +var debugs = {}; +var debugEnviron; +exports.debuglog = function(set) { + if (isUndefined(debugEnviron)) + debugEnviron = process.env.NODE_DEBUG || ''; + set = set.toUpperCase(); + if (!debugs[set]) { + if (new RegExp('\\b' + set + '\\b', 'i').test(debugEnviron)) { + var pid = process.pid; + debugs[set] = function() { + var msg = exports.format.apply(exports, arguments); + console.error('%s %d: %s', set, pid, msg); + }; + } else { + debugs[set] = function() {}; + } + } + return debugs[set]; +}; + + +/** + * Echos the value of a value. Trys to print the value out + * in the best way possible given the different types. + * + * @param {Object} obj The object to print out. + * @param {Object} opts Optional options object that alters the output. + */ +/* legacy: obj, showHidden, depth, colors*/ +function inspect(obj, opts) { + // default options + var ctx = { + seen: [], + stylize: stylizeNoColor + }; + // legacy... + if (arguments.length >= 3) ctx.depth = arguments[2]; + if (arguments.length >= 4) ctx.colors = arguments[3]; + if (isBoolean(opts)) { + // legacy... + ctx.showHidden = opts; + } else if (opts) { + // got an "options" object + exports._extend(ctx, opts); + } + // set default options + if (isUndefined(ctx.showHidden)) ctx.showHidden = false; + if (isUndefined(ctx.depth)) ctx.depth = 2; + if (isUndefined(ctx.colors)) ctx.colors = false; + if (isUndefined(ctx.customInspect)) ctx.customInspect = true; + if (ctx.colors) ctx.stylize = stylizeWithColor; + return formatValue(ctx, obj, ctx.depth); +} +exports.inspect = inspect; + + +// http://en.wikipedia.org/wiki/ANSI_escape_code#graphics +inspect.colors = { + 'bold' : [1, 22], + 'italic' : [3, 23], + 'underline' : [4, 24], + 'inverse' : [7, 27], + 'white' : [37, 39], + 'grey' : [90, 39], + 'black' : [30, 39], + 'blue' : [34, 39], + 'cyan' : [36, 39], + 'green' : [32, 39], + 'magenta' : [35, 39], + 'red' : [31, 39], + 'yellow' : [33, 39] +}; + +// Don't use 'blue' not visible on cmd.exe +inspect.styles = { + 'special': 'cyan', + 'number': 'yellow', + 'boolean': 'yellow', + 'undefined': 'grey', + 'null': 'bold', + 'string': 'green', + 'date': 'magenta', + // "name": intentionally not styling + 'regexp': 'red' +}; + + +function stylizeWithColor(str, styleType) { + var style = inspect.styles[styleType]; + + if (style) { + return '\u001b[' + inspect.colors[style][0] + 'm' + str + + '\u001b[' + inspect.colors[style][1] + 'm'; + } else { + return str; + } +} + + +function stylizeNoColor(str, styleType) { + return str; +} + + +function arrayToHash(array) { + var hash = {}; + + array.forEach(function(val, idx) { + hash[val] = true; + }); + + return hash; +} + + +function formatValue(ctx, value, recurseTimes) { + // Provide a hook for user-specified inspect functions. + // Check that value is an object with an inspect function on it + if (ctx.customInspect && + value && + isFunction(value.inspect) && + // Filter out the util module, it's inspect function is special + value.inspect !== exports.inspect && + // Also filter out any prototype objects using the circular check. + !(value.constructor && value.constructor.prototype === value)) { + var ret = value.inspect(recurseTimes, ctx); + if (!isString(ret)) { + ret = formatValue(ctx, ret, recurseTimes); + } + return ret; + } + + // Primitive types cannot have properties + var primitive = formatPrimitive(ctx, value); + if (primitive) { + return primitive; + } + + // Look up the keys of the object. + var keys = Object.keys(value); + var visibleKeys = arrayToHash(keys); + + if (ctx.showHidden) { + keys = Object.getOwnPropertyNames(value); + } + + // IE doesn't make error fields non-enumerable + // http://msdn.microsoft.com/en-us/library/ie/dww52sbt(v=vs.94).aspx + if (isError(value) + && (keys.indexOf('message') >= 0 || keys.indexOf('description') >= 0)) { + return formatError(value); + } + + // Some type of object without properties can be shortcutted. + if (keys.length === 0) { + if (isFunction(value)) { + var name = value.name ? ': ' + value.name : ''; + return ctx.stylize('[Function' + name + ']', 'special'); + } + if (isRegExp(value)) { + return ctx.stylize(RegExp.prototype.toString.call(value), 'regexp'); + } + if (isDate(value)) { + return ctx.stylize(Date.prototype.toString.call(value), 'date'); + } + if (isError(value)) { + return formatError(value); + } + } + + var base = '', array = false, braces = ['{', '}']; + + // Make Array say that they are Array + if (isArray(value)) { + array = true; + braces = ['[', ']']; + } + + // Make functions say that they are functions + if (isFunction(value)) { + var n = value.name ? ': ' + value.name : ''; + base = ' [Function' + n + ']'; + } + + // Make RegExps say that they are RegExps + if (isRegExp(value)) { + base = ' ' + RegExp.prototype.toString.call(value); + } + + // Make dates with properties first say the date + if (isDate(value)) { + base = ' ' + Date.prototype.toUTCString.call(value); + } + + // Make error with message first say the error + if (isError(value)) { + base = ' ' + formatError(value); + } + + if (keys.length === 0 && (!array || value.length == 0)) { + return braces[0] + base + braces[1]; + } + + if (recurseTimes < 0) { + if (isRegExp(value)) { + return ctx.stylize(RegExp.prototype.toString.call(value), 'regexp'); + } else { + return ctx.stylize('[Object]', 'special'); + } + } + + ctx.seen.push(value); + + var output; + if (array) { + output = formatArray(ctx, value, recurseTimes, visibleKeys, keys); + } else { + output = keys.map(function(key) { + return formatProperty(ctx, value, recurseTimes, visibleKeys, key, array); + }); + } + + ctx.seen.pop(); + + return reduceToSingleString(output, base, braces); +} + + +function formatPrimitive(ctx, value) { + if (isUndefined(value)) + return ctx.stylize('undefined', 'undefined'); + if (isString(value)) { + var simple = '\'' + JSON.stringify(value).replace(/^"|"$/g, '') + .replace(/'/g, "\\'") + .replace(/\\"/g, '"') + '\''; + return ctx.stylize(simple, 'string'); + } + if (isNumber(value)) + return ctx.stylize('' + value, 'number'); + if (isBoolean(value)) + return ctx.stylize('' + value, 'boolean'); + // For some reason typeof null is "object", so special case here. + if (isNull(value)) + return ctx.stylize('null', 'null'); +} + + +function formatError(value) { + return '[' + Error.prototype.toString.call(value) + ']'; +} + + +function formatArray(ctx, value, recurseTimes, visibleKeys, keys) { + var output = []; + for (var i = 0, l = value.length; i < l; ++i) { + if (hasOwnProperty(value, String(i))) { + output.push(formatProperty(ctx, value, recurseTimes, visibleKeys, + String(i), true)); + } else { + output.push(''); + } + } + keys.forEach(function(key) { + if (!key.match(/^\d+$/)) { + output.push(formatProperty(ctx, value, recurseTimes, visibleKeys, + key, true)); + } + }); + return output; +} + + +function formatProperty(ctx, value, recurseTimes, visibleKeys, key, array) { + var name, str, desc; + desc = Object.getOwnPropertyDescriptor(value, key) || { value: value[key] }; + if (desc.get) { + if (desc.set) { + str = ctx.stylize('[Getter/Setter]', 'special'); + } else { + str = ctx.stylize('[Getter]', 'special'); + } + } else { + if (desc.set) { + str = ctx.stylize('[Setter]', 'special'); + } + } + if (!hasOwnProperty(visibleKeys, key)) { + name = '[' + key + ']'; + } + if (!str) { + if (ctx.seen.indexOf(desc.value) < 0) { + if (isNull(recurseTimes)) { + str = formatValue(ctx, desc.value, null); + } else { + str = formatValue(ctx, desc.value, recurseTimes - 1); + } + if (str.indexOf('\n') > -1) { + if (array) { + str = str.split('\n').map(function(line) { + return ' ' + line; + }).join('\n').substr(2); + } else { + str = '\n' + str.split('\n').map(function(line) { + return ' ' + line; + }).join('\n'); + } + } + } else { + str = ctx.stylize('[Circular]', 'special'); + } + } + if (isUndefined(name)) { + if (array && key.match(/^\d+$/)) { + return str; + } + name = JSON.stringify('' + key); + if (name.match(/^"([a-zA-Z_][a-zA-Z_0-9]*)"$/)) { + name = name.substr(1, name.length - 2); + name = ctx.stylize(name, 'name'); + } else { + name = name.replace(/'/g, "\\'") + .replace(/\\"/g, '"') + .replace(/(^"|"$)/g, "'"); + name = ctx.stylize(name, 'string'); + } + } + + return name + ': ' + str; +} + + +function reduceToSingleString(output, base, braces) { + var numLinesEst = 0; + var length = output.reduce(function(prev, cur) { + numLinesEst++; + if (cur.indexOf('\n') >= 0) numLinesEst++; + return prev + cur.replace(/\u001b\[\d\d?m/g, '').length + 1; + }, 0); + + if (length > 60) { + return braces[0] + + (base === '' ? '' : base + '\n ') + + ' ' + + output.join(',\n ') + + ' ' + + braces[1]; + } + + return braces[0] + base + ' ' + output.join(', ') + ' ' + braces[1]; +} + + +// NOTE: These type checking functions intentionally don't use `instanceof` +// because it is fragile and can be easily faked with `Object.create()`. +function isArray(ar) { + return Array.isArray(ar); +} +exports.isArray = isArray; + +function isBoolean(arg) { + return typeof arg === 'boolean'; +} +exports.isBoolean = isBoolean; + +function isNull(arg) { + return arg === null; +} +exports.isNull = isNull; + +function isNullOrUndefined(arg) { + return arg == null; +} +exports.isNullOrUndefined = isNullOrUndefined; + +function isNumber(arg) { + return typeof arg === 'number'; +} +exports.isNumber = isNumber; + +function isString(arg) { + return typeof arg === 'string'; +} +exports.isString = isString; + +function isSymbol(arg) { + return typeof arg === 'symbol'; +} +exports.isSymbol = isSymbol; + +function isUndefined(arg) { + return arg === void 0; +} +exports.isUndefined = isUndefined; + +function isRegExp(re) { + return isObject(re) && objectToString(re) === '[object RegExp]'; +} +exports.isRegExp = isRegExp; + +function isObject(arg) { + return typeof arg === 'object' && arg !== null; +} +exports.isObject = isObject; + +function isDate(d) { + return isObject(d) && objectToString(d) === '[object Date]'; +} +exports.isDate = isDate; + +function isError(e) { + return isObject(e) && + (objectToString(e) === '[object Error]' || e instanceof Error); +} +exports.isError = isError; + +function isFunction(arg) { + return typeof arg === 'function'; +} +exports.isFunction = isFunction; + +function isPrimitive(arg) { + return arg === null || + typeof arg === 'boolean' || + typeof arg === 'number' || + typeof arg === 'string' || + typeof arg === 'symbol' || // ES6 symbol + typeof arg === 'undefined'; +} +exports.isPrimitive = isPrimitive; + +exports.isBuffer = require('./support/isBuffer'); + +function objectToString(o) { + return Object.prototype.toString.call(o); +} + + +function pad(n) { + return n < 10 ? '0' + n.toString(10) : n.toString(10); +} + + +var months = ['Jan', 'Feb', 'Mar', 'Apr', 'May', 'Jun', 'Jul', 'Aug', 'Sep', + 'Oct', 'Nov', 'Dec']; + +// 26 Feb 16:19:34 +function timestamp() { + var d = new Date(); + var time = [pad(d.getHours()), + pad(d.getMinutes()), + pad(d.getSeconds())].join(':'); + return [d.getDate(), months[d.getMonth()], time].join(' '); +} + + +// log is just a thin wrapper to console.log that prepends a timestamp +exports.log = function() { + console.log('%s - %s', timestamp(), exports.format.apply(exports, arguments)); +}; + + +/** + * Inherit the prototype methods from one constructor into another. + * + * The Function.prototype.inherits from lang.js rewritten as a standalone + * function (not on Function.prototype). NOTE: If this file is to be loaded + * during bootstrapping this function needs to be rewritten using some native + * functions as prototype setup using normal JavaScript does not work as + * expected during bootstrapping (see mirror.js in r114903). + * + * @param {function} ctor Constructor function which needs to inherit the + * prototype. + * @param {function} superCtor Constructor function to inherit prototype from. + */ +exports.inherits = require('inherits'); + +exports._extend = function(origin, add) { + // Don't do anything if add isn't an object + if (!add || !isObject(add)) return origin; + + var keys = Object.keys(add); + var i = keys.length; + while (i--) { + origin[keys[i]] = add[keys[i]]; + } + return origin; +}; + +function hasOwnProperty(obj, prop) { + return Object.prototype.hasOwnProperty.call(obj, prop); +} + +}).call(this,require('_process'),typeof global !== "undefined" ? global : typeof self !== "undefined" ? self : typeof window !== "undefined" ? window : {}) +},{"./support/isBuffer":74,"_process":58,"inherits":53}]},{},[1]); diff --git a/test/vendor/primus.min.js b/test/vendor/primus.min.js new file mode 100644 index 0000000..c03bb01 --- /dev/null +++ b/test/vendor/primus.min.js @@ -0,0 +1 @@ +!function(e,t,n,r){t[e]=n.call(t);for(var o=0;o1e4||!(n=r.exec(e)))return 0;switch(t=parseFloat(n[1]),n[2].toLowerCase()){case"years":case"year":case"yrs":case"yr":case"y":return t*u;case"weeks":case"week":case"wks":case"wk":case"w":return t*a;case"days":case"day":case"d":return t*c;case"hours":case"hour":case"hrs":case"hr":case"h":return t*s;case"minutes":case"minute":case"mins":case"min":case"m":return t*i;case"seconds":case"second":case"secs":case"sec":case"s":return t*o;default:return t}}},{}],6:[function(e,t,n){"use strict";t.exports=function(e){function t(){return r?n:(r=1,n=e.apply(this,arguments),e=null,n)}var n,r=0;return t.displayName=e.displayName||e.name||t.displayName||t.name,t}},{}],7:[function(e,t,n){"use strict";function r(e){for(var t,n=/([^=?&]+)=?([^&]*)/g,r={};t=n.exec(e);r[decodeURIComponent(t[1])]=decodeURIComponent(t[2]));return r}function o(e,t){t=t||"";var n=[];"string"!=typeof t&&(t="?");for(var r in e)i.call(e,r)&&n.push(encodeURIComponent(r)+"="+encodeURIComponent(e[r]));return n.length?t+n.join("&"):""}var i=Object.prototype.hasOwnProperty;n.stringify=o,n.parse=r},{}],8:[function(e,t,n){"use strict";function r(e,t,n){return s(e in n?n[e]:e in t?t[e]:o[e])}function o(e){var t=this;return t instanceof o?(e=e||{},t.attempt=null,t._fn=null,t["reconnect timeout"]=r("reconnect timeout",t,e),t.retries=r("retries",t,e),t.factor=r("factor",t,e),t.max=r("max",t,e),t.min=r("min",t,e),void(t.timers=new a(t))):new o(e)}var i=e("eventemitter3"),s=e("millisecond"),c=e("demolish"),a=e("tick-tock"),u=e("one-time");o.prototype=new i,o.prototype.constructor=o,o["reconnect timeout"]="30 seconds",o.max=1/0,o.min="500 ms",o.retries=10,o.factor=2,o.prototype.reconnect=function(){var e=this;return e.backoff(function(t,n){return n.duration=+new Date-n.start,t?e.emit("reconnect failed",t,n):void e.emit("reconnected",n)},e.attempt)},o.prototype.backoff=function(e,t){var n=this;return t=t||n.attempt||{},t.backoff?n:(t["reconnect timeout"]=r("reconnect timeout",n,t),t.retries=r("retries",n,t),t.factor=r("factor",n,t),t.max=r("max",n,t),t.min=r("min",n,t),t.start=+t.start||+new Date,t.duration=+t.duration||0,t.attempt=+t.attempt||0,t.attempt===t.retries?(e.call(n,new Error("Unable to recover"),t),n):(t.backoff=!0,t.attempt++,n.attempt=t,t.scheduled=1!==t.attempt?Math.min(Math.round((Math.random()+1)*t.min*Math.pow(t.factor,t.attempt-1)),t.max):t.min,n.timers.setTimeout("reconnect",function(){t.duration=+new Date-t.start,t.backoff=!1,n.timers.clear("reconnect, timeout");var r=n._fn=u(function(r){return n.reset(),r?n.backoff(e,t):void e.call(n,void 0,t)});n.emit("reconnect",t,r),n.timers.setTimeout("timeout",function(){var e=new Error("Failed to reconnect in a timely manner");t.duration=+new Date-t.start,n.emit("reconnect timeout",e,t),r(e)},t["reconnect timeout"])},t.scheduled),n.emit("reconnect scheduled",t),n))},o.prototype.reconnecting=function(){return!!this.attempt},o.prototype.reconnected=function(e){return this._fn&&this._fn(e),this},o.prototype.reset=function(){return this._fn=this.attempt=null,this.timers.clear("reconnect, timeout"),this},o.prototype.destroy=c("timers attempt _fn"),t.exports=o},{demolish:1,eventemitter3:9,millisecond:5,"one-time":6,"tick-tock":11}],9:[function(e,t,n){"use strict";function r(e,t,n){this.fn=e,this.context=t,this.once=n||!1}function o(){}var i="function"!=typeof Object.create&&"~";o.prototype._events=void 0,o.prototype.listeners=function(e,t){var n=i?i+e:e,r=this._events&&this._events[n];if(t)return!!r;if(!r)return[];if(r.fn)return[r.fn];for(var o=0,s=r.length,c=new Array(s);o0);return t}function o(e){var t=0;for(p=0;p