target
stringlengths
5
300
feat_repo_name
stringlengths
6
76
text
stringlengths
26
1.05M
client/components/Comments.js
yinkyo/react-redux-learning
import React from 'react'; const Comment = (comment) => ( <div className="comment"> <p> <strong>{comment.user}</strong> {comment.text} <button className="remove-comment">&times;</button> </p> </div> ) const Comments = ({comments}) => ( <div className="comment"> {comments.map( (comment, i) => <Comment {...comment} key={i} i={i} /> )} </div> ) export default Comments;
fixtures/nesting/src/shared/ThemeContext.js
ArunTesco/react
import {createContext} from 'react'; const ThemeContext = createContext(null); export default ThemeContext;
ajax/libs/es6-shim/0.26.0/es6-shim.js
JacquesMarais/cdnjs
/*! * https://github.com/paulmillr/es6-shim * @license es6-shim Copyright 2013-2015 by Paul Miller (http://paulmillr.com) * and contributors, MIT License * es6-shim: v0.26.0 * see https://github.com/paulmillr/es6-shim/blob/0.26.0/LICENSE * Details and documentation: * https://github.com/paulmillr/es6-shim/ */ // UMD (Universal Module Definition) // see https://github.com/umdjs/umd/blob/master/returnExports.js (function (root, factory) { /*global define, module, exports */ if (typeof define === 'function' && define.amd) { // AMD. Register as an anonymous module. define(factory); } else if (typeof exports === 'object') { // Node. Does not work with strict CommonJS, but // only CommonJS-like enviroments that support module.exports, // like Node. module.exports = factory(); } else { // Browser globals (root is window) root.returnExports = factory(); } }(this, function () { 'use strict'; var isCallableWithoutNew = function (func) { try { func(); } catch (e) { return false; } return true; }; var supportsSubclassing = function (C, f) { /* jshint proto:true */ try { var Sub = function () { C.apply(this, arguments); }; if (!Sub.__proto__) { return false; /* skip test on IE < 11 */ } Object.setPrototypeOf(Sub, C); Sub.prototype = Object.create(C.prototype, { constructor: { value: C } }); return f(Sub); } catch (e) { return false; } }; var arePropertyDescriptorsSupported = function () { try { Object.defineProperty({}, 'x', {}); return true; } catch (e) { /* this is IE 8. */ return false; } }; var startsWithRejectsRegex = function () { var rejectsRegex = false; if (String.prototype.startsWith) { try { '/a/'.startsWith(/a/); } catch (e) { /* this is spec compliant */ rejectsRegex = true; } } return rejectsRegex; }; /*jshint evil: true */ var getGlobal = new Function('return this;'); /*jshint evil: false */ var globals = getGlobal(); var global_isFinite = globals.isFinite; var supportsDescriptors = !!Object.defineProperty && arePropertyDescriptorsSupported(); var startsWithIsCompliant = startsWithRejectsRegex(); var _indexOf = Function.call.bind(String.prototype.indexOf); var _toString = Function.call.bind(Object.prototype.toString); var _hasOwnProperty = Function.call.bind(Object.prototype.hasOwnProperty); var ArrayIterator; // make our implementation private var noop = function () {}; var Symbol = globals.Symbol || {}; var symbolSpecies = Symbol.species || '@@species'; var Type = { object: function (x) { return x !== null && typeof x === 'object'; }, string: function (x) { return _toString(x) === '[object String]'; }, regex: function (x) { return _toString(x) === '[object RegExp]'; }, symbol: function (x) { /*jshint notypeof: true */ return typeof globals.Symbol === 'function' && typeof x === 'symbol'; /*jshint notypeof: false */ } }; var defineProperty = function (object, name, value, force) { if (!force && name in object) { return; } if (supportsDescriptors) { Object.defineProperty(object, name, { configurable: true, enumerable: false, writable: true, value: value }); } else { object[name] = value; } }; var Value = { getter: function (object, name, getter) { if (!supportsDescriptors) { throw new TypeError('getters require true ES5 support'); } Object.defineProperty(object, name, { configurable: true, enumerable: false, get: getter }); }, proxy: function (originalObject, key, targetObject) { if (!supportsDescriptors) { throw new TypeError('getters require true ES5 support'); } var originalDescriptor = Object.getOwnPropertyDescriptor(originalObject, key); Object.defineProperty(targetObject, key, { configurable: originalDescriptor.configurable, enumerable: originalDescriptor.enumerable, get: function getKey() { return originalObject[key]; }, set: function setKey(value) { originalObject[key] = value; } }); }, redefine: function (object, property, newValue) { if (supportsDescriptors) { var descriptor = Object.getOwnPropertyDescriptor(object, property); descriptor.value = newValue; Object.defineProperty(object, property, descriptor); } else { object[property] = newValue; } }, preserveToString: function (target, source) { defineProperty(target, 'toString', source.toString.bind(source), true); } }; // Define configurable, writable and non-enumerable props // if they don’t exist. var defineProperties = function (object, map) { Object.keys(map).forEach(function (name) { var method = map[name]; defineProperty(object, name, method, false); }); }; // Simple shim for Object.create on ES3 browsers // (unlike real shim, no attempt to support `prototype === null`) var create = Object.create || function (prototype, properties) { function Prototype() {} Prototype.prototype = prototype; var object = new Prototype(); if (typeof properties !== 'undefined') { defineProperties(object, properties); } return object; }; // This is a private name in the es6 spec, equal to '[Symbol.iterator]' // we're going to use an arbitrary _-prefixed name to make our shims // work properly with each other, even though we don't have full Iterator // support. That is, `Array.from(map.keys())` will work, but we don't // pretend to export a "real" Iterator interface. var $iterator$ = Type.symbol(Symbol.iterator) ? Symbol.iterator : '_es6-shim iterator_'; // Firefox ships a partial implementation using the name @@iterator. // https://bugzilla.mozilla.org/show_bug.cgi?id=907077#c14 // So use that name if we detect it. if (globals.Set && typeof new globals.Set()['@@iterator'] === 'function') { $iterator$ = '@@iterator'; } var addIterator = function (prototype, impl) { if (!impl) { impl = function iterator() { return this; }; } var o = {}; o[$iterator$] = impl; defineProperties(prototype, o); if (!prototype[$iterator$] && Type.symbol($iterator$)) { // implementations are buggy when $iterator$ is a Symbol prototype[$iterator$] = impl; } }; // taken directly from https://github.com/ljharb/is-arguments/blob/master/index.js // can be replaced with require('is-arguments') if we ever use a build process instead var isArguments = function isArguments(value) { var str = _toString(value); var result = str === '[object Arguments]'; if (!result) { result = str !== '[object Array]' && value !== null && typeof value === 'object' && typeof value.length === 'number' && value.length >= 0 && _toString(value.callee) === '[object Function]'; } return result; }; var safeApply = Function.call.bind(Function.apply); var ES = { // https://people.mozilla.org/~jorendorff/es6-draft.html#sec-call-f-v-args Call: function Call(F, V) { var args = arguments.length > 2 ? arguments[2] : []; if (!ES.IsCallable(F)) { throw new TypeError(F + ' is not a function'); } return safeApply(F, V, args); }, RequireObjectCoercible: function (x, optMessage) { /* jshint eqnull:true */ if (x == null) { throw new TypeError(optMessage || 'Cannot call method on ' + x); } }, TypeIsObject: function (x) { /* jshint eqnull:true */ // this is expensive when it returns false; use this function // when you expect it to return true in the common case. return x != null && Object(x) === x; }, ToObject: function (o, optMessage) { ES.RequireObjectCoercible(o, optMessage); return Object(o); }, IsCallable: function (x) { // some versions of IE say that typeof /abc/ === 'function' return typeof x === 'function' && _toString(x) === '[object Function]'; }, ToInt32: function (x) { return ES.ToNumber(x) >> 0; }, ToUint32: function (x) { return ES.ToNumber(x) >>> 0; }, ToNumber: function (value) { if (_toString(value) === '[object Symbol]') { throw new TypeError('Cannot convert a Symbol value to a number'); } return +value; }, ToInteger: function (value) { var number = ES.ToNumber(value); if (Number.isNaN(number)) { return 0; } if (number === 0 || !Number.isFinite(number)) { return number; } return (number > 0 ? 1 : -1) * Math.floor(Math.abs(number)); }, ToLength: function (value) { var len = ES.ToInteger(value); if (len <= 0) { return 0; } // includes converting -0 to +0 if (len > Number.MAX_SAFE_INTEGER) { return Number.MAX_SAFE_INTEGER; } return len; }, SameValue: function (a, b) { if (a === b) { // 0 === -0, but they are not identical. if (a === 0) { return 1 / a === 1 / b; } return true; } return Number.isNaN(a) && Number.isNaN(b); }, SameValueZero: function (a, b) { // same as SameValue except for SameValueZero(+0, -0) == true return (a === b) || (Number.isNaN(a) && Number.isNaN(b)); }, IsIterable: function (o) { return ES.TypeIsObject(o) && (typeof o[$iterator$] !== 'undefined' || isArguments(o)); }, GetIterator: function (o) { if (isArguments(o)) { // special case support for `arguments` return new ArrayIterator(o, 'value'); } var itFn = o[$iterator$]; if (!ES.IsCallable(itFn)) { throw new TypeError('value is not an iterable'); } var it = itFn.call(o); if (!ES.TypeIsObject(it)) { throw new TypeError('bad iterator'); } return it; }, IteratorNext: function (it) { var result = arguments.length > 1 ? it.next(arguments[1]) : it.next(); if (!ES.TypeIsObject(result)) { throw new TypeError('bad iterator'); } return result; }, Construct: function (C, args) { // CreateFromConstructor var obj; if (ES.IsCallable(C[symbolSpecies])) { obj = C[symbolSpecies](); } else { // OrdinaryCreateFromConstructor obj = create(C.prototype || null); } // Mark that we've used the es6 construct path // (see emulateES6construct) defineProperties(obj, { _es6construct: true }); // Call the constructor. var result = ES.Call(C, obj, args); return ES.TypeIsObject(result) ? result : obj; }, CreateHTML: function (string, tag, attribute, value) { var S = String(string); var p1 = '<' + tag; if (attribute !== '') { var V = String(value); var escapedV = V.replace(/"/g, '&quot;'); p1 += ' ' + attribute + '="' + escapedV + '"'; } var p2 = p1 + '>'; var p3 = p2 + S; return p3 + '</' + tag + '>'; } }; var emulateES6construct = function (o) { if (!ES.TypeIsObject(o)) { throw new TypeError('bad object'); } // es5 approximation to es6 subclass semantics: in es6, 'new Foo' // would invoke Foo.@@species to allocation/initialize the new object. // In es5 we just get the plain object. So if we detect an // uninitialized object, invoke o.constructor.@@species if (!o._es6construct) { if (o.constructor && ES.IsCallable(o.constructor[symbolSpecies])) { o = o.constructor[symbolSpecies](o); } defineProperties(o, { _es6construct: true }); } return o; }; var numberConversion = (function () { // from https://github.com/inexorabletash/polyfill/blob/master/typedarray.js#L176-L266 // with permission and license, per https://twitter.com/inexorabletash/status/372206509540659200 function roundToEven(n) { var w = Math.floor(n), f = n - w; if (f < 0.5) { return w; } if (f > 0.5) { return w + 1; } return w % 2 ? w + 1 : w; } function packIEEE754(v, ebits, fbits) { var bias = (1 << (ebits - 1)) - 1, s, e, f, i, bits, str, bytes; // Compute sign, exponent, fraction if (v !== v) { // NaN // http://dev.w3.org/2006/webapi/WebIDL/#es-type-mapping e = (1 << ebits) - 1; f = Math.pow(2, fbits - 1); s = 0; } else if (v === Infinity || v === -Infinity) { e = (1 << ebits) - 1; f = 0; s = (v < 0) ? 1 : 0; } else if (v === 0) { e = 0; f = 0; s = (1 / v === -Infinity) ? 1 : 0; } else { s = v < 0; v = Math.abs(v); if (v >= Math.pow(2, 1 - bias)) { e = Math.min(Math.floor(Math.log(v) / Math.LN2), 1023); f = roundToEven(v / Math.pow(2, e) * Math.pow(2, fbits)); if (f / Math.pow(2, fbits) >= 2) { e = e + 1; f = 1; } if (e > bias) { // Overflow e = (1 << ebits) - 1; f = 0; } else { // Normal e = e + bias; f = f - Math.pow(2, fbits); } } else { // Subnormal e = 0; f = roundToEven(v / Math.pow(2, 1 - bias - fbits)); } } // Pack sign, exponent, fraction bits = []; for (i = fbits; i; i -= 1) { bits.push(f % 2 ? 1 : 0); f = Math.floor(f / 2); } for (i = ebits; i; i -= 1) { bits.push(e % 2 ? 1 : 0); e = Math.floor(e / 2); } bits.push(s ? 1 : 0); bits.reverse(); str = bits.join(''); // Bits to bytes bytes = []; while (str.length) { bytes.push(parseInt(str.slice(0, 8), 2)); str = str.slice(8); } return bytes; } function unpackIEEE754(bytes, ebits, fbits) { // Bytes to bits var bits = [], i, j, b, str, bias, s, e, f; for (i = bytes.length; i; i -= 1) { b = bytes[i - 1]; for (j = 8; j; j -= 1) { bits.push(b % 2 ? 1 : 0); b = b >> 1; } } bits.reverse(); str = bits.join(''); // Unpack sign, exponent, fraction bias = (1 << (ebits - 1)) - 1; s = parseInt(str.slice(0, 1), 2) ? -1 : 1; e = parseInt(str.slice(1, 1 + ebits), 2); f = parseInt(str.slice(1 + ebits), 2); // Produce number if (e === (1 << ebits) - 1) { return f !== 0 ? NaN : s * Infinity; } else if (e > 0) { // Normalized return s * Math.pow(2, e - bias) * (1 + f / Math.pow(2, fbits)); } else if (f !== 0) { // Denormalized return s * Math.pow(2, -(bias - 1)) * (f / Math.pow(2, fbits)); } else { return s < 0 ? -0 : 0; } } function unpackFloat64(b) { return unpackIEEE754(b, 11, 52); } function packFloat64(v) { return packIEEE754(v, 11, 52); } function unpackFloat32(b) { return unpackIEEE754(b, 8, 23); } function packFloat32(v) { return packIEEE754(v, 8, 23); } var conversions = { toFloat32: function (num) { return unpackFloat32(packFloat32(num)); } }; if (typeof Float32Array !== 'undefined') { var float32array = new Float32Array(1); conversions.toFloat32 = function (num) { float32array[0] = num; return float32array[0]; }; } return conversions; }()); defineProperties(String, { fromCodePoint: function fromCodePoint(codePoints) { var result = []; var next; for (var i = 0, length = arguments.length; i < length; i++) { next = Number(arguments[i]); if (!ES.SameValue(next, ES.ToInteger(next)) || next < 0 || next > 0x10FFFF) { throw new RangeError('Invalid code point ' + next); } if (next < 0x10000) { result.push(String.fromCharCode(next)); } else { next -= 0x10000; result.push(String.fromCharCode((next >> 10) + 0xD800)); result.push(String.fromCharCode((next % 0x400) + 0xDC00)); } } return result.join(''); }, raw: function raw(callSite) { var cooked = ES.ToObject(callSite, 'bad callSite'); var rawValue = cooked.raw; var rawString = ES.ToObject(rawValue, 'bad raw value'); var len = rawString.length; var literalsegments = ES.ToLength(len); if (literalsegments <= 0) { return ''; } var stringElements = []; var nextIndex = 0; var nextKey, next, nextSeg, nextSub; while (nextIndex < literalsegments) { nextKey = String(nextIndex); next = rawString[nextKey]; nextSeg = String(next); stringElements.push(nextSeg); if (nextIndex + 1 >= literalsegments) { break; } next = nextIndex + 1 < arguments.length ? arguments[nextIndex + 1] : ''; nextSub = String(next); stringElements.push(nextSub); nextIndex++; } return stringElements.join(''); } }); // Firefox 31 reports this function's length as 0 // https://bugzilla.mozilla.org/show_bug.cgi?id=1062484 if (String.fromCodePoint.length !== 1) { var originalFromCodePoint = Function.apply.bind(String.fromCodePoint); defineProperty(String, 'fromCodePoint', function fromCodePoint(codePoints) { return originalFromCodePoint(this, arguments); }, true); } // Fast repeat, uses the `Exponentiation by squaring` algorithm. // Perf: http://jsperf.com/string-repeat2/2 var stringRepeat = function repeat(s, times) { if (times < 1) { return ''; } if (times % 2) { return repeat(s, times - 1) + s; } var half = repeat(s, times / 2); return half + half; }; var stringMaxLength = Infinity; var StringShims = { repeat: function repeat(times) { ES.RequireObjectCoercible(this); var thisStr = String(this); times = ES.ToInteger(times); if (times < 0 || times >= stringMaxLength) { throw new RangeError('repeat count must be less than infinity and not overflow maximum string size'); } return stringRepeat(thisStr, times); }, startsWith: function (searchStr) { ES.RequireObjectCoercible(this); var thisStr = String(this); if (Type.regex(searchStr)) { throw new TypeError('Cannot call method "startsWith" with a regex'); } searchStr = String(searchStr); var startArg = arguments.length > 1 ? arguments[1] : void 0; var start = Math.max(ES.ToInteger(startArg), 0); return thisStr.slice(start, start + searchStr.length) === searchStr; }, endsWith: function (searchStr) { ES.RequireObjectCoercible(this); var thisStr = String(this); if (Type.regex(searchStr)) { throw new TypeError('Cannot call method "endsWith" with a regex'); } searchStr = String(searchStr); var thisLen = thisStr.length; var posArg = arguments.length > 1 ? arguments[1] : void 0; var pos = typeof posArg === 'undefined' ? thisLen : ES.ToInteger(posArg); var end = Math.min(Math.max(pos, 0), thisLen); return thisStr.slice(end - searchStr.length, end) === searchStr; }, includes: function includes(searchString) { var position = arguments.length > 1 ? arguments[1] : void 0; // Somehow this trick makes method 100% compat with the spec. return _indexOf(this, searchString, position) !== -1; }, codePointAt: function (pos) { ES.RequireObjectCoercible(this); var thisStr = String(this); var position = ES.ToInteger(pos); var length = thisStr.length; if (position >= 0 && position < length) { var first = thisStr.charCodeAt(position); var isEnd = (position + 1 === length); if (first < 0xD800 || first > 0xDBFF || isEnd) { return first; } var second = thisStr.charCodeAt(position + 1); if (second < 0xDC00 || second > 0xDFFF) { return first; } return ((first - 0xD800) * 1024) + (second - 0xDC00) + 0x10000; } } }; defineProperties(String.prototype, StringShims); var hasStringTrimBug = '\u0085'.trim().length !== 1; if (hasStringTrimBug) { delete String.prototype.trim; // whitespace from: http://es5.github.io/#x15.5.4.20 // implementation from https://github.com/es-shims/es5-shim/blob/v3.4.0/es5-shim.js#L1304-L1324 var ws = [ '\x09\x0A\x0B\x0C\x0D\x20\xA0\u1680\u180E\u2000\u2001\u2002\u2003', '\u2004\u2005\u2006\u2007\u2008\u2009\u200A\u202F\u205F\u3000\u2028', '\u2029\uFEFF' ].join(''); var trimRegexp = new RegExp('(^[' + ws + ']+)|([' + ws + ']+$)', 'g'); defineProperties(String.prototype, { trim: function () { if (typeof this === 'undefined' || this === null) { throw new TypeError("can't convert " + this + ' to object'); } return String(this).replace(trimRegexp, ''); } }); } // see https://people.mozilla.org/~jorendorff/es6-draft.html#sec-string.prototype-@@iterator var StringIterator = function (s) { ES.RequireObjectCoercible(s); this._s = String(s); this._i = 0; }; StringIterator.prototype.next = function () { var s = this._s, i = this._i; if (typeof s === 'undefined' || i >= s.length) { this._s = void 0; return { value: void 0, done: true }; } var first = s.charCodeAt(i), second, len; if (first < 0xD800 || first > 0xDBFF || (i + 1) === s.length) { len = 1; } else { second = s.charCodeAt(i + 1); len = (second < 0xDC00 || second > 0xDFFF) ? 1 : 2; } this._i = i + len; return { value: s.substr(i, len), done: false }; }; addIterator(StringIterator.prototype); addIterator(String.prototype, function () { return new StringIterator(this); }); if (!startsWithIsCompliant) { // Firefox has a noncompliant startsWith implementation defineProperty(String.prototype, 'startsWith', StringShims.startsWith, true); defineProperty(String.prototype, 'endsWith', StringShims.endsWith, true); } var ArrayShims = { from: function (iterable) { var mapFn = arguments.length > 1 ? arguments[1] : void 0; var list = ES.ToObject(iterable, 'bad iterable'); if (typeof mapFn !== 'undefined' && !ES.IsCallable(mapFn)) { throw new TypeError('Array.from: when provided, the second argument must be a function'); } var hasThisArg = arguments.length > 2; var thisArg = hasThisArg ? arguments[2] : void 0; var usingIterator = ES.IsIterable(list); // does the spec really mean that Arrays should use ArrayIterator? // https://bugs.ecmascript.org/show_bug.cgi?id=2416 //if (Array.isArray(list)) { usingIterator=false; } var length; var result, i, value; if (usingIterator) { i = 0; result = ES.IsCallable(this) ? Object(new this()) : []; var it = usingIterator ? ES.GetIterator(list) : null; var iterationValue; do { iterationValue = ES.IteratorNext(it); if (!iterationValue.done) { value = iterationValue.value; if (mapFn) { result[i] = hasThisArg ? mapFn.call(thisArg, value, i) : mapFn(value, i); } else { result[i] = value; } i += 1; } } while (!iterationValue.done); length = i; } else { length = ES.ToLength(list.length); result = ES.IsCallable(this) ? Object(new this(length)) : new Array(length); for (i = 0; i < length; ++i) { value = list[i]; if (mapFn) { result[i] = hasThisArg ? mapFn.call(thisArg, value, i) : mapFn(value, i); } else { result[i] = value; } } } result.length = length; return result; }, of: function () { return Array.from(arguments); } }; defineProperties(Array, ArrayShims); var arrayFromSwallowsNegativeLengths = function () { try { return Array.from({ length: -1 }).length === 0; } catch (e) { return false; } }; // Fixes a Firefox bug in v32 // https://bugzilla.mozilla.org/show_bug.cgi?id=1063993 if (!arrayFromSwallowsNegativeLengths()) { defineProperty(Array, 'from', ArrayShims.from, true); } // Given an argument x, it will return an IteratorResult object, // with value set to x and done to false. // Given no arguments, it will return an iterator completion object. var iterator_result = function (x) { return { value: x, done: arguments.length === 0 }; }; // Our ArrayIterator is private; see // https://github.com/paulmillr/es6-shim/issues/252 ArrayIterator = function (array, kind) { this.i = 0; this.array = array; this.kind = kind; }; defineProperties(ArrayIterator.prototype, { next: function () { var i = this.i, array = this.array; if (!(this instanceof ArrayIterator)) { throw new TypeError('Not an ArrayIterator'); } if (typeof array !== 'undefined') { var len = ES.ToLength(array.length); for (; i < len; i++) { var kind = this.kind; var retval; if (kind === 'key') { retval = i; } else if (kind === 'value') { retval = array[i]; } else if (kind === 'entry') { retval = [i, array[i]]; } this.i = i + 1; return { value: retval, done: false }; } } this.array = void 0; return { value: void 0, done: true }; } }); addIterator(ArrayIterator.prototype); var ObjectIterator = function (object, kind) { this.object = object; // Don't generate keys yet. this.array = null; this.kind = kind; }; function getAllKeys(object) { var keys = []; for (var key in object) { keys.push(key); } return keys; } defineProperties(ObjectIterator.prototype, { next: function () { var key, array = this.array; if (!(this instanceof ObjectIterator)) { throw new TypeError('Not an ObjectIterator'); } // Keys not generated if (array === null) { array = this.array = getAllKeys(this.object); } // Find next key in the object while (ES.ToLength(array.length) > 0) { key = array.shift(); // The candidate key isn't defined on object. // Must have been deleted, or object[[Prototype]] // has been modified. if (!(key in this.object)) { continue; } if (this.kind === 'key') { return iterator_result(key); } else if (this.kind === 'value') { return iterator_result(this.object[key]); } else { return iterator_result([key, this.object[key]]); } } return iterator_result(); } }); addIterator(ObjectIterator.prototype); var ArrayPrototypeShims = { copyWithin: function (target, start) { var end = arguments[2]; // copyWithin.length must be 2 var o = ES.ToObject(this); var len = ES.ToLength(o.length); target = ES.ToInteger(target); start = ES.ToInteger(start); var to = target < 0 ? Math.max(len + target, 0) : Math.min(target, len); var from = start < 0 ? Math.max(len + start, 0) : Math.min(start, len); end = typeof end === 'undefined' ? len : ES.ToInteger(end); var fin = end < 0 ? Math.max(len + end, 0) : Math.min(end, len); var count = Math.min(fin - from, len - to); var direction = 1; if (from < to && to < (from + count)) { direction = -1; from += count - 1; to += count - 1; } while (count > 0) { if (_hasOwnProperty(o, from)) { o[to] = o[from]; } else { delete o[from]; } from += direction; to += direction; count -= 1; } return o; }, fill: function (value) { var start = arguments.length > 1 ? arguments[1] : void 0; var end = arguments.length > 2 ? arguments[2] : void 0; var O = ES.ToObject(this); var len = ES.ToLength(O.length); start = ES.ToInteger(typeof start === 'undefined' ? 0 : start); end = ES.ToInteger(typeof end === 'undefined' ? len : end); var relativeStart = start < 0 ? Math.max(len + start, 0) : Math.min(start, len); var relativeEnd = end < 0 ? len + end : end; for (var i = relativeStart; i < len && i < relativeEnd; ++i) { O[i] = value; } return O; }, find: function find(predicate) { var list = ES.ToObject(this); var length = ES.ToLength(list.length); if (!ES.IsCallable(predicate)) { throw new TypeError('Array#find: predicate must be a function'); } var thisArg = arguments.length > 1 ? arguments[1] : null; for (var i = 0, value; i < length; i++) { value = list[i]; if (thisArg) { if (predicate.call(thisArg, value, i, list)) { return value; } } else if (predicate(value, i, list)) { return value; } } }, findIndex: function findIndex(predicate) { var list = ES.ToObject(this); var length = ES.ToLength(list.length); if (!ES.IsCallable(predicate)) { throw new TypeError('Array#findIndex: predicate must be a function'); } var thisArg = arguments.length > 1 ? arguments[1] : null; for (var i = 0; i < length; i++) { if (thisArg) { if (predicate.call(thisArg, list[i], i, list)) { return i; } } else if (predicate(list[i], i, list)) { return i; } } return -1; }, keys: function () { return new ArrayIterator(this, 'key'); }, values: function () { return new ArrayIterator(this, 'value'); }, entries: function () { return new ArrayIterator(this, 'entry'); } }; // Safari 7.1 defines Array#keys and Array#entries natively, // but the resulting ArrayIterator objects don't have a "next" method. if (Array.prototype.keys && !ES.IsCallable([1].keys().next)) { delete Array.prototype.keys; } if (Array.prototype.entries && !ES.IsCallable([1].entries().next)) { delete Array.prototype.entries; } // Chrome 38 defines Array#keys and Array#entries, and Array#@@iterator, but not Array#values if (Array.prototype.keys && Array.prototype.entries && !Array.prototype.values && Array.prototype[$iterator$]) { defineProperties(Array.prototype, { values: Array.prototype[$iterator$] }); if (Type.symbol(Symbol.unscopables)) { Array.prototype[Symbol.unscopables].values = true; } } defineProperties(Array.prototype, ArrayPrototypeShims); addIterator(Array.prototype, function () { return this.values(); }); // Chrome defines keys/values/entries on Array, but doesn't give us // any way to identify its iterator. So add our own shimmed field. if (Object.getPrototypeOf) { addIterator(Object.getPrototypeOf([].values())); } var maxSafeInteger = Math.pow(2, 53) - 1; defineProperties(Number, { MAX_SAFE_INTEGER: maxSafeInteger, MIN_SAFE_INTEGER: -maxSafeInteger, EPSILON: 2.220446049250313e-16, parseInt: globals.parseInt, parseFloat: globals.parseFloat, isFinite: function (value) { return typeof value === 'number' && global_isFinite(value); }, isInteger: function (value) { return Number.isFinite(value) && ES.ToInteger(value) === value; }, isSafeInteger: function (value) { return Number.isInteger(value) && Math.abs(value) <= Number.MAX_SAFE_INTEGER; }, isNaN: function (value) { // NaN !== NaN, but they are identical. // NaNs are the only non-reflexive value, i.e., if x !== x, // then x is NaN. // isNaN is broken: it converts its argument to number, so // isNaN('foo') => true return value !== value; } }); // Work around bugs in Array#find and Array#findIndex -- early // implementations skipped holes in sparse arrays. (Note that the // implementations of find/findIndex indirectly use shimmed // methods of Number, so this test has to happen down here.) /*jshint elision: true */ if (![, 1].find(function (item, idx) { return idx === 0; })) { defineProperty(Array.prototype, 'find', ArrayPrototypeShims.find, true); } if ([, 1].findIndex(function (item, idx) { return idx === 0; }) !== 0) { defineProperty(Array.prototype, 'findIndex', ArrayPrototypeShims.findIndex, true); } /*jshint elision: false */ if (supportsDescriptors) { defineProperties(Object, { // 19.1.3.1 assign: function (target, source) { if (!ES.TypeIsObject(target)) { throw new TypeError('target must be an object'); } return Array.prototype.reduce.call(arguments, function (target, source) { return Object.keys(Object(source)).reduce(function (target, key) { target[key] = source[key]; return target; }, target); }); }, is: function (a, b) { return ES.SameValue(a, b); }, // 19.1.3.9 // shim from https://gist.github.com/WebReflection/5593554 setPrototypeOf: (function (Object, magic) { var set; var checkArgs = function (O, proto) { if (!ES.TypeIsObject(O)) { throw new TypeError('cannot set prototype on a non-object'); } if (!(proto === null || ES.TypeIsObject(proto))) { throw new TypeError('can only set prototype to an object or null' + proto); } }; var setPrototypeOf = function (O, proto) { checkArgs(O, proto); set.call(O, proto); return O; }; try { // this works already in Firefox and Safari set = Object.getOwnPropertyDescriptor(Object.prototype, magic).set; set.call({}, null); } catch (e) { if (Object.prototype !== {}[magic]) { // IE < 11 cannot be shimmed return; } // probably Chrome or some old Mobile stock browser set = function (proto) { this[magic] = proto; }; // please note that this will **not** work // in those browsers that do not inherit // __proto__ by mistake from Object.prototype // in these cases we should probably throw an error // or at least be informed about the issue setPrototypeOf.polyfill = setPrototypeOf( setPrototypeOf({}, null), Object.prototype ) instanceof Object; // setPrototypeOf.polyfill === true means it works as meant // setPrototypeOf.polyfill === false means it's not 100% reliable // setPrototypeOf.polyfill === undefined // or // setPrototypeOf.polyfill == null means it's not a polyfill // which means it works as expected // we can even delete Object.prototype.__proto__; } return setPrototypeOf; }(Object, '__proto__')) }); } // Workaround bug in Opera 12 where setPrototypeOf(x, null) doesn't work, // but Object.create(null) does. if (Object.setPrototypeOf && Object.getPrototypeOf && Object.getPrototypeOf(Object.setPrototypeOf({}, null)) !== null && Object.getPrototypeOf(Object.create(null)) === null) { (function () { var FAKENULL = Object.create(null); var gpo = Object.getPrototypeOf, spo = Object.setPrototypeOf; Object.getPrototypeOf = function (o) { var result = gpo(o); return result === FAKENULL ? null : result; }; Object.setPrototypeOf = function (o, p) { if (p === null) { p = FAKENULL; } return spo(o, p); }; Object.setPrototypeOf.polyfill = false; }()); } var objectKeysAcceptsPrimitives = (function () { try { Object.keys('foo'); return true; } catch (e) { return false; } }()); if (!objectKeysAcceptsPrimitives) { var originalObjectKeys = Object.keys; defineProperty(Object, 'keys', function keys(value) { return originalObjectKeys(ES.ToObject(value)); }, true); Value.preserveToString(Object.keys, originalObjectKeys); } if (Object.getOwnPropertyNames) { var objectGOPNAcceptsPrimitives = (function () { try { Object.getOwnPropertyNames('foo'); return true; } catch (e) { return false; } }()); if (!objectGOPNAcceptsPrimitives) { var originalObjectGetOwnPropertyNames = Object.getOwnPropertyNames; defineProperty(Object, 'getOwnPropertyNames', function getOwnPropertyNames(value) { return originalObjectGetOwnPropertyNames(ES.ToObject(value)); }, true); Value.preserveToString(Object.getOwnPropertyNames, originalObjectGetOwnPropertyNames); } } if (Object.getOwnPropertyDescriptor) { var objectGOPDAcceptsPrimitives = (function () { try { Object.getOwnPropertyDescriptor('foo', 'bar'); return true; } catch (e) { return false; } }()); if (!objectGOPDAcceptsPrimitives) { var originalObjectGetOwnPropertyDescriptor = Object.getOwnPropertyDescriptor; defineProperty(Object, 'getOwnPropertyDescriptor', function getOwnPropertyDescriptor(value, property) { return originalObjectGetOwnPropertyDescriptor(ES.ToObject(value), property); }, true); Value.preserveToString(Object.getOwnPropertyDescriptor, originalObjectGetOwnPropertyDescriptor); } } if (Object.seal) { var objectSealAcceptsPrimitives = (function () { try { Object.seal('foo'); return true; } catch (e) { return false; } }()); if (!objectSealAcceptsPrimitives) { var originalObjectSeal = Object.seal; defineProperty(Object, 'seal', function seal(value) { if (!Type.object(value)) { return value; } return originalObjectSeal(value); }, true); Value.preserveToString(Object.seal, originalObjectSeal); } } if (Object.isSealed) { var objectIsSealedAcceptsPrimitives = (function () { try { Object.isSealed('foo'); return true; } catch (e) { return false; } }()); if (!objectIsSealedAcceptsPrimitives) { var originalObjectIsSealed = Object.isSealed; defineProperty(Object, 'isSealed', function isSealed(value) { if (!Type.object(value)) { return true; } return originalObjectIsSealed(value); }, true); Value.preserveToString(Object.isSealed, originalObjectIsSealed); } } if (Object.freeze) { var objectFreezeAcceptsPrimitives = (function () { try { Object.freeze('foo'); return true; } catch (e) { return false; } }()); if (!objectFreezeAcceptsPrimitives) { var originalObjectFreeze = Object.freeze; defineProperty(Object, 'freeze', function freeze(value) { if (!Type.object(value)) { return value; } return originalObjectFreeze(value); }, true); Value.preserveToString(Object.freeze, originalObjectFreeze); } } if (Object.isFrozen) { var objectIsFrozenAcceptsPrimitives = (function () { try { Object.isFrozen('foo'); return true; } catch (e) { return false; } }()); if (!objectIsFrozenAcceptsPrimitives) { var originalObjectIsFrozen = Object.isFrozen; defineProperty(Object, 'isFrozen', function isFrozen(value) { if (!Type.object(value)) { return true; } return originalObjectIsFrozen(value); }, true); Value.preserveToString(Object.isFrozen, originalObjectIsFrozen); } } if (Object.preventExtensions) { var objectPreventExtensionsAcceptsPrimitives = (function () { try { Object.preventExtensions('foo'); return true; } catch (e) { return false; } }()); if (!objectPreventExtensionsAcceptsPrimitives) { var originalObjectPreventExtensions = Object.preventExtensions; defineProperty(Object, 'preventExtensions', function preventExtensions(value) { if (!Type.object(value)) { return value; } return originalObjectPreventExtensions(value); }, true); Value.preserveToString(Object.preventExtensions, originalObjectPreventExtensions); } } if (Object.isExtensible) { var objectIsExtensibleAcceptsPrimitives = (function () { try { Object.isExtensible('foo'); return true; } catch (e) { return false; } }()); if (!objectIsExtensibleAcceptsPrimitives) { var originalObjectIsExtensible = Object.isExtensible; defineProperty(Object, 'isExtensible', function isExtensible(value) { if (!Type.object(value)) { return false; } return originalObjectIsExtensible(value); }, true); Value.preserveToString(Object.isExtensible, originalObjectIsExtensible); } } if (Object.getPrototypeOf) { var objectGetProtoAcceptsPrimitives = (function () { try { Object.getPrototypeOf('foo'); return true; } catch (e) { return false; } }()); if (!objectGetProtoAcceptsPrimitives) { var originalGetProto = Object.getPrototypeOf; defineProperty(Object, 'getPrototypeOf', function getPrototypeOf(value) { return originalGetProto(ES.ToObject(value)); }, true); Value.preserveToString(Object.getPrototypeOf, originalGetProto); } } if (!RegExp.prototype.flags && supportsDescriptors) { var regExpFlagsGetter = function flags() { if (!ES.TypeIsObject(this)) { throw new TypeError('Method called on incompatible type: must be an object.'); } var result = ''; if (this.global) { result += 'g'; } if (this.ignoreCase) { result += 'i'; } if (this.multiline) { result += 'm'; } if (this.unicode) { result += 'u'; } if (this.sticky) { result += 'y'; } return result; }; Value.getter(RegExp.prototype, 'flags', regExpFlagsGetter); } var regExpSupportsFlagsWithRegex = (function () { try { return String(new RegExp(/a/g, 'i')) === '/a/i'; } catch (e) { return false; } }()); if (!regExpSupportsFlagsWithRegex && supportsDescriptors) { var OrigRegExp = RegExp; var RegExpShim = function RegExp(pattern, flags) { if (Type.regex(pattern) && Type.string(flags)) { return new RegExp(pattern.source, flags); } return new OrigRegExp(pattern, flags); }; Value.preserveToString(RegExpShim, OrigRegExp); if (Object.setPrototypeOf) { // sets up proper prototype chain where possible Object.setPrototypeOf(OrigRegExp, RegExpShim); } Object.getOwnPropertyNames(OrigRegExp).forEach(function (key) { if (key === '$input') { return; } // Chrome < v39 & Opera < 26 have a nonstandard "$input" property if (key in noop) { return; } Value.proxy(OrigRegExp, key, RegExpShim); }); RegExpShim.prototype = OrigRegExp.prototype; Value.redefine(OrigRegExp.prototype, 'constructor', RegExpShim); /*globals RegExp: true */ RegExp = RegExpShim; Value.redefine(globals, 'RegExp', RegExpShim); /*globals RegExp: false */ } var MathShims = { acosh: function (value) { var x = Number(value); if (Number.isNaN(x) || value < 1) { return NaN; } if (x === 1) { return 0; } if (x === Infinity) { return x; } return Math.log(x / Math.E + Math.sqrt(x + 1) * Math.sqrt(x - 1) / Math.E) + 1; }, asinh: function (value) { value = Number(value); if (value === 0 || !global_isFinite(value)) { return value; } return value < 0 ? -Math.asinh(-value) : Math.log(value + Math.sqrt(value * value + 1)); }, atanh: function (value) { value = Number(value); if (Number.isNaN(value) || value < -1 || value > 1) { return NaN; } if (value === -1) { return -Infinity; } if (value === 1) { return Infinity; } if (value === 0) { return value; } return 0.5 * Math.log((1 + value) / (1 - value)); }, cbrt: function (value) { value = Number(value); if (value === 0) { return value; } var negate = value < 0, result; if (negate) { value = -value; } result = Math.pow(value, 1 / 3); return negate ? -result : result; }, clz32: function (value) { // See https://bugs.ecmascript.org/show_bug.cgi?id=2465 value = Number(value); var number = ES.ToUint32(value); if (number === 0) { return 32; } return 32 - (number).toString(2).length; }, cosh: function (value) { value = Number(value); if (value === 0) { return 1; } // +0 or -0 if (Number.isNaN(value)) { return NaN; } if (!global_isFinite(value)) { return Infinity; } if (value < 0) { value = -value; } if (value > 21) { return Math.exp(value) / 2; } return (Math.exp(value) + Math.exp(-value)) / 2; }, expm1: function (value) { var x = Number(value); if (x === -Infinity) { return -1; } if (!global_isFinite(x) || value === 0) { return x; } if (Math.abs(x) > 0.5) { return Math.exp(x) - 1; } // A more precise approximation using Taylor series expansion // from https://github.com/paulmillr/es6-shim/issues/314#issuecomment-70293986 var t = x; var sum = 0; var n = 1; while (sum + t !== sum) { sum += t; n += 1; t *= x / n; } return sum; }, hypot: function (x, y) { var anyNaN = false; var allZero = true; var anyInfinity = false; var numbers = []; Array.prototype.every.call(arguments, function (arg) { var num = Number(arg); if (Number.isNaN(num)) { anyNaN = true; } else if (num === Infinity || num === -Infinity) { anyInfinity = true; } else if (num !== 0) { allZero = false; } if (anyInfinity) { return false; } else if (!anyNaN) { numbers.push(Math.abs(num)); } return true; }); if (anyInfinity) { return Infinity; } if (anyNaN) { return NaN; } if (allZero) { return 0; } numbers.sort(function (a, b) { return b - a; }); var largest = numbers[0]; var divided = numbers.map(function (number) { return number / largest; }); var sum = divided.reduce(function (sum, number) { return sum + (number * number); }, 0); return largest * Math.sqrt(sum); }, log2: function (value) { return Math.log(value) * Math.LOG2E; }, log10: function (value) { return Math.log(value) * Math.LOG10E; }, log1p: function (value) { var x = Number(value); if (x < -1 || Number.isNaN(x)) { return NaN; } if (x === 0 || x === Infinity) { return x; } if (x === -1) { return -Infinity; } return (1 + x) - 1 === 0 ? x : x * (Math.log(1 + x) / ((1 + x) - 1)); }, sign: function (value) { var number = +value; if (number === 0) { return number; } if (Number.isNaN(number)) { return number; } return number < 0 ? -1 : 1; }, sinh: function (value) { var x = Number(value); if (!global_isFinite(value) || value === 0) { return value; } if (Math.abs(x) < 1) { return (Math.expm1(x) - Math.expm1(-x)) / 2; } return (Math.exp(x - 1) - Math.exp(-x - 1)) * Math.E / 2; }, tanh: function (value) { var x = Number(value); if (Number.isNaN(value) || x === 0) { return x; } if (x === Infinity) { return 1; } if (x === -Infinity) { return -1; } var a = Math.expm1(x); var b = Math.expm1(-x); if (a === Infinity) { return 1; } if (b === Infinity) { return -1; } return (a - b) / (Math.exp(x) + Math.exp(-x)); }, trunc: function (value) { var number = Number(value); return number < 0 ? -Math.floor(-number) : Math.floor(number); }, imul: function (x, y) { // taken from https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Math/imul x = ES.ToUint32(x); y = ES.ToUint32(y); var ah = (x >>> 16) & 0xffff; var al = x & 0xffff; var bh = (y >>> 16) & 0xffff; var bl = y & 0xffff; // the shift by 0 fixes the sign on the high part // the final |0 converts the unsigned value into a signed value return ((al * bl) + (((ah * bl + al * bh) << 16) >>> 0) | 0); }, fround: function (x) { if (x === 0 || x === Infinity || x === -Infinity || Number.isNaN(x)) { return x; } var num = Number(x); return numberConversion.toFloat32(num); } }; defineProperties(Math, MathShims); // Chrome 40 has an imprecise Math.tanh with very small numbers defineProperty(Math, 'tanh', MathShims.tanh, Math.tanh(-2e-17) !== -2e-17); // Chrome 40 loses Math.acosh precision with high numbers defineProperty(Math, 'acosh', MathShims.acosh, Math.acosh(Number.MAX_VALUE) === Infinity); // node 0.11 has an imprecise Math.sinh with very small numbers defineProperty(Math, 'sinh', MathShims.sinh, Math.sinh(-2e-17) !== -2e-17); // FF 35 on Linux reports 22025.465794806725 for Math.expm1(10) var expm1OfTen = Math.expm1(10); defineProperty(Math, 'expm1', MathShims.expm1, expm1OfTen > 22025.465794806719 || expm1OfTen < 22025.4657948067165168); var roundHandlesBoundaryConditions = Math.round(0.5 - Number.EPSILON / 4) === 0 && Math.round(-0.5 + Number.EPSILON / 3.99) === 1; var origMathRound = Math.round; defineProperty(Math, 'round', function round(x) { if (-0.5 <= x && x < 0.5 && x !== 0) { return Math.sign(x * 0); } return origMathRound(x); }, !roundHandlesBoundaryConditions); if (Math.imul(0xffffffff, 5) !== -5) { // Safari 6.1, at least, reports "0" for this value Math.imul = MathShims.imul; } // Promises // Simplest possible implementation; use a 3rd-party library if you // want the best possible speed and/or long stack traces. var PromiseShim = (function () { var Promise, Promise$prototype; ES.IsPromise = function (promise) { if (!ES.TypeIsObject(promise)) { return false; } if (!promise._promiseConstructor) { // _promiseConstructor is a bit more unique than _status, so we'll // check that instead of the [[PromiseStatus]] internal field. return false; } if (typeof promise._status === 'undefined') { return false; // uninitialized } return true; }; // "PromiseCapability" in the spec is what most promise implementations // call a "deferred". var PromiseCapability = function (C) { if (!ES.IsCallable(C)) { throw new TypeError('bad promise constructor'); } var capability = this; var resolver = function (resolve, reject) { capability.resolve = resolve; capability.reject = reject; }; capability.promise = ES.Construct(C, [resolver]); // see https://bugs.ecmascript.org/show_bug.cgi?id=2478 if (!capability.promise._es6construct) { throw new TypeError('bad promise constructor'); } if (!(ES.IsCallable(capability.resolve) && ES.IsCallable(capability.reject))) { throw new TypeError('bad promise constructor'); } }; // find an appropriate setImmediate-alike var setTimeout = globals.setTimeout; var makeZeroTimeout; /*global window */ if (typeof window !== 'undefined' && ES.IsCallable(window.postMessage)) { makeZeroTimeout = function () { // from http://dbaron.org/log/20100309-faster-timeouts var timeouts = []; var messageName = 'zero-timeout-message'; var setZeroTimeout = function (fn) { timeouts.push(fn); window.postMessage(messageName, '*'); }; var handleMessage = function (event) { if (event.source === window && event.data === messageName) { event.stopPropagation(); if (timeouts.length === 0) { return; } var fn = timeouts.shift(); fn(); } }; window.addEventListener('message', handleMessage, true); return setZeroTimeout; }; } var makePromiseAsap = function () { // An efficient task-scheduler based on a pre-existing Promise // implementation, which we can use even if we override the // global Promise below (in order to workaround bugs) // https://github.com/Raynos/observ-hash/issues/2#issuecomment-35857671 var P = globals.Promise; return P && P.resolve && function (task) { return P.resolve().then(task); }; }; /*global process */ var enqueue = ES.IsCallable(globals.setImmediate) ? globals.setImmediate.bind(globals) : typeof process === 'object' && process.nextTick ? process.nextTick : makePromiseAsap() || (ES.IsCallable(makeZeroTimeout) ? makeZeroTimeout() : function (task) { setTimeout(task, 0); }); // fallback var updatePromiseFromPotentialThenable = function (x, capability) { if (!ES.TypeIsObject(x)) { return false; } var resolve = capability.resolve; var reject = capability.reject; try { var then = x.then; // only one invocation of accessor if (!ES.IsCallable(then)) { return false; } then.call(x, resolve, reject); } catch (e) { reject(e); } return true; }; var triggerPromiseReactions = function (reactions, x) { reactions.forEach(function (reaction) { enqueue(function () { // PromiseReactionTask var handler = reaction.handler; var capability = reaction.capability; var resolve = capability.resolve; var reject = capability.reject; try { var result = handler(x); if (result === capability.promise) { throw new TypeError('self resolution'); } var updateResult = updatePromiseFromPotentialThenable(result, capability); if (!updateResult) { resolve(result); } } catch (e) { reject(e); } }); }); }; var promiseResolutionHandler = function (promise, onFulfilled, onRejected) { return function (x) { if (x === promise) { return onRejected(new TypeError('self resolution')); } var C = promise._promiseConstructor; var capability = new PromiseCapability(C); var updateResult = updatePromiseFromPotentialThenable(x, capability); if (updateResult) { return capability.promise.then(onFulfilled, onRejected); } else { return onFulfilled(x); } }; }; Promise = function (resolver) { var promise = this; promise = emulateES6construct(promise); if (!promise._promiseConstructor) { // we use _promiseConstructor as a stand-in for the internal // [[PromiseStatus]] field; it's a little more unique. throw new TypeError('bad promise'); } if (typeof promise._status !== 'undefined') { throw new TypeError('promise already initialized'); } // see https://bugs.ecmascript.org/show_bug.cgi?id=2482 if (!ES.IsCallable(resolver)) { throw new TypeError('not a valid resolver'); } promise._status = 'unresolved'; promise._resolveReactions = []; promise._rejectReactions = []; var resolve = function (resolution) { if (promise._status !== 'unresolved') { return; } var reactions = promise._resolveReactions; promise._result = resolution; promise._resolveReactions = void 0; promise._rejectReactions = void 0; promise._status = 'has-resolution'; triggerPromiseReactions(reactions, resolution); }; var reject = function (reason) { if (promise._status !== 'unresolved') { return; } var reactions = promise._rejectReactions; promise._result = reason; promise._resolveReactions = void 0; promise._rejectReactions = void 0; promise._status = 'has-rejection'; triggerPromiseReactions(reactions, reason); }; try { resolver(resolve, reject); } catch (e) { reject(e); } return promise; }; Promise$prototype = Promise.prototype; var _promiseAllResolver = function (index, values, capability, remaining) { var done = false; return function (x) { if (done) { return; } // protect against being called multiple times done = true; values[index] = x; if ((--remaining.count) === 0) { var resolve = capability.resolve; resolve(values); // call w/ this===undefined } }; }; defineProperty(Promise, symbolSpecies, function (obj) { var constructor = this; // AllocatePromise // The `obj` parameter is a hack we use for es5 // compatibility. var prototype = constructor.prototype || Promise$prototype; obj = obj || create(prototype); defineProperties(obj, { _status: void 0, _result: void 0, _resolveReactions: void 0, _rejectReactions: void 0, _promiseConstructor: void 0 }); obj._promiseConstructor = constructor; return obj; }); defineProperties(Promise, { all: function all(iterable) { var C = this; var capability = new PromiseCapability(C); var resolve = capability.resolve; var reject = capability.reject; try { if (!ES.IsIterable(iterable)) { throw new TypeError('bad iterable'); } var it = ES.GetIterator(iterable); var values = [], remaining = { count: 1 }; for (var index = 0; ; index++) { var next = ES.IteratorNext(it); if (next.done) { break; } var nextPromise = C.resolve(next.value); var resolveElement = _promiseAllResolver( index, values, capability, remaining ); remaining.count++; nextPromise.then(resolveElement, capability.reject); } if ((--remaining.count) === 0) { resolve(values); // call w/ this===undefined } } catch (e) { reject(e); } return capability.promise; }, race: function race(iterable) { var C = this; var capability = new PromiseCapability(C); var resolve = capability.resolve; var reject = capability.reject; try { if (!ES.IsIterable(iterable)) { throw new TypeError('bad iterable'); } var it = ES.GetIterator(iterable); while (true) { var next = ES.IteratorNext(it); if (next.done) { // If iterable has no items, resulting promise will never // resolve; see: // https://github.com/domenic/promises-unwrapping/issues/75 // https://bugs.ecmascript.org/show_bug.cgi?id=2515 break; } var nextPromise = C.resolve(next.value); nextPromise.then(resolve, reject); } } catch (e) { reject(e); } return capability.promise; }, reject: function reject(reason) { var C = this; var capability = new PromiseCapability(C); var rejectPromise = capability.reject; rejectPromise(reason); // call with this===undefined return capability.promise; }, resolve: function resolve(v) { var C = this; if (ES.IsPromise(v)) { var constructor = v._promiseConstructor; if (constructor === C) { return v; } } var capability = new PromiseCapability(C); var resolvePromise = capability.resolve; resolvePromise(v); // call with this===undefined return capability.promise; } }); defineProperties(Promise$prototype, { 'catch': function (onRejected) { return this.then(void 0, onRejected); }, then: function then(onFulfilled, onRejected) { var promise = this; if (!ES.IsPromise(promise)) { throw new TypeError('not a promise'); } // this.constructor not this._promiseConstructor; see // https://bugs.ecmascript.org/show_bug.cgi?id=2513 var C = this.constructor; var capability = new PromiseCapability(C); if (!ES.IsCallable(onRejected)) { onRejected = function (e) { throw e; }; } if (!ES.IsCallable(onFulfilled)) { onFulfilled = function (x) { return x; }; } var resolutionHandler = promiseResolutionHandler(promise, onFulfilled, onRejected); var resolveReaction = { capability: capability, handler: resolutionHandler }; var rejectReaction = { capability: capability, handler: onRejected }; switch (promise._status) { case 'unresolved': promise._resolveReactions.push(resolveReaction); promise._rejectReactions.push(rejectReaction); break; case 'has-resolution': triggerPromiseReactions([resolveReaction], promise._result); break; case 'has-rejection': triggerPromiseReactions([rejectReaction], promise._result); break; default: throw new TypeError('unexpected'); } return capability.promise; } }); return Promise; }()); // Chrome's native Promise has extra methods that it shouldn't have. Let's remove them. if (globals.Promise) { delete globals.Promise.accept; delete globals.Promise.defer; delete globals.Promise.prototype.chain; } // export the Promise constructor. defineProperties(globals, { Promise: PromiseShim }); // In Chrome 33 (and thereabouts) Promise is defined, but the // implementation is buggy in a number of ways. Let's check subclassing // support to see if we have a buggy implementation. var promiseSupportsSubclassing = supportsSubclassing(globals.Promise, function (S) { return S.resolve(42) instanceof S; }); var promiseIgnoresNonFunctionThenCallbacks = (function () { try { globals.Promise.reject(42).then(null, 5).then(null, noop); return true; } catch (ex) { return false; } }()); var promiseRequiresObjectContext = (function () { /*global Promise */ try { Promise.call(3, noop); } catch (e) { return true; } return false; }()); if (!promiseSupportsSubclassing || !promiseIgnoresNonFunctionThenCallbacks || !promiseRequiresObjectContext) { /*globals Promise: true */ Promise = PromiseShim; /*globals Promise: false */ defineProperty(globals, 'Promise', PromiseShim, true); } // Map and Set require a true ES5 environment // Their fast path also requires that the environment preserve // property insertion order, which is not guaranteed by the spec. var testOrder = function (a) { var b = Object.keys(a.reduce(function (o, k) { o[k] = true; return o; }, {})); return a.join(':') === b.join(':'); }; var preservesInsertionOrder = testOrder(['z', 'a', 'bb']); // some engines (eg, Chrome) only preserve insertion order for string keys var preservesNumericInsertionOrder = testOrder(['z', 1, 'a', '3', 2]); if (supportsDescriptors) { var fastkey = function fastkey(key) { if (!preservesInsertionOrder) { return null; } var type = typeof key; if (type === 'string') { return '$' + key; } else if (type === 'number') { // note that -0 will get coerced to "0" when used as a property key if (!preservesNumericInsertionOrder) { return 'n' + key; } return key; } return null; }; var emptyObject = function emptyObject() { // accomodate some older not-quite-ES5 browsers return Object.create ? Object.create(null) : {}; }; var collectionShims = { Map: (function () { var empty = {}; function MapEntry(key, value) { this.key = key; this.value = value; this.next = null; this.prev = null; } MapEntry.prototype.isRemoved = function () { return this.key === empty; }; function MapIterator(map, kind) { this.head = map._head; this.i = this.head; this.kind = kind; } MapIterator.prototype = { next: function () { var i = this.i, kind = this.kind, head = this.head, result; if (typeof this.i === 'undefined') { return { value: void 0, done: true }; } while (i.isRemoved() && i !== head) { // back up off of removed entries i = i.prev; } // advance to next unreturned element. while (i.next !== head) { i = i.next; if (!i.isRemoved()) { if (kind === 'key') { result = i.key; } else if (kind === 'value') { result = i.value; } else { result = [i.key, i.value]; } this.i = i; return { value: result, done: false }; } } // once the iterator is done, it is done forever. this.i = void 0; return { value: void 0, done: true }; } }; addIterator(MapIterator.prototype); function Map(iterable) { var map = this; if (!ES.TypeIsObject(map)) { throw new TypeError('Map does not accept arguments when called as a function'); } map = emulateES6construct(map); if (!map._es6map) { throw new TypeError('bad map'); } var head = new MapEntry(null, null); // circular doubly-linked list. head.next = head.prev = head; defineProperties(map, { _head: head, _storage: emptyObject(), _size: 0 }); // Optionally initialize map from iterable if (typeof iterable !== 'undefined' && iterable !== null) { var it = ES.GetIterator(iterable); var adder = map.set; if (!ES.IsCallable(adder)) { throw new TypeError('bad map'); } while (true) { var next = ES.IteratorNext(it); if (next.done) { break; } var nextItem = next.value; if (!ES.TypeIsObject(nextItem)) { throw new TypeError('expected iterable of pairs'); } adder.call(map, nextItem[0], nextItem[1]); } } return map; } var Map$prototype = Map.prototype; defineProperty(Map, symbolSpecies, function (obj) { var constructor = this; var prototype = constructor.prototype || Map$prototype; obj = obj || create(prototype); defineProperties(obj, { _es6map: true }); return obj; }); Value.getter(Map.prototype, 'size', function () { if (typeof this._size === 'undefined') { throw new TypeError('size method called on incompatible Map'); } return this._size; }); defineProperties(Map.prototype, { get: function (key) { var fkey = fastkey(key); if (fkey !== null) { // fast O(1) path var entry = this._storage[fkey]; if (entry) { return entry.value; } else { return; } } var head = this._head, i = head; while ((i = i.next) !== head) { if (ES.SameValueZero(i.key, key)) { return i.value; } } }, has: function (key) { var fkey = fastkey(key); if (fkey !== null) { // fast O(1) path return typeof this._storage[fkey] !== 'undefined'; } var head = this._head, i = head; while ((i = i.next) !== head) { if (ES.SameValueZero(i.key, key)) { return true; } } return false; }, set: function (key, value) { var head = this._head, i = head, entry; var fkey = fastkey(key); if (fkey !== null) { // fast O(1) path if (typeof this._storage[fkey] !== 'undefined') { this._storage[fkey].value = value; return this; } else { entry = this._storage[fkey] = new MapEntry(key, value); i = head.prev; // fall through } } while ((i = i.next) !== head) { if (ES.SameValueZero(i.key, key)) { i.value = value; return this; } } entry = entry || new MapEntry(key, value); if (ES.SameValue(-0, key)) { entry.key = +0; // coerce -0 to +0 in entry } entry.next = this._head; entry.prev = this._head.prev; entry.prev.next = entry; entry.next.prev = entry; this._size += 1; return this; }, 'delete': function (key) { var head = this._head, i = head; var fkey = fastkey(key); if (fkey !== null) { // fast O(1) path if (typeof this._storage[fkey] === 'undefined') { return false; } i = this._storage[fkey].prev; delete this._storage[fkey]; // fall through } while ((i = i.next) !== head) { if (ES.SameValueZero(i.key, key)) { i.key = i.value = empty; i.prev.next = i.next; i.next.prev = i.prev; this._size -= 1; return true; } } return false; }, clear: function () { this._size = 0; this._storage = emptyObject(); var head = this._head, i = head, p = i.next; while ((i = p) !== head) { i.key = i.value = empty; p = i.next; i.next = i.prev = head; } head.next = head.prev = head; }, keys: function () { return new MapIterator(this, 'key'); }, values: function () { return new MapIterator(this, 'value'); }, entries: function () { return new MapIterator(this, 'key+value'); }, forEach: function (callback) { var context = arguments.length > 1 ? arguments[1] : null; var it = this.entries(); for (var entry = it.next(); !entry.done; entry = it.next()) { if (context) { callback.call(context, entry.value[1], entry.value[0], this); } else { callback(entry.value[1], entry.value[0], this); } } } }); addIterator(Map.prototype, function () { return this.entries(); }); return Map; }()), Set: (function () { // Creating a Map is expensive. To speed up the common case of // Sets containing only string or numeric keys, we use an object // as backing storage and lazily create a full Map only when // required. var SetShim = function Set(iterable) { var set = this; if (!ES.TypeIsObject(set)) { throw new TypeError('Set does not accept arguments when called as a function'); } set = emulateES6construct(set); if (!set._es6set) { throw new TypeError('bad set'); } defineProperties(set, { '[[SetData]]': null, _storage: emptyObject() }); // Optionally initialize map from iterable if (typeof iterable !== 'undefined' && iterable !== null) { var it = ES.GetIterator(iterable); var adder = set.add; if (!ES.IsCallable(adder)) { throw new TypeError('bad set'); } while (true) { var next = ES.IteratorNext(it); if (next.done) { break; } var nextItem = next.value; adder.call(set, nextItem); } } return set; }; var Set$prototype = SetShim.prototype; defineProperty(SetShim, symbolSpecies, function (obj) { var constructor = this; var prototype = constructor.prototype || Set$prototype; obj = obj || create(prototype); defineProperties(obj, { _es6set: true }); return obj; }); // Switch from the object backing storage to a full Map. var ensureMap = function ensureMap(set) { if (!set['[[SetData]]']) { var m = set['[[SetData]]'] = new collectionShims.Map(); Object.keys(set._storage).forEach(function (k) { // fast check for leading '$' if (k.charCodeAt(0) === 36) { k = k.slice(1); } else if (k.charAt(0) === 'n') { k = +k.slice(1); } else { k = +k; } m.set(k, k); }); set._storage = null; // free old backing storage } }; Value.getter(SetShim.prototype, 'size', function () { if (typeof this._storage === 'undefined') { // https://github.com/paulmillr/es6-shim/issues/176 throw new TypeError('size method called on incompatible Set'); } ensureMap(this); return this['[[SetData]]'].size; }); defineProperties(SetShim.prototype, { has: function (key) { var fkey; if (this._storage && (fkey = fastkey(key)) !== null) { return !!this._storage[fkey]; } ensureMap(this); return this['[[SetData]]'].has(key); }, add: function (key) { var fkey; if (this._storage && (fkey = fastkey(key)) !== null) { this._storage[fkey] = true; return this; } ensureMap(this); this['[[SetData]]'].set(key, key); return this; }, 'delete': function (key) { var fkey; if (this._storage && (fkey = fastkey(key)) !== null) { var hasFKey = _hasOwnProperty(this._storage, fkey); return (delete this._storage[fkey]) && hasFKey; } ensureMap(this); return this['[[SetData]]']['delete'](key); }, clear: function () { if (this._storage) { this._storage = emptyObject(); } else { this['[[SetData]]'].clear(); } }, values: function () { ensureMap(this); return this['[[SetData]]'].values(); }, entries: function () { ensureMap(this); return this['[[SetData]]'].entries(); }, forEach: function (callback) { var context = arguments.length > 1 ? arguments[1] : null; var entireSet = this; ensureMap(entireSet); this['[[SetData]]'].forEach(function (value, key) { if (context) { callback.call(context, key, key, entireSet); } else { callback(key, key, entireSet); } }); } }); defineProperty(SetShim, 'keys', SetShim.values, true); addIterator(SetShim.prototype, function () { return this.values(); }); return SetShim; }()) }; defineProperties(globals, collectionShims); if (globals.Map || globals.Set) { /* - In Firefox < 23, Map#size is a function. - In all current Firefox, Set#entries/keys/values & Map#clear do not exist - https://bugzilla.mozilla.org/show_bug.cgi?id=869996 - In Firefox 24, Map and Set do not implement forEach - In Firefox 25 at least, Map and Set are callable without "new" */ if ( typeof globals.Map.prototype.clear !== 'function' || new globals.Set().size !== 0 || new globals.Map().size !== 0 || typeof globals.Map.prototype.keys !== 'function' || typeof globals.Set.prototype.keys !== 'function' || typeof globals.Map.prototype.forEach !== 'function' || typeof globals.Set.prototype.forEach !== 'function' || isCallableWithoutNew(globals.Map) || isCallableWithoutNew(globals.Set) || !supportsSubclassing(globals.Map, function (M) { var m = new M([]); // Firefox 32 is ok with the instantiating the subclass but will // throw when the map is used. m.set(42, 42); return m instanceof M; }) ) { globals.Map = collectionShims.Map; globals.Set = collectionShims.Set; } } if (globals.Set.prototype.keys !== globals.Set.prototype.values) { defineProperty(globals.Set.prototype, 'keys', globals.Set.prototype.values, true); } // Shim incomplete iterator implementations. addIterator(Object.getPrototypeOf((new globals.Map()).keys())); addIterator(Object.getPrototypeOf((new globals.Set()).keys())); } // Reflect if (!globals.Reflect) { defineProperty(globals, 'Reflect', {}); } var Reflect = globals.Reflect; var throwUnlessTargetIsObject = function throwUnlessTargetIsObject(target) { if (!ES.TypeIsObject(target)) { throw new TypeError('target must be an object'); } }; // Some Reflect methods are basically the same as // those on the Object global, except that a TypeError is thrown if // target isn't an object. As well as returning a boolean indicating // the success of the operation. defineProperties(globals.Reflect, { // Apply method in a functional form. apply: function apply() { return ES.Call.apply(null, arguments); }, // New operator in a functional form. construct: function construct(constructor, args) { if (!ES.IsCallable(constructor)) { throw new TypeError('First argument must be callable.'); } return ES.Construct(constructor, args); }, // When deleting a non-existent or configurable property, // true is returned. // When attempting to delete a non-configurable property, // it will return false. deleteProperty: function deleteProperty(target, key) { throwUnlessTargetIsObject(target); if (supportsDescriptors) { var desc = Object.getOwnPropertyDescriptor(target, key); if (desc && !desc.configurable) { return false; } } // Will return true. return delete target[key]; }, enumerate: function enumerate(target) { throwUnlessTargetIsObject(target); return new ObjectIterator(target, 'key'); }, has: function has(target, key) { throwUnlessTargetIsObject(target); return key in target; } }); if (Object.getOwnPropertyNames) { defineProperties(globals.Reflect, { // Basically the result of calling the internal [[OwnPropertyKeys]]. // Concatenating propertyNames and propertySymbols should do the trick. // This should continue to work together with a Symbol shim // which overrides Object.getOwnPropertyNames and implements // Object.getOwnPropertySymbols. ownKeys: function ownKeys(target) { throwUnlessTargetIsObject(target); var keys = Object.getOwnPropertyNames(target); if (ES.IsCallable(Object.getOwnPropertySymbols)) { keys.push.apply(keys, Object.getOwnPropertySymbols(target)); } return keys; } }); } if (Object.preventExtensions) { defineProperties(globals.Reflect, { isExtensible: function isExtensible(target) { throwUnlessTargetIsObject(target); return Object.isExtensible(target); }, preventExtensions: function preventExtensions(target) { throwUnlessTargetIsObject(target); return callAndCatchException(function () { Object.preventExtensions(target); }); } }); } if (supportsDescriptors) { var internal_get = function get(target, key, receiver) { var desc = Object.getOwnPropertyDescriptor(target, key); if (!desc) { var parent = Object.getPrototypeOf(target); if (parent === null) { return undefined; } return internal_get(parent, key, receiver); } if ('value' in desc) { return desc.value; } if (desc.get) { return desc.get.call(receiver); } return undefined; }; var internal_set = function set(target, key, value, receiver) { var desc = Object.getOwnPropertyDescriptor(target, key); if (!desc) { var parent = Object.getPrototypeOf(target); if (parent !== null) { return internal_set(parent, key, value, receiver); } desc = { value: void 0, writable: true, enumerable: true, configurable: true }; } if ('value' in desc) { if (!desc.writable) { return false; } if (!ES.TypeIsObject(receiver)) { return false; } var existingDesc = Object.getOwnPropertyDescriptor(receiver, key); if (existingDesc) { return Reflect.defineProperty(receiver, key, { value: value }); } else { return Reflect.defineProperty(receiver, key, { value: value, writable: true, enumerable: true, configurable: true }); } } if (desc.set) { desc.set.call(receiver, value); return true; } return false; }; var callAndCatchException = function ConvertExceptionToBoolean(func) { try { func(); } catch (_) { return false; } return true; }; defineProperties(globals.Reflect, { defineProperty: function defineProperty(target, propertyKey, attributes) { throwUnlessTargetIsObject(target); return callAndCatchException(function () { Object.defineProperty(target, propertyKey, attributes); }); }, getOwnPropertyDescriptor: function getOwnPropertyDescriptor(target, propertyKey) { throwUnlessTargetIsObject(target); return Object.getOwnPropertyDescriptor(target, propertyKey); }, // Syntax in a functional form. get: function get(target, key) { throwUnlessTargetIsObject(target); var receiver = arguments.length > 2 ? arguments[2] : target; return internal_get(target, key, receiver); }, set: function set(target, key, value) { throwUnlessTargetIsObject(target); var receiver = arguments.length > 3 ? arguments[3] : target; return internal_set(target, key, value, receiver); } }); } if (Object.getPrototypeOf) { var objectDotGetPrototypeOf = Object.getPrototypeOf; defineProperties(globals.Reflect, { getPrototypeOf: function getPrototypeOf(target) { throwUnlessTargetIsObject(target); return objectDotGetPrototypeOf(target); } }); } if (Object.setPrototypeOf) { var willCreateCircularPrototype = function (object, proto) { while (proto) { if (object === proto) { return true; } proto = Reflect.getPrototypeOf(proto); } return false; }; defineProperties(globals.Reflect, { // Sets the prototype of the given object. // Returns true on success, otherwise false. setPrototypeOf: function setPrototypeOf(object, proto) { throwUnlessTargetIsObject(object); if (proto !== null && !ES.TypeIsObject(proto)) { throw new TypeError('proto must be an object or null'); } // If they already are the same, we're done. if (proto === Reflect.getPrototypeOf(object)) { return true; } // Cannot alter prototype if object not extensible. if (Reflect.isExtensible && !Reflect.isExtensible(object)) { return false; } // Ensure that we do not create a circular prototype chain. if (willCreateCircularPrototype(object, proto)) { return false; } Object.setPrototypeOf(object, proto); return true; } }); } if (String(new Date(NaN)) !== 'Invalid Date') { var dateToString = Date.prototype.toString; var shimmedDateToString = function toString() { var valueOf = +this; if (valueOf !== valueOf) { return 'Invalid Date'; } return dateToString.call(this); }; defineProperty(shimmedDateToString, 'toString', dateToString.toString, true); defineProperty(Date.prototype, 'toString', shimmedDateToString, true); } // Annex B HTML methods // https://people.mozilla.org/~jorendorff/es6-draft.html#sec-additional-properties-of-the-string.prototype-object var stringHTMLshims = { anchor: function anchor(name) { return ES.CreateHTML(this, 'a', 'name', name); }, big: function big() { return ES.CreateHTML(this, 'big', '', ''); }, blink: function blink() { return ES.CreateHTML(this, 'blink', '', ''); }, bold: function bold() { return ES.CreateHTML(this, 'b', '', ''); }, fixed: function fixed() { return ES.CreateHTML(this, 'tt', '', ''); }, fontcolor: function fontcolor(color) { return ES.CreateHTML(this, 'font', 'color', color); }, fontsize: function fontsize(size) { return ES.CreateHTML(this, 'font', 'size', size); }, italics: function italics() { return ES.CreateHTML(this, 'i', '', ''); }, link: function link(url) { return ES.CreateHTML(this, 'a', 'href', url); }, small: function small() { return ES.CreateHTML(this, 'small', '', ''); }, strike: function strike() { return ES.CreateHTML(this, 'strike', '', ''); }, sub: function sub() { return ES.CreateHTML(this, 'sub', '', ''); }, sup: function sub() { return ES.CreateHTML(this, 'sup', '', ''); } }; defineProperties(String.prototype, stringHTMLshims); Object.keys(stringHTMLshims).forEach(function (key) { var method = String.prototype[key]; var shouldOverwrite = false; if (ES.IsCallable(method)) { var output = method.call('', ' " '); var quotesCount = [].concat(output.match(/"/g)).length; shouldOverwrite = output !== output.toLowerCase() || quotesCount > 2; } else { shouldOverwrite = true; } if (shouldOverwrite) { defineProperty(String.prototype, key, stringHTMLshims[key], true); } }); return globals; }));
index.android.js
vaskort/react-native
import React, { Component } from 'react'; import { AppRegistry, } from 'react-native'; import update from 'immutability-helper'; import App from './src/App'; export default class LocationSaver extends Component { render() { return ( <App /> ); } } AppRegistry.registerComponent('LocationSaver', () => LocationSaver);
src/components/SvgIcon/SvgIcon.js
sk-iv/iva-app
import React from 'react'; import type { Node } from 'react'; import classNames from 'classnames'; if(process.env.WEBPACK) require('./SvgIcon.css'); export type Props = { /** * Elements passed into the SVG Icon. */ children: Node, /** * @ignore */ className?: string, /** * Provides a human-readable title for the element that contains it. * https://www.w3.org/TR/SVG-access/#Equivalent */ titleAccess?: string, /** * Allows you to redefine what the coordinates without units mean inside an svg element. * For example, if the SVG element is 500 (width) by 200 (height), * and you pass viewBox="0 0 50 20", * this means that the coordinates inside the svg will go from the top left corner (0,0) * to bottom right (50,20) and each unit will be worth 10px. */ viewBox?: string, }; function SvgIcon(props: Props) { const { children, className, titleAccess, viewBox, ...other } = props; return ( <svg className={classNames('icon', className)} focusable="false" viewBox={viewBox} aria-hidden={titleAccess ? 'false' : 'true'} {...other} > {titleAccess ? <title>{titleAccess}</title> : null} {children} </svg> ); } SvgIcon.defaultProps = { viewBox: '0 0 24 24', }; SvgIcon.muiName = 'SvgIcon'; export default SvgIcon;
src/index.js
OlehHappy/oleh_008-DnD_React_transhand01
// require('./index.html') import React from 'react' import ReactDOM from 'react-dom' import scatterThings from './prepare' import App from './App' scatterThings() ReactDOM.render(<App/>, document.querySelector('#mount-app'))
src/routes/error/index.js
samdenicola/react-starter-kit
/** * React Starter Kit (https://www.reactstarterkit.com/) * * Copyright © 2014-2016 Kriasoft, LLC. All rights reserved. * * This source code is licensed under the MIT license found in the * LICENSE.txt file in the root directory of this source tree. */ import React from 'react'; import ErrorPage from './ErrorPage'; export default { path: '/error', action({ error }) { return { title: error.name, description: error.message, component: <ErrorPage error={error} />, status: error.status || 500, }; }, };
src/components/HomePage/HomePage.js
vk92kokil/My-react-boilerplate
/** * Created by vikramaditya on 7/29/15. */ import React from 'react'; import Router from 'react-router'; import mui from 'material-ui'; import Reflux from 'reflux'; import AppStore from '../../stores/AppStore'; import Actions from '../../actions/AppActions'; var ThemeManager = new mui.Styles.ThemeManager(); import customTheme from '../../lib/MUI_Theme/custom-theme' var {AppBar} = mui; class HomePage extends React.Component{ constructor(){ super(); } getChildContext() { return { muiTheme: ThemeManager.getCurrentTheme() }; } changePage(){ this.context.router.transitionTo('/anypage'); } handleChange(){ } render(){ ThemeManager.setTheme(customTheme); //comment this and see. return( <div> <AppBar title='Home'/> <h3>HOMEPAGE</h3> <input type = 'text' value = '' onChange = {this.handleChange}/> <button onClick={this.changePage.bind(this)}>Click HERE</button> </div> ) } } HomePage.childContextTypes = { muiTheme: React.PropTypes.object, router: React.PropTypes.func }; HomePage.contextTypes = { router: React.PropTypes.func }; export default HomePage;
resources/assets/admin/components/utilities/Shell.js
DoSomething/northstar
import React from 'react'; const BaseShell = ({ title, subtitle, children }) => ( <div> <header className="header" role="banner"> <div className="wrapper"> <h1 className="header__title">{title}</h1> <p className="header__subtitle">{subtitle}</p> </div> </header> <div className="container"> <div className="wrapper">{children}</div> </div> </div> ); const Shell = ({ title, subtitle, children, error, loading }) => { if (error) { return ( <BaseShell title="Oops!" subtitle="Something went wrong..."> <div className="placeholder flex-center-xy">{error.toString()}</div> </BaseShell> ); } if (loading) { return ( <BaseShell title={title || 'Loading...'} subtitle={subtitle || '...'}> <div className="h-content flex-center-xy"> <div className="spinner" /> </div> </BaseShell> ); } return ( <BaseShell title={title} subtitle={subtitle}> {children} </BaseShell> ); }; export default Shell;
__tests__/components/Select-test.js
codeswan/grommet
// (C) Copyright 2014-2016 Hewlett Packard Enterprise Development LP import React from 'react'; import renderer from 'react/lib/ReactTestRenderer'; import Select from '../../src/js/components/Select'; // needed because this: // https://github.com/facebook/jest/issues/1353 jest.mock('react-dom'); describe('Select', () => { it('has correct default options', () => { const component = renderer.create( <Select id="item1" name="item-1" value="one" /> ); let tree = component.toJSON(); expect(tree).toMatchSnapshot(); }); });
src/js/components/icons/base/PlatformHpi.js
linde12/grommet
// (C) Copyright 2014-2015 Hewlett Packard Enterprise Development LP import React, { Component } from 'react'; import PropTypes from 'prop-types'; import classnames from 'classnames'; import CSSClassnames from '../../../utils/CSSClassnames'; import Intl from '../../../utils/Intl'; import Props from '../../../utils/Props'; const CLASS_ROOT = CSSClassnames.CONTROL_ICON; const COLOR_INDEX = CSSClassnames.COLOR_INDEX; export default class Icon extends Component { render () { const { className, colorIndex } = this.props; let { a11yTitle, size, responsive } = this.props; let { intl } = this.context; const classes = classnames( CLASS_ROOT, `${CLASS_ROOT}-platform-hpi`, className, { [`${CLASS_ROOT}--${size}`]: size, [`${CLASS_ROOT}--responsive`]: responsive, [`${COLOR_INDEX}-${colorIndex}`]: colorIndex } ); a11yTitle = a11yTitle || Intl.getMessage(intl, 'platform-hpi'); const restProps = Props.omit(this.props, Object.keys(Icon.propTypes)); return <svg {...restProps} version="1.1" viewBox="0 0 24 24" width="24px" height="24px" role="img" className={classes} aria-label={a11yTitle}><path fill="#0096D6" fillRule="evenodd" d="M15.7928421,15.3333704 C15.9768442,15.3333704 16.1755131,15.1915021 16.2349804,15.0183002 L18.4310048,8.64836276 C18.4908721,8.47529417 18.3902043,8.33315926 18.2063356,8.33315926 L17.2052578,8.33315926 C17.0219225,8.33315926 16.8228536,8.47529417 16.7629863,8.64836276 L14.5570951,15.0183002 C14.4973611,15.1915021 14.5981622,15.3333704 14.7821642,15.3333704 L15.7928421,15.3333704 Z M24.0002667,12 C24.0002667,18.627007 18.6267403,24 12,24 C11.8170646,24 11.6393293,23.9803998 11.4581273,23.9727997 L13.8777542,16.981922 C13.9382882,16.8085868 14.1365571,16.6668519 14.3205591,16.6668519 L16.0003111,16.6668519 C18.6083401,16.6668519 18.632207,15.8021756 18.9066101,15.0079001 C19.5488839,13.1445461 20.6560962,9.93424371 20.8714319,9.30583673 C21.1779686,8.40956011 21.2793031,7.00007778 19.0002111,7.00007778 L15.0000333,7.00007778 C14.816698,7.00007778 14.6177624,7.14194602 14.5570951,7.31528128 L8.92489917,23.5871954 C3.79030878,22.2271803 0,17.5617951 0,12 C0,6.69394104 3.44790498,2.20055778 8.22275803,0.615473505 L2.77589751,16.3513817 C2.71523017,16.5248503 2.81643129,16.6668519 3.00003333,16.6668519 L4.99965555,16.6668519 C5.1836576,16.6668519 5.38232647,16.5248503 5.44272714,16.3513817 L8.1092901,8.64836276 C8.16915744,8.47529417 8.36755964,8.33315926 8.55102834,8.33315926 L9.539706,8.33315926 C9.72330804,8.33315926 9.82410916,8.47529417 9.76424182,8.64836276 L7.10847898,16.3513817 C7.04914499,16.5248503 7.14994611,16.6668519 7.33328148,16.6668519 L9.33357037,16.6668519 C9.51690574,16.6668519 9.71570795,16.5248503 9.77544195,16.3513817 C9.77544195,16.3513817 11.6389293,10.9485217 12.2016022,9.3149035 C12.7649418,7.68155202 12.3125368,7.00007778 10.3462483,7.00007778 L9.01290014,7.00007778 C8.82956477,7.00007778 8.72889699,6.8580762 8.78916432,6.68514095 L11.0862565,0.0464005156 C11.3887932,0.0234669274 11.6913299,0 12,0 C18.6267403,0 24.0002667,5.37299303 24.0002667,12 L24.0002667,12 Z" stroke="none"/></svg>; } }; Icon.contextTypes = { intl: PropTypes.object }; Icon.defaultProps = { responsive: true }; Icon.displayName = 'PlatformHpi'; Icon.icon = true; Icon.propTypes = { a11yTitle: PropTypes.string, colorIndex: PropTypes.string, size: PropTypes.oneOf(['xsmall', 'small', 'medium', 'large', 'xlarge', 'huge']), responsive: PropTypes.bool };
src/components/Footer/index.js
korabh/quran.com-frontend
import React from 'react'; import Link from 'react-router/lib/Link'; import LocaleFormattedMessage from 'components/LocaleFormattedMessage'; const styles = require('./style.scss'); const Footer = () => ( <footer className={styles.footer}> <div className="container"> <div className="row"> <div className="col-md-10 col-md-offset-1"> <div className="row"> <div className={`${styles.about} col-md-2 col-sm-4 col-xs-12`}> <p className={styles.header}> <LocaleFormattedMessage id="nav.navigate" defaultMessage="Navigate" /> </p> <ul className={`source-sans ${styles.list}`}> <li> <Link to="/about"> <LocaleFormattedMessage id="nav.aboutUs" defaultMessage="About Us" /> </Link> </li> <li> <a href="https://quran.zendesk.com/hc/en-us/requests/new"> <LocaleFormattedMessage id="nav.contactUs" defaultMessage="Contact Us" /> </a> </li> <li> <a href="https://quran.zendesk.com/hc/en-us/articles/210090626-Development-help" target="_blank" rel="noopener noreferrer" data-metrics-event-name="Footer:Link:Developer" > <LocaleFormattedMessage id="nav.developers" defaultMessage="Developers" /> </a> </li> </ul> </div> <div className={`${styles.links} col-md-3 col-sm-4 col-xs-12`}> <p className={styles.header}> <LocaleFormattedMessage id="nav.usefulSites" defaultMessage="USEFUL SITES" /> </p> <ul className={`source-sans ${styles.list}`}> <li> <a target="_blank" rel="noopener noreferrer" href="http://sunnah.com/" data-metrics-event-name="Footer:Link:Sunnah" > Sunnah.com </a> </li> <li> <a target="_blank" rel="noopener noreferrer" href="http://salah.com/" data-metrics-event-name="Footer:Link:Salah" > Salah.com </a> </li> <li> <a target="_blank" rel="noopener noreferrer" href="http://quranicaudio.com/" data-metrics-event-name="Footer:Link:QuranicAudio" > QuranicAudio.com </a> </li> <li> <a target="_blank" rel="noopener noreferrer" href="http://corpus.quran.com/wordbyword.jsp" data-metrics-event-name="Footer:Link:Corpus" > Corpus: Word by Word </a> </li> </ul> </div> <div className={`${styles.links} col-md-3 col-sm-4 col-xs-12`}> <p className={styles.header}> <LocaleFormattedMessage id="nav.otherLinks" defaultMessage="Other links" /> </p> <ul className={`source-sans ${styles.list}`}> <li> <a href="https://quran.com/sitemaps/sitemap.xml.gz" target="_blank" rel="noopener noreferrer" > Sitemap </a> </li> <li> <Link to="/36" data-metrics-event-name="Footer:Link:Click" data-metrics-surah-id="36" > Surah Yasin, Yaseen (يس) </Link> </li> <li> <Link to="/2/255" data-metrics-event-name="Footer:Link:Click" data-metrics-surah-id="2/255" > Ayat Al-Kursi (آية الكرسي) </Link> </li> </ul> </div> <div className={`${styles.links} col-md-4 col-sm-12 col-xs-12`}> <p className="monserrat"> <LocaleFormattedMessage id="nav.aboutQuranProject" defaultMessage="QURAN.COM (ALSO KNOWN AS THE NOBLE QURAN, AL QURAN, HOLY QURAN, KORAN) IS A PRO BONO PROJECT." /> . </p> <p className="monserrat"> © { new Date().getFullYear() } Quran.com. {' '} <LocaleFormattedMessage id="nav.rightsReserved" defaultMessage="All Rights Reserved" /> . </p> </div> </div> </div> </div> </div> </footer> ); export default Footer;
node_modules/react-native/node_modules/react-transform-hmr/lib/index.js
ninamanalo19/react-native-sliding-up-panel
'use strict'; Object.defineProperty(exports, '__esModule', { value: true }); var _slicedToArray = (function () { function sliceIterator(arr, i) { var _arr = []; var _n = true; var _d = false; var _e = undefined; try { for (var _i = arr[Symbol.iterator](), _s; !(_n = (_s = _i.next()).done); _n = true) { _arr.push(_s.value); if (i && _arr.length === i) break; } } catch (err) { _d = true; _e = err; } finally { try { if (!_n && _i['return']) _i['return'](); } finally { if (_d) throw _e; } } return _arr; } return function (arr, i) { if (Array.isArray(arr)) { return arr; } else if (Symbol.iterator in Object(arr)) { return sliceIterator(arr, i); } else { throw new TypeError('Invalid attempt to destructure non-iterable instance'); } }; })(); exports['default'] = proxyReactComponents; function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { 'default': obj }; } var _reactProxy = require('react-proxy'); var _globalWindow = require('global/window'); var _globalWindow2 = _interopRequireDefault(_globalWindow); var componentProxies = undefined; if (_globalWindow2['default'].__reactComponentProxies) { componentProxies = _globalWindow2['default'].__reactComponentProxies; } else { componentProxies = {}; Object.defineProperty(_globalWindow2['default'], '__reactComponentProxies', { configurable: true, enumerable: false, writable: false, value: componentProxies }); } function proxyReactComponents(_ref) { var filename = _ref.filename; var components = _ref.components; var imports = _ref.imports; var locals = _ref.locals; var _imports = _slicedToArray(imports, 1); var React = _imports[0]; var _locals = _slicedToArray(locals, 1); var hot = _locals[0].hot; if (!React.Component) { throw new Error('imports[0] for react-transform-hmr does not look like React.'); } if (!hot || typeof hot.accept !== 'function') { throw new Error('locals[0] does not appear to be a `module` object with Hot Module ' + 'replacement API enabled. You should disable react-transform-hmr in ' + 'production by using `env` section in Babel configuration. See the ' + 'example in README: https://github.com/gaearon/react-transform-hmr'); } if (Object.keys(components).some(function (key) { return !components[key].isInFunction; })) { hot.accept(function (err) { if (err) { console.warn('[React Transform HMR] There was an error updating ' + filename + ':'); console.error(err); } }); } var forceUpdate = (0, _reactProxy.getForceUpdate)(React); return function wrapWithProxy(ReactClass, uniqueId) { var _components$uniqueId = components[uniqueId]; var _components$uniqueId$isInFunction = _components$uniqueId.isInFunction; var isInFunction = _components$uniqueId$isInFunction === undefined ? false : _components$uniqueId$isInFunction; var _components$uniqueId$displayName = _components$uniqueId.displayName; var displayName = _components$uniqueId$displayName === undefined ? uniqueId : _components$uniqueId$displayName; if (isInFunction) { return ReactClass; } var globalUniqueId = filename + '$' + uniqueId; if (componentProxies[globalUniqueId]) { (function () { console.info('[React Transform HMR] Patching ' + displayName); var instances = componentProxies[globalUniqueId].update(ReactClass); setTimeout(function () { return instances.forEach(forceUpdate); }); })(); } else { componentProxies[globalUniqueId] = (0, _reactProxy.createProxy)(ReactClass); } return componentProxies[globalUniqueId].get(); }; } module.exports = exports['default'];
ajax/libs/webshim/1.15.7/dev/shims/es6.js
dryajov/cdnjs
// ES6-shim 0.15.0 (c) 2013-2014 Paul Miller (http://paulmillr.com) // ES6-shim may be freely distributed under the MIT license. // For more details and documentation: // https://github.com/paulmillr/es6-shim/ webshim.register('es6', function($, webshim, window, document, undefined){ 'use strict'; var isCallableWithoutNew = function(func) { try { func(); } catch (e) { return false; } return true; }; var supportsSubclassing = function(C, f) { /* jshint proto:true */ try { var Sub = function() { C.apply(this, arguments); }; if (!Sub.__proto__) { return false; /* skip test on IE < 11 */ } Object.setPrototypeOf(Sub, C); Sub.prototype = Object.create(C.prototype, { constructor: { value: C } }); return f(Sub); } catch (e) { return false; } }; var arePropertyDescriptorsSupported = function() { try { Object.defineProperty({}, 'x', {}); return true; } catch (e) { /* this is IE 8. */ return false; } }; var startsWithRejectsRegex = function() { var rejectsRegex = false; if (String.prototype.startsWith) { try { '/a/'.startsWith(/a/); } catch (e) { /* this is spec compliant */ rejectsRegex = true; } } return rejectsRegex; }; /*jshint evil: true */ var getGlobal = new Function('return this;'); /*jshint evil: false */ var main = function() { var globals = getGlobal(); var global_isFinite = globals.isFinite; var supportsDescriptors = !!Object.defineProperty && arePropertyDescriptorsSupported(); var startsWithIsCompliant = startsWithRejectsRegex(); var _slice = Array.prototype.slice; var _indexOf = String.prototype.indexOf; var _toString = Object.prototype.toString; var _hasOwnProperty = Object.prototype.hasOwnProperty; var ArrayIterator; // make our implementation private // Define configurable, writable and non-enumerable props // if they don’t exist. var defineProperties = function(object, map) { Object.keys(map).forEach(function(name) { var method = map[name]; if (name in object) return; if (supportsDescriptors) { Object.defineProperty(object, name, { configurable: true, enumerable: false, writable: true, value: method }); } else { object[name] = method; } }); }; // Simple shim for Object.create on ES3 browsers // (unlike real shim, no attempt to support `prototype === null`) var create = Object.create || function(prototype, properties) { function Type() {} Type.prototype = prototype; var object = new Type(); if (typeof properties !== "undefined") { defineProperties(object, properties); } return object; }; // This is a private name in the es6 spec, equal to '[Symbol.iterator]' // we're going to use an arbitrary _-prefixed name to make our shims // work properly with each other, even though we don't have full Iterator // support. That is, `Array.from(map.keys())` will work, but we don't // pretend to export a "real" Iterator interface. var $iterator$ = (typeof Symbol === 'function' && Symbol.iterator) || '_es6shim_iterator_'; // Firefox ships a partial implementation using the name @@iterator. // https://bugzilla.mozilla.org/show_bug.cgi?id=907077#c14 // So use that name if we detect it. if (globals.Set && typeof new globals.Set()['@@iterator'] === 'function') { $iterator$ = '@@iterator'; } var addIterator = function(prototype, impl) { if (!impl) { impl = function iterator() { return this; }; } var o = {}; o[$iterator$] = impl; defineProperties(prototype, o); }; // taken directly from https://github.com/ljharb/is-arguments/blob/master/index.js // can be replaced with require('is-arguments') if we ever use a build process instead var isArguments = function isArguments(value) { var str = _toString.call(value); var result = str === '[object Arguments]'; if (!result) { result = str !== '[object Array]' && value !== null && typeof value === 'object' && typeof value.length === 'number' && value.length >= 0 && _toString.call(value.callee) === '[object Function]'; } return result; }; var emulateES6construct = function(o) { if (!ES.TypeIsObject(o)) throw new TypeError('bad object'); // es5 approximation to es6 subclass semantics: in es6, 'new Foo' // would invoke Foo.@@create to allocation/initialize the new object. // In es5 we just get the plain object. So if we detect an // uninitialized object, invoke o.constructor.@@create if (!o._es6construct) { if (o.constructor && ES.IsCallable(o.constructor['@@create'])) { o = o.constructor['@@create'](o); } defineProperties(o, { _es6construct: true }); } return o; }; var ES = { CheckObjectCoercible: function(x, optMessage) { /* jshint eqnull:true */ if (x == null) throw new TypeError(optMessage || ('Cannot call method on ' + x)); return x; }, TypeIsObject: function(x) { /* jshint eqnull:true */ // this is expensive when it returns false; use this function // when you expect it to return true in the common case. return x != null && Object(x) === x; }, ToObject: function(o, optMessage) { return Object(ES.CheckObjectCoercible(o, optMessage)); }, IsCallable: function(x) { return typeof x === 'function' && // some versions of IE say that typeof /abc/ === 'function' _toString.call(x) === '[object Function]'; }, ToInt32: function(x) { return x >> 0; }, ToUint32: function(x) { return x >>> 0; }, ToInteger: function(value) { var number = +value; if (Number.isNaN(number)) return 0; if (number === 0 || !Number.isFinite(number)) return number; return Math.sign(number) * Math.floor(Math.abs(number)); }, ToLength: function(value) { var len = ES.ToInteger(value); if (len <= 0) return 0; // includes converting -0 to +0 if (len > Number.MAX_SAFE_INTEGER) return Number.MAX_SAFE_INTEGER; return len; }, SameValue: function(a, b) { if (a === b) { // 0 === -0, but they are not identical. if (a === 0) return 1 / a === 1 / b; return true; } return Number.isNaN(a) && Number.isNaN(b); }, SameValueZero: function(a, b) { // same as SameValue except for SameValueZero(+0, -0) == true return (a === b) || (Number.isNaN(a) && Number.isNaN(b)); }, IsIterable: function(o) { return ES.TypeIsObject(o) && (o[$iterator$] !== undefined || isArguments(o)); }, GetIterator: function(o) { if (isArguments(o)) { // special case support for `arguments` return new ArrayIterator(o, "value"); } var it = o[$iterator$](); if (!ES.TypeIsObject(it)) { throw new TypeError('bad iterator'); } return it; }, IteratorNext: function(it) { var result = (arguments.length > 1) ? it.next(arguments[1]) : it.next(); if (!ES.TypeIsObject(result)) { throw new TypeError('bad iterator'); } return result; }, Construct: function(C, args) { // CreateFromConstructor var obj; if (ES.IsCallable(C['@@create'])) { obj = C['@@create'](); } else { // OrdinaryCreateFromConstructor obj = create(C.prototype || null); } // Mark that we've used the es6 construct path // (see emulateES6construct) defineProperties(obj, { _es6construct: true }); // Call the constructor. var result = C.apply(obj, args); return ES.TypeIsObject(result) ? result : obj; } }; var numberConversion = (function () { // from https://github.com/inexorabletash/polyfill/blob/master/typedarray.js#L176-L266 // with permission and license, per https://twitter.com/inexorabletash/status/372206509540659200 function roundToEven(n) { var w = Math.floor(n), f = n - w; if (f < 0.5) { return w; } if (f > 0.5) { return w + 1; } return w % 2 ? w + 1 : w; } function packIEEE754(v, ebits, fbits) { var bias = (1 << (ebits - 1)) - 1, s, e, f, ln, i, bits, str, bytes; // Compute sign, exponent, fraction if (v !== v) { // NaN // http://dev.w3.org/2006/webapi/WebIDL/#es-type-mapping e = (1 << ebits) - 1; f = Math.pow(2, fbits - 1); s = 0; } else if (v === Infinity || v === -Infinity) { e = (1 << ebits) - 1; f = 0; s = (v < 0) ? 1 : 0; } else if (v === 0) { e = 0; f = 0; s = (1 / v === -Infinity) ? 1 : 0; } else { s = v < 0; v = Math.abs(v); if (v >= Math.pow(2, 1 - bias)) { e = Math.min(Math.floor(Math.log(v) / Math.LN2), 1023); f = roundToEven(v / Math.pow(2, e) * Math.pow(2, fbits)); if (f / Math.pow(2, fbits) >= 2) { e = e + 1; f = 1; } if (e > bias) { // Overflow e = (1 << ebits) - 1; f = 0; } else { // Normal e = e + bias; f = f - Math.pow(2, fbits); } } else { // Subnormal e = 0; f = roundToEven(v / Math.pow(2, 1 - bias - fbits)); } } // Pack sign, exponent, fraction bits = []; for (i = fbits; i; i -= 1) { bits.push(f % 2 ? 1 : 0); f = Math.floor(f / 2); } for (i = ebits; i; i -= 1) { bits.push(e % 2 ? 1 : 0); e = Math.floor(e / 2); } bits.push(s ? 1 : 0); bits.reverse(); str = bits.join(''); // Bits to bytes bytes = []; while (str.length) { bytes.push(parseInt(str.slice(0, 8), 2)); str = str.slice(8); } return bytes; } function unpackIEEE754(bytes, ebits, fbits) { // Bytes to bits var bits = [], i, j, b, str, bias, s, e, f; for (i = bytes.length; i; i -= 1) { b = bytes[i - 1]; for (j = 8; j; j -= 1) { bits.push(b % 2 ? 1 : 0); b = b >> 1; } } bits.reverse(); str = bits.join(''); // Unpack sign, exponent, fraction bias = (1 << (ebits - 1)) - 1; s = parseInt(str.slice(0, 1), 2) ? -1 : 1; e = parseInt(str.slice(1, 1 + ebits), 2); f = parseInt(str.slice(1 + ebits), 2); // Produce number if (e === (1 << ebits) - 1) { return f !== 0 ? NaN : s * Infinity; } else if (e > 0) { // Normalized return s * Math.pow(2, e - bias) * (1 + f / Math.pow(2, fbits)); } else if (f !== 0) { // Denormalized return s * Math.pow(2, -(bias - 1)) * (f / Math.pow(2, fbits)); } else { return s < 0 ? -0 : 0; } } function unpackFloat64(b) { return unpackIEEE754(b, 11, 52); } function packFloat64(v) { return packIEEE754(v, 11, 52); } function unpackFloat32(b) { return unpackIEEE754(b, 8, 23); } function packFloat32(v) { return packIEEE754(v, 8, 23); } var conversions = { toFloat32: function (num) { return unpackFloat32(packFloat32(num)); } }; if (typeof Float32Array !== 'undefined') { var float32array = new Float32Array(1); conversions.toFloat32 = function (num) { float32array[0] = num; return float32array[0]; }; } return conversions; }()); defineProperties(String, { fromCodePoint: function(_) { // length = 1 var points = _slice.call(arguments, 0, arguments.length); var result = []; var next; for (var i = 0, length = points.length; i < length; i++) { next = Number(points[i]); if (!ES.SameValue(next, ES.ToInteger(next)) || next < 0 || next > 0x10FFFF) { throw new RangeError('Invalid code point ' + next); } if (next < 0x10000) { result.push(String.fromCharCode(next)); } else { next -= 0x10000; result.push(String.fromCharCode((next >> 10) + 0xD800)); result.push(String.fromCharCode((next % 0x400) + 0xDC00)); } } return result.join(''); }, raw: function(callSite) { // raw.length===1 var substitutions = _slice.call(arguments, 1, arguments.length); var cooked = ES.ToObject(callSite, 'bad callSite'); var rawValue = cooked.raw; var raw = ES.ToObject(rawValue, 'bad raw value'); var len = Object.keys(raw).length; var literalsegments = ES.ToLength(len); if (literalsegments === 0) { return ''; } var stringElements = []; var nextIndex = 0; var nextKey, next, nextSeg, nextSub; while (nextIndex < literalsegments) { nextKey = String(nextIndex); next = raw[nextKey]; nextSeg = String(next); stringElements.push(nextSeg); if (nextIndex + 1 >= literalsegments) { break; } next = substitutions[nextKey]; if (next === undefined) { break; } nextSub = String(next); stringElements.push(nextSub); nextIndex++; } return stringElements.join(''); } }); var StringShims = { // Fast repeat, uses the `Exponentiation by squaring` algorithm. // Perf: http://jsperf.com/string-repeat2/2 repeat: (function() { var repeat = function(s, times) { if (times < 1) return ''; if (times % 2) return repeat(s, times - 1) + s; var half = repeat(s, times / 2); return half + half; }; return function(times) { var thisStr = String(ES.CheckObjectCoercible(this)); times = ES.ToInteger(times); if (times < 0 || times === Infinity) { throw new RangeError('Invalid String#repeat value'); } return repeat(thisStr, times); }; })(), startsWith: function(searchStr) { var thisStr = String(ES.CheckObjectCoercible(this)); if (_toString.call(searchStr) === '[object RegExp]') throw new TypeError('Cannot call method "startsWith" with a regex'); searchStr = String(searchStr); var startArg = arguments.length > 1 ? arguments[1] : undefined; var start = Math.max(ES.ToInteger(startArg), 0); return thisStr.slice(start, start + searchStr.length) === searchStr; }, endsWith: function(searchStr) { var thisStr = String(ES.CheckObjectCoercible(this)); if (_toString.call(searchStr) === '[object RegExp]') throw new TypeError('Cannot call method "endsWith" with a regex'); searchStr = String(searchStr); var thisLen = thisStr.length; var posArg = arguments.length > 1 ? arguments[1] : undefined; var pos = posArg === undefined ? thisLen : ES.ToInteger(posArg); var end = Math.min(Math.max(pos, 0), thisLen); return thisStr.slice(end - searchStr.length, end) === searchStr; }, contains: function(searchString) { var position = arguments.length > 1 ? arguments[1] : undefined; // Somehow this trick makes method 100% compat with the spec. return _indexOf.call(this, searchString, position) !== -1; }, codePointAt: function(pos) { var thisStr = String(ES.CheckObjectCoercible(this)); var position = ES.ToInteger(pos); var length = thisStr.length; if (position < 0 || position >= length) return undefined; var first = thisStr.charCodeAt(position); var isEnd = (position + 1 === length); if (first < 0xD800 || first > 0xDBFF || isEnd) return first; var second = thisStr.charCodeAt(position + 1); if (second < 0xDC00 || second > 0xDFFF) return first; return ((first - 0xD800) * 1024) + (second - 0xDC00) + 0x10000; } }; defineProperties(String.prototype, StringShims); var hasStringTrimBug = '\u0085'.trim().length !== 1; if (hasStringTrimBug) { var originalStringTrim = String.prototype.trim; delete String.prototype.trim; // whitespace from: http://es5.github.io/#x15.5.4.20 // implementation from https://github.com/es-shims/es5-shim/blob/v3.4.0/es5-shim.js#L1304-L1324 var ws = [ '\x09\x0A\x0B\x0C\x0D\x20\xA0\u1680\u180E\u2000\u2001\u2002\u2003', '\u2004\u2005\u2006\u2007\u2008\u2009\u200A\u202F\u205F\u3000\u2028', '\u2029\uFEFF' ].join(''); var trimBeginRegexp = new RegExp('^[' + ws + '][' + ws + ']*'); var trimEndRegexp = new RegExp('[' + ws + '][' + ws + ']*$'); defineProperties(String.prototype, { trim: function() { if (this === undefined || this === null) { throw new TypeError("can't convert " + this + " to object"); } return String(this) .replace(trimBeginRegexp, "") .replace(trimEndRegexp, ""); } }); } // see https://people.mozilla.org/~jorendorff/es6-draft.html#sec-string.prototype-@@iterator var StringIterator = function(s) { this._s = String(ES.CheckObjectCoercible(s)); this._i = 0; }; StringIterator.prototype.next = function() { var s = this._s, i = this._i; if (s === undefined || i >= s.length) { this._s = undefined; return { value: undefined, done: true }; } var first = s.charCodeAt(i), second, len; if (first < 0xD800 || first > 0xDBFF || (i+1) == s.length) { len = 1; } else { second = s.charCodeAt(i+1); len = (second < 0xDC00 || second > 0xDFFF) ? 1 : 2; } this._i = i + len; return { value: s.substr(i, len), done: false }; }; addIterator(StringIterator.prototype); addIterator(String.prototype, function() { return new StringIterator(this); }); if (!startsWithIsCompliant) { // Firefox has a noncompliant startsWith implementation String.prototype.startsWith = StringShims.startsWith; String.prototype.endsWith = StringShims.endsWith; } defineProperties(Array, { from: function(iterable) { var mapFn = arguments.length > 1 ? arguments[1] : undefined; var thisArg = arguments.length > 2 ? arguments[2] : undefined; var list = ES.ToObject(iterable, 'bad iterable'); if (mapFn !== undefined && !ES.IsCallable(mapFn)) { throw new TypeError('Array.from: when provided, the second argument must be a function'); } var usingIterator = ES.IsIterable(list); // does the spec really mean that Arrays should use ArrayIterator? // https://bugs.ecmascript.org/show_bug.cgi?id=2416 //if (Array.isArray(list)) { usingIterator=false; } var length = usingIterator ? 0 : ES.ToLength(list.length); var result = ES.IsCallable(this) ? Object(usingIterator ? new this() : new this(length)) : new Array(length); var it = usingIterator ? ES.GetIterator(list) : null; var value; for (var i = 0; usingIterator || (i < length); i++) { if (usingIterator) { value = ES.IteratorNext(it); if (value.done) { length = i; break; } value = value.value; } else { value = list[i]; } if (mapFn) { result[i] = thisArg ? mapFn.call(thisArg, value, i) : mapFn(value, i); } else { result[i] = value; } } result.length = length; return result; }, of: function() { return Array.from(arguments); } }); // Our ArrayIterator is private; see // https://github.com/paulmillr/es6-shim/issues/252 ArrayIterator = function(array, kind) { this.i = 0; this.array = array; this.kind = kind; }; defineProperties(ArrayIterator.prototype, { next: function() { var i = this.i, array = this.array; if (i === undefined || this.kind === undefined) { throw new TypeError('Not an ArrayIterator'); } if (array!==undefined) { var len = ES.ToLength(array.length); for (; i < len; i++) { var kind = this.kind; var retval; if (kind === "key") { retval = i; } else if (kind === "value") { retval = array[i]; } else if (kind === "entry") { retval = [i, array[i]]; } this.i = i + 1; return { value: retval, done: false }; } } this.array = undefined; return { value: undefined, done: true }; } }); addIterator(ArrayIterator.prototype); defineProperties(Array.prototype, { copyWithin: function(target, start) { var end = arguments[2]; // copyWithin.length must be 2 var o = ES.ToObject(this); var len = ES.ToLength(o.length); target = ES.ToInteger(target); start = ES.ToInteger(start); var to = target < 0 ? Math.max(len + target, 0) : Math.min(target, len); var from = start < 0 ? Math.max(len + start, 0) : Math.min(start, len); end = (end===undefined) ? len : ES.ToInteger(end); var fin = end < 0 ? Math.max(len + end, 0) : Math.min(end, len); var count = Math.min(fin - from, len - to); var direction = 1; if (from < to && to < (from + count)) { direction = -1; from += count - 1; to += count - 1; } while (count > 0) { if (_hasOwnProperty.call(o, from)) { o[to] = o[from]; } else { delete o[from]; } from += direction; to += direction; count -= 1; } return o; }, fill: function(value) { var start = arguments.length > 1 ? arguments[1] : undefined; var end = arguments.length > 2 ? arguments[2] : undefined; var O = ES.ToObject(this); var len = ES.ToLength(O.length); start = ES.ToInteger(start === undefined ? 0 : start); end = ES.ToInteger(end === undefined ? len : end); var relativeStart = start < 0 ? Math.max(len + start, 0) : Math.min(start, len); var relativeEnd = end < 0 ? len + end : end; for (var i = relativeStart; i < len && i < relativeEnd; ++i) { O[i] = value; } return O; }, find: function(predicate) { var list = ES.ToObject(this); var length = ES.ToLength(list.length); if (!ES.IsCallable(predicate)) { throw new TypeError('Array#find: predicate must be a function'); } var thisArg = arguments[1]; for (var i = 0, value; i < length; i++) { if (i in list) { value = list[i]; if (predicate.call(thisArg, value, i, list)) return value; } } return undefined; }, findIndex: function(predicate) { var list = ES.ToObject(this); var length = ES.ToLength(list.length); if (!ES.IsCallable(predicate)) { throw new TypeError('Array#findIndex: predicate must be a function'); } var thisArg = arguments[1]; for (var i = 0; i < length; i++) { if (i in list) { if (predicate.call(thisArg, list[i], i, list)) return i; } } return -1; }, keys: function() { return new ArrayIterator(this, "key"); }, values: function() { return new ArrayIterator(this, "value"); }, entries: function() { return new ArrayIterator(this, "entry"); } }); addIterator(Array.prototype, function() { return this.values(); }); // Chrome defines keys/values/entries on Array, but doesn't give us // any way to identify its iterator. So add our own shimmed field. if (Object.getPrototypeOf) { addIterator(Object.getPrototypeOf([].values())); } var maxSafeInteger = Math.pow(2, 53) - 1; defineProperties(Number, { MAX_SAFE_INTEGER: maxSafeInteger, MIN_SAFE_INTEGER: -maxSafeInteger, EPSILON: 2.220446049250313e-16, parseInt: globals.parseInt, parseFloat: globals.parseFloat, isFinite: function(value) { return typeof value === 'number' && global_isFinite(value); }, isInteger: function(value) { return Number.isFinite(value) && ES.ToInteger(value) === value; }, isSafeInteger: function(value) { return Number.isInteger(value) && Math.abs(value) <= Number.MAX_SAFE_INTEGER; }, isNaN: function(value) { // NaN !== NaN, but they are identical. // NaNs are the only non-reflexive value, i.e., if x !== x, // then x is NaN. // isNaN is broken: it converts its argument to number, so // isNaN('foo') => true return value !== value; } }); if (supportsDescriptors) { defineProperties(Object, { getPropertyDescriptor: function(subject, name) { var pd = Object.getOwnPropertyDescriptor(subject, name); var proto = Object.getPrototypeOf(subject); while (pd === undefined && proto !== null) { pd = Object.getOwnPropertyDescriptor(proto, name); proto = Object.getPrototypeOf(proto); } return pd; }, getPropertyNames: function(subject) { var result = Object.getOwnPropertyNames(subject); var proto = Object.getPrototypeOf(subject); var addProperty = function(property) { if (result.indexOf(property) === -1) { result.push(property); } }; while (proto !== null) { Object.getOwnPropertyNames(proto).forEach(addProperty); proto = Object.getPrototypeOf(proto); } return result; } }); defineProperties(Object, { // 19.1.3.1 assign: function(target, source) { if (!ES.TypeIsObject(target)) { throw new TypeError('target must be an object'); } return Array.prototype.reduce.call(arguments, function(target, source) { return Object.keys(Object(source)).reduce(function(target, key) { target[key] = source[key]; return target; }, target); }); }, is: function(a, b) { return ES.SameValue(a, b); }, // 19.1.3.9 // shim from https://gist.github.com/WebReflection/5593554 setPrototypeOf: (function(Object, magic) { var set; var checkArgs = function(O, proto) { if (!ES.TypeIsObject(O)) { throw new TypeError('cannot set prototype on a non-object'); } if (!(proto===null || ES.TypeIsObject(proto))) { throw new TypeError('can only set prototype to an object or null'+proto); } }; var setPrototypeOf = function(O, proto) { checkArgs(O, proto); set.call(O, proto); return O; }; try { // this works already in Firefox and Safari set = Object.getOwnPropertyDescriptor(Object.prototype, magic).set; set.call({}, null); } catch (e) { if (Object.prototype !== {}[magic]) { // IE < 11 cannot be shimmed return; } // probably Chrome or some old Mobile stock browser set = function(proto) { this[magic] = proto; }; // please note that this will **not** work // in those browsers that do not inherit // __proto__ by mistake from Object.prototype // in these cases we should probably throw an error // or at least be informed about the issue setPrototypeOf.polyfill = setPrototypeOf( setPrototypeOf({}, null), Object.prototype ) instanceof Object; // setPrototypeOf.polyfill === true means it works as meant // setPrototypeOf.polyfill === false means it's not 100% reliable // setPrototypeOf.polyfill === undefined // or // setPrototypeOf.polyfill == null means it's not a polyfill // which means it works as expected // we can even delete Object.prototype.__proto__; } return setPrototypeOf; })(Object, '__proto__') }); } // Workaround bug in Opera 12 where setPrototypeOf(x, null) doesn't work, // but Object.create(null) does. if (Object.setPrototypeOf && Object.getPrototypeOf && Object.getPrototypeOf(Object.setPrototypeOf({}, null)) !== null && Object.getPrototypeOf(Object.create(null)) === null) { (function() { var FAKENULL = Object.create(null); var gpo = Object.getPrototypeOf, spo = Object.setPrototypeOf; Object.getPrototypeOf = function(o) { var result = gpo(o); return result === FAKENULL ? null : result; }; Object.setPrototypeOf = function(o, p) { if (p === null) { p = FAKENULL; } return spo(o, p); }; Object.setPrototypeOf.polyfill = false; })(); } try { Object.keys('foo'); } catch (e) { var originalObjectKeys = Object.keys; Object.keys = function (obj) { return originalObjectKeys(ES.ToObject(obj)); }; } var MathShims = { acosh: function(value) { value = Number(value); if (Number.isNaN(value) || value < 1) return NaN; if (value === 1) return 0; if (value === Infinity) return value; return Math.log(value + Math.sqrt(value * value - 1)); }, asinh: function(value) { value = Number(value); if (value === 0 || !global_isFinite(value)) { return value; } return value < 0 ? -Math.asinh(-value) : Math.log(value + Math.sqrt(value * value + 1)); }, atanh: function(value) { value = Number(value); if (Number.isNaN(value) || value < -1 || value > 1) { return NaN; } if (value === -1) return -Infinity; if (value === 1) return Infinity; if (value === 0) return value; return 0.5 * Math.log((1 + value) / (1 - value)); }, cbrt: function(value) { value = Number(value); if (value === 0) return value; var negate = value < 0, result; if (negate) value = -value; result = Math.pow(value, 1/3); return negate ? -result : result; }, clz32: function(value) { // See https://bugs.ecmascript.org/show_bug.cgi?id=2465 value = Number(value); var number = ES.ToUint32(value); if (number === 0) { return 32; } return 32 - (number).toString(2).length; }, cosh: function(value) { value = Number(value); if (value === 0) return 1; // +0 or -0 if (Number.isNaN(value)) return NaN; if (!global_isFinite(value)) return Infinity; if (value < 0) value = -value; if (value > 21) return Math.exp(value) / 2; return (Math.exp(value) + Math.exp(-value)) / 2; }, expm1: function(value) { value = Number(value); if (value === -Infinity) return -1; if (!global_isFinite(value) || value === 0) return value; return Math.exp(value) - 1; }, hypot: function(x, y) { var anyNaN = false; var allZero = true; var anyInfinity = false; var numbers = []; Array.prototype.every.call(arguments, function(arg) { var num = Number(arg); if (Number.isNaN(num)) anyNaN = true; else if (num === Infinity || num === -Infinity) anyInfinity = true; else if (num !== 0) allZero = false; if (anyInfinity) { return false; } else if (!anyNaN) { numbers.push(Math.abs(num)); } return true; }); if (anyInfinity) return Infinity; if (anyNaN) return NaN; if (allZero) return 0; numbers.sort(function (a, b) { return b - a; }); var largest = numbers[0]; var divided = numbers.map(function (number) { return number / largest; }); var sum = divided.reduce(function (sum, number) { return sum += number * number; }, 0); return largest * Math.sqrt(sum); }, log2: function(value) { return Math.log(value) * Math.LOG2E; }, log10: function(value) { return Math.log(value) * Math.LOG10E; }, log1p: function(value) { value = Number(value); if (value < -1 || Number.isNaN(value)) return NaN; if (value === 0 || value === Infinity) return value; if (value === -1) return -Infinity; var result = 0; var n = 50; if (value < 0 || value > 1) return Math.log(1 + value); for (var i = 1; i < n; i++) { if ((i % 2) === 0) { result -= Math.pow(value, i) / i; } else { result += Math.pow(value, i) / i; } } return result; }, sign: function(value) { var number = +value; if (number === 0) return number; if (Number.isNaN(number)) return number; return number < 0 ? -1 : 1; }, sinh: function(value) { value = Number(value); if (!global_isFinite(value) || value === 0) return value; return (Math.exp(value) - Math.exp(-value)) / 2; }, tanh: function(value) { value = Number(value); if (Number.isNaN(value) || value === 0) return value; if (value === Infinity) return 1; if (value === -Infinity) return -1; return (Math.exp(value) - Math.exp(-value)) / (Math.exp(value) + Math.exp(-value)); }, trunc: function(value) { var number = Number(value); return number < 0 ? -Math.floor(-number) : Math.floor(number); }, imul: function(x, y) { // taken from https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Math/imul x = ES.ToUint32(x); y = ES.ToUint32(y); var ah = (x >>> 16) & 0xffff; var al = x & 0xffff; var bh = (y >>> 16) & 0xffff; var bl = y & 0xffff; // the shift by 0 fixes the sign on the high part // the final |0 converts the unsigned value into a signed value return ((al * bl) + (((ah * bl + al * bh) << 16) >>> 0)|0); }, fround: function(x) { if (x === 0 || x === Infinity || x === -Infinity || Number.isNaN(x)) { return x; } var num = Number(x); return numberConversion.toFloat32(num); } }; defineProperties(Math, MathShims); if (Math.imul(0xffffffff, 5) !== -5) { // Safari 6.1, at least, reports "0" for this value Math.imul = MathShims.imul; } // Promises // Simplest possible implementation; use a 3rd-party library if you // want the best possible speed and/or long stack traces. var PromiseShim = (function() { var Promise, Promise$prototype; ES.IsPromise = function(promise) { if (!ES.TypeIsObject(promise)) { return false; } if (!promise._promiseConstructor) { // _promiseConstructor is a bit more unique than _status, so we'll // check that instead of the [[PromiseStatus]] internal field. return false; } if (promise._status === undefined) { return false; // uninitialized } return true; }; // "PromiseCapability" in the spec is what most promise implementations // call a "deferred". var PromiseCapability = function(C) { if (!ES.IsCallable(C)) { throw new TypeError('bad promise constructor'); } var capability = this; var resolver = function(resolve, reject) { capability.resolve = resolve; capability.reject = reject; }; capability.promise = ES.Construct(C, [resolver]); // see https://bugs.ecmascript.org/show_bug.cgi?id=2478 if (!capability.promise._es6construct) { throw new TypeError('bad promise constructor'); } if (!(ES.IsCallable(capability.resolve) && ES.IsCallable(capability.reject))) { throw new TypeError('bad promise constructor'); } }; // find an appropriate setImmediate-alike var setTimeout = globals.setTimeout; var makeZeroTimeout; if (typeof window !== 'undefined' && ES.IsCallable(window.postMessage)) { makeZeroTimeout = function() { // from http://dbaron.org/log/20100309-faster-timeouts var timeouts = []; var messageName = "zero-timeout-message"; var setZeroTimeout = function(fn) { timeouts.push(fn); window.postMessage(messageName, "*"); }; var handleMessage = function(event) { if (event.source == window && event.data == messageName) { event.stopPropagation(); if (timeouts.length === 0) { return; } var fn = timeouts.shift(); fn(); } }; window.addEventListener("message", handleMessage, true); return setZeroTimeout; }; } var makePromiseAsap = function() { // An efficient task-scheduler based on a pre-existing Promise // implementation, which we can use even if we override the // global Promise below (in order to workaround bugs) // https://github.com/Raynos/observ-hash/issues/2#issuecomment-35857671 var P = globals.Promise; return P && P.resolve && function(task) { return P.resolve().then(task); }; }; var enqueue = ES.IsCallable(globals.setImmediate) ? globals.setImmediate.bind(globals) : typeof process === 'object' && process.nextTick ? process.nextTick : makePromiseAsap() || (ES.IsCallable(makeZeroTimeout) ? makeZeroTimeout() : function(task) { setTimeout(task, 0); }); // fallback var triggerPromiseReactions = function(reactions, x) { reactions.forEach(function(reaction) { enqueue(function() { // PromiseReactionTask var handler = reaction.handler; var capability = reaction.capability; var resolve = capability.resolve; var reject = capability.reject; try { var result = handler(x); if (result === capability.promise) { throw new TypeError('self resolution'); } var updateResult = updatePromiseFromPotentialThenable(result, capability); if (!updateResult) { resolve(result); } } catch (e) { reject(e); } }); }); }; var updatePromiseFromPotentialThenable = function(x, capability) { if (!ES.TypeIsObject(x)) { return false; } var resolve = capability.resolve; var reject = capability.reject; try { var then = x.then; // only one invocation of accessor if (!ES.IsCallable(then)) { return false; } then.call(x, resolve, reject); } catch(e) { reject(e); } return true; }; var promiseResolutionHandler = function(promise, onFulfilled, onRejected){ return function(x) { if (x === promise) { return onRejected(new TypeError('self resolution')); } var C = promise._promiseConstructor; var capability = new PromiseCapability(C); var updateResult = updatePromiseFromPotentialThenable(x, capability); if (updateResult) { return capability.promise.then(onFulfilled, onRejected); } else { return onFulfilled(x); } }; }; Promise = function(resolver) { var promise = this; promise = emulateES6construct(promise); if (!promise._promiseConstructor) { // we use _promiseConstructor as a stand-in for the internal // [[PromiseStatus]] field; it's a little more unique. throw new TypeError('bad promise'); } if (promise._status !== undefined) { throw new TypeError('promise already initialized'); } // see https://bugs.ecmascript.org/show_bug.cgi?id=2482 if (!ES.IsCallable(resolver)) { throw new TypeError('not a valid resolver'); } promise._status = 'unresolved'; promise._resolveReactions = []; promise._rejectReactions = []; var resolve = function(resolution) { if (promise._status !== 'unresolved') { return; } var reactions = promise._resolveReactions; promise._result = resolution; promise._resolveReactions = undefined; promise._rejectReactions = undefined; promise._status = 'has-resolution'; triggerPromiseReactions(reactions, resolution); }; var reject = function(reason) { if (promise._status !== 'unresolved') { return; } var reactions = promise._rejectReactions; promise._result = reason; promise._resolveReactions = undefined; promise._rejectReactions = undefined; promise._status = 'has-rejection'; triggerPromiseReactions(reactions, reason); }; try { resolver(resolve, reject); } catch (e) { reject(e); } return promise; }; Promise$prototype = Promise.prototype; defineProperties(Promise, { '@@create': function(obj) { var constructor = this; // AllocatePromise // The `obj` parameter is a hack we use for es5 // compatibility. var prototype = constructor.prototype || Promise$prototype; obj = obj || create(prototype); defineProperties(obj, { _status: undefined, _result: undefined, _resolveReactions: undefined, _rejectReactions: undefined, _promiseConstructor: undefined }); obj._promiseConstructor = constructor; return obj; } }); var _promiseAllResolver = function(index, values, capability, remaining) { var done = false; return function(x) { if (done) { return; } // protect against being called multiple times done = true; values[index] = x; if ((--remaining.count) === 0) { var resolve = capability.resolve; resolve(values); // call w/ this===undefined } }; }; Promise.all = function(iterable) { var C = this; var capability = new PromiseCapability(C); var resolve = capability.resolve; var reject = capability.reject; try { if (!ES.IsIterable(iterable)) { throw new TypeError('bad iterable'); } var it = ES.GetIterator(iterable); var values = [], remaining = { count: 1 }; for (var index = 0; ; index++) { var next = ES.IteratorNext(it); if (next.done) { break; } var nextPromise = C.resolve(next.value); var resolveElement = _promiseAllResolver( index, values, capability, remaining ); remaining.count++; nextPromise.then(resolveElement, capability.reject); } if ((--remaining.count) === 0) { resolve(values); // call w/ this===undefined } } catch (e) { reject(e); } return capability.promise; }; Promise.race = function(iterable) { var C = this; var capability = new PromiseCapability(C); var resolve = capability.resolve; var reject = capability.reject; try { if (!ES.IsIterable(iterable)) { throw new TypeError('bad iterable'); } var it = ES.GetIterator(iterable); while (true) { var next = ES.IteratorNext(it); if (next.done) { // If iterable has no items, resulting promise will never // resolve; see: // https://github.com/domenic/promises-unwrapping/issues/75 // https://bugs.ecmascript.org/show_bug.cgi?id=2515 break; } var nextPromise = C.resolve(next.value); nextPromise.then(resolve, reject); } } catch (e) { reject(e); } return capability.promise; }; Promise.reject = function(reason) { var C = this; var capability = new PromiseCapability(C); var reject = capability.reject; reject(reason); // call with this===undefined return capability.promise; }; Promise.resolve = function(v) { var C = this; if (ES.IsPromise(v)) { var constructor = v._promiseConstructor; if (constructor === C) { return v; } } var capability = new PromiseCapability(C); var resolve = capability.resolve; resolve(v); // call with this===undefined return capability.promise; }; Promise.prototype['catch'] = function( onRejected ) { return this.then(undefined, onRejected); }; Promise.prototype.then = function( onFulfilled, onRejected ) { var promise = this; if (!ES.IsPromise(promise)) { throw new TypeError('not a promise'); } // this.constructor not this._promiseConstructor; see // https://bugs.ecmascript.org/show_bug.cgi?id=2513 var C = this.constructor; var capability = new PromiseCapability(C); if (!ES.IsCallable(onRejected)) { onRejected = function(e) { throw e; }; } if (!ES.IsCallable(onFulfilled)) { onFulfilled = function(x) { return x; }; } var resolutionHandler = promiseResolutionHandler(promise, onFulfilled, onRejected); var resolveReaction = { capability: capability, handler: resolutionHandler }; var rejectReaction = { capability: capability, handler: onRejected }; switch (promise._status) { case 'unresolved': promise._resolveReactions.push(resolveReaction); promise._rejectReactions.push(rejectReaction); break; case 'has-resolution': triggerPromiseReactions([resolveReaction], promise._result); break; case 'has-rejection': triggerPromiseReactions([rejectReaction], promise._result); break; default: throw new TypeError('unexpected'); } return capability.promise; }; return Promise; })(); // export the Promise constructor. defineProperties(globals, { Promise: PromiseShim }); // In Chrome 33 (and thereabouts) Promise is defined, but the // implementation is buggy in a number of ways. Let's check subclassing // support to see if we have a buggy implementation. var promiseSupportsSubclassing = supportsSubclassing(globals.Promise, function(S) { return S.resolve(42) instanceof S; }); var promiseIgnoresNonFunctionThenCallbacks = (function () { try { globals.Promise.reject(42).then(null, 5).then(null, function () {}); return true; } catch (ex) { return false; } }()); if (!promiseSupportsSubclassing || !promiseIgnoresNonFunctionThenCallbacks) { globals.Promise = PromiseShim; } // Map and Set require a true ES5 environment if (supportsDescriptors) { var fastkey = function fastkey(key) { var type = typeof key; if (type === 'string') { return '$' + key; } else if (type === 'number') { // note that -0 will get coerced to "0" when used as a property key return key; } return null; }; var emptyObject = function emptyObject() { // accomodate some older not-quite-ES5 browsers return Object.create ? Object.create(null) : {}; }; var collectionShims = { Map: (function() { var empty = {}; function MapEntry(key, value) { this.key = key; this.value = value; this.next = null; this.prev = null; } MapEntry.prototype.isRemoved = function() { return this.key === empty; }; function MapIterator(map, kind) { this.head = map._head; this.i = this.head; this.kind = kind; } MapIterator.prototype = { next: function() { var i = this.i, kind = this.kind, head = this.head, result; if (this.i === undefined) { return { value: undefined, done: true }; } while (i.isRemoved() && i !== head) { // back up off of removed entries i = i.prev; } // advance to next unreturned element. while (i.next !== head) { i = i.next; if (!i.isRemoved()) { if (kind === "key") { result = i.key; } else if (kind === "value") { result = i.value; } else { result = [i.key, i.value]; } this.i = i; return { value: result, done: false }; } } // once the iterator is done, it is done forever. this.i = undefined; return { value: undefined, done: true }; } }; addIterator(MapIterator.prototype); function Map(iterable) { var map = this; map = emulateES6construct(map); if (!map._es6map) { throw new TypeError('bad map'); } var head = new MapEntry(null, null); // circular doubly-linked list. head.next = head.prev = head; defineProperties(map, { '_head': head, '_storage': emptyObject(), '_size': 0 }); // Optionally initialize map from iterable if (iterable !== undefined && iterable !== null) { var it = ES.GetIterator(iterable); var adder = map.set; if (!ES.IsCallable(adder)) { throw new TypeError('bad map'); } while (true) { var next = ES.IteratorNext(it); if (next.done) { break; } var nextItem = next.value; if (!ES.TypeIsObject(nextItem)) { throw new TypeError('expected iterable of pairs'); } adder.call(map, nextItem[0], nextItem[1]); } } return map; } var Map$prototype = Map.prototype; defineProperties(Map, { '@@create': function(obj) { var constructor = this; var prototype = constructor.prototype || Map$prototype; obj = obj || create(prototype); defineProperties(obj, { _es6map: true }); return obj; } }); Object.defineProperty(Map.prototype, 'size', { configurable: true, enumerable: false, get: function() { if (typeof this._size === 'undefined') { throw new TypeError('size method called on incompatible Map'); } return this._size; } }); defineProperties(Map.prototype, { get: function(key) { var fkey = fastkey(key); if (fkey !== null) { // fast O(1) path var entry = this._storage[fkey]; return entry ? entry.value : undefined; } var head = this._head, i = head; while ((i = i.next) !== head) { if (ES.SameValueZero(i.key, key)) { return i.value; } } return undefined; }, has: function(key) { var fkey = fastkey(key); if (fkey !== null) { // fast O(1) path return typeof this._storage[fkey] !== 'undefined'; } var head = this._head, i = head; while ((i = i.next) !== head) { if (ES.SameValueZero(i.key, key)) { return true; } } return false; }, set: function(key, value) { var head = this._head, i = head, entry; var fkey = fastkey(key); if (fkey !== null) { // fast O(1) path if (typeof this._storage[fkey] !== 'undefined') { this._storage[fkey].value = value; return; } else { entry = this._storage[fkey] = new MapEntry(key, value); i = head.prev; // fall through } } while ((i = i.next) !== head) { if (ES.SameValueZero(i.key, key)) { i.value = value; return; } } entry = entry || new MapEntry(key, value); if (ES.SameValue(-0, key)) { entry.key = +0; // coerce -0 to +0 in entry } entry.next = this._head; entry.prev = this._head.prev; entry.prev.next = entry; entry.next.prev = entry; this._size += 1; }, 'delete': function(key) { var head = this._head, i = head; var fkey = fastkey(key); if (fkey !== null) { // fast O(1) path if (typeof this._storage[fkey] === 'undefined') { return false; } i = this._storage[fkey].prev; delete this._storage[fkey]; // fall through } while ((i = i.next) !== head) { if (ES.SameValueZero(i.key, key)) { i.key = i.value = empty; i.prev.next = i.next; i.next.prev = i.prev; this._size -= 1; return true; } } return false; }, clear: function() { this._size = 0; this._storage = emptyObject(); var head = this._head, i = head, p = i.next; while ((i = p) !== head) { i.key = i.value = empty; p = i.next; i.next = i.prev = head; } head.next = head.prev = head; }, keys: function() { return new MapIterator(this, "key"); }, values: function() { return new MapIterator(this, "value"); }, entries: function() { return new MapIterator(this, "key+value"); }, forEach: function(callback) { var context = arguments.length > 1 ? arguments[1] : null; var it = this.entries(); for (var entry = it.next(); !entry.done; entry = it.next()) { callback.call(context, entry.value[1], entry.value[0], this); } } }); addIterator(Map.prototype, function() { return this.entries(); }); return Map; })(), Set: (function() { // Creating a Map is expensive. To speed up the common case of // Sets containing only string or numeric keys, we use an object // as backing storage and lazily create a full Map only when // required. var SetShim = function Set(iterable) { var set = this; set = emulateES6construct(set); if (!set._es6set) { throw new TypeError('bad set'); } defineProperties(set, { '[[SetData]]': null, '_storage': emptyObject() }); // Optionally initialize map from iterable if (iterable !== undefined && iterable !== null) { var it = ES.GetIterator(iterable); var adder = set.add; if (!ES.IsCallable(adder)) { throw new TypeError('bad set'); } while (true) { var next = ES.IteratorNext(it); if (next.done) { break; } var nextItem = next.value; adder.call(set, nextItem); } } return set; }; var Set$prototype = SetShim.prototype; defineProperties(SetShim, { '@@create': function(obj) { var constructor = this; var prototype = constructor.prototype || Set$prototype; obj = obj || create(prototype); defineProperties(obj, { _es6set: true }); return obj; } }); // Switch from the object backing storage to a full Map. var ensureMap = function ensureMap(set) { if (!set['[[SetData]]']) { var m = set['[[SetData]]'] = new collectionShims.Map(); Object.keys(set._storage).forEach(function(k) { // fast check for leading '$' if (k.charCodeAt(0) === 36) { k = k.slice(1); } else { k = +k; } m.set(k, k); }); set._storage = null; // free old backing storage } }; Object.defineProperty(SetShim.prototype, 'size', { configurable: true, enumerable: false, get: function() { if (typeof this._storage === 'undefined') { // https://github.com/paulmillr/es6-shim/issues/176 throw new TypeError('size method called on incompatible Set'); } ensureMap(this); return this['[[SetData]]'].size; } }); defineProperties(SetShim.prototype, { has: function(key) { var fkey; if (this._storage && (fkey = fastkey(key)) !== null) { return !!this._storage[fkey]; } ensureMap(this); return this['[[SetData]]'].has(key); }, add: function(key) { var fkey; if (this._storage && (fkey = fastkey(key)) !== null) { this._storage[fkey]=true; return; } ensureMap(this); return this['[[SetData]]'].set(key, key); }, 'delete': function(key) { var fkey; if (this._storage && (fkey = fastkey(key)) !== null) { delete this._storage[fkey]; return; } ensureMap(this); return this['[[SetData]]']['delete'](key); }, clear: function() { if (this._storage) { this._storage = emptyObject(); return; } return this['[[SetData]]'].clear(); }, keys: function() { ensureMap(this); return this['[[SetData]]'].keys(); }, values: function() { ensureMap(this); return this['[[SetData]]'].values(); }, entries: function() { ensureMap(this); return this['[[SetData]]'].entries(); }, forEach: function(callback) { var context = arguments.length > 1 ? arguments[1] : null; var entireSet = this; ensureMap(this); this['[[SetData]]'].forEach(function(value, key) { callback.call(context, key, key, entireSet); }); } }); addIterator(SetShim.prototype, function() { return this.values(); }); return SetShim; })() }; defineProperties(globals, collectionShims); if (globals.Map || globals.Set) { /* - In Firefox < 23, Map#size is a function. - In all current Firefox, Set#entries/keys/values & Map#clear do not exist - https://bugzilla.mozilla.org/show_bug.cgi?id=869996 - In Firefox 24, Map and Set do not implement forEach - In Firefox 25 at least, Map and Set are callable without "new" */ if ( typeof globals.Map.prototype.clear !== 'function' || new globals.Set().size !== 0 || new globals.Map().size !== 0 || typeof globals.Map.prototype.keys !== 'function' || typeof globals.Set.prototype.keys !== 'function' || typeof globals.Map.prototype.forEach !== 'function' || typeof globals.Set.prototype.forEach !== 'function' || isCallableWithoutNew(globals.Map) || isCallableWithoutNew(globals.Set) || !supportsSubclassing(globals.Map, function(M) { return (new M([])) instanceof M; }) ) { globals.Map = collectionShims.Map; globals.Set = collectionShims.Set; } } // Shim incomplete iterator implementations. addIterator(Object.getPrototypeOf((new globals.Map()).keys())); addIterator(Object.getPrototypeOf((new globals.Set()).keys())); } }; main(); // CommonJS and <script> });
lib/theme.js
lodev09/react-native-cell-components
import { PixelRatio, Platform, StyleSheet, Dimensions } from 'react-native'; const colors = { warning: '#f1c40f', success: '#2ecc71', danger: '#e74c3c', info: '#3498db', primary: '#3498db', white: '#ffffff', muted: '#999999', mutedLighten: '#cccccc', mutedDarken: '#666666', black: '#333333', border: '#dddddd', lightest: '#fafafa', light: '#f3f3f3', lightGrey: '#e9e9e9' }; const value = (ios = null, android = null) => { return Platform.select({ ios, android }); }; // https://github.com/ptelad/react-native-iphone-x-helper/blob/master/index.js const isIphoneX = (function() { const dimen = Dimensions.get('window'); return ( Platform.OS === 'ios' && !Platform.isPad && !Platform.isTVOS && ((dimen.height === 812 || dimen.width === 812) || (dimen.height === 896 || dimen.width === 896)) ); })(); const borderWidth = StyleSheet.hairlineWidth; const radius = value(5, 2); const padding = value(10, 16); const margin = value(10, 8); const bottomOffset = isIphoneX ? 34 : 0; const topOffset = isIphoneX ? 44 : 20; const borders = {}; const borderRadius = {}; ['Bottom', 'Top', 'Left', 'Right'].forEach((key) => { const keyName = key === 'all' ? '' : key; borders[key.toLowerCase()] = { ['border' + keyName + 'Width']: borderWidth, ['border' + keyName + 'Color']: colors.border }; borderRadius[key.toLowerCase()] = { ['border' + keyName + 'RightRadius']: radius, ['border' + keyName + 'LeftRadius']: radius, }; }); export default { border: { ...borders }, borderRadius: { ...borderRadius }, separator: { backgroundColor: colors.border, height: borderWidth }, color: colors, font: { xxsmall: 10, xsmall: 12, small: 14, medium: 16, large: 18, xlarge: 20, xxlarge: 22 }, background: colors.light, backgroundDarker: colors.lightGrey, borderColor: colors.border, iconWidth: 29, styles: { left: { alignItems: 'flex-start' }, right: { alignItems: 'flex-end' } }, isAndroid: value(false, true), isIOS: value(true, false), isIphoneX, bottomOffset, topOffset, borderWidth, radius, padding, margin, value };
app/javascript/mastodon/components/column.js
Arukas/mastodon
import React from 'react'; import PropTypes from 'prop-types'; import detectPassiveEvents from 'detect-passive-events'; import { scrollTop } from '../scroll'; export default class Column extends React.PureComponent { static propTypes = { children: PropTypes.node, }; scrollTop () { const scrollable = this.node.querySelector('.scrollable'); if (!scrollable) { return; } this._interruptScrollAnimation = scrollTop(scrollable); } handleWheel = () => { if (typeof this._interruptScrollAnimation !== 'function') { return; } this._interruptScrollAnimation(); } setRef = c => { this.node = c; } componentDidMount () { this.node.addEventListener('wheel', this.handleWheel, detectPassiveEvents.hasSupport ? { passive: true } : false); } componentWillUnmount () { this.node.removeEventListener('wheel', this.handleWheel); } render () { const { children } = this.props; return ( <div role='region' className='column' ref={this.setRef}> {children} </div> ); } }
pages/work/air.js
k97/node-slasher-app
import React from 'react'; import axios from 'axios'; import ReactMarkdown from 'react-markdown'; import mediumZoom from 'medium-zoom'; import Layout from '../../components/Layout/index'; import ProjectTitle from '../../components/Work/ProjectTitle'; import EditProject from '../../components/Work/EditProject'; import UILoader from '../../components/Home/UILoader'; class ProjectAir extends React.Component { constructor(props) { super(props); this.state = { project: {}, loading: true }; this.fetchProjectDetail = this.fetchProjectDetail.bind(this); } componentDidMount() { this.fetchProjectDetail(); } fetchProjectDetail() { axios.get('/api/project/air').then(response => { this.setState({ project: response.data, loading: false }); mediumZoom('.work-detail-wrapper img',{ margin: 70 }) }).catch(error => { this.setState({ loading: false }); }); } render() { const content = this.state.project.content; return ( <Layout title={`Airport Info Repo - Karthik`}> <div className='body-content'> <ProjectTitle heading="Airport Info Repo" date="September, 2016" bgColor="bg-air" /> <section className='w-100 ph2 ph3-m ph4-l'> <div className='cf pa2'> <section className="work-detail-wrapper fw4 measure-wide db center f4 lh-copy black-60 ft-serif"> <UILoader loading={this.state.loading} /> {content ? <ReactMarkdown source={content} /> : ''} </section> </div> </section> <EditProject project={this.state.project} /> </div> </Layout> ); } } export default ProjectAir
src/modules/cart/components/ShoppingCart.js
neilff/react-redux-performance
import React from 'react'; import { getFinalTotal, getItemSubtotal } from 'modules/cart/selectors'; import CartItems from 'modules/cart/components/CartItems'; import TaxCalculator from 'modules/cart/components/TaxCalculator'; import DisplayValue from 'modules/cart/components/DisplayValue'; import AvailableItems from 'modules/cart/components/AvailableItems'; function ShoppingCart() { return ( <main style={{ maxWidth: 900, margin: '4rem auto' }} className="flex flex-column justify-center"> <div className="flex-auto"> <table className="table table-light"> <thead> <tr> <th>Item</th> <th>Quantity</th> <th>Cost Per Unit</th> <th>Total</th> <th /> </tr> </thead> <CartItems /> <tfoot> <tr> <td className="bold align-middle" colSpan="4"> <div className="right">Total Tax</div> </td> <td className="bold align-middle"> <TaxCalculator /> </td> </tr> <tr> <td className="bold align-middle" colSpan="4"> <div className="right">Subtotal</div> </td> <td className="bold align-middle"> <DisplayValue id="subtotal" selector={ getItemSubtotal } /> </td> </tr> <tr> <td className="bold align-middle" colSpan="4"> <div className="right">Total</div> </td> <td className="bold align-middle"> <DisplayValue id="total" selector={ getFinalTotal } /> </td> </tr> </tfoot> </table> </div> <div className="flex-auto"> <AvailableItems /> </div> </main> ); } ShoppingCart.displayName = 'ShoppingCart'; ShoppingCart.propTypes = {}; ShoppingCart.defaultProps = {}; export default ShoppingCart;
frontend/app_v2/src/common/icons/ChevronDown.js
First-Peoples-Cultural-Council/fv-web-ui
import React from 'react' import PropTypes from 'prop-types' /** * @summary ChevronDown * @component * * @param {object} props * * @returns {node} jsx markup */ function ChevronDown({ styling }) { return ( <svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 24 24" className={styling}> <path d="M0 0h24v24H0z" fill="none" /> <path d="M16.59 8.59L12 13.17 7.41 8.59 6 10l6 6 6-6z" /> </svg> ) } // PROPTYPES const { string } = PropTypes ChevronDown.propTypes = { styling: string, } export default ChevronDown
client/screens/Guia/GuiaContainer.js
francixcoag/trace_packages
import React, {Component} from 'react' import { reduxForm } from 'redux-form'; import { connect } from 'react-redux'; import Guia from './Guia'; class GuiaItem extends React.Component { constructor(props) { super(props) console.log(props); } render() { return ( <Guia accountId={this.props.user.group} codProcess={this.props.codProcess} /> ); } } const mapStateToProps = (state) => { const user = state.auth.user; return { user: user }; }; // decorate with redux export default connect( mapStateToProps )(GuiaItem);
react/react-16.2.0/fixtures/ssr/src/index.js
isubham/isubham.github.io
import React from 'react'; import {hydrate} from 'react-dom'; import App from './components/App'; hydrate(<App assets={window.assetManifest} />, document);
www/src/components/Navbar.js
TaitoUnited/taito-cli
import React from 'react'; import styled from '@emotion/styled'; import { Link } from 'gatsby'; import { FaGithub } from 'react-icons/fa'; import { desktopOnly } from '../utils'; import theme from '../theme'; import Spacing from './Spacing'; import Search from './search'; const Navbar = () => { const activeStyle = { fontWeight: 500, borderColor: theme.primary[500], }; return ( <Nav> <NavLinks> <NavLink to="/"> <strong>Taito</strong>&nbsp;CLI </NavLink> <Spacing amount={64} /> <NavLink to="/docs" activeStyle={activeStyle} partiallyActive> Docs </NavLink> <Spacing amount={32} /> <NavLink to="/tutorial" activeStyle={activeStyle} partiallyActive> Tutorial </NavLink> <Spacing amount={32} /> <NavLink to="/plugins" activeStyle={activeStyle}> Plugins </NavLink> <Spacing amount={32} /> <NavLink to="/templates" activeStyle={activeStyle}> Templates </NavLink> <Spacing amount={32} /> <NavLink to="/extensions" activeStyle={activeStyle}> Extensions </NavLink> <div style={{ flex: 1 }} /> <Search /> <Spacing /> <a href="https://github.com/TaitoUnited/taito-cli" target="__blank" rel="noopener noreferrer" > <FaGithub color="#fff" size={24} /> </a> </NavLinks> </Nav> ); }; const Nav = styled.nav` position: fixed; top: 0; left: 0; right: 0; background-color: ${props => props.theme.primary[700]}; z-index: 1; ${desktopOnly} `; const NavLinks = styled.nav` display: flex; flex-direction: row; align-items: center; padding: 0px 16px; `; const NavLink = styled(Link)` height: 50px; display: flex; justify-content: center; align-items: center; text-decoration: none; color: #fff; border-bottom: 4px solid ${props => props.theme.primary[700]}; position: relative; &:hover { border-bottom: 4px solid ${props => props.theme.primary[900]}; } `; export default Navbar;
modules/Redirect.js
hgezim/react-router
import React from 'react' import invariant from 'invariant' import { createRouteFromReactElement } from './RouteUtils' import { formatPattern } from './PatternUtils' import { falsy } from './PropTypes' const { string, object } = React.PropTypes /** * A <Redirect> is used to declare another URL path a client should be sent * to when they request a given URL. * * Redirects are placed alongside routes in the route configuration and are * traversed in the same manner. */ const Redirect = React.createClass({ statics: { createRouteFromReactElement(element) { const route = createRouteFromReactElement(element) if (route.from) route.path = route.from // TODO: Handle relative pathnames, see #1658 invariant( route.to.charAt(0) === '/', '<Redirect to> must be an absolute path. This should be fixed in the future' ) route.onEnter = function (nextState, replaceState) { const { location, params } = nextState const pathname = route.to ? formatPattern(route.to, params) : location.pathname replaceState( route.state || location.state, pathname, route.query || location.query ) } return route } }, propTypes: { path: string, from: string, // Alias for path to: string.isRequired, query: object, state: object, onEnter: falsy, children: falsy }, render() { invariant( false, '<Redirect> elements are for router configuration only and should not be rendered' ) } }) export default Redirect
admin/src/components/Footer.js
belafontestudio/keystone
import blacklist from 'blacklist'; import classnames from 'classnames'; import React from 'react'; import { Container } from 'elemental'; var Footer = React.createClass({ displayName: 'Footer', propTypes: { appversion: React.PropTypes.string, backUrl: React.PropTypes.string, brand: React.PropTypes.string, User: React.PropTypes.object, user: React.PropTypes.object, version: React.PropTypes.string, }, renderUser () { let { User, user } = this.props; if (!User || !user) return null; return ( <span> <span>Signed in as </span> <a href={'/keystone/' + User.path + '/' + user.id} tabIndex="-1" className="keystone-footer__link"> {User.getDocumentName(user)} </a> <span>.</span> </span> ); }, render () { let { backUrl, brand, appversion, version } = this.props; return ( <footer className="keystone-footer"> <Container> <a href={backUrl} tabIndex="-1" className="keystone-footer__link">{brand + (appversion ? (' ' + appversion) : '')}</a> <span> powered by </span> <a href="http://keystonejs.com" target="_blank" className="keystone-footer__link" tabIndex="-1">KeystoneJS</a> <span> version {version}.</span> {this.renderUser()} </Container> </footer> ); } }); module.exports = Footer;
client/node_modules/ember-cli/node_modules/bower/node_modules/inquirer/node_modules/rx/src/core/linq/observable/never.js
mitchlloyd/training
/** * Returns a non-terminating observable sequence, which can be used to denote an infinite duration (e.g. when using reactive joins). * @returns {Observable} An observable sequence whose observers will never get called. */ var observableNever = Observable.never = function () { return new AnonymousObservable(function () { return disposableEmpty; }); };
ajax/libs/swagger-ui/3.0.16/swagger-ui.js
maruilian11/cdnjs
!function(e,t){"object"==typeof exports&&"object"==typeof module?module.exports=t(require("babel-polyfill"),require("deep-extend"),require("redux"),require("immutable"),require("redux-immutable"),require("serialize-error"),require("base64-js"),require("ieee754"),require("isarray"),require("shallowequal"),require("xml"),require("memoizee"),require("reselect"),require("js-yaml"),require("url-parse"),require("react"),require("react-dom"),require("react-redux"),require("yaml-js"),require("swagger-client"),require("react-split-pane"),require("react-immutable-proptypes"),require("react-addons-shallow-compare"),require("react-collapse"),require("react-remarkable"),require("sanitize-html")):"function"==typeof define&&define.amd?define(["babel-polyfill","deep-extend","redux","immutable","redux-immutable","serialize-error","base64-js","ieee754","isarray","shallowequal","xml","memoizee","reselect","js-yaml","url-parse","react","react-dom","react-redux","yaml-js","swagger-client","react-split-pane","react-immutable-proptypes","react-addons-shallow-compare","react-collapse","react-remarkable","sanitize-html"],t):"object"==typeof exports?exports.SwaggerUICore=t(require("babel-polyfill"),require("deep-extend"),require("redux"),require("immutable"),require("redux-immutable"),require("serialize-error"),require("base64-js"),require("ieee754"),require("isarray"),require("shallowequal"),require("xml"),require("memoizee"),require("reselect"),require("js-yaml"),require("url-parse"),require("react"),require("react-dom"),require("react-redux"),require("yaml-js"),require("swagger-client"),require("react-split-pane"),require("react-immutable-proptypes"),require("react-addons-shallow-compare"),require("react-collapse"),require("react-remarkable"),require("sanitize-html")):e.SwaggerUICore=t(e["babel-polyfill"],e["deep-extend"],e.redux,e.immutable,e["redux-immutable"],e["serialize-error"],e["base64-js"],e.ieee754,e.isarray,e.shallowequal,e.xml,e.memoizee,e.reselect,e["js-yaml"],e["url-parse"],e.react,e["react-dom"],e["react-redux"],e["yaml-js"],e["swagger-client"],e["react-split-pane"],e["react-immutable-proptypes"],e["react-addons-shallow-compare"],e["react-collapse"],e["react-remarkable"],e["sanitize-html"])}(this,function(e,t,r,n,o,a,u,i,s,l,c,f,p,d,h,y,m,v,b,g,_,E,w,j,P,O){return function(e){function t(n){if(r[n])return r[n].exports;var o=r[n]={exports:{},id:n,loaded:!1};return e[n].call(o.exports,o,o.exports,t),o.loaded=!0,o.exports}var r={};return t.m=e,t.c=r,t.p="/dist",t(0)}(function(e){for(var t in e)if(Object.prototype.hasOwnProperty.call(e,t))switch(typeof e[t]){case"function":break;case"object":e[t]=function(t){var r=t.slice(1),n=e[t[0]];return function(e,t,o){n.apply(this,[e,t,o].concat(r))}}(e[t]);break;default:e[t]=e[e[t]]}return e}([function(e,t,r){r(1),r(2),e.exports=r(3)},function(e,t){e.exports=require("babel-polyfill")},function(e,t){},function(e,t,r){"use strict";function n(e){if(e&&e.__esModule)return e;var t={};if(null!=e)for(var r in e)Object.prototype.hasOwnProperty.call(e,r)&&(t[r]=e[r]);return t.default=e,t}function o(e){return e&&e.__esModule?e:{default:e}}var a="function"==typeof Symbol&&"symbol"==typeof Symbol.iterator?function(e){return typeof e}:function(e){return e&&"function"==typeof Symbol&&e.constructor===Symbol&&e!==Symbol.prototype?"symbol":typeof e},u=r(4),i=o(u),s=r(5),l=o(s),c=r(11),f=o(c),p=r(157),d=o(p),h=r(316),y=n(h),m=r(12),v=["url","spec","validatorUrl","onComplete","onFailure","authorizations","docExpansion","apisSorter","operationsSorter","supportedSubmitMethods","dom_id","defaultModelRendering","oauth2RedirectUrl","showRequestHeaders","custom","modelPropertyMacro","parameterMacro","displayOperationId"],b={PACKAGE_VERSION:"3.0.16",GIT_COMMIT:"gafcb7d3",GIT_DIRTY:!1},g=b.GIT_DIRTY,_=b.GIT_COMMIT,E=b.PACKAGE_VERSION;e.exports=function(e){f.default.versions=f.default.versions||{},f.default.versions.swaggerUi=E+"/"+(_||"unknown")+(g?"-dirty":"");var t={dom_id:null,spec:{},url:"",layout:"BaseLayout",docExpansion:"list",validatorUrl:"https://online.swagger.io/validator",configs:{},custom:{},displayOperationId:!1,presets:[],plugins:[],fn:{},components:{},state:{},store:{}},r=(0,i.default)({},t,e),n=(0,i.default)({},r.store,{system:{configs:r.configs},plugins:r.presets,state:{layout:{layout:r.layout},spec:{spec:"",url:r.url}}}),o=function(){return{fn:r.fn,components:r.components,state:r.state}},u=new l.default(n);u.register([r.plugins,o]);var s=u.getSystem(),c=(0,m.parseSeach)();s.initOAuth=s.authActions.configureAuth;var p=function(e){if("object"!==("undefined"==typeof r?"undefined":a(r)))return s;var t=s.specSelectors.getLocalConfig?s.specSelectors.getLocalConfig():{},n=(0,i.default)({},t,r,e||{},c);return u.setConfigs((0,m.filterConfigs)(n,v)),null!==e&&(!c.url&&"object"===a(n.spec)&&Object.keys(n.spec).length?(s.specActions.updateUrl(""),s.specActions.updateLoadingStatus("success"),s.specActions.updateSpec(JSON.stringify(n.spec))):s.specActions.download&&n.url&&(s.specActions.updateUrl(n.url),s.specActions.download(n.url))),n.dom_id?s.render(n.dom_id,"App"):console.error("Skipped rendering: no `dom_id` was specified"),s},d=c.config||r.configUrl;if(!d||!s.specActions.getConfigByUrl||s.specActions.getConfigByUrl&&!s.specActions.getConfigByUrl(d,p))return p()},e.exports.presets={apis:d.default},e.exports.plugins=y},function(e,t){e.exports=require("deep-extend")},function(e,t,r){"use strict";function n(e){return e&&e.__esModule?e:{default:e}}function o(e,t,r){return t in e?Object.defineProperty(e,t,{value:r,enumerable:!0,configurable:!0,writable:!0}):e[t]=r,e}function a(e,t){if(!(e instanceof t))throw new TypeError("Cannot call a class as a function")}function u(e,t,r){var n=[(0,O.systemThunkMiddleware)(r)],o=P.default.__REDUX_DEVTOOLS_EXTENSION_COMPOSE__||h.compose;return(0,h.createStore)(e,t,o(h.applyMiddleware.apply(void 0,n)))}function i(e,t){return(0,O.isObject)(e)&&!(0,O.isArray)(e)?e:(0,O.isFunc)(e)?i(e(t),t):(0,O.isArray)(e)?e.map(function(e){return i(e,t)}).reduce(s,{}):{}}function s(){var e=arguments.length>0&&void 0!==arguments[0]?arguments[0]:{},t=arguments.length>1&&void 0!==arguments[1]?arguments[1]:{};if(!(0,O.isObject)(e))return{};if(!(0,O.isObject)(t))return e;var r=e.statePlugins;if((0,O.isObject)(r))for(var n in r){var o=r[n];if((0,O.isObject)(o)&&(0,O.isObject)(o.wrapActions)){var a=o.wrapActions;for(var u in a){var i=a[u];Array.isArray(i)||(i=[i],a[u]=i),t&&t.statePlugins&&t.statePlugins[n]&&t.statePlugins[n].wrapActions&&t.statePlugins[n].wrapActions[u]&&(t.statePlugins[n].wrapActions[u]=a[u].concat(t.statePlugins[n].wrapActions[u]))}}}return(0,b.default)(e,t)}function l(e){var t=(0,O.objMap)(e,function(e){return e.reducers});return c(t)}function c(e){var t=Object.keys(e).reduce(function(t,r){return t[r]=f(e[r]),t},{});return Object.keys(t).length?(0,g.combineReducers)(t):T}function f(e){return function(){var t=arguments.length>0&&void 0!==arguments[0]?arguments[0]:new y.Map,r=arguments[1];if(!e)return t;var n=e[r.type];return n?n(t,r):t}}function p(e,t,r){var n=u(e,t,r);return n}Object.defineProperty(t,"__esModule",{value:!0});var d=function(){function e(e,t){for(var r=0;r<t.length;r++){var n=t[r];n.enumerable=n.enumerable||!1,n.configurable=!0,"value"in n&&(n.writable=!0),Object.defineProperty(e,n.key,n)}}return function(t,r,n){return r&&e(t.prototype,r),n&&e(t,n),t}}(),h=r(6),y=r(7),m=n(y),v=r(4),b=n(v),g=r(8),_=r(9),E=n(_),w=r(10),j=r(11),P=n(j),O=r(12),T=function(e){return e},S=function(){function e(){var t=arguments.length>0&&void 0!==arguments[0]?arguments[0]:{};a(this,e),(0,b.default)(this,{state:{},plugins:[],system:{configs:{},fn:{},components:{},rootInjects:{},statePlugins:{}},boundSystem:{},toolbox:{}},t),this.getSystem=this._getSystem.bind(this),this.store=p(T,(0,y.fromJS)(this.state),this.getSystem),this.buildSystem(!1),this.register(this.plugins)}return d(e,[{key:"getStore",value:function(){return this.store}},{key:"register",value:function(e){var t=!(arguments.length>1&&void 0!==arguments[1])||arguments[1],r=i(e,this.getSystem());s(this.system,r),t&&this.buildSystem()}},{key:"buildSystem",value:function(){var e=!(arguments.length>0&&void 0!==arguments[0])||arguments[0],t=this.getStore().dispatch,r=this.getStore().getState;this.boundSystem=Object.assign({},this.getRootInjects(),this.getWrappedAndBoundActions(t),this.getBoundSelectors(r,this.getSystem),this.getStateThunks(r),this.getFn(),this.getConfigs()),e&&this.rebuildReducer()}},{key:"_getSystem",value:function(){return this.boundSystem}},{key:"getRootInjects",value:function(){return Object.assign({getSystem:this.getSystem,getStore:this.getStore.bind(this),getComponents:this.getComponents.bind(this),getState:this.getStore().getState,getConfigs:this._getConfigs.bind(this),Im:m.default},this.system.rootInjects||{})}},{key:"_getConfigs",value:function(){return this.system.configs}},{key:"getConfigs",value:function(){return{configs:this.system.configs}}},{key:"setConfigs",value:function(e){this.system.configs=e}},{key:"rebuildReducer",value:function(){this.store.replaceReducer(l(this.system.statePlugins))}},{key:"getType",value:function(e){var t=e[0].toUpperCase()+e.slice(1);return(0,O.objReduce)(this.system.statePlugins,function(r,n){var a=r[e];if(a)return o({},n+t,a)})}},{key:"getSelectors",value:function(){return this.getType("selectors")}},{key:"getActions",value:function(){var e=this.getType("actions");return(0,O.objMap)(e,function(e){return(0,O.objReduce)(e,function(e,t){if((0,O.isFn)(e))return o({},t,e)})})}},{key:"getWrappedAndBoundActions",value:function(e){var t=this,r=this.getBoundActions(e);return(0,O.objMap)(r,function(e,r){var n=t.system.statePlugins[r.slice(0,-7)].wrapActions;return n?(0,O.objMap)(e,function(e,r){var o=n[r];return o?(Array.isArray(o)||(o=[o]),o.reduce(function(e,r){var n=function(){return r(e,t.getSystem()).apply(void 0,arguments)};if(!(0,O.isFn)(n))throw new TypeError("wrapActions needs to return a function that returns a new function (ie the wrapped action)");return n},e||Function.prototype)):e}):e})}},{key:"getStates",value:function(e){return Object.keys(this.system.statePlugins).reduce(function(t,r){return t[r]=e.get(r),t},{})}},{key:"getStateThunks",value:function(e){return Object.keys(this.system.statePlugins).reduce(function(t,r){return t[r]=function(){return e().get(r)},t},{})}},{key:"getFn",value:function(){return{fn:this.system.fn}}},{key:"getComponents",value:function(e){return"undefined"!=typeof e?this.system.components[e]:this.system.components}},{key:"getBoundSelectors",value:function(e,t){return(0,O.objMap)(this.getSelectors(),function(r,n){var o=[n.slice(0,-9)],a=function(){return e().getIn(o)};return(0,O.objMap)(r,function(e){return function(){for(var r=arguments.length,n=Array(r),o=0;o<r;o++)n[o]=arguments[o];var u=e.apply(null,[a()].concat(n));return"function"==typeof u&&(u=u(t())),u}})})}},{key:"getBoundActions",value:function(e){e=e||this.getStore().dispatch;var t=function e(t){return"function"!=typeof t?(0,O.objMap)(t,function(t){return e(t)}):function(){var e=null;try{e=t.apply(void 0,arguments)}catch(t){e={type:w.NEW_THROWN_ERR,error:!0,payload:(0,E.default)(t)}}finally{return e}}};return(0,O.objMap)(this.getActions(),function(r){return(0,h.bindActionCreators)(t(r),e)})}},{key:"getMapStateToProps",value:function(){var e=this;return function(){var t=Object.assign({},e.getSystem());return t}}},{key:"getMapDispatchToProps",value:function(e){var t=this;return function(r){return(0,b.default)({},t.getWrappedAndBoundActions(r),t.getFn(),e)}}}]),e}();t.default=S},function(e,t){e.exports=require("redux")},function(e,t){e.exports=require("immutable")},function(e,t){e.exports=require("redux-immutable")},function(e,t){e.exports=require("serialize-error")},function(e,t,r){"use strict";function n(e){return e&&e.__esModule?e:{default:e}}function o(e,t){return{type:f,payload:{action:t,error:(0,c.default)(e)}}}function a(e){return{type:p,payload:e}}function u(e){return{type:d,payload:e}}function i(e){return{type:h,payload:e}}function s(){var e=arguments.length>0&&void 0!==arguments[0]?arguments[0]:{};return{type:y,payload:e}}Object.defineProperty(t,"__esModule",{value:!0}),t.CLEAR=t.NEW_AUTH_ERR=t.NEW_SPEC_ERR=t.NEW_THROWN_ERR_BATCH=t.NEW_THROWN_ERR=void 0,t.newThrownErr=o,t.newThrownErrBatch=a,t.newSpecErr=u,t.newAuthErr=i,t.clear=s;var l=r(9),c=n(l),f=t.NEW_THROWN_ERR="err_new_thrown_err",p=t.NEW_THROWN_ERR_BATCH="err_new_thrown_err_batch",d=t.NEW_SPEC_ERR="err_new_spec_err",h=t.NEW_AUTH_ERR="err_new_auth_err",y=t.CLEAR="err_clear"},function(e,t){"use strict";function r(){var e={location:{},history:{},open:function(){},close:function(){},File:function(){}};if("undefined"==typeof window)return e;try{e=window;var t=["File","Blob","FormData"],r=!0,n=!1,o=void 0;try{for(var a,u=t[Symbol.iterator]();!(r=(a=u.next()).done);r=!0){var i=a.value;i in window&&(e[i]=window[i])}}catch(e){n=!0,o=e}finally{try{!r&&u.return&&u.return()}finally{if(n)throw o}}}catch(e){console.error(e)}return e}e.exports=r()},function(e,t,r){(function(e){"use strict";function n(e){return e&&e.__esModule?e:{default:e}}function o(e){return c(e)?V(e)?e.toObject():e:{}}function a(e){return e?e.toArray?e.toArray():s(e):[]}function u(e){return V(e)?e:e instanceof F.default.File?e:c(e)?Array.isArray(e)?S.default.Seq(e).map(u).toList():S.default.Seq(e).map(u).toOrderedMap():e}function i(e,t){var r={};return Object.keys(e).filter(function(t){return"function"==typeof e[t]}).forEach(function(n){return r[n]=e[n].bind(null,t)}),r}function s(e){return Array.isArray(e)?e:[e]}function l(e){return"function"==typeof e}function c(e){return!!e&&"object"===("undefined"==typeof e?"undefined":O(e))}function f(e){return"function"==typeof e}function p(e){return Array.isArray(e)}function d(e,t){return Object.keys(e).reduce(function(r,n){return r[n]=t(e[n],n),r},{})}function h(e,t){return Object.keys(e).reduce(function(r,n){var o=t(e[n],n);return o&&"object"===("undefined"==typeof o?"undefined":O(o))&&Object.assign(r,o),r},{})}function y(e){return function(t){t.dispatch,t.getState;return function(t){return function(r){return"function"==typeof r?r(e()):t(r)}}}}function m(e){var t=e.keySeq();return t.contains(J)?J:t.filter(function(e){return"2"===(e+"")[0]}).sort().first()}function v(e,t){if(!S.default.Iterable.isIterable(e))return S.default.List();var r=e.getIn(Array.isArray(t)?t:[t]);return S.default.List.isList(r)?r:S.default.List()}function b(e){var t,r,n,o,a,u,i,s,l,c,f,p;for(c=/(>)(<)(\/*)/g,p=/[ ]*(.*)[ ]+\n/g,t=/(<.+>)(.+\n)/g,e=e.replace(/\r\n/g,"\n").replace(c,"$1\n$2$3").replace(p,"$1\n").replace(t,"$1\n$2"),n="",s=e.split("\n"),o=0,u="other",f={"single->single":0,"single->closing":-1,"single->opening":0,"single->other":0,"closing->single":0,"closing->closing":-1,"closing->opening":0,"closing->other":0,"opening->single":1,"opening->closing":0,"opening->opening":1,"opening->other":1,"other->single":0,"other->closing":-1,"other->opening":0,"other->other":0},r=function(e){var t,r,a,i,s,l;s={single:Boolean(e.match(/<.+\/>/)),closing:Boolean(e.match(/<\/.+>/)),opening:Boolean(e.match(/<[^!?].*>/))},i=function(){var e;e=[];for(r in s)l=s[r],l&&e.push(r);return e}()[0],i=void 0===i?"other":i,t=u+"->"+i,u=i,a="",o+=f[t],a=function(){var e,t,r,n;for(r=[],n=e=0,t=o;0<=t?e<t:e>t;n=0<=t?++e:--e)r.push(" ");return r}().join(""),"opening->closing"===t?n=n.substr(0,n.length-1)+e+"\n":n+=a+e+"\n"},a=0,i=s.length;a<i;a++)l=s[a],r(l);return n}function g(e){var t=5e3,r=document,n="appendChild",o="test";if(!e)return"";if(e.textContent.length>t)return e.textContent;var a=function(e){for(var t,a,u,i,s,l=e.textContent,c=0,f=l[0],p=1,d=e.innerHTML="",h=0;a=t,t=h<7&&"\\"==t?1:p;){if(p=f,f=l[++c],i=d.length>1,!p||h>8&&"\n"==p||[/\S/[o](p),1,1,!/[$\w]/[o](p),("/"==t||"\n"==t)&&i,'"'==t&&i,"'"==t&&i,l[c-4]+a+t=="-->",a+t=="*/"][h])for(d&&(e[n](s=r.createElement("span")).setAttribute("style",["color: #555; font-weight: bold;","","","color: #555;",""][h?h<3?2:h>6?4:h>3?3:+/^(a(bstract|lias|nd|rguments|rray|s(m|sert)?|uto)|b(ase|egin|ool(ean)?|reak|yte)|c(ase|atch|har|hecked|lass|lone|ompl|onst|ontinue)|de(bugger|cimal|clare|f(ault|er)?|init|l(egate|ete)?)|do|double|e(cho|ls?if|lse(if)?|nd|nsure|num|vent|x(cept|ec|p(licit|ort)|te(nds|nsion|rn)))|f(allthrough|alse|inal(ly)?|ixed|loat|or(each)?|riend|rom|unc(tion)?)|global|goto|guard|i(f|mp(lements|licit|ort)|n(it|clude(_once)?|line|out|stanceof|t(erface|ernal)?)?|s)|l(ambda|et|ock|ong)|m(icrolight|odule|utable)|NaN|n(amespace|ative|ext|ew|il|ot|ull)|o(bject|perator|r|ut|verride)|p(ackage|arams|rivate|rotected|rotocol|ublic)|r(aise|e(adonly|do|f|gister|peat|quire(_once)?|scue|strict|try|turn))|s(byte|ealed|elf|hort|igned|izeof|tatic|tring|truct|ubscript|uper|ynchronized|witch)|t(emplate|hen|his|hrows?|ransient|rue|ry|ype(alias|def|id|name|of))|u(n(checked|def(ined)?|ion|less|signed|til)|se|sing)|v(ar|irtual|oid|olatile)|w(char_t|hen|here|hile|ith)|xor|yield)$/[o](d):0]),s[n](r.createTextNode(d))),u=h&&h<7?h:u,d="",h=11;![1,/[\/{}[(\-+*=<>:;|\\.,?!&@~]/[o](p),/[\])]/[o](p),/[$\w]/[o](p),"/"==p&&u<2&&"<"!=t,'"'==p,"'"==p,p+f+l[c+1]+l[c+2]=="<!--",p+f=="/*",p+f=="//","#"==p][--h];);d+=p}};return a(e)}function _(e){var t=arguments.length>1&&void 0!==arguments[1]?arguments[1]:"key",r=arguments.length>2&&void 0!==arguments[2]?arguments[2]:S.default.Map();if(!S.default.Map.isMap(e)||!e.size)return S.default.List();if(Array.isArray(t)||(t=[t]),t.length<1)return e.merge(r);var n=S.default.List(),o=t[0],a=!0,u=!1,i=void 0;try{for(var s,l=e.entries()[Symbol.iterator]();!(a=(s=l.next()).done);a=!0){var c=s.value,f=P(c,2),p=f[0],d=f[1],h=_(d,t.slice(1),r.set(o,p));n=S.default.List.isList(h)?n.concat(h):n.push(h)}}catch(e){u=!0,i=e}finally{try{!a&&l.return&&l.return()}finally{if(u)throw i}}return n}function E(e){return(0,q.default)((0,R.default)(e))}function w(e){return E(e.replace(/\.[^.\/]*$/,""))}function j(e,t,r){return!!r.find(function(r){return!(0,C.default)(e[r],t[r])})}Object.defineProperty(t,"__esModule",{value:!0}),t.filterConfigs=t.buildFormData=t.sorters=t.btoa=t.parseSeach=t.getSampleSchema=t.validateParam=t.propChecker=t.errorLog=t.memoize=t.isImmutable=void 0;var P=function(){function e(e,t){var r=[],n=!0,o=!1,a=void 0;try{for(var u,i=e[Symbol.iterator]();!(n=(u=i.next()).done)&&(r.push(u.value),!t||r.length!==t);n=!0);}catch(e){o=!0,a=e}finally{try{!n&&i.return&&i.return()}finally{if(o)throw a}}return r}return function(t,r){if(Array.isArray(t))return t;if(Symbol.iterator in Object(t))return e(t,r);throw new TypeError("Invalid attempt to destructure non-iterable instance")}}(),O="function"==typeof Symbol&&"symbol"==typeof Symbol.iterator?function(e){return typeof e}:function(e){return e&&"function"==typeof Symbol&&e.constructor===Symbol&&e!==Symbol.prototype?"symbol":typeof e};t.objectify=o,t.arrayify=a,t.fromJSOrdered=u,t.bindToState=i,t.normalizeArray=s,t.isFn=l,t.isObject=c,t.isFunc=f,t.isArray=p,t.objMap=d,t.objReduce=h,t.systemThunkMiddleware=y,t.defaultStatusCode=m,t.getList=v,t.formatXml=b,t.highlight=g,t.mapToList=_,t.pascalCase=E,t.pascalCaseFilename=w,t.shallowEqualKeys=j;var T=r(7),S=n(T),x=r(17),C=n(x),A=r(18),R=n(A),k=r(32),q=n(k),M=r(49),N=n(M),I=r(82),U=n(I),z=r(71),D=n(z),L=r(154),B=r(11),F=n(B),J="default",V=t.isImmutable=function(e){return S.default.Iterable.isIterable(e)},W=(t.memoize=N.default,t.errorLog=function(e){return function(){return function(t){return function(r){try{t(r)}catch(t){e().errActions.newThrownErr(t,r)}}}}},t.propChecker=function(e,t){var r=arguments.length>2&&void 0!==arguments[2]?arguments[2]:[],n=arguments.length>3&&void 0!==arguments[3]?arguments[3]:[];return Object.keys(e).length!==Object.keys(t).length||((0,U.default)(e,function(e,r){if(n.includes(r))return!1;var o=t[r];return S.default.Iterable.isIterable(e)?!S.default.is(e,o):("object"!==("undefined"==typeof e?"undefined":O(e))||"object"!==("undefined"==typeof o?"undefined":O(o)))&&e!==o})||r.some(function(r){return!(0,D.default)(e[r],t[r])}))},function(e){if(!/^-?\d+(.?\d+)?$/.test(e))return"Value must be a number"}),H=function(e){if(!/^-?\d+$/.test(e))return"Value must be integer"};t.validateParam=function(e,t){var r=[],n=t&&"body"===e.get("in")?e.get("value_xml"):e.get("value"),o=e.get("required"),a=e.get("type");if(o&&(!n||"array"===a&&Array.isArray(n)&&!n.length))return r.push("Required field is not provided"),r;if(!n)return r;if("number"===a){var u=W(n);if(!u)return r;r.push(u)}else if("integer"===a){var i=H(n);if(!i)return r;r.push(i)}else if("array"===a){var s=void 0;if(!n.count())return r;s=e.getIn(["items","type"]),n.forEach(function(e,t){var n=void 0;"number"===s?n=W(e):"integer"===s&&(n=H(e)),n&&r.push({index:t,error:n})})}return r},t.getSampleSchema=function(e){var t=arguments.length>1&&void 0!==arguments[1]?arguments[1]:"",r=arguments.length>2&&void 0!==arguments[2]?arguments[2]:{};if(/xml/.test(t)){if(!e.xml||!e.xml.name){if(e.xml=e.xml||{},!e.$$ref)return e.type||e.items||e.properties||e.additionalProperties?'<?xml version="1.0" encoding="UTF-8"?>\n<!-- XML example cannot be generated -->':null;var n=e.$$ref.match(/\S*\/(\S+)$/);e.xml.name=n[1]}return(0,L.memoizedCreateXMLExample)(e,r)}return JSON.stringify((0,L.memoizedSampleFromSchema)(e,r),null,2)},t.parseSeach=function(){var e={},t=window.location.search;if(""!=t){var r=t.substr(1).split("&");for(var n in r)n=r[n].split("="),e[decodeURIComponent(n[0])]=decodeURIComponent(n[1])}return e},t.btoa=function(t){var r=void 0;return r=t instanceof e?t:new e(t.toString(),"utf-8"),r.toString("base64")},t.sorters={operationsSorter:{alpha:function(e,t){return e.get("path").localeCompare(t.get("path"))},method:function(e,t){return e.get("method").localeCompare(t.get("method"))}}},t.buildFormData=function(e){var t=[];for(var r in e){var n=e[r];void 0!==n&&""!==n&&t.push([r,"=",encodeURIComponent(n).replace(/%20/g,"+")].join(""))}return t.join("&")},t.filterConfigs=function(e,t){var r=void 0,n={};for(r in e)t.indexOf(r)!==-1&&(n[r]=e[r]);return n}}).call(t,r(13).Buffer)},function(e,t,r){(function(e){/*! * The buffer module from node.js, for the browser. * * @author Feross Aboukhadijeh <[email protected]> <http://feross.org> * @license MIT */ "use strict";function n(){try{var e=new Uint8Array(1);return e.__proto__={__proto__:Uint8Array.prototype,foo:function(){return 42}},42===e.foo()&&"function"==typeof e.subarray&&0===e.subarray(1,1).byteLength}catch(e){return!1}}function o(){return u.TYPED_ARRAY_SUPPORT?2147483647:1073741823}function a(e,t){if(o()<t)throw new RangeError("Invalid typed array length");return u.TYPED_ARRAY_SUPPORT?(e=new Uint8Array(t),e.__proto__=u.prototype):(null===e&&(e=new u(t)),e.length=t),e}function u(e,t,r){if(!(u.TYPED_ARRAY_SUPPORT||this instanceof u))return new u(e,t,r);if("number"==typeof e){if("string"==typeof t)throw new Error("If encoding is specified then the first argument must be a string");return c(this,e)}return i(this,e,t,r)}function i(e,t,r,n){if("number"==typeof t)throw new TypeError('"value" argument must not be a number');return"undefined"!=typeof ArrayBuffer&&t instanceof ArrayBuffer?d(e,t,r,n):"string"==typeof t?f(e,t,r):h(e,t)}function s(e){if("number"!=typeof e)throw new TypeError('"size" argument must be a number');if(e<0)throw new RangeError('"size" argument must not be negative')}function l(e,t,r,n){return s(t),t<=0?a(e,t):void 0!==r?"string"==typeof n?a(e,t).fill(r,n):a(e,t).fill(r):a(e,t)}function c(e,t){if(s(t),e=a(e,t<0?0:0|y(t)),!u.TYPED_ARRAY_SUPPORT)for(var r=0;r<t;++r)e[r]=0;return e}function f(e,t,r){if("string"==typeof r&&""!==r||(r="utf8"),!u.isEncoding(r))throw new TypeError('"encoding" must be a valid string encoding');var n=0|v(t,r);e=a(e,n);var o=e.write(t,r);return o!==n&&(e=e.slice(0,o)),e}function p(e,t){var r=t.length<0?0:0|y(t.length);e=a(e,r);for(var n=0;n<r;n+=1)e[n]=255&t[n];return e}function d(e,t,r,n){if(t.byteLength,r<0||t.byteLength<r)throw new RangeError("'offset' is out of bounds");if(t.byteLength<r+(n||0))throw new RangeError("'length' is out of bounds");return t=void 0===r&&void 0===n?new Uint8Array(t):void 0===n?new Uint8Array(t,r):new Uint8Array(t,r,n),u.TYPED_ARRAY_SUPPORT?(e=t,e.__proto__=u.prototype):e=p(e,t),e}function h(e,t){if(u.isBuffer(t)){var r=0|y(t.length);return e=a(e,r),0===e.length?e:(t.copy(e,0,0,r),e)}if(t){if("undefined"!=typeof ArrayBuffer&&t.buffer instanceof ArrayBuffer||"length"in t)return"number"!=typeof t.length||X(t.length)?a(e,0):p(e,t);if("Buffer"===t.type&&Q(t.data))return p(e,t.data)}throw new TypeError("First argument must be a string, Buffer, ArrayBuffer, Array, or array-like object.")}function y(e){if(e>=o())throw new RangeError("Attempt to allocate Buffer larger than maximum size: 0x"+o().toString(16)+" bytes");return 0|e}function m(e){return+e!=e&&(e=0),u.alloc(+e)}function v(e,t){if(u.isBuffer(e))return e.length;if("undefined"!=typeof ArrayBuffer&&"function"==typeof ArrayBuffer.isView&&(ArrayBuffer.isView(e)||e instanceof ArrayBuffer))return e.byteLength;"string"!=typeof e&&(e=""+e);var r=e.length;if(0===r)return 0;for(var n=!1;;)switch(t){case"ascii":case"latin1":case"binary":return r;case"utf8":case"utf-8":case void 0:return W(e).length;case"ucs2":case"ucs-2":case"utf16le":case"utf-16le":return 2*r;case"hex":return r>>>1;case"base64":return $(e).length;default:if(n)return W(e).length;t=(""+t).toLowerCase(),n=!0}}function b(e,t,r){var n=!1;if((void 0===t||t<0)&&(t=0),t>this.length)return"";if((void 0===r||r>this.length)&&(r=this.length),r<=0)return"";if(r>>>=0,t>>>=0,r<=t)return"";for(e||(e="utf8");;)switch(e){case"hex":return q(this,t,r);case"utf8":case"utf-8":return C(this,t,r);case"ascii":return R(this,t,r);case"latin1":case"binary":return k(this,t,r);case"base64":return x(this,t,r);case"ucs2":case"ucs-2":case"utf16le":case"utf-16le":return M(this,t,r);default:if(n)throw new TypeError("Unknown encoding: "+e);e=(e+"").toLowerCase(),n=!0}}function g(e,t,r){var n=e[t];e[t]=e[r],e[r]=n}function _(e,t,r,n,o){if(0===e.length)return-1;if("string"==typeof r?(n=r,r=0):r>2147483647?r=2147483647:r<-2147483648&&(r=-2147483648),r=+r,isNaN(r)&&(r=o?0:e.length-1),r<0&&(r=e.length+r),r>=e.length){if(o)return-1;r=e.length-1}else if(r<0){if(!o)return-1;r=0}if("string"==typeof t&&(t=u.from(t,n)),u.isBuffer(t))return 0===t.length?-1:E(e,t,r,n,o);if("number"==typeof t)return t&=255,u.TYPED_ARRAY_SUPPORT&&"function"==typeof Uint8Array.prototype.indexOf?o?Uint8Array.prototype.indexOf.call(e,t,r):Uint8Array.prototype.lastIndexOf.call(e,t,r):E(e,[t],r,n,o);throw new TypeError("val must be string, number or Buffer")}function E(e,t,r,n,o){function a(e,t){return 1===u?e[t]:e.readUInt16BE(t*u)}var u=1,i=e.length,s=t.length;if(void 0!==n&&(n=String(n).toLowerCase(),"ucs2"===n||"ucs-2"===n||"utf16le"===n||"utf-16le"===n)){if(e.length<2||t.length<2)return-1;u=2,i/=2,s/=2,r/=2}var l;if(o){var c=-1;for(l=r;l<i;l++)if(a(e,l)===a(t,c===-1?0:l-c)){if(c===-1&&(c=l),l-c+1===s)return c*u}else c!==-1&&(l-=l-c),c=-1}else for(r+s>i&&(r=i-s),l=r;l>=0;l--){for(var f=!0,p=0;p<s;p++)if(a(e,l+p)!==a(t,p)){f=!1;break}if(f)return l}return-1}function w(e,t,r,n){r=Number(r)||0;var o=e.length-r;n?(n=Number(n),n>o&&(n=o)):n=o;var a=t.length;if(a%2!==0)throw new TypeError("Invalid hex string");n>a/2&&(n=a/2);for(var u=0;u<n;++u){var i=parseInt(t.substr(2*u,2),16);if(isNaN(i))return u;e[r+u]=i}return u}function j(e,t,r,n){return K(W(t,e.length-r),e,r,n)}function P(e,t,r,n){return K(H(t),e,r,n)}function O(e,t,r,n){return P(e,t,r,n)}function T(e,t,r,n){return K($(t),e,r,n)}function S(e,t,r,n){return K(Y(t,e.length-r),e,r,n)}function x(e,t,r){return 0===t&&r===e.length?G.fromByteArray(e):G.fromByteArray(e.slice(t,r))}function C(e,t,r){r=Math.min(e.length,r);for(var n=[],o=t;o<r;){var a=e[o],u=null,i=a>239?4:a>223?3:a>191?2:1;if(o+i<=r){var s,l,c,f;switch(i){case 1:a<128&&(u=a);break;case 2:s=e[o+1],128===(192&s)&&(f=(31&a)<<6|63&s,f>127&&(u=f));break;case 3:s=e[o+1],l=e[o+2],128===(192&s)&&128===(192&l)&&(f=(15&a)<<12|(63&s)<<6|63&l,f>2047&&(f<55296||f>57343)&&(u=f));break;case 4:s=e[o+1],l=e[o+2],c=e[o+3],128===(192&s)&&128===(192&l)&&128===(192&c)&&(f=(15&a)<<18|(63&s)<<12|(63&l)<<6|63&c,f>65535&&f<1114112&&(u=f))}}null===u?(u=65533,i=1):u>65535&&(u-=65536,n.push(u>>>10&1023|55296),u=56320|1023&u),n.push(u),o+=i}return A(n)}function A(e){var t=e.length;if(t<=ee)return String.fromCharCode.apply(String,e);for(var r="",n=0;n<t;)r+=String.fromCharCode.apply(String,e.slice(n,n+=ee));return r}function R(e,t,r){var n="";r=Math.min(e.length,r);for(var o=t;o<r;++o)n+=String.fromCharCode(127&e[o]);return n}function k(e,t,r){var n="";r=Math.min(e.length,r);for(var o=t;o<r;++o)n+=String.fromCharCode(e[o]);return n}function q(e,t,r){var n=e.length;(!t||t<0)&&(t=0),(!r||r<0||r>n)&&(r=n);for(var o="",a=t;a<r;++a)o+=V(e[a]);return o}function M(e,t,r){for(var n=e.slice(t,r),o="",a=0;a<n.length;a+=2)o+=String.fromCharCode(n[a]+256*n[a+1]);return o}function N(e,t,r){if(e%1!==0||e<0)throw new RangeError("offset is not uint");if(e+t>r)throw new RangeError("Trying to access beyond buffer length")}function I(e,t,r,n,o,a){if(!u.isBuffer(e))throw new TypeError('"buffer" argument must be a Buffer instance');if(t>o||t<a)throw new RangeError('"value" argument is out of bounds');if(r+n>e.length)throw new RangeError("Index out of range")}function U(e,t,r,n){t<0&&(t=65535+t+1);for(var o=0,a=Math.min(e.length-r,2);o<a;++o)e[r+o]=(t&255<<8*(n?o:1-o))>>>8*(n?o:1-o)}function z(e,t,r,n){t<0&&(t=4294967295+t+1);for(var o=0,a=Math.min(e.length-r,4);o<a;++o)e[r+o]=t>>>8*(n?o:3-o)&255}function D(e,t,r,n,o,a){if(r+n>e.length)throw new RangeError("Index out of range");if(r<0)throw new RangeError("Index out of range")}function L(e,t,r,n,o){return o||D(e,t,r,4,3.4028234663852886e38,-3.4028234663852886e38),Z.write(e,t,r,n,23,4),r+4}function B(e,t,r,n,o){return o||D(e,t,r,8,1.7976931348623157e308,-1.7976931348623157e308),Z.write(e,t,r,n,52,8),r+8}function F(e){if(e=J(e).replace(te,""),e.length<2)return"";for(;e.length%4!==0;)e+="=";return e}function J(e){return e.trim?e.trim():e.replace(/^\s+|\s+$/g,"")}function V(e){return e<16?"0"+e.toString(16):e.toString(16)}function W(e,t){t=t||1/0;for(var r,n=e.length,o=null,a=[],u=0;u<n;++u){if(r=e.charCodeAt(u),r>55295&&r<57344){if(!o){if(r>56319){(t-=3)>-1&&a.push(239,191,189);continue}if(u+1===n){(t-=3)>-1&&a.push(239,191,189);continue}o=r;continue}if(r<56320){(t-=3)>-1&&a.push(239,191,189),o=r;continue}r=(o-55296<<10|r-56320)+65536}else o&&(t-=3)>-1&&a.push(239,191,189);if(o=null,r<128){if((t-=1)<0)break;a.push(r)}else if(r<2048){if((t-=2)<0)break;a.push(r>>6|192,63&r|128)}else if(r<65536){if((t-=3)<0)break;a.push(r>>12|224,r>>6&63|128,63&r|128)}else{if(!(r<1114112))throw new Error("Invalid code point");if((t-=4)<0)break;a.push(r>>18|240,r>>12&63|128,r>>6&63|128,63&r|128)}}return a}function H(e){for(var t=[],r=0;r<e.length;++r)t.push(255&e.charCodeAt(r));return t}function Y(e,t){for(var r,n,o,a=[],u=0;u<e.length&&!((t-=2)<0);++u)r=e.charCodeAt(u),n=r>>8,o=r%256,a.push(o),a.push(n);return a}function $(e){return G.toByteArray(F(e))}function K(e,t,r,n){for(var o=0;o<n&&!(o+r>=t.length||o>=e.length);++o)t[o+r]=e[o];return o}function X(e){return e!==e}var G=r(14),Z=r(15),Q=r(16);t.Buffer=u,t.SlowBuffer=m,t.INSPECT_MAX_BYTES=50,u.TYPED_ARRAY_SUPPORT=void 0!==e.TYPED_ARRAY_SUPPORT?e.TYPED_ARRAY_SUPPORT:n(),t.kMaxLength=o(),u.poolSize=8192,u._augment=function(e){return e.__proto__=u.prototype,e},u.from=function(e,t,r){return i(null,e,t,r)},u.TYPED_ARRAY_SUPPORT&&(u.prototype.__proto__=Uint8Array.prototype,u.__proto__=Uint8Array,"undefined"!=typeof Symbol&&Symbol.species&&u[Symbol.species]===u&&Object.defineProperty(u,Symbol.species,{value:null,configurable:!0})),u.alloc=function(e,t,r){return l(null,e,t,r)},u.allocUnsafe=function(e){return c(null,e)},u.allocUnsafeSlow=function(e){return c(null,e)},u.isBuffer=function(e){return!(null==e||!e._isBuffer)},u.compare=function(e,t){if(!u.isBuffer(e)||!u.isBuffer(t))throw new TypeError("Arguments must be Buffers");if(e===t)return 0;for(var r=e.length,n=t.length,o=0,a=Math.min(r,n);o<a;++o)if(e[o]!==t[o]){r=e[o],n=t[o];break}return r<n?-1:n<r?1:0},u.isEncoding=function(e){switch(String(e).toLowerCase()){case"hex":case"utf8":case"utf-8":case"ascii":case"latin1":case"binary":case"base64":case"ucs2":case"ucs-2":case"utf16le":case"utf-16le":return!0;default:return!1}},u.concat=function(e,t){if(!Q(e))throw new TypeError('"list" argument must be an Array of Buffers');if(0===e.length)return u.alloc(0);var r;if(void 0===t)for(t=0,r=0;r<e.length;++r)t+=e[r].length;var n=u.allocUnsafe(t),o=0;for(r=0;r<e.length;++r){var a=e[r];if(!u.isBuffer(a))throw new TypeError('"list" argument must be an Array of Buffers');a.copy(n,o),o+=a.length}return n},u.byteLength=v,u.prototype._isBuffer=!0,u.prototype.swap16=function(){var e=this.length;if(e%2!==0)throw new RangeError("Buffer size must be a multiple of 16-bits");for(var t=0;t<e;t+=2)g(this,t,t+1);return this},u.prototype.swap32=function(){var e=this.length;if(e%4!==0)throw new RangeError("Buffer size must be a multiple of 32-bits");for(var t=0;t<e;t+=4)g(this,t,t+3),g(this,t+1,t+2);return this},u.prototype.swap64=function(){var e=this.length;if(e%8!==0)throw new RangeError("Buffer size must be a multiple of 64-bits");for(var t=0;t<e;t+=8)g(this,t,t+7),g(this,t+1,t+6),g(this,t+2,t+5),g(this,t+3,t+4);return this},u.prototype.toString=function(){var e=0|this.length;return 0===e?"":0===arguments.length?C(this,0,e):b.apply(this,arguments)},u.prototype.equals=function(e){if(!u.isBuffer(e))throw new TypeError("Argument must be a Buffer");return this===e||0===u.compare(this,e)},u.prototype.inspect=function(){var e="",r=t.INSPECT_MAX_BYTES;return this.length>0&&(e=this.toString("hex",0,r).match(/.{2}/g).join(" "),this.length>r&&(e+=" ... ")),"<Buffer "+e+">"},u.prototype.compare=function(e,t,r,n,o){if(!u.isBuffer(e))throw new TypeError("Argument must be a Buffer");if(void 0===t&&(t=0),void 0===r&&(r=e?e.length:0),void 0===n&&(n=0),void 0===o&&(o=this.length),t<0||r>e.length||n<0||o>this.length)throw new RangeError("out of range index");if(n>=o&&t>=r)return 0;if(n>=o)return-1;if(t>=r)return 1;if(t>>>=0,r>>>=0,n>>>=0,o>>>=0,this===e)return 0;for(var a=o-n,i=r-t,s=Math.min(a,i),l=this.slice(n,o),c=e.slice(t,r),f=0;f<s;++f)if(l[f]!==c[f]){a=l[f],i=c[f];break}return a<i?-1:i<a?1:0},u.prototype.includes=function(e,t,r){return this.indexOf(e,t,r)!==-1},u.prototype.indexOf=function(e,t,r){return _(this,e,t,r,!0)},u.prototype.lastIndexOf=function(e,t,r){return _(this,e,t,r,!1)},u.prototype.write=function(e,t,r,n){if(void 0===t)n="utf8",r=this.length,t=0;else if(void 0===r&&"string"==typeof t)n=t,r=this.length,t=0;else{if(!isFinite(t))throw new Error("Buffer.write(string, encoding, offset[, length]) is no longer supported");t|=0,isFinite(r)?(r|=0,void 0===n&&(n="utf8")):(n=r,r=void 0)}var o=this.length-t;if((void 0===r||r>o)&&(r=o),e.length>0&&(r<0||t<0)||t>this.length)throw new RangeError("Attempt to write outside buffer bounds");n||(n="utf8");for(var a=!1;;)switch(n){case"hex":return w(this,e,t,r);case"utf8":case"utf-8":return j(this,e,t,r);case"ascii":return P(this,e,t,r);case"latin1":case"binary":return O(this,e,t,r);case"base64":return T(this,e,t,r);case"ucs2":case"ucs-2":case"utf16le":case"utf-16le":return S(this,e,t,r);default:if(a)throw new TypeError("Unknown encoding: "+n);n=(""+n).toLowerCase(),a=!0}},u.prototype.toJSON=function(){return{type:"Buffer",data:Array.prototype.slice.call(this._arr||this,0)}};var ee=4096;u.prototype.slice=function(e,t){var r=this.length;e=~~e,t=void 0===t?r:~~t,e<0?(e+=r,e<0&&(e=0)):e>r&&(e=r),t<0?(t+=r,t<0&&(t=0)):t>r&&(t=r),t<e&&(t=e);var n;if(u.TYPED_ARRAY_SUPPORT)n=this.subarray(e,t),n.__proto__=u.prototype;else{var o=t-e;n=new u(o,void 0);for(var a=0;a<o;++a)n[a]=this[a+e]}return n},u.prototype.readUIntLE=function(e,t,r){e|=0,t|=0,r||N(e,t,this.length);for(var n=this[e],o=1,a=0;++a<t&&(o*=256);)n+=this[e+a]*o;return n},u.prototype.readUIntBE=function(e,t,r){e|=0,t|=0,r||N(e,t,this.length);for(var n=this[e+--t],o=1;t>0&&(o*=256);)n+=this[e+--t]*o;return n},u.prototype.readUInt8=function(e,t){return t||N(e,1,this.length),this[e]},u.prototype.readUInt16LE=function(e,t){return t||N(e,2,this.length),this[e]|this[e+1]<<8},u.prototype.readUInt16BE=function(e,t){return t||N(e,2,this.length),this[e]<<8|this[e+1]},u.prototype.readUInt32LE=function(e,t){return t||N(e,4,this.length),(this[e]|this[e+1]<<8|this[e+2]<<16)+16777216*this[e+3]},u.prototype.readUInt32BE=function(e,t){return t||N(e,4,this.length),16777216*this[e]+(this[e+1]<<16|this[e+2]<<8|this[e+3])},u.prototype.readIntLE=function(e,t,r){e|=0,t|=0,r||N(e,t,this.length);for(var n=this[e],o=1,a=0;++a<t&&(o*=256);)n+=this[e+a]*o;return o*=128,n>=o&&(n-=Math.pow(2,8*t)),n},u.prototype.readIntBE=function(e,t,r){e|=0,t|=0,r||N(e,t,this.length);for(var n=t,o=1,a=this[e+--n];n>0&&(o*=256);)a+=this[e+--n]*o;return o*=128,a>=o&&(a-=Math.pow(2,8*t)),a},u.prototype.readInt8=function(e,t){return t||N(e,1,this.length),128&this[e]?(255-this[e]+1)*-1:this[e]},u.prototype.readInt16LE=function(e,t){t||N(e,2,this.length);var r=this[e]|this[e+1]<<8;return 32768&r?4294901760|r:r},u.prototype.readInt16BE=function(e,t){t||N(e,2,this.length);var r=this[e+1]|this[e]<<8;return 32768&r?4294901760|r:r},u.prototype.readInt32LE=function(e,t){return t||N(e,4,this.length),this[e]|this[e+1]<<8|this[e+2]<<16|this[e+3]<<24},u.prototype.readInt32BE=function(e,t){return t||N(e,4,this.length),this[e]<<24|this[e+1]<<16|this[e+2]<<8|this[e+3]},u.prototype.readFloatLE=function(e,t){return t||N(e,4,this.length),Z.read(this,e,!0,23,4)},u.prototype.readFloatBE=function(e,t){return t||N(e,4,this.length),Z.read(this,e,!1,23,4)},u.prototype.readDoubleLE=function(e,t){return t||N(e,8,this.length),Z.read(this,e,!0,52,8)},u.prototype.readDoubleBE=function(e,t){return t||N(e,8,this.length),Z.read(this,e,!1,52,8)},u.prototype.writeUIntLE=function(e,t,r,n){if(e=+e,t|=0,r|=0,!n){var o=Math.pow(2,8*r)-1;I(this,e,t,r,o,0)}var a=1,u=0;for(this[t]=255&e;++u<r&&(a*=256);)this[t+u]=e/a&255;return t+r},u.prototype.writeUIntBE=function(e,t,r,n){if(e=+e,t|=0,r|=0,!n){var o=Math.pow(2,8*r)-1;I(this,e,t,r,o,0)}var a=r-1,u=1;for(this[t+a]=255&e;--a>=0&&(u*=256);)this[t+a]=e/u&255;return t+r},u.prototype.writeUInt8=function(e,t,r){return e=+e,t|=0,r||I(this,e,t,1,255,0),u.TYPED_ARRAY_SUPPORT||(e=Math.floor(e)),this[t]=255&e,t+1},u.prototype.writeUInt16LE=function(e,t,r){return e=+e,t|=0,r||I(this,e,t,2,65535,0),u.TYPED_ARRAY_SUPPORT?(this[t]=255&e,this[t+1]=e>>>8):U(this,e,t,!0),t+2},u.prototype.writeUInt16BE=function(e,t,r){return e=+e,t|=0,r||I(this,e,t,2,65535,0),u.TYPED_ARRAY_SUPPORT?(this[t]=e>>>8,this[t+1]=255&e):U(this,e,t,!1),t+2},u.prototype.writeUInt32LE=function(e,t,r){return e=+e,t|=0,r||I(this,e,t,4,4294967295,0),u.TYPED_ARRAY_SUPPORT?(this[t+3]=e>>>24,this[t+2]=e>>>16,this[t+1]=e>>>8,this[t]=255&e):z(this,e,t,!0),t+4},u.prototype.writeUInt32BE=function(e,t,r){return e=+e,t|=0,r||I(this,e,t,4,4294967295,0),u.TYPED_ARRAY_SUPPORT?(this[t]=e>>>24,this[t+1]=e>>>16,this[t+2]=e>>>8,this[t+3]=255&e):z(this,e,t,!1),t+4},u.prototype.writeIntLE=function(e,t,r,n){if(e=+e,t|=0,!n){var o=Math.pow(2,8*r-1);I(this,e,t,r,o-1,-o)}var a=0,u=1,i=0;for(this[t]=255&e;++a<r&&(u*=256);)e<0&&0===i&&0!==this[t+a-1]&&(i=1),this[t+a]=(e/u>>0)-i&255;return t+r},u.prototype.writeIntBE=function(e,t,r,n){if(e=+e,t|=0,!n){var o=Math.pow(2,8*r-1);I(this,e,t,r,o-1,-o)}var a=r-1,u=1,i=0;for(this[t+a]=255&e;--a>=0&&(u*=256);)e<0&&0===i&&0!==this[t+a+1]&&(i=1),this[t+a]=(e/u>>0)-i&255;return t+r},u.prototype.writeInt8=function(e,t,r){return e=+e,t|=0,r||I(this,e,t,1,127,-128),u.TYPED_ARRAY_SUPPORT||(e=Math.floor(e)),e<0&&(e=255+e+1),this[t]=255&e,t+1},u.prototype.writeInt16LE=function(e,t,r){return e=+e,t|=0,r||I(this,e,t,2,32767,-32768),u.TYPED_ARRAY_SUPPORT?(this[t]=255&e,this[t+1]=e>>>8):U(this,e,t,!0),t+2},u.prototype.writeInt16BE=function(e,t,r){return e=+e,t|=0,r||I(this,e,t,2,32767,-32768),u.TYPED_ARRAY_SUPPORT?(this[t]=e>>>8,this[t+1]=255&e):U(this,e,t,!1),t+2},u.prototype.writeInt32LE=function(e,t,r){return e=+e,t|=0,r||I(this,e,t,4,2147483647,-2147483648),u.TYPED_ARRAY_SUPPORT?(this[t]=255&e,this[t+1]=e>>>8,this[t+2]=e>>>16,this[t+3]=e>>>24):z(this,e,t,!0),t+4},u.prototype.writeInt32BE=function(e,t,r){return e=+e,t|=0,r||I(this,e,t,4,2147483647,-2147483648),e<0&&(e=4294967295+e+1),u.TYPED_ARRAY_SUPPORT?(this[t]=e>>>24,this[t+1]=e>>>16,this[t+2]=e>>>8,this[t+3]=255&e):z(this,e,t,!1),t+4},u.prototype.writeFloatLE=function(e,t,r){return L(this,e,t,!0,r)},u.prototype.writeFloatBE=function(e,t,r){return L(this,e,t,!1,r)},u.prototype.writeDoubleLE=function(e,t,r){return B(this,e,t,!0,r)},u.prototype.writeDoubleBE=function(e,t,r){return B(this,e,t,!1,r)},u.prototype.copy=function(e,t,r,n){if(r||(r=0),n||0===n||(n=this.length),t>=e.length&&(t=e.length),t||(t=0),n>0&&n<r&&(n=r),n===r)return 0;if(0===e.length||0===this.length)return 0;if(t<0)throw new RangeError("targetStart out of bounds");if(r<0||r>=this.length)throw new RangeError("sourceStart out of bounds");if(n<0)throw new RangeError("sourceEnd out of bounds");n>this.length&&(n=this.length),e.length-t<n-r&&(n=e.length-t+r);var o,a=n-r;if(this===e&&r<t&&t<n)for(o=a-1;o>=0;--o)e[o+t]=this[o+r];else if(a<1e3||!u.TYPED_ARRAY_SUPPORT)for(o=0;o<a;++o)e[o+t]=this[o+r];else Uint8Array.prototype.set.call(e,this.subarray(r,r+a),t);return a},u.prototype.fill=function(e,t,r,n){if("string"==typeof e){if("string"==typeof t?(n=t,t=0,r=this.length):"string"==typeof r&&(n=r,r=this.length),1===e.length){var o=e.charCodeAt(0);o<256&&(e=o)}if(void 0!==n&&"string"!=typeof n)throw new TypeError("encoding must be a string");if("string"==typeof n&&!u.isEncoding(n))throw new TypeError("Unknown encoding: "+n)}else"number"==typeof e&&(e&=255);if(t<0||this.length<t||this.length<r)throw new RangeError("Out of range index");if(r<=t)return this;t>>>=0,r=void 0===r?this.length:r>>>0,e||(e=0);var a;if("number"==typeof e)for(a=t;a<r;++a)this[a]=e;else{var i=u.isBuffer(e)?e:W(new u(e,n).toString()),s=i.length;for(a=0;a<r-t;++a)this[a+t]=i[a%s]}return this};var te=/[^+\/0-9A-Za-z-_]/g}).call(t,function(){return this}())},function(e,t){e.exports=require("base64-js")},function(e,t){e.exports=require("ieee754")},function(e,t){e.exports=require("isarray")},function(e,t){e.exports=require("shallowequal")},function(e,t,r){var n=r(19),o=r(40),a=o(function(e,t,r){return t=t.toLowerCase(),e+(r?n(t):t)});e.exports=a},function(e,t,r){function n(e){return a(o(e).toLowerCase())}var o=r(20),a=r(32);e.exports=n},function(e,t,r){function n(e){return null==e?"":o(e)}var o=r(21);e.exports=n},function(e,t,r){function n(e){if("string"==typeof e)return e;if(u(e))return a(e,n)+"";if(i(e))return c?c.call(e):"";var t=e+"";return"0"==t&&1/e==-s?"-0":t}var o=r(22),a=r(25),u=r(26),i=r(27),s=1/0,l=o?o.prototype:void 0,c=l?l.toString:void 0;e.exports=n},function(e,t,r){var n=r(23),o=n.Symbol;e.exports=o},function(e,t,r){var n=r(24),o="object"==typeof self&&self&&self.Object===Object&&self,a=n||o||Function("return this")();e.exports=a},function(e,t){(function(t){var r="object"==typeof t&&t&&t.Object===Object&&t;e.exports=r}).call(t,function(){return this}())},function(e,t){function r(e,t){for(var r=-1,n=null==e?0:e.length,o=Array(n);++r<n;)o[r]=t(e[r],r,e);return o}e.exports=r},function(e,t){var r=Array.isArray;e.exports=r},function(e,t,r){function n(e){return"symbol"==typeof e||a(e)&&o(e)==u}var o=r(28),a=r(31),u="[object Symbol]";e.exports=n},function(e,t,r){function n(e){return null==e?void 0===e?s:i:(e=Object(e),l&&l in e?a(e):u(e))}var o=r(22),a=r(29),u=r(30),i="[object Null]",s="[object Undefined]",l=o?o.toStringTag:void 0;e.exports=n},function(e,t,r){function n(e){var t=u.call(e,s),r=e[s];try{e[s]=void 0;var n=!0}catch(e){}var o=i.call(e);return n&&(t?e[s]=r:delete e[s]),o}var o=r(22),a=Object.prototype,u=a.hasOwnProperty,i=a.toString,s=o?o.toStringTag:void 0;e.exports=n},function(e,t){function r(e){return o.call(e)}var n=Object.prototype,o=n.toString;e.exports=r},function(e,t){function r(e){return null!=e&&"object"==typeof e}e.exports=r},function(e,t,r){var n=r(33),o=n("toUpperCase");e.exports=o},function(e,t,r){function n(e){return function(t){t=i(t);var r=a(t)?u(t):void 0,n=r?r[0]:t.charAt(0),s=r?o(r,1).join(""):t.slice(1);return n[e]()+s}}var o=r(34),a=r(36),u=r(37),i=r(20);e.exports=n},function(e,t,r){function n(e,t,r){var n=e.length;return r=void 0===r?n:r,!t&&r>=n?e:o(e,t,r)}var o=r(35);e.exports=n},function(e,t){function r(e,t,r){var n=-1,o=e.length;t<0&&(t=-t>o?0:o+t),r=r>o?o:r,r<0&&(r+=o),o=t>r?0:r-t>>>0,t>>>=0;for(var a=Array(o);++n<o;)a[n]=e[n+t];return a}e.exports=r},function(e,t){function r(e){return c.test(e)}var n="\\ud800-\\udfff",o="\\u0300-\\u036f",a="\\ufe20-\\ufe2f",u="\\u20d0-\\u20ff",i=o+a+u,s="\\ufe0e\\ufe0f",l="\\u200d",c=RegExp("["+l+n+i+s+"]");e.exports=r},function(e,t,r){function n(e){return a(e)?u(e):o(e)}var o=r(38),a=r(36),u=r(39);e.exports=n},function(e,t){function r(e){return e.split("")}e.exports=r},function(e,t){function r(e){return e.match(w)||[]}var n="\\ud800-\\udfff",o="\\u0300-\\u036f",a="\\ufe20-\\ufe2f",u="\\u20d0-\\u20ff",i=o+a+u,s="\\ufe0e\\ufe0f",l="["+n+"]",c="["+i+"]",f="\\ud83c[\\udffb-\\udfff]",p="(?:"+c+"|"+f+")",d="[^"+n+"]",h="(?:\\ud83c[\\udde6-\\uddff]){2}",y="[\\ud800-\\udbff][\\udc00-\\udfff]",m="\\u200d",v=p+"?",b="["+s+"]?",g="(?:"+m+"(?:"+[d,h,y].join("|")+")"+b+v+")*",_=b+v+g,E="(?:"+[d+c+"?",c,h,y,l].join("|")+")",w=RegExp(f+"(?="+f+")|"+E+_,"g");e.exports=r},function(e,t,r){function n(e){return function(t){return o(u(a(t).replace(s,"")),e,"")}}var o=r(41),a=r(42),u=r(45),i="['’]",s=RegExp(i,"g");e.exports=n},function(e,t){function r(e,t,r,n){var o=-1,a=null==e?0:e.length;for(n&&a&&(r=e[++o]);++o<a;)r=t(r,e[o],o,e);return r}e.exports=r},function(e,t,r){function n(e){return e=a(e),e&&e.replace(u,o).replace(p,"")}var o=r(43),a=r(20),u=/[\xc0-\xd6\xd8-\xf6\xf8-\xff\u0100-\u017f]/g,i="\\u0300-\\u036f",s="\\ufe20-\\ufe2f",l="\\u20d0-\\u20ff",c=i+s+l,f="["+c+"]",p=RegExp(f,"g");e.exports=n},function(e,t,r){var n=r(44),o={"À":"A","Á":"A","Â":"A","Ã":"A","Ä":"A","Å":"A","à":"a","á":"a","â":"a","ã":"a","ä":"a","å":"a","Ç":"C","ç":"c","Ð":"D","ð":"d","È":"E","É":"E","Ê":"E","Ë":"E","è":"e","é":"e","ê":"e","ë":"e","Ì":"I","Í":"I","Î":"I","Ï":"I","ì":"i","í":"i","î":"i","ï":"i","Ñ":"N","ñ":"n","Ò":"O","Ó":"O","Ô":"O","Õ":"O","Ö":"O","Ø":"O","ò":"o","ó":"o","ô":"o","õ":"o","ö":"o","ø":"o","Ù":"U","Ú":"U","Û":"U","Ü":"U","ù":"u","ú":"u","û":"u","ü":"u","Ý":"Y","ý":"y","ÿ":"y","Æ":"Ae","æ":"ae","Þ":"Th","þ":"th","ß":"ss","Ā":"A","Ă":"A","Ą":"A","ā":"a","ă":"a","ą":"a","Ć":"C","Ĉ":"C","Ċ":"C","Č":"C","ć":"c","ĉ":"c","ċ":"c","č":"c","Ď":"D","Đ":"D","ď":"d","đ":"d","Ē":"E","Ĕ":"E","Ė":"E","Ę":"E","Ě":"E","ē":"e","ĕ":"e","ė":"e","ę":"e","ě":"e","Ĝ":"G","Ğ":"G","Ġ":"G","Ģ":"G","ĝ":"g","ğ":"g","ġ":"g","ģ":"g","Ĥ":"H","Ħ":"H","ĥ":"h","ħ":"h","Ĩ":"I","Ī":"I","Ĭ":"I","Į":"I","İ":"I","ĩ":"i","ī":"i","ĭ":"i","į":"i","ı":"i","Ĵ":"J","ĵ":"j","Ķ":"K","ķ":"k","ĸ":"k","Ĺ":"L","Ļ":"L","Ľ":"L","Ŀ":"L","Ł":"L","ĺ":"l","ļ":"l","ľ":"l","ŀ":"l","ł":"l","Ń":"N","Ņ":"N","Ň":"N","Ŋ":"N","ń":"n","ņ":"n","ň":"n","ŋ":"n","Ō":"O","Ŏ":"O","Ő":"O","ō":"o","ŏ":"o","ő":"o","Ŕ":"R","Ŗ":"R","Ř":"R","ŕ":"r","ŗ":"r","ř":"r","Ś":"S","Ŝ":"S","Ş":"S","Š":"S","ś":"s","ŝ":"s","ş":"s","š":"s","Ţ":"T","Ť":"T","Ŧ":"T","ţ":"t","ť":"t","ŧ":"t","Ũ":"U","Ū":"U","Ŭ":"U","Ů":"U","Ű":"U","Ų":"U","ũ":"u","ū":"u","ŭ":"u","ů":"u","ű":"u","ų":"u","Ŵ":"W","ŵ":"w","Ŷ":"Y","ŷ":"y","Ÿ":"Y","Ź":"Z","Ż":"Z","Ž":"Z","ź":"z","ż":"z","ž":"z","IJ":"IJ","ij":"ij","Œ":"Oe","œ":"oe","ʼn":"'n","ſ":"s"},a=n(o);e.exports=a},function(e,t){function r(e){return function(t){return null==e?void 0:e[t]}}e.exports=r},function(e,t,r){function n(e,t,r){return e=u(e),t=r?void 0:t,void 0===t?a(e)?i(e):o(e):e.match(t)||[]}var o=r(46),a=r(47),u=r(20),i=r(48);e.exports=n},function(e,t){function r(e){return e.match(n)||[]}var n=/[^\x00-\x2f\x3a-\x40\x5b-\x60\x7b-\x7f]+/g;e.exports=r},function(e,t){function r(e){return n.test(e)}var n=/[a-z][A-Z]|[A-Z]{2,}[a-z]|[0-9][a-zA-Z]|[a-zA-Z][0-9]|[^a-zA-Z0-9 ]/;e.exports=r},function(e,t){function r(e){return e.match(F)||[]}var n="\\ud800-\\udfff",o="\\u0300-\\u036f",a="\\ufe20-\\ufe2f",u="\\u20d0-\\u20ff",i=o+a+u,s="\\u2700-\\u27bf",l="a-z\\xdf-\\xf6\\xf8-\\xff",c="\\xac\\xb1\\xd7\\xf7",f="\\x00-\\x2f\\x3a-\\x40\\x5b-\\x60\\x7b-\\xbf",p="\\u2000-\\u206f",d=" \\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",h="A-Z\\xc0-\\xd6\\xd8-\\xde",y="\\ufe0e\\ufe0f",m=c+f+p+d,v="['’]",b="["+m+"]",g="["+i+"]",_="\\d+",E="["+s+"]",w="["+l+"]",j="[^"+n+m+_+s+l+h+"]",P="\\ud83c[\\udffb-\\udfff]",O="(?:"+g+"|"+P+")",T="[^"+n+"]",S="(?:\\ud83c[\\udde6-\\uddff]){2}",x="[\\ud800-\\udbff][\\udc00-\\udfff]",C="["+h+"]",A="\\u200d",R="(?:"+w+"|"+j+")",k="(?:"+C+"|"+j+")",q="(?:"+v+"(?:d|ll|m|re|s|t|ve))?",M="(?:"+v+"(?:D|LL|M|RE|S|T|VE))?",N=O+"?",I="["+y+"]?",U="(?:"+A+"(?:"+[T,S,x].join("|")+")"+I+N+")*",z="\\d*(?:(?:1st|2nd|3rd|(?![123])\\dth)\\b)",D="\\d*(?:(?:1ST|2ND|3RD|(?![123])\\dTH)\\b)",L=I+N+U,B="(?:"+[E,S,x].join("|")+")"+L,F=RegExp([C+"?"+w+"+"+q+"(?="+[b,C,"$"].join("|")+")",k+"+"+M+"(?="+[b,C+R,"$"].join("|")+")",C+"?"+R+"+"+q,C+"+"+M,D,z,_,B].join("|"),"g");e.exports=r},function(e,t,r){function n(e,t){if("function"!=typeof e||null!=t&&"function"!=typeof t)throw new TypeError(a);var r=function(){var n=arguments,o=t?t.apply(this,n):n[0],a=r.cache;if(a.has(o))return a.get(o);var u=e.apply(this,n);return r.cache=a.set(o,u)||a,u};return r.cache=new(n.Cache||o),r}var o=r(50),a="Expected a function";n.Cache=o,e.exports=n},function(e,t,r){function n(e){var t=-1,r=null==e?0:e.length;for(this.clear();++t<r;){var n=e[t];this.set(n[0],n[1])}}var o=r(51),a=r(76),u=r(79),i=r(80),s=r(81);n.prototype.clear=o,n.prototype.delete=a,n.prototype.get=u,n.prototype.has=i,n.prototype.set=s,e.exports=n},function(e,t,r){function n(){this.size=0,this.__data__={hash:new o,map:new(u||a),string:new o}}var o=r(52),a=r(67),u=r(75);e.exports=n},function(e,t,r){function n(e){var t=-1,r=null==e?0:e.length;for(this.clear();++t<r;){var n=e[t];this.set(n[0],n[1])}}var o=r(53),a=r(63),u=r(64),i=r(65),s=r(66);n.prototype.clear=o,n.prototype.delete=a,n.prototype.get=u,n.prototype.has=i,n.prototype.set=s,e.exports=n},function(e,t,r){function n(){this.__data__=o?o(null):{},this.size=0}var o=r(54);e.exports=n},function(e,t,r){var n=r(55),o=n(Object,"create");e.exports=o},function(e,t,r){function n(e,t){var r=a(e,t);return o(r)?r:void 0}var o=r(56),a=r(62);e.exports=n},function(e,t,r){function n(e){if(!u(e)||a(e))return!1;var t=o(e)?h:l;return t.test(i(e))}var o=r(57),a=r(59),u=r(58),i=r(61),s=/[\\^$.*+?()[\]{}|]/g,l=/^\[object .+?Constructor\]$/,c=Function.prototype,f=Object.prototype,p=c.toString,d=f.hasOwnProperty,h=RegExp("^"+p.call(d).replace(s,"\\$&").replace(/hasOwnProperty|(function).*?(?=\\\()| for .+?(?=\\\])/g,"$1.*?")+"$");e.exports=n},function(e,t,r){function n(e){if(!a(e))return!1;var t=o(e);return t==i||t==s||t==u||t==l}var o=r(28),a=r(58),u="[object AsyncFunction]",i="[object Function]",s="[object GeneratorFunction]",l="[object Proxy]";e.exports=n},function(e,t){function r(e){var t=typeof e;return null!=e&&("object"==t||"function"==t)}e.exports=r},function(e,t,r){function n(e){return!!a&&a in e}var o=r(60),a=function(){var e=/[^.]+$/.exec(o&&o.keys&&o.keys.IE_PROTO||"");return e?"Symbol(src)_1."+e:""}();e.exports=n},function(e,t,r){var n=r(23),o=n["__core-js_shared__"];e.exports=o},function(e,t){function r(e){if(null!=e){try{return o.call(e)}catch(e){}try{return e+""}catch(e){}}return""}var n=Function.prototype,o=n.toString;e.exports=r},function(e,t){function r(e,t){return null==e?void 0:e[t]}e.exports=r},function(e,t){function r(e){var t=this.has(e)&&delete this.__data__[e];return this.size-=t?1:0,t}e.exports=r},function(e,t,r){function n(e){var t=this.__data__;if(o){var r=t[e];return r===a?void 0:r}return i.call(t,e)?t[e]:void 0}var o=r(54),a="__lodash_hash_undefined__",u=Object.prototype,i=u.hasOwnProperty;e.exports=n},function(e,t,r){function n(e){var t=this.__data__;return o?void 0!==t[e]:u.call(t,e)}var o=r(54),a=Object.prototype,u=a.hasOwnProperty;e.exports=n},function(e,t,r){function n(e,t){var r=this.__data__;return this.size+=this.has(e)?0:1,r[e]=o&&void 0===t?a:t,this}var o=r(54),a="__lodash_hash_undefined__";e.exports=n},function(e,t,r){function n(e){var t=-1,r=null==e?0:e.length;for(this.clear();++t<r;){var n=e[t];this.set(n[0],n[1])}}var o=r(68),a=r(69),u=r(72),i=r(73),s=r(74);n.prototype.clear=o,n.prototype.delete=a,n.prototype.get=u,n.prototype.has=i,n.prototype.set=s,e.exports=n},function(e,t){function r(){this.__data__=[],this.size=0}e.exports=r},function(e,t,r){function n(e){var t=this.__data__,r=o(t,e);if(r<0)return!1;var n=t.length-1;return r==n?t.pop():u.call(t,r,1),--this.size,!0}var o=r(70),a=Array.prototype,u=a.splice;e.exports=n},function(e,t,r){function n(e,t){for(var r=e.length;r--;)if(o(e[r][0],t))return r;return-1}var o=r(71);e.exports=n},function(e,t){function r(e,t){return e===t||e!==e&&t!==t}e.exports=r},function(e,t,r){function n(e){var t=this.__data__,r=o(t,e);return r<0?void 0:t[r][1]}var o=r(70);e.exports=n},function(e,t,r){function n(e){return o(this.__data__,e)>-1}var o=r(70);e.exports=n},function(e,t,r){function n(e,t){var r=this.__data__,n=o(r,e);return n<0?(++this.size,r.push([e,t])):r[n][1]=t,this}var o=r(70);e.exports=n},function(e,t,r){var n=r(55),o=r(23),a=n(o,"Map");e.exports=a},function(e,t,r){function n(e){var t=o(this,e).delete(e);return this.size-=t?1:0,t}var o=r(77);e.exports=n},function(e,t,r){function n(e,t){var r=e.__data__;return o(t)?r["string"==typeof t?"string":"hash"]:r.map}var o=r(78);e.exports=n},function(e,t){function r(e){var t=typeof e;return"string"==t||"number"==t||"symbol"==t||"boolean"==t?"__proto__"!==e:null===e}e.exports=r},function(e,t,r){function n(e){return o(this,e).get(e)}var o=r(77);e.exports=n},function(e,t,r){function n(e){return o(this,e).has(e)}var o=r(77);e.exports=n},function(e,t,r){function n(e,t){var r=o(this,e),n=r.size;return r.set(e,t),this.size+=r.size==n?0:1,this}var o=r(77);e.exports=n},function(e,t,r){function n(e,t,r){var n=i(e)?o:u;return r&&s(e,t,r)&&(t=void 0), n(e,a(t,3))}var o=r(83),a=r(84),u=r(147),i=r(26),s=r(153);e.exports=n},function(e,t){function r(e,t){for(var r=-1,n=null==e?0:e.length;++r<n;)if(t(e[r],r,e))return!0;return!1}e.exports=r},function(e,t,r){function n(e){return"function"==typeof e?e:null==e?u:"object"==typeof e?i(e)?a(e[0],e[1]):o(e):s(e)}var o=r(85),a=r(132),u=r(143),i=r(26),s=r(144);e.exports=n},function(e,t,r){function n(e){var t=a(e);return 1==t.length&&t[0][2]?u(t[0][0],t[0][1]):function(r){return r===e||o(r,e,t)}}var o=r(86),a=r(129),u=r(131);e.exports=n},function(e,t,r){function n(e,t,r,n){var s=r.length,l=s,c=!n;if(null==e)return!l;for(e=Object(e);s--;){var f=r[s];if(c&&f[2]?f[1]!==e[f[0]]:!(f[0]in e))return!1}for(;++s<l;){f=r[s];var p=f[0],d=e[p],h=f[1];if(c&&f[2]){if(void 0===d&&!(p in e))return!1}else{var y=new o;if(n)var m=n(d,h,p,e,t,y);if(!(void 0===m?a(h,d,u|i,n,y):m))return!1}}return!0}var o=r(87),a=r(93),u=1,i=2;e.exports=n},function(e,t,r){function n(e){var t=this.__data__=new o(e);this.size=t.size}var o=r(67),a=r(88),u=r(89),i=r(90),s=r(91),l=r(92);n.prototype.clear=a,n.prototype.delete=u,n.prototype.get=i,n.prototype.has=s,n.prototype.set=l,e.exports=n},function(e,t,r){function n(){this.__data__=new o,this.size=0}var o=r(67);e.exports=n},function(e,t){function r(e){var t=this.__data__,r=t.delete(e);return this.size=t.size,r}e.exports=r},function(e,t){function r(e){return this.__data__.get(e)}e.exports=r},function(e,t){function r(e){return this.__data__.has(e)}e.exports=r},function(e,t,r){function n(e,t){var r=this.__data__;if(r instanceof o){var n=r.__data__;if(!a||n.length<i-1)return n.push([e,t]),this.size=++r.size,this;r=this.__data__=new u(n)}return r.set(e,t),this.size=r.size,this}var o=r(67),a=r(75),u=r(50),i=200;e.exports=n},function(e,t,r){function n(e,t,r,i,s){return e===t||(null==e||null==t||!a(e)&&!u(t)?e!==e&&t!==t:o(e,t,r,i,n,s))}var o=r(94),a=r(58),u=r(31);e.exports=n},function(e,t,r){function n(e,t,r,n,m,b){var g=l(e),_=l(t),E=h,w=h;g||(E=s(e),E=E==d?y:E),_||(w=s(t),w=w==d?y:w);var j=E==y,P=w==y,O=E==w;if(O&&c(e)){if(!c(t))return!1;g=!0,j=!1}if(O&&!j)return b||(b=new o),g||f(e)?a(e,t,r,n,m,b):u(e,t,E,r,n,m,b);if(!(r&p)){var T=j&&v.call(e,"__wrapped__"),S=P&&v.call(t,"__wrapped__");if(T||S){var x=T?e.value():e,C=S?t.value():t;return b||(b=new o),m(x,C,r,n,b)}}return!!O&&(b||(b=new o),i(e,t,r,n,m,b))}var o=r(87),a=r(95),u=r(100),i=r(104),s=r(124),l=r(26),c=r(110),f=r(114),p=1,d="[object Arguments]",h="[object Array]",y="[object Object]",m=Object.prototype,v=m.hasOwnProperty;e.exports=n},function(e,t,r){function n(e,t,r,n,l,c){var f=r&i,p=e.length,d=t.length;if(p!=d&&!(f&&d>p))return!1;var h=c.get(e);if(h&&c.get(t))return h==t;var y=-1,m=!0,v=r&s?new o:void 0;for(c.set(e,t),c.set(t,e);++y<p;){var b=e[y],g=t[y];if(n)var _=f?n(g,b,y,t,e,c):n(b,g,y,e,t,c);if(void 0!==_){if(_)continue;m=!1;break}if(v){if(!a(t,function(e,t){if(!u(v,t)&&(b===e||l(b,e,r,n,c)))return v.push(t)})){m=!1;break}}else if(b!==g&&!l(b,g,r,n,c)){m=!1;break}}return c.delete(e),c.delete(t),m}var o=r(96),a=r(83),u=r(99),i=1,s=2;e.exports=n},function(e,t,r){function n(e){var t=-1,r=null==e?0:e.length;for(this.__data__=new o;++t<r;)this.add(e[t])}var o=r(50),a=r(97),u=r(98);n.prototype.add=n.prototype.push=a,n.prototype.has=u,e.exports=n},function(e,t){function r(e){return this.__data__.set(e,n),this}var n="__lodash_hash_undefined__";e.exports=r},function(e,t){function r(e){return this.__data__.has(e)}e.exports=r},function(e,t){function r(e,t){return e.has(t)}e.exports=r},function(e,t,r){function n(e,t,r,n,o,j,O){switch(r){case w:if(e.byteLength!=t.byteLength||e.byteOffset!=t.byteOffset)return!1;e=e.buffer,t=t.buffer;case E:return!(e.byteLength!=t.byteLength||!j(new a(e),new a(t)));case p:case d:case m:return u(+e,+t);case h:return e.name==t.name&&e.message==t.message;case v:case g:return e==t+"";case y:var T=s;case b:var S=n&c;if(T||(T=l),e.size!=t.size&&!S)return!1;var x=O.get(e);if(x)return x==t;n|=f,O.set(e,t);var C=i(T(e),T(t),n,o,j,O);return O.delete(e),C;case _:if(P)return P.call(e)==P.call(t)}return!1}var o=r(22),a=r(101),u=r(71),i=r(95),s=r(102),l=r(103),c=1,f=2,p="[object Boolean]",d="[object Date]",h="[object Error]",y="[object Map]",m="[object Number]",v="[object RegExp]",b="[object Set]",g="[object String]",_="[object Symbol]",E="[object ArrayBuffer]",w="[object DataView]",j=o?o.prototype:void 0,P=j?j.valueOf:void 0;e.exports=n},function(e,t,r){var n=r(23),o=n.Uint8Array;e.exports=o},function(e,t){function r(e){var t=-1,r=Array(e.size);return e.forEach(function(e,n){r[++t]=[n,e]}),r}e.exports=r},function(e,t){function r(e){var t=-1,r=Array(e.size);return e.forEach(function(e){r[++t]=e}),r}e.exports=r},function(e,t,r){function n(e,t,r,n,u,s){var l=r&a,c=o(e),f=c.length,p=o(t),d=p.length;if(f!=d&&!l)return!1;for(var h=f;h--;){var y=c[h];if(!(l?y in t:i.call(t,y)))return!1}var m=s.get(e);if(m&&s.get(t))return m==t;var v=!0;s.set(e,t),s.set(t,e);for(var b=l;++h<f;){y=c[h];var g=e[y],_=t[y];if(n)var E=l?n(_,g,y,t,e,s):n(g,_,y,e,t,s);if(!(void 0===E?g===_||u(g,_,r,n,s):E)){v=!1;break}b||(b="constructor"==y)}if(v&&!b){var w=e.constructor,j=t.constructor;w!=j&&"constructor"in e&&"constructor"in t&&!("function"==typeof w&&w instanceof w&&"function"==typeof j&&j instanceof j)&&(v=!1)}return s.delete(e),s.delete(t),v}var o=r(105),a=1,u=Object.prototype,i=u.hasOwnProperty;e.exports=n},function(e,t,r){function n(e){return u(e)?o(e):a(e)}var o=r(106),a=r(119),u=r(123);e.exports=n},function(e,t,r){function n(e,t){var r=u(e),n=!r&&a(e),c=!r&&!n&&i(e),p=!r&&!n&&!c&&l(e),d=r||n||c||p,h=d?o(e.length,String):[],y=h.length;for(var m in e)!t&&!f.call(e,m)||d&&("length"==m||c&&("offset"==m||"parent"==m)||p&&("buffer"==m||"byteLength"==m||"byteOffset"==m)||s(m,y))||h.push(m);return h}var o=r(107),a=r(108),u=r(26),i=r(110),s=r(113),l=r(114),c=Object.prototype,f=c.hasOwnProperty;e.exports=n},function(e,t){function r(e,t){for(var r=-1,n=Array(e);++r<e;)n[r]=t(r);return n}e.exports=r},function(e,t,r){var n=r(109),o=r(31),a=Object.prototype,u=a.hasOwnProperty,i=a.propertyIsEnumerable,s=n(function(){return arguments}())?n:function(e){return o(e)&&u.call(e,"callee")&&!i.call(e,"callee")};e.exports=s},function(e,t,r){function n(e){return a(e)&&o(e)==u}var o=r(28),a=r(31),u="[object Arguments]";e.exports=n},function(e,t,r){(function(e){var n=r(23),o=r(112),a="object"==typeof t&&t&&!t.nodeType&&t,u=a&&"object"==typeof e&&e&&!e.nodeType&&e,i=u&&u.exports===a,s=i?n.Buffer:void 0,l=s?s.isBuffer:void 0,c=l||o;e.exports=c}).call(t,r(111)(e))},function(e,t){e.exports=function(e){return e.webpackPolyfill||(e.deprecate=function(){},e.paths=[],e.children=[],e.webpackPolyfill=1),e}},function(e,t){function r(){return!1}e.exports=r},function(e,t){function r(e,t){return t=null==t?n:t,!!t&&("number"==typeof e||o.test(e))&&e>-1&&e%1==0&&e<t}var n=9007199254740991,o=/^(?:0|[1-9]\d*)$/;e.exports=r},function(e,t,r){var n=r(115),o=r(117),a=r(118),u=a&&a.isTypedArray,i=u?o(u):n;e.exports=i},function(e,t,r){function n(e){return u(e)&&a(e.length)&&!!R[o(e)]}var o=r(28),a=r(116),u=r(31),i="[object Arguments]",s="[object Array]",l="[object Boolean]",c="[object Date]",f="[object Error]",p="[object Function]",d="[object Map]",h="[object Number]",y="[object Object]",m="[object RegExp]",v="[object Set]",b="[object String]",g="[object WeakMap]",_="[object ArrayBuffer]",E="[object DataView]",w="[object Float32Array]",j="[object Float64Array]",P="[object Int8Array]",O="[object Int16Array]",T="[object Int32Array]",S="[object Uint8Array]",x="[object Uint8ClampedArray]",C="[object Uint16Array]",A="[object Uint32Array]",R={};R[w]=R[j]=R[P]=R[O]=R[T]=R[S]=R[x]=R[C]=R[A]=!0,R[i]=R[s]=R[_]=R[l]=R[E]=R[c]=R[f]=R[p]=R[d]=R[h]=R[y]=R[m]=R[v]=R[b]=R[g]=!1,e.exports=n},function(e,t){function r(e){return"number"==typeof e&&e>-1&&e%1==0&&e<=n}var n=9007199254740991;e.exports=r},function(e,t){function r(e){return function(t){return e(t)}}e.exports=r},function(e,t,r){(function(e){var n=r(24),o="object"==typeof t&&t&&!t.nodeType&&t,a=o&&"object"==typeof e&&e&&!e.nodeType&&e,u=a&&a.exports===o,i=u&&n.process,s=function(){try{return i&&i.binding&&i.binding("util")}catch(e){}}();e.exports=s}).call(t,r(111)(e))},function(e,t,r){function n(e){if(!o(e))return a(e);var t=[];for(var r in Object(e))i.call(e,r)&&"constructor"!=r&&t.push(r);return t}var o=r(120),a=r(121),u=Object.prototype,i=u.hasOwnProperty;e.exports=n},function(e,t){function r(e){var t=e&&e.constructor,r="function"==typeof t&&t.prototype||n;return e===r}var n=Object.prototype;e.exports=r},function(e,t,r){var n=r(122),o=n(Object.keys,Object);e.exports=o},function(e,t){function r(e,t){return function(r){return e(t(r))}}e.exports=r},function(e,t,r){function n(e){return null!=e&&a(e.length)&&!o(e)}var o=r(57),a=r(116);e.exports=n},function(e,t,r){var n=r(125),o=r(75),a=r(126),u=r(127),i=r(128),s=r(28),l=r(61),c="[object Map]",f="[object Object]",p="[object Promise]",d="[object Set]",h="[object WeakMap]",y="[object DataView]",m=l(n),v=l(o),b=l(a),g=l(u),_=l(i),E=s;(n&&E(new n(new ArrayBuffer(1)))!=y||o&&E(new o)!=c||a&&E(a.resolve())!=p||u&&E(new u)!=d||i&&E(new i)!=h)&&(E=function(e){var t=s(e),r=t==f?e.constructor:void 0,n=r?l(r):"";if(n)switch(n){case m:return y;case v:return c;case b:return p;case g:return d;case _:return h}return t}),e.exports=E},function(e,t,r){var n=r(55),o=r(23),a=n(o,"DataView");e.exports=a},function(e,t,r){var n=r(55),o=r(23),a=n(o,"Promise");e.exports=a},function(e,t,r){var n=r(55),o=r(23),a=n(o,"Set");e.exports=a},function(e,t,r){var n=r(55),o=r(23),a=n(o,"WeakMap");e.exports=a},function(e,t,r){function n(e){for(var t=a(e),r=t.length;r--;){var n=t[r],u=e[n];t[r]=[n,u,o(u)]}return t}var o=r(130),a=r(105);e.exports=n},function(e,t,r){function n(e){return e===e&&!o(e)}var o=r(58);e.exports=n},function(e,t){function r(e,t){return function(r){return null!=r&&(r[e]===t&&(void 0!==t||e in Object(r)))}}e.exports=r},function(e,t,r){function n(e,t){return i(e)&&s(t)?l(c(e),t):function(r){var n=a(r,e);return void 0===n&&n===t?u(r,e):o(t,n,f|p)}}var o=r(93),a=r(133),u=r(140),i=r(136),s=r(130),l=r(131),c=r(139),f=1,p=2;e.exports=n},function(e,t,r){function n(e,t,r){var n=null==e?void 0:o(e,t);return void 0===n?r:n}var o=r(134);e.exports=n},function(e,t,r){function n(e,t){t=o(t,e);for(var r=0,n=t.length;null!=e&&r<n;)e=e[a(t[r++])];return r&&r==n?e:void 0}var o=r(135),a=r(139);e.exports=n},function(e,t,r){function n(e,t){return o(e)?e:a(e,t)?[e]:u(i(e))}var o=r(26),a=r(136),u=r(137),i=r(20);e.exports=n},function(e,t,r){function n(e,t){if(o(e))return!1;var r=typeof e;return!("number"!=r&&"symbol"!=r&&"boolean"!=r&&null!=e&&!a(e))||(i.test(e)||!u.test(e)||null!=t&&e in Object(t))}var o=r(26),a=r(27),u=/\.|\[(?:[^[\]]*|(["'])(?:(?!\1)[^\\]|\\.)*?\1)\]/,i=/^\w*$/;e.exports=n},function(e,t,r){var n=r(138),o=/^\./,a=/[^.[\]]+|\[(?:(-?\d+(?:\.\d+)?)|(["'])((?:(?!\2)[^\\]|\\.)*?)\2)\]|(?=(?:\.|\[\])(?:\.|\[\]|$))/g,u=/\\(\\)?/g,i=n(function(e){var t=[];return o.test(e)&&t.push(""),e.replace(a,function(e,r,n,o){t.push(n?o.replace(u,"$1"):r||e)}),t});e.exports=i},function(e,t,r){function n(e){var t=o(e,function(e){return r.size===a&&r.clear(),e}),r=t.cache;return t}var o=r(49),a=500;e.exports=n},function(e,t,r){function n(e){if("string"==typeof e||o(e))return e;var t=e+"";return"0"==t&&1/e==-a?"-0":t}var o=r(27),a=1/0;e.exports=n},function(e,t,r){function n(e,t){return null!=e&&a(e,t,o)}var o=r(141),a=r(142);e.exports=n},function(e,t){function r(e,t){return null!=e&&t in Object(e)}e.exports=r},function(e,t,r){function n(e,t,r){t=o(t,e);for(var n=-1,c=t.length,f=!1;++n<c;){var p=l(t[n]);if(!(f=null!=e&&r(e,p)))break;e=e[p]}return f||++n!=c?f:(c=null==e?0:e.length,!!c&&s(c)&&i(p,c)&&(u(e)||a(e)))}var o=r(135),a=r(108),u=r(26),i=r(113),s=r(116),l=r(139);e.exports=n},function(e,t){function r(e){return e}e.exports=r},function(e,t,r){function n(e){return u(e)?o(i(e)):a(e)}var o=r(145),a=r(146),u=r(136),i=r(139);e.exports=n},function(e,t){function r(e){return function(t){return null==t?void 0:t[e]}}e.exports=r},function(e,t,r){function n(e){return function(t){return o(t,e)}}var o=r(134);e.exports=n},function(e,t,r){function n(e,t){var r;return o(e,function(e,n,o){return r=t(e,n,o),!r}),!!r}var o=r(148);e.exports=n},function(e,t,r){var n=r(149),o=r(152),a=o(n);e.exports=a},function(e,t,r){function n(e,t){return e&&o(e,t,a)}var o=r(150),a=r(105);e.exports=n},function(e,t,r){var n=r(151),o=n();e.exports=o},function(e,t){function r(e){return function(t,r,n){for(var o=-1,a=Object(t),u=n(t),i=u.length;i--;){var s=u[e?i:++o];if(r(a[s],s,a)===!1)break}return t}}e.exports=r},function(e,t,r){function n(e,t){return function(r,n){if(null==r)return r;if(!o(r))return e(r,n);for(var a=r.length,u=t?a:-1,i=Object(r);(t?u--:++u<a)&&n(i[u],u,i)!==!1;);return r}}var o=r(123);e.exports=n},function(e,t,r){function n(e,t,r){if(!i(r))return!1;var n=typeof t;return!!("number"==n?a(r)&&u(t,r.length):"string"==n&&t in r)&&o(r[t],e)}var o=r(71),a=r(123),u=r(113),i=r(58);e.exports=n},function(e,t,r){"use strict";function n(e){return e&&e.__esModule?e:{default:e}}function o(e,t){var r=d(e,t);if(r)return(0,i.default)(r,{declaration:!0,indent:"\t"})}Object.defineProperty(t,"__esModule",{value:!0}),t.memoizedSampleFromSchema=t.memoizedCreateXMLExample=t.sampleXmlFromSchema=t.inferSchema=t.sampleFromSchema=void 0,t.createXMLExample=o;var a=r(12),u=r(155),i=n(u),s=r(156),l=n(s),c={string:function(){return"string"},string_email:function(){return"[email protected]"},"string_date-time":function(){return(new Date).toISOString()},number:function(){return 0},number_float:function(){return 0},integer:function(){return 0},boolean:function(){return!0}},f=function(e){e=(0,a.objectify)(e);var t=e,r=t.type,n=t.format,o=c[r+"_"+n]||c[r];return(0,a.isFunc)(o)?o(e):"Unknown Type: "+e.type},p=t.sampleFromSchema=function e(t){var r=arguments.length>1&&void 0!==arguments[1]?arguments[1]:{},n=(0,a.objectify)(t),o=n.type,u=n.example,i=n.properties,s=n.additionalProperties,l=n.items,c=r.includeReadOnly;if(void 0!==u)return u;if(!o)if(i)o="object";else{if(!l)return;o="array"}if("object"===o){var p=(0,a.objectify)(i),d={};for(var h in p)p[h].readOnly&&!c||(d[h]=e(p[h],{includeReadOnly:c}));if(s===!0)d.additionalProp1={};else if(s)for(var y=(0,a.objectify)(s),m=e(y,{includeReadOnly:c}),v=1;v<4;v++)d["additionalProp"+v]=m;return d}return"array"===o?[e(l,{includeReadOnly:c})]:t.enum?t.default?t.default:(0,a.normalizeArray)(t.enum)[0]:f(t)},d=(t.inferSchema=function(e){return e.schema&&(e=e.schema),e.properties&&(e.type="object"),e},t.sampleXmlFromSchema=function e(t){var r=arguments.length>1&&void 0!==arguments[1]?arguments[1]:{},n=(0,a.objectify)(t),o=n.type,u=n.properties,i=n.additionalProperties,s=n.items,l=n.example,c=r.includeReadOnly,p=n.default,d={},h={},y=t.xml,m=y.name,v=y.prefix,b=y.namespace,g=n.enum,_=void 0,E=void 0;if(!o)if(u||i)o="object";else{if(!s)return;o="array"}if(m=m||"notagname",_=(v?v+":":"")+m,b){var w=v?"xmlns:"+v:"xmlns";h[w]=b}if("array"===o&&s){if(s.xml=s.xml||y||{},s.xml.name=s.xml.name||y.name,y.wrapped)return d[_]=[],Array.isArray(l)?l.forEach(function(t){s.example=t,d[_].push(e(s,r))}):Array.isArray(p)?p.forEach(function(t){s.default=t,d[_].push(e(s,r))}):d[_]=[e(s,r)],h&&d[_].push({_attr:h}),d;var j=[];return Array.isArray(l)?(l.forEach(function(t){s.example=t,j.push(e(s,r))}),j):Array.isArray(p)?(p.forEach(function(t){s.default=t,j.push(e(s,r))}),j):e(s,r)}if("object"===o){var P=(0,a.objectify)(u);d[_]=[],l=l||{};for(var O in P)if(!P[O].readOnly||c)if(P[O].xml=P[O].xml||{},P[O].xml.attribute){var T=Array.isArray(P[O].enum)&&P[O].enum[0],S=P[O].example,x=P[O].default;h[P[O].xml.name||O]=void 0!==S&&S||void 0!==l[O]&&l[O]||void 0!==x&&x||T||f(P[O])}else{P[O].xml.name=P[O].xml.name||O,P[O].example=void 0!==P[O].example?P[O].example:l[O];var C=e(P[O]);Array.isArray(C)?d[_]=d[_].concat(C):d[_].push(C)}return i===!0?d[_].push({additionalProp:"Anything can be here"}):i&&d[_].push({additionalProp:f(i)}),h&&d[_].push({_attr:h}),d}return E=void 0!==l?l:void 0!==p?p:Array.isArray(g)?g[0]:f(t),d[_]=h?[{_attr:h},E]:E,d});t.memoizedCreateXMLExample=(0,l.default)(o),t.memoizedSampleFromSchema=(0,l.default)(p)},function(e,t){e.exports=require("xml")},function(e,t){e.exports=require("memoizee")},function(e,t,r){"use strict";function n(e){return e&&e.__esModule?e:{default:e}}function o(){return[u.default]}Object.defineProperty(t,"__esModule",{value:!0}),t.default=o;var a=r(158),u=n(a)},function(e,t,r){"use strict";function n(e){if(e&&e.__esModule)return e;var t={};if(null!=e)for(var r in e)Object.prototype.hasOwnProperty.call(e,r)&&(t[r]=e[r]);return t.default=e,t}function o(e){return e&&e.__esModule?e:{default:e}}Object.defineProperty(t,"__esModule",{value:!0}),t.default=function(){var e={components:{App:A.default,authorizationPopup:k.default,authorizeBtn:M.default,authorizeOperationBtn:I.default,auths:z.default,authError:L.default,oauth2:H.default,apiKeyAuth:F.default,basicAuth:V.default,clear:$.default,liveResponse:X.default,info:Te.default,onlineValidatorBadge:Z.default,operations:ee.default,operation:re.default,highlightCode:oe.default,responses:ue.default,response:se.default,responseBody:ce.default,parameters:pe.default,parameterRow:he.default,execute:me.default,headers:be.default,errors:_e.default,contentType:we.default,overview:Pe.default,footer:xe.default,ParamBody:Ae.default,curl:ke.default,schemes:Me.default,modelExample:Ie.default,model:ze.default,models:Le.default,TryItOutButton:Fe.default,Markdown:Ve.default,BaseLayout:He.default}},t={components:$e},r={components:Xe};return[P.default,m.default,p.default,c.default,u.default,s.default,h.default,e,t,_.default,r,w.default,b.default,T.default,x.default]};var a=r(159),u=o(a),i=r(174),s=o(i),l=r(178),c=o(l),f=r(185),p=o(f),d=r(240),h=o(d),y=r(241),m=o(y),v=r(242),b=o(v),g=r(253),_=o(g),E=r(255),w=o(E),j=r(260),P=o(j),O=r(262),T=o(O),S=r(268),x=o(S),C=r(269),A=o(C),R=r(270),k=o(R),q=r(271),M=o(q),N=r(272),I=o(N),U=r(274),z=o(U),D=r(275),L=o(D),B=r(276),F=o(B),J=r(277),V=o(J),W=r(278),H=o(W),Y=r(280),$=o(Y),K=r(281),X=o(K),G=r(282),Z=o(G),Q=r(283),ee=o(Q),te=r(284),re=o(te),ne=r(287),oe=o(ne),ae=r(288),ue=o(ae),ie=r(289),se=o(ie),le=r(290),ce=o(le),fe=r(292),pe=o(fe),de=r(293),he=o(de),ye=r(294),me=o(ye),ve=r(295),be=o(ve),ge=r(296),_e=o(ge),Ee=r(298),we=o(Ee),je=r(299),Pe=o(je),Oe=r(301),Te=o(Oe),Se=r(302),xe=o(Se),Ce=r(303),Ae=o(Ce),Re=r(304),ke=o(Re),qe=r(306),Me=o(qe),Ne=r(307),Ie=o(Ne),Ue=r(308),ze=o(Ue),De=r(309),Le=o(De),Be=r(310),Fe=o(Be),Je=r(311),Ve=o(Je),We=r(314),He=o(We),Ye=r(300),$e=n(Ye),Ke=r(315),Xe=n(Ke)},function(e,t,r){"use strict";function n(e){if(e&&e.__esModule)return e;var t={};if(null!=e)for(var r in e)Object.prototype.hasOwnProperty.call(e,r)&&(t[r]=e[r]);return t.default=e,t}function o(e){return e&&e.__esModule?e:{default:e}}Object.defineProperty(t,"__esModule",{value:!0}),t.default=function(e){return{statePlugins:{err:{reducers:(0,u.default)(e),actions:s,selectors:c}}}};var a=r(160),u=o(a),i=r(10),s=n(i),l=r(172),c=n(l)},function(e,t,r){"use strict";function n(e){return e&&e.__esModule?e:{default:e}}function o(e,t,r){return t in e?Object.defineProperty(e,t,{value:r,enumerable:!0,configurable:!0,writable:!0}):e[t]=r,e}Object.defineProperty(t,"__esModule",{value:!0}),t.default=function(e){var t;return t={},o(t,a.NEW_THROWN_ERR,function(t,r){var n=r.payload,o=Object.assign(p,n,{type:"thrown"});return t.update("errors",function(e){return(e||(0,s.List)()).push((0,s.fromJS)(o))}).update("errors",function(t){return(0,f.default)(t,e.getSystem())})}),o(t,a.NEW_THROWN_ERR_BATCH,function(t,r){var n=r.payload;return n=n.map(function(e){return(0,s.fromJS)(Object.assign(p,e,{type:"thrown"}))}),t.update("errors",function(e){return(e||(0,s.List)()).concat((0,s.fromJS)(n))}).update("errors",function(t){return(0,f.default)(t,e.getSystem())})}),o(t,a.NEW_SPEC_ERR,function(t,r){var n=r.payload,o=(0,s.fromJS)(n);return o=o.set("type","spec"),t.update("errors",function(e){return(e||(0,s.List)()).push((0,s.fromJS)(o)).sortBy(function(e){return e.get("line")})}).update("errors",function(t){return(0,f.default)(t,e.getSystem())})}),o(t,a.NEW_AUTH_ERR,function(t,r){var n=r.payload,o=(0,s.fromJS)(Object.assign({},n));return o=o.set("type","auth"),t.update("errors",function(e){return(e||(0,s.List)()).push((0,s.fromJS)(o))}).update("errors",function(t){return(0,f.default)(t,e.getSystem())})}),o(t,a.CLEAR,function(e,t){var r=t.payload;if(r){var n=l.default.fromJS((0,i.default)((e.get("errors")||(0,s.List)()).toJS(),r));return e.merge({errors:n})}}),t};var a=r(10),u=r(161),i=n(u),s=r(7),l=n(s),c=r(165),f=n(c),p={line:0,level:"error",message:"Unknown error"}},function(e,t,r){function n(e,t){var r=i(e)?o:a;return r(e,s(u(t,3)))}var o=r(162),a=r(163),u=r(84),i=r(26),s=r(164);e.exports=n},function(e,t){function r(e,t){for(var r=-1,n=null==e?0:e.length,o=0,a=[];++r<n;){var u=e[r];t(u,r,e)&&(a[o++]=u)}return a}e.exports=r},function(e,t,r){function n(e,t){var r=[];return o(e,function(e,n,o){t(e,n,o)&&r.push(e)}),r}var o=r(148);e.exports=n},function(e,t){function r(e){if("function"!=typeof e)throw new TypeError(n);return function(){var t=arguments;switch(t.length){case 0:return!e.call(this);case 1:return!e.call(this,t[0]);case 2:return!e.call(this,t[0],t[1]);case 3:return!e.call(this,t[0],t[1],t[2])}return!e.apply(this,t)}}var n="Expected a function";e.exports=r},function(e,t,r){"use strict";function n(e){return e&&e.__esModule?e:{default:e}}function o(e,t){var r={jsSpec:t.specSelectors.specJson().toJS()},n=(0,i.default)(l,function(e,t){try{var n=t.transform(e,r);return n.filter(function(e){return!!e})}catch(t){return console.error("Transformer error:",t),e}},e);return n.filter(function(e){return!!e}).map(function(e){return!e.get("line")&&e.get("path"),e})}function a(e){return e.split("-").map(function(e){return e[0].toUpperCase()+e.slice(1)}).join("")}Object.defineProperty(t,"__esModule",{value:!0}),t.default=o;var u=r(166),i=n(u),s=r(168),l=[];s.keys().forEach(function(e){"./hook.js"!==e&&e.match(/js$/)&&(e.slice(2).indexOf("/")>-1||l.push({name:a(e).replace(".js","").replace("./",""),transform:s(e).transform}))})},function(e,t,r){function n(e,t,r){var n=s(e)?o:i,l=arguments.length<3;return n(e,u(t,4),r,l,a)}var o=r(41),a=r(148),u=r(84),i=r(167),s=r(26);e.exports=n},function(e,t){function r(e,t,r,n,o){return o(e,function(e,o,a){r=n?(n=!1,e):t(r,e,o,a)}),r}e.exports=r},function(e,t,r){function n(e){return r(o(e))}function o(e){return a[e]||function(){throw new Error("Cannot find module '"+e+"'.")}()}var a={"./not-of-type.js":169,"./parameter-oneof.js":170,"./strip-instance.js":171};n.keys=function(){return Object.keys(a)},n.resolve=o,e.exports=n,n.id=168},function(e,t){"use strict";function r(e){return e.map(function(e){var t="is not of a type(s)",r=e.get("message").indexOf(t);if(r>-1){var o=e.get("message").slice(r+t.length).split(",");return e.set("message",e.get("message").slice(0,r)+n(o))}return e})}function n(e){return e.reduce(function(e,t,r,n){return r===n.length-1&&n.length>1?e+"or "+t:n[r+1]&&n.length>2?e+t+", ":n[r+1]?e+t+" ":e+t},"should be a")}Object.defineProperty(t,"__esModule",{value:!0}),t.transform=r},function(e,t,r){"use strict";function n(e){return e&&e.__esModule?e:{default:e}}function o(e,t){t.jsSpec;return e}Object.defineProperty(t,"__esModule",{value:!0}),t.transform=o;var a=r(133);n(a),r(7)},function(e,t){"use strict";function r(e){return e.map(function(e){return e.set("message",n(e.get("message"),"instance."))})}function n(e,t){return e.replace(new RegExp(t,"g"),"")}Object.defineProperty(t,"__esModule",{value:!0}),t.transform=r},function(e,t,r){"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.lastError=t.allErrors=void 0;var n=r(7),o=r(173),a=function(e){return e},u=t.allErrors=(0,o.createSelector)(a,function(e){return e.get("errors",(0,n.List)())});t.lastError=(0,o.createSelector)(u,function(e){return e.last()})},function(e,t){e.exports=require("reselect")},function(e,t,r){"use strict";function n(e){if(e&&e.__esModule)return e;var t={};if(null!=e)for(var r in e)Object.prototype.hasOwnProperty.call(e,r)&&(t[r]=e[r]);return t.default=e,t}function o(e){return e&&e.__esModule?e:{default:e}}Object.defineProperty(t,"__esModule",{value:!0}),t.default=function(){return{statePlugins:{layout:{reducers:u.default,actions:s,selectors:c}}}};var a=r(175),u=o(a),i=r(176),s=n(i),l=r(177),c=n(l)},function(e,t,r){"use strict";function n(e,t,r){return t in e?Object.defineProperty(e,t,{value:r,enumerable:!0,configurable:!0,writable:!0}):e[t]=r,e}Object.defineProperty(t,"__esModule",{value:!0});var o,a=r(176);t.default=(o={},n(o,a.UPDATE_LAYOUT,function(e,t){return e.set("layout",t.payload)}),n(o,a.SHOW,function(e,t){var r=t.payload.thing,n=t.payload.shown;return e.setIn(["shown"].concat(r),n)}),n(o,a.UPDATE_MODE,function(e,t){var r=t.payload.thing,n=t.payload.mode;return e.setIn(["modes"].concat(r),(n||"")+"")}),o)},function(e,t,r){"use strict";function n(e){return{type:i,payload:e}}function o(e){var t=!(arguments.length>1&&void 0!==arguments[1])||arguments[1];return e=(0,u.normalizeArray)(e),{type:l,payload:{thing:e,shown:t}}}function a(e){var t=arguments.length>1&&void 0!==arguments[1]?arguments[1]:"";return e=(0,u.normalizeArray)(e),{type:s,payload:{thing:e,mode:t}}}Object.defineProperty(t,"__esModule",{value:!0}),t.SHOW=t.UPDATE_MODE=t.UPDATE_LAYOUT=void 0,t.updateLayout=n,t.show=o,t.changeMode=a;var u=r(12),i=t.UPDATE_LAYOUT="layout_update_layout",s=t.UPDATE_MODE="layout_update_mode",l=t.SHOW="layout_show"},function(e,t,r){"use strict";function n(e){if(Array.isArray(e)){for(var t=0,r=Array(e.length);t<e.length;t++)r[t]=e[t];return r}return Array.from(e)}Object.defineProperty(t,"__esModule",{value:!0}),t.showSummary=t.whatMode=t.isShown=t.current=void 0;var o=r(173),a=r(12),u=function(e){return e},i=(t.current=function(e){return e.get("layout")},t.isShown=function(e,t,r){return t=(0,a.normalizeArray)(t),Boolean(e.getIn(["shown"].concat(n(t)),r))});t.whatMode=function(e,t){var r=arguments.length>2&&void 0!==arguments[2]?arguments[2]:"";return t=(0,a.normalizeArray)(t),e.getIn(["modes"].concat(n(t)),r)},t.showSummary=(0,o.createSelector)(u,function(e){return!i(e,"editor")})},function(e,t,r){"use strict";function n(e){if(e&&e.__esModule)return e;var t={};if(null!=e)for(var r in e)Object.prototype.hasOwnProperty.call(e,r)&&(t[r]=e[r]);return t.default=e,t}function o(e){return e&&e.__esModule?e:{default:e}}Object.defineProperty(t,"__esModule",{value:!0}),t.default=function(){return{statePlugins:{spec:{wrapActions:p,reducers:u.default,actions:s,selectors:c}}}};var a=r(179),u=o(a),i=r(180),s=n(i),l=r(183),c=n(l),f=r(184),p=n(f)},function(e,t,r){"use strict";function n(e){return e&&e.__esModule?e:{default:e}}function o(e,t,r){return t in e?Object.defineProperty(e,t,{value:r,enumerable:!0,configurable:!0,writable:!0}):e[t]=r,e}function a(e){if(Array.isArray(e)){for(var t=0,r=Array(e.length);t<e.length;t++)r[t]=e[t];return r}return Array.from(e)}Object.defineProperty(t,"__esModule",{value:!0});var u,i=r(7),s=r(12),l=r(11),c=n(l),f=r(180);t.default=(u={},o(u,f.UPDATE_SPEC,function(e,t){return"string"==typeof t.payload?e.set("spec",t.payload):e}),o(u,f.UPDATE_URL,function(e,t){return e.set("url",t.payload+"")}),o(u,f.UPDATE_JSON,function(e,t){return e.set("json",(0,s.fromJSOrdered)(t.payload))}),o(u,f.UPDATE_RESOLVED,function(e,t){return e.setIn(["resolved"],(0,s.fromJSOrdered)(t.payload))}),o(u,f.UPDATE_PARAM,function(e,t){var r=t.payload,n=r.path,o=r.paramName,u=r.value,l=r.isXml;return e.updateIn(["resolved","paths"].concat(a(n),["parameters"]),(0,i.fromJS)([]),function(e){var t=e.findIndex(function(e){return e.get("name")===o});return u instanceof c.default.File||(u=(0,s.fromJSOrdered)(u)),e.setIn([t,l?"value_xml":"value"],u)})}),o(u,f.VALIDATE_PARAMS,function(e,t){var r=t.payload.pathMethod,n=e.getIn(["resolved","paths"].concat(a(r))),o=/xml/i.test(n.get("consumes_value"));return e.updateIn(["resolved","paths"].concat(a(r),["parameters"]),(0,i.fromJS)([]),function(e){return e.withMutations(function(e){for(var t=0,r=e.count();t<r;t++){var n=(0,s.validateParam)(e.get(t),o);e.setIn([t,"errors"],(0,i.fromJS)(n))}})})}),o(u,f.ClEAR_VALIDATE_PARAMS,function(e,t){var r=t.payload.pathMethod;return e.updateIn(["resolved","paths"].concat(a(r),["parameters"]),(0,i.fromJS)([]),function(e){return e.withMutations(function(e){for(var t=0,r=e.count();t<r;t++)e.setIn([t,"errors"],(0,i.fromJS)({}))})})}),o(u,f.SET_RESPONSE,function(e,t){var r=t.payload,n=r.res,o=r.path,a=r.method,u=void 0;u=n.error?Object.assign({error:!0},n.err):n,u.headers=u.headers||{};var i=e.setIn(["responses",o,a],(0,s.fromJSOrdered)(u));return n.data instanceof c.default.Blob&&(i=i.setIn(["responses",o,a,"text"],n.data)),i}),o(u,f.SET_REQUEST,function(e,t){var r=t.payload,n=r.req,o=r.path,a=r.method;return e.setIn(["requests",o,a],(0,s.fromJSOrdered)(n))}),o(u,f.UPDATE_OPERATION_VALUE,function(e,t){var r=t.payload,n=r.path,o=r.value,u=r.key,s=["resolved","paths"].concat(a(n));return e.getIn(s)?e.setIn([].concat(a(s),[u]),(0,i.fromJS)(o)):e}),o(u,f.CLEAR_RESPONSE,function(e,t){var r=t.payload,n=r.path,o=r.method;return e.deleteIn(["responses",n,o])}),o(u,f.CLEAR_REQUEST,function(e,t){var r=t.payload,n=r.path,o=r.method;return e.deleteIn(["requests",n,o])}),o(u,f.SET_SCHEME,function(e,t){var r=t.payload,n=r.scheme,o=r.path,a=r.method;return o&&a?e.setIn(["scheme",o,a],n):o||a?void 0:e.setIn(["scheme","_defaultScheme"],n)}),u)},function(e,t,r){"use strict";function n(e){return e&&e.__esModule?e:{default:e}}function o(e,t){var r={};for(var n in e)t.indexOf(n)>=0||Object.prototype.hasOwnProperty.call(e,n)&&(r[n]=e[n]);return r}function a(e){return e instanceof Error?{type:O,error:!0,payload:e}:"string"==typeof e?{type:O,payload:e.replace(/\t/g," ")||""}:{type:O,payload:""}}function u(e){return{type:U,payload:e}}function i(e){return{type:T,payload:e}}function s(e){if(!e||"object"!==("undefined"==typeof e?"undefined":b(e)))throw new Error("updateJson must only accept a simple JSON object");return{type:S,payload:e}}function l(e,t,r,n){return{type:x,payload:{path:e,value:r,paramName:t,isXml:n}}}function c(e){return{type:C,payload:{pathMethod:e}}}function f(e){return{type:N,payload:{pathMethod:e}}}function p(e,t){return{type:I,payload:{path:e,value:t,key:"consumes_value"}}}function d(e,t){return{type:I,payload:{path:e,value:t,key:"produces_value"}}}function h(e,t){return{type:q,payload:{path:e,method:t}}}function y(e,t){return{type:M,payload:{path:e,method:t}}}function m(e,t,r){return{type:z,payload:{scheme:e,path:t,method:r}}}Object.defineProperty(t,"__esModule",{value:!0}),t.execute=t.executeRequest=t.logRequest=t.setRequest=t.setResponse=t.formatIntoYaml=t.resolveSpec=t.parseToJson=t.SET_SCHEME=t.UPDATE_RESOLVED=t.UPDATE_OPERATION_VALUE=t.ClEAR_VALIDATE_PARAMS=t.CLEAR_REQUEST=t.CLEAR_RESPONSE=t.LOG_REQUEST=t.SET_REQUEST=t.SET_RESPONSE=t.VALIDATE_PARAMS=t.UPDATE_PARAM=t.UPDATE_JSON=t.UPDATE_URL=t.UPDATE_SPEC=void 0;var v=Object.assign||function(e){for(var t=1;t<arguments.length;t++){var r=arguments[t];for(var n in r)Object.prototype.hasOwnProperty.call(r,n)&&(e[n]=r[n])}return e},b="function"==typeof Symbol&&"symbol"==typeof Symbol.iterator?function(e){return typeof e}:function(e){return e&&"function"==typeof Symbol&&e.constructor===Symbol&&e!==Symbol.prototype?"symbol":typeof e};t.updateSpec=a,t.updateResolved=u,t.updateUrl=i,t.updateJsonSpec=s,t.changeParam=l,t.validateParams=c,t.clearValidateParams=f,t.changeConsumesValue=p,t.changeProducesValue=d,t.clearResponse=h,t.clearRequest=y,t.setScheme=m;var g=r(181),_=n(g),E=r(182),w=n(E),j=r(9),P=n(j),O=t.UPDATE_SPEC="spec_update_spec",T=t.UPDATE_URL="spec_update_url",S=t.UPDATE_JSON="spec_update_json",x=t.UPDATE_PARAM="spec_update_param",C=t.VALIDATE_PARAMS="spec_validate_param",A=t.SET_RESPONSE="spec_set_response",R=t.SET_REQUEST="spec_set_request",k=t.LOG_REQUEST="spec_log_request",q=t.CLEAR_RESPONSE="spec_clear_response",M=t.CLEAR_REQUEST="spec_clear_request",N=t.ClEAR_VALIDATE_PARAMS="spec_clear_validate_param",I=t.UPDATE_OPERATION_VALUE="spec_update_operation_value",U=t.UPDATE_RESOLVED="spec_update_resolved",z=t.SET_SCHEME="set_scheme",D=(t.parseToJson=function(e){ return function(t){var r=t.specActions,n=t.specSelectors,o=t.errActions,a=n.specStr,u=null;try{e=e||a(),o.clear({source:"parser"}),u=_.default.safeLoad(e)}catch(e){return console.error(e),o.newSpecErr({source:"parser",level:"error",message:e.reason,line:e.mark&&e.mark.line?e.mark.line+1:void 0})}return r.updateJsonSpec(u)}},t.resolveSpec=function(e,t){return function(r){var n=r.specActions,o=r.specSelectors,a=r.errActions,u=r.fn,i=u.fetch,s=u.resolve,l=u.AST,c=r.getConfigs,f=c(),p=f.modelPropertyMacro,d=f.parameterMacro;"undefined"==typeof e&&(e=o.specJson()),"undefined"==typeof t&&(t=o.url());var h=l.getLineNumberForPath,y=o.specStr();return s({fetch:i,spec:e,baseDoc:t,modelPropertyMacro:p,parameterMacro:d}).then(function(e){var t=e.spec,r=e.errors;if(a.clear({type:"thrown"}),r.length>0){var o=r.map(function(e){return console.error(e),e.line=e.fullPath?h(y,e.fullPath):null,e.path=e.fullPath?e.fullPath.join("."):null,e.level="error",e.type="thrown",e.source="resolver",Object.defineProperty(e,"message",{enumerable:!0,value:e.message}),e});a.newThrownErrBatch(o)}return n.updateResolved(t)})}},t.formatIntoYaml=function(){return function(e){var t=e.specActions,r=e.specSelectors,n=r.specStr,o=t.updateSpec;try{var a=_.default.safeDump(_.default.safeLoad(n()),{indent:2});o(a)}catch(e){o(e)}}},t.setResponse=function(e,t,r){return{payload:{path:e,method:t,res:r},type:A}},t.setRequest=function(e,t,r){return{payload:{path:e,method:t,req:r},type:R}},t.logRequest=function(e){return{payload:e,type:k}},t.executeRequest=function(e){return function(t){var r=t.fn,n=t.specActions,o=t.specSelectors,a=e.pathName,u=e.method,i=e.operation,s=i.toJS();e.contextUrl=(0,w.default)(o.url()).toString(),s&&s.operationId?e.operationId=s.operationId:s&&a&&u&&(e.operationId=r.opId(s,a,u));var l=Object.assign({},e);return l=r.buildRequest(l),n.setRequest(e.pathName,e.method,l),r.execute(e).then(function(t){return n.setResponse(e.pathName,e.method,t)}).catch(function(t){return n.setResponse(e.pathName,e.method,{error:!0,err:(0,P.default)(t)})})}},function(){var e=arguments.length>0&&void 0!==arguments[0]?arguments[0]:{},t=e.path,r=e.method,n=o(e,["path","method"]);return function(e){var o=e.fn.fetch,a=e.specSelectors,u=e.specActions,i=a.spec().toJS(),s=a.operationScheme(t,r),l=a.contentTypeValues([t,r]).toJS(),c=l.requestContentType,f=l.responseContentType,p=/xml/i.test(c),d=a.parameterValues([t,r],p).toJS();return u.executeRequest(v({fetch:o,spec:i,pathName:t,method:r,parameters:d,requestContentType:c,scheme:s,responseContentType:f},n))}});t.execute=D},function(e,t){e.exports=require("js-yaml")},function(e,t){e.exports=require("url-parse")},function(e,t,r){"use strict";function n(e){if(Array.isArray(e)){for(var t=0,r=Array(e.length);t<e.length;t++)r[t]=e[t];return r}return Array.from(e)}function o(e,t,r){var o=b(e).getIn(["paths"].concat(n(t),["parameters"]),(0,d.fromJS)([]));return o.filter(function(e){return d.Map.isMap(e)&&e.get("name")===r}).first()}function a(e,t,r){var o=b(e).getIn(["paths"].concat(n(t),["parameters"]),(0,d.fromJS)([]));return o.reduce(function(e,t){var n=r&&"body"===t.get("in")?t.get("value_xml"):t.get("value");return e.set(t.get("name"),n)},(0,d.fromJS)({}))}function u(e){var t=arguments.length>1&&void 0!==arguments[1]?arguments[1]:"";if(d.List.isList(e))return e.some(function(e){return d.Map.isMap(e)&&e.get("in")===t})}function i(e){var t=arguments.length>1&&void 0!==arguments[1]?arguments[1]:"";if(d.List.isList(e))return e.some(function(e){return d.Map.isMap(e)&&e.get("type")===t})}function s(e,t){var r=b(e).getIn(["paths"].concat(n(t)),(0,d.fromJS)({})),o=r.get("parameters")||new d.List,a=i(o,"file")?"multipart/form-data":u(o,"formData")?"application/x-www-form-urlencoded":r.get("consumes_value");return(0,d.fromJS)({requestContentType:a,responseContentType:r.get("produces_value")})}function l(e,t){return b(e).getIn(["paths"].concat(n(t),["consumes"]),(0,d.fromJS)({}))}function c(e){return d.Map.isMap(e)?e:new d.Map}Object.defineProperty(t,"__esModule",{value:!0}),t.validateBeforeExecute=t.canExecuteScheme=t.operationScheme=t.hasHost=t.allowTryItOutFor=t.requestFor=t.responseFor=t.requests=t.responses=t.taggedOperations=t.operationsWithTags=t.tagDetails=t.tags=t.operationsWithRootInherited=t.schemes=t.host=t.basePath=t.definitions=t.findDefinition=t.securityDefinitions=t.security=t.produces=t.consumes=t.operations=t.paths=t.semver=t.version=t.externalDocs=t.info=t.spec=t.specResolved=t.specJson=t.specSource=t.specStr=t.url=t.lastError=void 0,t.getParameter=o,t.parameterValues=a,t.parametersIncludeIn=u,t.parametersIncludeType=i,t.contentTypeValues=s,t.operationConsumes=l;var f=r(173),p=r(12),d=r(7),h="default",y=["get","put","post","delete","options","head","patch"],m=function(e){return e||(0,d.Map)()},v=(t.lastError=(0,f.createSelector)(m,function(e){return e.get("lastError")}),t.url=(0,f.createSelector)(m,function(e){return e.get("url")}),t.specStr=(0,f.createSelector)(m,function(e){return e.get("spec")||""}),t.specSource=(0,f.createSelector)(m,function(e){return e.get("specSource")||"not-editor"}),t.specJson=(0,f.createSelector)(m,function(e){return e.get("json",(0,d.Map)())}),t.specResolved=(0,f.createSelector)(m,function(e){return e.get("resolved",(0,d.Map)())})),b=t.spec=function(e){var t=v(e);return t},g=t.info=(0,f.createSelector)(b,function(e){return c(e&&e.get("info"))}),_=(t.externalDocs=(0,f.createSelector)(b,function(e){return c(e&&e.get("externalDocs"))}),t.version=(0,f.createSelector)(g,function(e){return e&&e.get("version")})),E=(t.semver=(0,f.createSelector)(_,function(e){return/v?([0-9]*)\.([0-9]*)\.([0-9]*)/i.exec(e).slice(1)}),t.paths=(0,f.createSelector)(b,function(e){return e.get("paths")})),w=t.operations=(0,f.createSelector)(E,function(e){if(!e||e.size<1)return(0,d.List)();var t=(0,d.List)();return e&&e.forEach?(e.forEach(function(e,r){return e&&e.forEach?void e.forEach(function(e,n){y.indexOf(n)!==-1&&(t=t.push((0,d.fromJS)({path:r,method:n,operation:e,id:n+"-"+r})))}):{}}),t):(0,d.List)()}),j=t.consumes=(0,f.createSelector)(b,function(e){return(0,d.Set)(e.get("consumes"))}),P=t.produces=(0,f.createSelector)(b,function(e){return(0,d.Set)(e.get("produces"))}),O=(t.security=(0,f.createSelector)(b,function(e){return e.get("security",(0,d.List)())}),t.securityDefinitions=(0,f.createSelector)(b,function(e){return e.get("securityDefinitions")}),t.findDefinition=function(e,t){return v(e).getIn(["definitions",t],null)},t.definitions=(0,f.createSelector)(b,function(e){return e.get("definitions")||(0,d.Map)()}),t.basePath=(0,f.createSelector)(b,function(e){return e.get("basePath")}),t.host=(0,f.createSelector)(b,function(e){return e.get("host")}),t.schemes=(0,f.createSelector)(b,function(e){return e.get("schemes",(0,d.Map)())}),t.operationsWithRootInherited=(0,f.createSelector)(w,j,P,function(e,t,r){return e.map(function(e){return e.update("operation",function(e){if(e){if(!d.Map.isMap(e))return;return e.withMutations(function(e){return e.get("consumes")||e.update("consumes",function(e){return(0,d.Set)(e).merge(t)}),e.get("produces")||e.update("produces",function(e){return(0,d.Set)(e).merge(r)}),e})}return(0,d.Map)()})})})),T=t.tags=(0,f.createSelector)(b,function(e){return e.get("tags",(0,d.List)())}),S=t.tagDetails=function(e,t){var r=T(e)||(0,d.List)();return r.filter(d.Map.isMap).find(function(e){return e.get("name")===t},(0,d.Map)())},x=t.operationsWithTags=(0,f.createSelector)(O,function(e){return e.reduce(function(e,t){var r=(0,d.Set)(t.getIn(["operation","tags"]));return r.count()<1?e.update(h,(0,d.List)(),function(e){return e.push(t)}):r.reduce(function(e,r){return e.update(r,(0,d.List)(),function(e){return e.push(t)})},e)},(0,d.Map)())}),C=(t.taggedOperations=function(e){return function(t){var r=t.getConfigs,n=r(),o=n.operationsSorter;return x(e).map(function(t,r){var n="function"==typeof o?o:p.sorters.operationsSorter[o],a=n?t.sort(n):t;return(0,d.Map)({tagDetails:S(e,r),operations:a})})}},t.responses=(0,f.createSelector)(m,function(e){return e.get("responses",(0,d.Map)())})),A=t.requests=(0,f.createSelector)(m,function(e){return e.get("requests",(0,d.Map)())}),R=(t.responseFor=function(e,t,r){return C(e).getIn([t,r],null)},t.requestFor=function(e,t,r){return A(e).getIn([t,r],null)},t.allowTryItOutFor=function(){return!0},t.hasHost=(0,f.createSelector)(b,function(e){var t=e.get("host");return"string"==typeof t&&t.length>0&&"/"!==t[0]}),t.operationScheme=function(e,t,r){var n=e.get("url"),o=n.match(/^([a-z][a-z0-9+\-.]*):/),a=Array.isArray(o)?o[1]:null;return e.getIn(["scheme",t,r])||e.getIn(["scheme","_defaultScheme"])||a||""});t.canExecuteScheme=function(e,t,r){return["http","https"].indexOf(R(e,t,r))>-1},t.validateBeforeExecute=function(e,t){var r=b(e).getIn(["paths"].concat(n(t),["parameters"]),(0,d.fromJS)([])),o=!0;return r.forEach(function(e){var t=e.get("errors");t&&t.count()&&(o=!1)}),o}},function(e,t){"use strict";Object.defineProperty(t,"__esModule",{value:!0});t.updateSpec=function(e,t){var r=t.specActions;return function(){e.apply(void 0,arguments),r.parseToJson.apply(r,arguments)}},t.updateJsonSpec=function(e,t){var r=t.specActions;return function(){e.apply(void 0,arguments),r.resolveSpec.apply(r,arguments)}},t.executeRequest=function(e,t){var r=t.specActions;return function(t){return r.logRequest(t),e(t)}}},function(e,t,r){"use strict";function n(e){if(e&&e.__esModule)return e;var t={};if(null!=e)for(var r in e)Object.prototype.hasOwnProperty.call(e,r)&&(t[r]=e[r]);return t.default=e,t}Object.defineProperty(t,"__esModule",{value:!0}),t.default=function(e){var t=e.getComponents,r=e.getStore,n=e.getSystem,o=a.getComponent,i=a.render,s=a.makeMappedContainer,l=(0,u.memoize)(o.bind(null,n,r,t)),c=(0,u.memoize)(s.bind(null,n,r,l,t));return{rootInjects:{getComponent:l,makeMappedContainer:c,render:i.bind(null,n,r,o,t)}}};var o=r(186),a=n(o),u=r(12)},function(e,t,r){"use strict";function n(e){return e&&e.__esModule?e:{default:e}}function o(e,t){if(!(e instanceof t))throw new TypeError("Cannot call a class as a function")}function a(e,t){if(!e)throw new ReferenceError("this hasn't been initialised - super() hasn't been called");return!t||"object"!=typeof t&&"function"!=typeof t?e:t}function u(e,t){if("function"!=typeof t&&null!==t)throw new TypeError("Super expression must either be null or a function, not "+typeof t);e.prototype=Object.create(t&&t.prototype,{constructor:{value:e,enumerable:!1,writable:!0,configurable:!0}}),t&&(Object.setPrototypeOf?Object.setPrototypeOf(e,t):e.__proto__=t)}Object.defineProperty(t,"__esModule",{value:!0}),t.getComponent=t.render=t.makeMappedContainer=void 0;var i="function"==typeof Symbol&&"symbol"==typeof Symbol.iterator?function(e){return typeof e}:function(e){return e&&"function"==typeof Symbol&&e.constructor===Symbol&&e!==Symbol.prototype?"symbol":typeof e},s=Object.assign||function(e){for(var t=1;t<arguments.length;t++){var r=arguments[t];for(var n in r)Object.prototype.hasOwnProperty.call(r,n)&&(e[n]=r[n])}return e},l=function(){function e(e,t){for(var r=0;r<t.length;r++){var n=t[r];n.enumerable=n.enumerable||!1,n.configurable=!0,"value"in n&&(n.writable=!0),Object.defineProperty(e,n.key,n)}}return function(t,r,n){return r&&e(t.prototype,r),n&&e(t,n),t}}(),c=r(187),f=n(c),p=r(188),d=n(p),h=r(189),y=r(190),m=n(y),v=function(e,t){return function(r){function n(){return o(this,n),a(this,(n.__proto__||Object.getPrototypeOf(n)).apply(this,arguments))}return u(n,r),l(n,[{key:"render",value:function(){return f.default.createElement(t,s({},e(),this.props,this.context))}}]),n}(c.Component)},b=function(e,t){return function(r){function n(){return o(this,n),a(this,(n.__proto__||Object.getPrototypeOf(n)).apply(this,arguments))}return u(n,r),l(n,[{key:"render",value:function(){return f.default.createElement(h.Provider,{store:e},f.default.createElement(t,s({},this.props,this.context)))}}]),n}(c.Component)},g=function(e,t,r){var n=v(e,t,r),o=(0,h.connect)(function(e){return{state:e}})(n);return r?b(r,o):o},_=function(e,t,r,n){for(var o in t){var a=t[o];"function"==typeof a&&a(r[o],n[o],e())}},E=(t.makeMappedContainer=function(e,t,r,n,i,s){return function(t){function n(t,r){o(this,n);var u=a(this,(n.__proto__||Object.getPrototypeOf(n)).call(this,t,r));return _(e,s,t,{}),u}return u(n,t),l(n,[{key:"componentWillReceiveProps",value:function(t){_(e,s,t,this.props)}},{key:"render",value:function(){var e=(0,m.default)(this.props,s?Object.keys(s):[]),t=r(i,"root");return f.default.createElement(t,e)}}]),n}(c.Component)},t.render=function(e,t,r,n,o){var a=document.querySelector(o),u=r(e,t,n,"App","root");d.default.render(f.default.createElement(u,null),a)},function(e){return f.default.createClass({render:function(){return e(this.props)}})}),w=function(e){var t=e.name;return f.default.createElement("div",{style:{padding:"1em",color:"#aaa"}},"😱 ",f.default.createElement("i",null,"Could not render ","t"===t?"this component":t,", see the console."))},j=function(e){var t=function(e){return!(e.prototype&&e.prototype.isReactComponent)},r=t(e)?E(e):e,n=r.prototype.render;return r.prototype.render=function(){try{for(var e=arguments.length,t=Array(e),o=0;o<e;o++)t[o]=arguments[o];return n.apply(this,t)}catch(e){return console.error(e),f.default.createElement(w,{error:e,name:r.name})}},r};t.getComponent=function(e,t,r,n,o){if("string"!=typeof n)throw new TypeError("Need a string, to fetch a component. Was given a "+("undefined"==typeof n?"undefined":i(n)));var a=r(n);return a?o?"root"===o?g(e,a,t()):g(e,a):j(a):(e().log.warn("Could not find component",n),null)}},function(e,t){e.exports=require("react")},function(e,t){e.exports=require("react-dom")},function(e,t){e.exports=require("react-redux")},function(e,t,r){var n=r(25),o=r(191),a=r(227),u=r(135),i=r(197),s=r(230),l=r(213),c=1,f=2,p=4,d=s(function(e,t){var r={};if(null==e)return r;var s=!1;t=n(t,function(t){return t=u(t,e),s||(s=t.length>1),t}),i(e,l(e),r),s&&(r=o(r,c|f|p));for(var d=t.length;d--;)a(r,t[d]);return r});e.exports=d},function(e,t,r){function n(e,t,r,S,x,C){var A,q=t&j,M=t&P,I=t&O;if(r&&(A=x?r(e,S,x,C):r(e)),void 0!==A)return A;if(!E(e))return e;var U=g(e);if(U){if(A=m(e),!q)return c(e,A)}else{var z=y(e),D=z==R||z==k;if(_(e))return l(e,q);if(z==N||z==T||D&&!x){if(A=M||D?{}:b(e),!q)return M?p(e,s(A,e)):f(e,i(A,e))}else{if(!Z[z])return x?e:{};A=v(e,z,n,q)}}C||(C=new o);var L=C.get(e);if(L)return L;C.set(e,A);var B=I?M?h:d:M?keysIn:w,F=U?void 0:B(e);return a(F||e,function(o,a){F&&(a=o,o=e[a]),u(A,a,n(o,t,r,a,e,C))}),A}var o=r(87),a=r(192),u=r(193),i=r(196),s=r(198),l=r(202),c=r(203),f=r(204),p=r(207),d=r(211),h=r(213),y=r(124),m=r(214),v=r(215),b=r(225),g=r(26),_=r(110),E=r(58),w=r(105),j=1,P=2,O=4,T="[object Arguments]",S="[object Array]",x="[object Boolean]",C="[object Date]",A="[object Error]",R="[object Function]",k="[object GeneratorFunction]",q="[object Map]",M="[object Number]",N="[object Object]",I="[object RegExp]",U="[object Set]",z="[object String]",D="[object Symbol]",L="[object WeakMap]",B="[object ArrayBuffer]",F="[object DataView]",J="[object Float32Array]",V="[object Float64Array]",W="[object Int8Array]",H="[object Int16Array]",Y="[object Int32Array]",$="[object Uint8Array]",K="[object Uint8ClampedArray]",X="[object Uint16Array]",G="[object Uint32Array]",Z={};Z[T]=Z[S]=Z[B]=Z[F]=Z[x]=Z[C]=Z[J]=Z[V]=Z[W]=Z[H]=Z[Y]=Z[q]=Z[M]=Z[N]=Z[I]=Z[U]=Z[z]=Z[D]=Z[$]=Z[K]=Z[X]=Z[G]=!0,Z[A]=Z[R]=Z[L]=!1,e.exports=n},function(e,t){function r(e,t){for(var r=-1,n=null==e?0:e.length;++r<n&&t(e[r],r,e)!==!1;);return e}e.exports=r},function(e,t,r){function n(e,t,r){var n=e[t];i.call(e,t)&&a(n,r)&&(void 0!==r||t in e)||o(e,t,r)}var o=r(194),a=r(71),u=Object.prototype,i=u.hasOwnProperty;e.exports=n},function(e,t,r){function n(e,t,r){"__proto__"==t&&o?o(e,t,{configurable:!0,enumerable:!0,value:r,writable:!0}):e[t]=r}var o=r(195);e.exports=n},function(e,t,r){var n=r(55),o=function(){try{var e=n(Object,"defineProperty");return e({},"",{}),e}catch(e){}}();e.exports=o},function(e,t,r){function n(e,t){return e&&o(t,a(t),e)}var o=r(197),a=r(105);e.exports=n},function(e,t,r){function n(e,t,r,n){var u=!r;r||(r={});for(var i=-1,s=t.length;++i<s;){var l=t[i],c=n?n(r[l],e[l],l,r,e):void 0;void 0===c&&(c=e[l]),u?a(r,l,c):o(r,l,c)}return r}var o=r(193),a=r(194);e.exports=n},function(e,t,r){function n(e,t){return e&&o(t,a(t),e)}var o=r(197),a=r(199);e.exports=n},function(e,t,r){function n(e){return u(e)?o(e,!0):a(e)}var o=r(106),a=r(200),u=r(123);e.exports=n},function(e,t,r){function n(e){if(!o(e))return u(e);var t=a(e),r=[];for(var n in e)("constructor"!=n||!t&&s.call(e,n))&&r.push(n);return r}var o=r(58),a=r(120),u=r(201),i=Object.prototype,s=i.hasOwnProperty;e.exports=n},function(e,t){function r(e){var t=[];if(null!=e)for(var r in Object(e))t.push(r);return t}e.exports=r},function(e,t,r){(function(e){function n(e,t){if(t)return e.slice();var r=e.length,n=l?l(r):new e.constructor(r);return e.copy(n),n}var o=r(23),a="object"==typeof t&&t&&!t.nodeType&&t,u=a&&"object"==typeof e&&e&&!e.nodeType&&e,i=u&&u.exports===a,s=i?o.Buffer:void 0,l=s?s.allocUnsafe:void 0;e.exports=n}).call(t,r(111)(e))},function(e,t){function r(e,t){var r=-1,n=e.length;for(t||(t=Array(n));++r<n;)t[r]=e[r];return t}e.exports=r},function(e,t,r){function n(e,t){return o(e,a(e),t)}var o=r(197),a=r(205);e.exports=n},function(e,t,r){var n=r(122),o=r(206),a=Object.getOwnPropertySymbols,u=a?n(a,Object):o;e.exports=u},function(e,t){function r(){return[]}e.exports=r},function(e,t,r){function n(e,t){return o(e,a(e),t)}var o=r(197),a=r(208);e.exports=n},function(e,t,r){var n=r(209),o=r(210),a=r(205),u=r(206),i=Object.getOwnPropertySymbols,s=i?function(e){for(var t=[];e;)n(t,a(e)),e=o(e);return t}:u;e.exports=s},function(e,t){function r(e,t){for(var r=-1,n=t.length,o=e.length;++r<n;)e[o+r]=t[r];return e}e.exports=r},function(e,t,r){var n=r(122),o=n(Object.getPrototypeOf,Object);e.exports=o},function(e,t,r){function n(e){return o(e,u,a)}var o=r(212),a=r(205),u=r(105);e.exports=n},function(e,t,r){function n(e,t,r){var n=t(e);return a(e)?n:o(n,r(e))}var o=r(209),a=r(26);e.exports=n},function(e,t,r){function n(e){return o(e,u,a)}var o=r(212),a=r(208),u=r(199);e.exports=n},function(e,t){function r(e){var t=e.length,r=e.constructor(t);return t&&"string"==typeof e[0]&&o.call(e,"index")&&(r.index=e.index,r.input=e.input),r}var n=Object.prototype,o=n.hasOwnProperty;e.exports=r},function(e,t,r){function n(e,t,r,n){var A=e.constructor;switch(t){case g:return o(e);case f:case p:return new A(+e);case _:return a(e,n);case E:case w:case j:case P:case O:case T:case S:case x:case C:return c(e,n);case d:return u(e,n,r);case h:case v:return new A(e);case y:return i(e);case m:return s(e,n,r);case b:return l(e)}}var o=r(216),a=r(217),u=r(218),i=r(220),s=r(221),l=r(223),c=r(224),f="[object Boolean]",p="[object Date]",d="[object Map]",h="[object Number]",y="[object RegExp]",m="[object Set]",v="[object String]",b="[object Symbol]",g="[object ArrayBuffer]",_="[object DataView]",E="[object Float32Array]",w="[object Float64Array]",j="[object Int8Array]",P="[object Int16Array]",O="[object Int32Array]",T="[object Uint8Array]",S="[object Uint8ClampedArray]",x="[object Uint16Array]",C="[object Uint32Array]";e.exports=n},function(e,t,r){function n(e){var t=new e.constructor(e.byteLength);return new o(t).set(new o(e)),t}var o=r(101);e.exports=n},function(e,t,r){function n(e,t){var r=t?o(e.buffer):e.buffer;return new e.constructor(r,e.byteOffset,e.byteLength)}var o=r(216);e.exports=n},function(e,t,r){function n(e,t,r){var n=t?r(u(e),i):u(e);return a(n,o,new e.constructor)}var o=r(219),a=r(41),u=r(102),i=1;e.exports=n},function(e,t){function r(e,t){return e.set(t[0],t[1]),e}e.exports=r},function(e,t){function r(e){var t=new e.constructor(e.source,n.exec(e));return t.lastIndex=e.lastIndex,t}var n=/\w*$/;e.exports=r},function(e,t,r){function n(e,t,r){var n=t?r(u(e),i):u(e);return a(n,o,new e.constructor)}var o=r(222),a=r(41),u=r(103),i=1;e.exports=n},function(e,t){function r(e,t){return e.add(t),e}e.exports=r},function(e,t,r){function n(e){return u?Object(u.call(e)):{}}var o=r(22),a=o?o.prototype:void 0,u=a?a.valueOf:void 0;e.exports=n},function(e,t,r){function n(e,t){var r=t?o(e.buffer):e.buffer;return new e.constructor(r,e.byteOffset,e.length)}var o=r(216);e.exports=n},function(e,t,r){function n(e){return"function"!=typeof e.constructor||u(e)?{}:o(a(e))}var o=r(226),a=r(210),u=r(120);e.exports=n},function(e,t,r){var n=r(58),o=Object.create,a=function(){function e(){}return function(t){if(!n(t))return{};if(o)return o(t);e.prototype=t;var r=new e;return e.prototype=void 0,r}}();e.exports=a},function(e,t,r){function n(e,t){return t=o(t,e),e=u(e,t),null==e||delete e[i(a(t))]}var o=r(135),a=r(228),u=r(229),i=r(139);e.exports=n},function(e,t){function r(e){var t=null==e?0:e.length;return t?e[t-1]:void 0}e.exports=r},function(e,t,r){function n(e,t){return t.length<2?e:o(e,a(t,0,-1))}var o=r(134),a=r(35);e.exports=n},function(e,t,r){function n(e){return u(a(e,void 0,o),e+"")}var o=r(231),a=r(234),u=r(236);e.exports=n},function(e,t,r){function n(e){var t=null==e?0:e.length;return t?o(e,1):[]}var o=r(232);e.exports=n},function(e,t,r){function n(e,t,r,u,i){var s=-1,l=e.length;for(r||(r=a),i||(i=[]);++s<l;){var c=e[s];t>0&&r(c)?t>1?n(c,t-1,r,u,i):o(i,c):u||(i[i.length]=c)}return i}var o=r(209),a=r(233);e.exports=n},function(e,t,r){function n(e){return u(e)||a(e)||!!(i&&e&&e[i])}var o=r(22),a=r(108),u=r(26),i=o?o.isConcatSpreadable:void 0;e.exports=n},function(e,t,r){function n(e,t,r){return t=a(void 0===t?e.length-1:t,0),function(){for(var n=arguments,u=-1,i=a(n.length-t,0),s=Array(i);++u<i;)s[u]=n[t+u];u=-1;for(var l=Array(t+1);++u<t;)l[u]=n[u];return l[t]=r(s),o(e,this,l)}}var o=r(235),a=Math.max;e.exports=n},function(e,t){function r(e,t,r){switch(r.length){case 0:return e.call(t);case 1:return e.call(t,r[0]);case 2:return e.call(t,r[0],r[1]);case 3:return e.call(t,r[0],r[1],r[2])}return e.apply(t,r)}e.exports=r},function(e,t,r){var n=r(237),o=r(239),a=o(n);e.exports=a},function(e,t,r){var n=r(238),o=r(195),a=r(143),u=o?function(e,t){return o(e,"toString",{configurable:!0,enumerable:!1,value:n(t),writable:!0})}:a;e.exports=u},function(e,t){function r(e){return function(){return e}}e.exports=r},function(e,t){function r(e){var t=0,r=0;return function(){var u=a(),i=o-(u-r);if(r=u,i>0){if(++t>=n)return arguments[0]}else t=0;return e.apply(void 0,arguments)}}var n=800,o=16,a=Date.now;e.exports=r},function(e,t,r){"use strict";function n(e){if(e&&e.__esModule)return e;var t={};if(null!=e)for(var r in e)Object.prototype.hasOwnProperty.call(e,r)&&(t[r]=e[r]);return t.default=e,t}Object.defineProperty(t,"__esModule",{value:!0}),t.default=function(){return{fn:a}};var o=r(154),a=n(o)},function(e,t){"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.default=function(e){function t(e){for(var t,r=arguments.length,n=Array(r>1?r-1:0),a=1;a<r;a++)n[a-1]=arguments[a];o(e)>=u&&(t=console)[e].apply(t,n)}var r=e.configs,n={debug:0,info:1,log:2,warn:3,error:4},o=function(e){return n[e]||-1},a=r.logLevel,u=o(a);return t.warn=t.bind(null,"warn"),t.error=t.bind(null,"error"),t.info=t.bind(null,"info"),t.debug=t.bind(null,"debug"),{rootInjects:{log:t}}}},function(e,t,r){"use strict";function n(e){return e&&e.__esModule?e:{default:e}}function o(e){if(e&&e.__esModule)return e;var t={};if(null!=e)for(var r in e)Object.prototype.hasOwnProperty.call(e,r)&&(t[r]=e[r]);return t.default=e,t}Object.defineProperty(t,"__esModule",{value:!0}),t.default=function(){return{fn:{AST:u},components:{JumpToPath:s.default}}};var a=r(243),u=o(a),i=r(252),s=n(i)},function(e,t,r){"use strict";function n(e){return e&&e.__esModule?e:{default:e}}function o(e,t){function r(e,t,o){if(!e)return o&&o.start_mark?o.start_mark.line:0;if(t.length&&e.tag===v)for(n=0;n<e.value.length;n++){var a=e.value[n],u=a[0],i=a[1];if(u.value===t[0])return r(i,t.slice(1),e);if(u.value===t[0].replace(/\[.*/,"")){var s=parseInt(t[0].match(/\[(.*)\]/)[1]);if(1===i.value.length&&0!==s&&s)var l=(0,h.default)(i.value[0],{value:s.toString()});else var l=i.value[s];return r(l,t.slice(1),i.value)}}if(t.length&&e.tag===b){var c=e.value[t[0]];if(c&&c.tag)return r(c,t.slice(1),e.value)}return e.tag!==v||Array.isArray(o)?e.start_mark.line+1:e.start_mark.line}if("string"!=typeof e)throw new TypeError("yaml should be a string");if(!(0,p.default)(t))throw new TypeError("path should be an array of strings");var n=0,o=m(e);return r(o,t)}function a(e,t){function r(e){if(e.tag===v)for(o=0;o<e.value.length;o++){var a=e.value[o],u=a[0],i=a[1];if(u.value===t[0])return t.shift(),r(i)}if(e.tag===b){var s=e.value[t[0]];if(s&&s.tag)return t.shift(),r(s)}return t.length?n:{start:{line:e.start_mark.line,column:e.start_mark.column},end:{line:e.end_mark.line,column:e.end_mark.column}}}if("string"!=typeof e)throw new TypeError("yaml should be a string");if(!(0,p.default)(t))throw new TypeError("path should be an array of strings");var n={start:{line:-1,column:-1},end:{line:-1,column:-1}},o=0,a=m(e);return r(a)}function u(e,t){function r(e){function n(e){return e.start_mark.line===e.end_mark.line?t.line===e.start_mark.line&&e.start_mark.column<=t.column&&e.end_mark.column>=t.column:t.line===e.start_mark.line?t.column>=e.start_mark.column:t.line===e.end_mark.line?t.column<=e.end_mark.column:e.start_mark.line<t.line&&e.end_mark.line>t.line}var a=0;if(!e||[v,b].indexOf(e.tag)===-1)return o;if(e.tag===v)for(a=0;a<e.value.length;a++){var u=e.value[a],i=u[0],s=u[1];if(n(i))return o;if(n(s))return o.push(i.value),r(s)}if(e.tag===b)for(a=0;a<e.value.length;a++){var l=e.value[a];if(n(l))return o.push(a.toString()),r(l)}return o}if("string"!=typeof e)throw new TypeError("yaml should be a string");if("object"!==("undefined"==typeof t?"undefined":s(t))||"number"!=typeof t.line||"number"!=typeof t.column)throw new TypeError("position should be an object with line and column properties");try{var n=m(e)}catch(r){return console.error("Error composing AST",r),console.error("Problem area:\n",e.split("\n").slice(t.line-5,t.line+5).join("\n")),null}var o=[];return r(n)}function i(e){return function(){for(var t=arguments.length,r=Array(t),n=0;n<t;n++)r[n]=arguments[n];return new Promise(function(t){return t(e.apply(void 0,r))})}}Object.defineProperty(t,"__esModule",{value:!0}),t.getLineNumberForPathAsync=t.positionRangeForPathAsync=t.pathForPositionAsync=void 0;var s="function"==typeof Symbol&&"symbol"==typeof Symbol.iterator?function(e){return typeof e}:function(e){return e&&"function"==typeof Symbol&&e.constructor===Symbol&&e!==Symbol.prototype?"symbol":typeof e};t.getLineNumberForPath=o,t.positionRangeForPath=a,t.pathForPosition=u;var l=r(244),c=n(l),f=r(26),p=n(f),d=r(245),h=n(d),y=r(12),m=(0,y.memoize)(c.default.compose),v="tag:yaml.org,2002:map",b="tag:yaml.org,2002:seq";t.pathForPositionAsync=i(u),t.positionRangeForPathAsync=i(a),t.getLineNumberForPathAsync=i(o)},function(e,t){e.exports=require("yaml-js")},function(e,t,r){var n=r(246),o=r(247),a=n(o);e.exports=a},function(e,t,r){function n(e){return function(t,r,n){var i=Object(t);if(!a(t)){var s=o(r,3);t=u(t),r=function(e){return s(i[e],e,i)}}var l=e(t,r,n);return l>-1?i[s?t[l]:l]:void 0}}var o=r(84),a=r(123),u=r(105);e.exports=n},function(e,t,r){function n(e,t,r){var n=null==e?0:e.length;if(!n)return-1;var s=null==r?0:u(r);return s<0&&(s=i(n+s,0)),o(e,a(t,3),s)}var o=r(248),a=r(84),u=r(249),i=Math.max;e.exports=n},function(e,t){function r(e,t,r,n){for(var o=e.length,a=r+(n?1:-1);n?a--:++a<o;)if(t(e[a],a,e))return a;return-1}e.exports=r},function(e,t,r){function n(e){var t=o(e),r=t%1;return t===t?r?t-r:t:0}var o=r(250);e.exports=n},function(e,t,r){function n(e){if(!e)return 0===e?e:0;if(e=o(e),e===a||e===-a){var t=e<0?-1:1;return t*u}return e===e?e:0}var o=r(251),a=1/0,u=1.7976931348623157e308;e.exports=n},function(e,t,r){function n(e){if("number"==typeof e)return e;if(a(e))return u;if(o(e)){var t="function"==typeof e.valueOf?e.valueOf():e;e=o(t)?t+"":t}if("string"!=typeof e)return 0===e?e:+e;e=e.replace(i,"");var r=l.test(e);return r||c.test(e)?f(e.slice(2),r?2:8):s.test(e)?u:+e}var o=r(58),a=r(27),u=NaN,i=/^\s+|\s+$/g,s=/^[-+]0x[0-9a-f]+$/i,l=/^0b[01]+$/i,c=/^0o[0-7]+$/i,f=parseInt;e.exports=n},function(e,t,r){"use strict";function n(e){return e&&e.__esModule?e:{default:e}}function o(e,t){if(!(e instanceof t))throw new TypeError("Cannot call a class as a function")}function a(e,t){if(!e)throw new ReferenceError("this hasn't been initialised - super() hasn't been called");return!t||"object"!=typeof t&&"function"!=typeof t?e:t}function u(e,t){if("function"!=typeof t&&null!==t)throw new TypeError("Super expression must either be null or a function, not "+typeof t);e.prototype=Object.create(t&&t.prototype,{constructor:{value:e,enumerable:!1,writable:!0,configurable:!0}}),t&&(Object.setPrototypeOf?Object.setPrototypeOf(e,t):e.__proto__=t)}Object.defineProperty(t,"__esModule",{value:!0});var i=function(){function e(e,t){for(var r=0;r<t.length;r++){var n=t[r];n.enumerable=n.enumerable||!1,n.configurable=!0,"value"in n&&(n.writable=!0),Object.defineProperty(e,n.key,n)}}return function(t,r,n){return r&&e(t.prototype,r),n&&e(t,n),t}}(),s=r(187),l=n(s),c=function(e){function t(){return o(this,t),a(this,(t.__proto__||Object.getPrototypeOf(t)).apply(this,arguments))}return u(t,e),i(t,[{key:"render",value:function(){return null}}]),t}(l.default.Component);t.default=c},function(e,t,r){"use strict";function n(e){return e&&e.__esModule?e:{default:e}}var o=r(254),a=n(o);e.exports=function(e){var t=e.configs;return{fn:{fetch:a.default.makeHttp(t.preFetch,t.postFetch),buildRequest:a.default.buildRequest,execute:a.default.execute,resolve:a.default.resolve,serializeRes:a.default.serializeRes,opId:a.default.helpers.opId}}}},function(e,t){e.exports=require("swagger-client")},function(e,t,r){"use strict";function n(e){if(e&&e.__esModule)return e;var t={};if(null!=e)for(var r in e)Object.prototype.hasOwnProperty.call(e,r)&&(t[r]=e[r]);return t.default=e,t}function o(e){return e&&e.__esModule?e:{default:e}}Object.defineProperty(t,"__esModule",{value:!0}),t.default=function(){return{statePlugins:{auth:{reducers:u.default,actions:s,selectors:c},spec:{wrapActions:p}}}};var a=r(256),u=o(a),i=r(257),s=n(i),l=r(258),c=n(l),f=r(259),p=n(f)},function(e,t,r){"use strict";function n(e,t,r){return t in e?Object.defineProperty(e,t,{value:r,enumerable:!0,configurable:!0,writable:!0}):e[t]=r,e}Object.defineProperty(t,"__esModule",{value:!0});var o,a=function(){function e(e,t){var r=[],n=!0,o=!1,a=void 0;try{for(var u,i=e[Symbol.iterator]();!(n=(u=i.next()).done)&&(r.push(u.value),!t||r.length!==t);n=!0);}catch(e){o=!0,a=e}finally{try{!n&&i.return&&i.return()}finally{if(o)throw a}}return r}return function(t,r){if(Array.isArray(t))return t;if(Symbol.iterator in Object(t))return e(t,r);throw new TypeError("Invalid attempt to destructure non-iterable instance")}}(),u=r(7),i=r(12),s=r(257);t.default=(o={},n(o,s.SHOW_AUTH_POPUP,function(e,t){var r=t.payload;return e.set("showDefinitions",r)}),n(o,s.AUTHORIZE,function(e,t){var r=t.payload,n=(0,u.fromJS)(r),o=e.get("authorized")||(0,u.Map)();return n.entrySeq().forEach(function(e){var t=a(e,2),r=t[0],n=t[1],u=n.getIn(["schema","type"]);if("apiKey"===u)o=o.set(r,n);else if("basic"===u){var s=n.getIn(["value","username"]),l=n.getIn(["value","password"]);o=o.setIn([r,"value"],{username:s,header:"Basic "+(0,i.btoa)(s+":"+l)}),o=o.setIn([r,"schema"],n.get("schema"))}}),e.set("authorized",o)}),n(o,s.AUTHORIZE_OAUTH2,function(e,t){var r=t.payload,n=r.auth,o=r.token,a=void 0;return n.token=o,a=(0,u.fromJS)(n),e.setIn(["authorized",a.get("name")],a)}),n(o,s.LOGOUT,function(e,t){var r=t.payload,n=e.get("authorized").withMutations(function(e){r.forEach(function(t){e.delete(t)})});return e.set("authorized",n)}),n(o,s.CONFIGURE_AUTH,function(e,t){var r=t.payload;return e.set("configs",r)}),o)},function(e,t,r){"use strict";function n(e){return e&&e.__esModule?e:{default:e}}function o(e){return{type:p,payload:e}}function a(e){return{type:d,payload:e}}function u(e){return{ type:h,payload:e}}function i(e){return{type:y,payload:e}}function s(e){return{type:m,payload:e}}Object.defineProperty(t,"__esModule",{value:!0}),t.authorizeRequest=t.authorizeAccessCode=t.authorizeApplication=t.authorizePassword=t.preAuthorizeImplicit=t.CONFIGURE_AUTH=t.VALIDATE=t.AUTHORIZE_OAUTH2=t.PRE_AUTHORIZE_OAUTH2=t.LOGOUT=t.AUTHORIZE=t.SHOW_AUTH_POPUP=void 0,t.showDefinitions=o,t.authorize=a,t.logout=u,t.authorizeOauth2=i,t.configureAuth=s;var l=r(11),c=n(l),f=r(12),p=t.SHOW_AUTH_POPUP="show_popup",d=t.AUTHORIZE="authorize",h=t.LOGOUT="logout",y=(t.PRE_AUTHORIZE_OAUTH2="pre_authorize_oauth2",t.AUTHORIZE_OAUTH2="authorize_oauth2"),m=(t.VALIDATE="validate",t.CONFIGURE_AUTH="configure_auth"),v=" ";t.preAuthorizeImplicit=function(e){return function(t){var r=t.authActions,n=t.errActions,o=e.auth,a=e.token,u=e.isValid,i=o.schema,s=o.name,l=i.get("flow");return delete c.default.swaggerUIRedirectOauth2,"accessCode"===l||u||n.newAuthErr({authId:s,source:"auth",level:"warning",message:"Authorization may be unsafe, passed state was changed in server Passed state wasn't returned from auth server"}),a.error?void n.newAuthErr({authId:s,source:"auth",level:"error",message:JSON.stringify(a)}):void r.authorizeOauth2({auth:o,token:a})}},t.authorizePassword=function(e){return function(t){var r=t.authActions,n=e.schema,o=e.name,a=e.username,u=e.password,i=e.passwordType,s=e.clientId,l=e.clientSecret,c={grant_type:"password",scopes:encodeURIComponent(e.scopes.join(v))},p={},d={};return"basic"===i?d.Authorization="Basic "+(0,f.btoa)(a+":"+u):(Object.assign(c,{username:a},{password:u}),"query"===i?(s&&(p.client_id=s),l&&(p.client_secret=l)):d.Authorization="Basic "+(0,f.btoa)(s+":"+l)),r.authorizeRequest({body:(0,f.buildFormData)(c),url:n.get("tokenUrl"),name:o,headers:d,query:p,auth:e})}},t.authorizeApplication=function(e){return function(t){var r=t.authActions,n=e.schema,o=e.scopes,a=e.name,u=e.clientId,i=e.clientSecret,s={Authorization:"Basic "+(0,f.btoa)(u+":"+i)},l={grant_type:"client_credentials",scope:o.join(v)};return r.authorizeRequest({body:(0,f.buildFormData)(l),name:a,url:n.get("tokenUrl"),auth:e,headers:s})}},t.authorizeAccessCode=function(e){var t=e.auth,r=e.redirectUrl;return function(e){var n=e.authActions,o=t.schema,a=t.name,u=t.clientId,i=t.clientSecret,s={grant_type:"authorization_code",code:t.code,client_id:u,client_secret:i,redirect_uri:r};return n.authorizeRequest({body:(0,f.buildFormData)(s),name:a,url:o.get("tokenUrl"),auth:t})}},t.authorizeRequest=function(e){return function(t){var r=t.fn,n=t.authActions,o=t.errActions,a=t.authSelectors,u=e.body,i=e.query,s=void 0===i?{}:i,l=e.headers,c=void 0===l?{}:l,f=e.name,p=e.url,d=e.auth,h=a.getConfigs()||{},y=h.additionalQueryStringParams,m=p;for(var v in y)p+="&"+v+"="+encodeURIComponent(y[v]);var b=Object.assign({Accept:"application/json, text/plain, */*","Access-Control-Allow-Origin":"*","Content-Type":"application/x-www-form-urlencoded"},c);r.fetch({url:m,method:"post",headers:b,query:s,body:u}).then(function(e){var t=JSON.parse(e.data),r=t&&(t.error||""),a=t&&(t.parseError||"");return e.ok?r||a?void o.newAuthErr({authId:f,level:"error",source:"auth",message:JSON.stringify(t)}):void n.authorizeOauth2({auth:d,token:t}):void o.newAuthErr({authId:f,level:"error",source:"auth",message:e.statusText})}).catch(function(e){var t=new Error(e);o.newAuthErr({authId:f,level:"error",source:"auth",message:t.message})})}}},function(e,t,r){"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.getConfigs=t.isAuthorized=t.authorized=t.getDefinitionsByNames=t.definitionsToAuthorize=t.shownDefinitions=void 0;var n=function(){function e(e,t){var r=[],n=!0,o=!1,a=void 0;try{for(var u,i=e[Symbol.iterator]();!(n=(u=i.next()).done)&&(r.push(u.value),!t||r.length!==t);n=!0);}catch(e){o=!0,a=e}finally{try{!n&&i.return&&i.return()}finally{if(o)throw a}}return r}return function(t,r){if(Array.isArray(t))return t;if(Symbol.iterator in Object(t))return e(t,r);throw new TypeError("Invalid attempt to destructure non-iterable instance")}}(),o=r(173),a=r(7),u=function(e){return e};t.shownDefinitions=(0,o.createSelector)(u,function(e){return e.get("showDefinitions")}),t.definitionsToAuthorize=(0,o.createSelector)(u,function(){return function(e){var t=e.specSelectors,r=t.securityDefinitions(),o=(0,a.List)();return r.entrySeq().forEach(function(e){var t=n(e,2),r=t[0],u=t[1],i=(0,a.Map)();i=i.set(r,u),o=o.push(i)}),o}}),t.getDefinitionsByNames=function(e,t){return function(e){var r=e.specSelectors,o=r.securityDefinitions(),u=(0,a.List)();return t.valueSeq().forEach(function(e){var t=(0,a.Map)();e.entrySeq().forEach(function(e){var r=n(e,2),a=r[0],u=r[1],i=o.get(a),s=void 0;"oauth2"===i.get("type")&&u.size&&(s=i.get("scopes"),s.keySeq().forEach(function(e){u.contains(e)||(s=s.delete(e))}),i=i.set("allowedScopes",s)),t=t.set(a,i)}),u=u.push(t)}),u}},t.authorized=(0,o.createSelector)(u,function(e){return e.get("authorized")||(0,a.Map)()}),t.isAuthorized=function(e,t){return function(e){var r=e.authSelectors,n=r.authorized();return a.List.isList(t)?!!t.toJS().filter(function(e){var t=!0;return Object.keys(e).map(function(e){return!t||!!n.get(e)}).indexOf(!1)===-1}).length:null}},t.getConfigs=(0,o.createSelector)(u,function(e){return e.get("configs")})},function(e,t){"use strict";Object.defineProperty(t,"__esModule",{value:!0});var r=Object.assign||function(e){for(var t=1;t<arguments.length;t++){var r=arguments[t];for(var n in r)Object.prototype.hasOwnProperty.call(r,n)&&(e[n]=r[n])}return e};t.execute=function(e,t){var n=t.authSelectors,o=t.specSelectors;return function(t){var a=t.path,u=t.method,i=t.operation,s=t.extras,l={authorized:n.authorized()&&n.authorized().toJS(),definitions:o.securityDefinitions()&&o.securityDefinitions().toJS(),specSecurity:o.security()&&o.security().toJS()};return e(r({path:a,method:u,operation:i,securities:l},s))}}},function(e,t,r){"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.default=function(){return{fn:{shallowEqualKeys:n.shallowEqualKeys,transformPathToArray:o.transformPathToArray}}};var n=r(12),o=r(261)},function(e,t,r){"use strict";function n(e){return e&&e.__esModule?e:{default:e}}function o(e,t){if("instance."===e.slice(0,9))var r=e.slice(9);else var r=e;var n=[];return r.split(".").map(function(e){if(e.includes("[")){var t=parseInt(e.match(/\[(.*)\]/)[1]),r=e.slice(0,e.indexOf("["));return[r,t.toString()]}return e}).reduce(function(e,t){return e.concat(t)},[]).concat([""]).reduce(function(e,r){var o=n.length?(0,i.default)(t,n):t;return(0,i.default)(o,a(e,r))?(e.length&&n.push(e),r.length&&n.push(r),""):""+e+(e.length?".":"")+r},""),"undefined"!=typeof(0,i.default)(t,n)?n:null}function a(e,t){var r=[];return e.length&&r.push(e),t.length&&r.push(t),r}Object.defineProperty(t,"__esModule",{value:!0}),t.transformPathToArray=o;var u=r(133),i=n(u)},function(e,t,r){"use strict";function n(e){if(e&&e.__esModule)return e;var t={};if(null!=e)for(var r in e)Object.prototype.hasOwnProperty.call(e,r)&&(t[r]=e[r]);return t.default=e,t}function o(){return{components:u}}Object.defineProperty(t,"__esModule",{value:!0}),t.default=o;var a=r(263),u=n(a)},function(e,t,r){"use strict";var n=r(12),o=r(264);o.keys().forEach(function(t){if("./index.js"!==t){var r=o(t);e.exports[(0,n.pascalCaseFilename)(t)]=r.default?r.default:r}})},function(e,t,r){function n(e){return r(o(e))}function o(e){return a[e]||function(){throw new Error("Cannot find module '"+e+"'.")}()}var a={"./index.js":263,"./split-pane-mode.jsx":265};n.keys=function(){return Object.keys(a)},n.resolve=o,e.exports=n,n.id=264},function(e,t,r){"use strict";function n(e){return e&&e.__esModule?e:{default:e}}function o(e,t){if(!(e instanceof t))throw new TypeError("Cannot call a class as a function")}function a(e,t){if(!e)throw new ReferenceError("this hasn't been initialised - super() hasn't been called");return!t||"object"!=typeof t&&"function"!=typeof t?e:t}function u(e,t){if("function"!=typeof t&&null!==t)throw new TypeError("Super expression must either be null or a function, not "+typeof t);e.prototype=Object.create(t&&t.prototype,{constructor:{value:e,enumerable:!1,writable:!0,configurable:!0}}),t&&(Object.setPrototypeOf?Object.setPrototypeOf(e,t):e.__proto__=t)}Object.defineProperty(t,"__esModule",{value:!0});var i=function(){function e(e,t){for(var r=0;r<t.length;r++){var n=t[r];n.enumerable=n.enumerable||!1,n.configurable=!0,"value"in n&&(n.writable=!0),Object.defineProperty(e,n.key,n)}}return function(t,r,n){return r&&e(t.prototype,r),n&&e(t,n),t}}(),s=r(187),l=n(s),c=r(266),f=n(c);r(267);var p=["split-pane-mode"],d="left",h="right",y="both",m=function(e){function t(){var e,r,n,u;o(this,t);for(var i=arguments.length,s=Array(i),l=0;l<i;l++)s[l]=arguments[l];return r=n=a(this,(e=t.__proto__||Object.getPrototypeOf(t)).call.apply(e,[this].concat(s))),n.onDragFinished=function(){var e=n.props,t=e.threshold,r=e.layoutActions,o=n.refs.splitPane.state,a=o.position,u=o.draggedSize;n.draggedSize=u;var i=a<=t,s=u<=t;r.changeMode(p,i?h:s?d:y)},n.sizeFromMode=function(e,t){return e===d?(n.draggedSize=null,"0px"):e===h?(n.draggedSize=null,"100%"):n.draggedSize||t},u=r,a(n,u)}return u(t,e),i(t,[{key:"render",value:function(){var e=this.props,t=e.children,r=e.layoutSelectors,n=r.whatMode(p),o=n===h?l.default.createElement("noscript",null):t[0],a=n===d?l.default.createElement("noscript",null):t[1],u=this.sizeFromMode(n,"50%");return l.default.createElement(f.default,{disabledClass:"",ref:"splitPane",split:"vertical",defaultSize:"50%",primary:"second",minSize:0,size:u,onDragFinished:this.onDragFinished,allowResize:n!==d&&n!==h,resizerStyle:{flex:"0 0 auto",position:"relative"}},o,a)}}]),t}(l.default.Component);m.propTypes={threshold:s.PropTypes.number,children:s.PropTypes.array,layoutSelectors:s.PropTypes.object.isRequired,layoutActions:s.PropTypes.object.isRequired},m.defaultProps={threshold:100,children:[]},t.default=m},function(e,t){e.exports=require("react-split-pane")},2,function(e,t,r){"use strict";function n(e){var t=e.fn,r={download:function(e){return function(r){function n(t){return t instanceof Error||t.status>=400?(u.updateLoadingStatus("failed"),o.newThrownErr(new Error(t.statusText+" "+e))):(u.updateLoadingStatus("success"),u.updateSpec(t.text),void u.updateUrl(e))}var o=r.errActions,a=r.specSelectors,u=r.specActions,i=t.fetch;e=e||a.url(),u.updateLoadingStatus("loading"),i({url:e,loadSpec:!0,credentials:"same-origin",headers:{Accept:"application/json,*/*"}}).then(n,n)}},updateLoadingStatus:function(e){var t=[null,"loading","failed","success","failedConfig"];return t.indexOf(e)===-1&&console.error("Error: "+e+" is not one of "+JSON.stringify(t)),{type:"spec_update_loading_status",payload:e}}},n={spec_update_loading_status:function(e,t){return"string"==typeof t.payload?e.set("loadingStatus",t.payload):e}},u={loadingStatus:(0,o.createSelector)(function(e){return e||(0,a.Map)()},function(e){return e.get("loadingStatus")||null})};return{statePlugins:{spec:{actions:r,reducers:n,selectors:u}}}}Object.defineProperty(t,"__esModule",{value:!0}),t.default=n;var o=r(173),a=r(7)},function(e,t,r){"use strict";function n(e){return e&&e.__esModule?e:{default:e}}function o(e,t){if(!(e instanceof t))throw new TypeError("Cannot call a class as a function")}function a(e,t){if(!e)throw new ReferenceError("this hasn't been initialised - super() hasn't been called");return!t||"object"!=typeof t&&"function"!=typeof t?e:t}function u(e,t){if("function"!=typeof t&&null!==t)throw new TypeError("Super expression must either be null or a function, not "+typeof t);e.prototype=Object.create(t&&t.prototype,{constructor:{value:e,enumerable:!1,writable:!0,configurable:!0}}),t&&(Object.setPrototypeOf?Object.setPrototypeOf(e,t):e.__proto__=t)}Object.defineProperty(t,"__esModule",{value:!0});var i=function(){function e(e,t){for(var r=0;r<t.length;r++){var n=t[r];n.enumerable=n.enumerable||!1,n.configurable=!0,"value"in n&&(n.writable=!0),Object.defineProperty(e,n.key,n)}}return function(t,r,n){return r&&e(t.prototype,r),n&&e(t,n),t}}(),s=r(187),l=n(s),c=function(e){function t(){return o(this,t),a(this,(t.__proto__||Object.getPrototypeOf(t)).apply(this,arguments))}return u(t,e),i(t,[{key:"getLayout",value:function(){var e=this.props,t=e.getComponent,r=e.layoutSelectors,n=r.current(),o=t(n,!0);return o?o:function(){return l.default.createElement("h1",null,' No layout defined for "',n,'" ')}}},{key:"render",value:function(){var e=this.getLayout();return l.default.createElement(e,null)}}]),t}(l.default.Component);t.default=c,c.propTypes={getComponent:s.PropTypes.func.isRequired,layoutSelectors:s.PropTypes.object.isRequired},c.defaultProps={}},function(e,t,r){"use strict";function n(e){return e&&e.__esModule?e:{default:e}}function o(e,t){if(!(e instanceof t))throw new TypeError("Cannot call a class as a function")}function a(e,t){if(!e)throw new ReferenceError("this hasn't been initialised - super() hasn't been called");return!t||"object"!=typeof t&&"function"!=typeof t?e:t}function u(e,t){if("function"!=typeof t&&null!==t)throw new TypeError("Super expression must either be null or a function, not "+typeof t);e.prototype=Object.create(t&&t.prototype,{constructor:{value:e,enumerable:!1,writable:!0,configurable:!0}}),t&&(Object.setPrototypeOf?Object.setPrototypeOf(e,t):e.__proto__=t)}Object.defineProperty(t,"__esModule",{value:!0});var i=function(){function e(e,t){for(var r=0;r<t.length;r++){var n=t[r];n.enumerable=n.enumerable||!1,n.configurable=!0,"value"in n&&(n.writable=!0),Object.defineProperty(e,n.key,n)}}return function(t,r,n){return r&&e(t.prototype,r),n&&e(t,n),t}}(),s=r(187),l=n(s),c=function(e){function t(){var e,r,n,u;o(this,t);for(var i=arguments.length,s=Array(i),l=0;l<i;l++)s[l]=arguments[l];return r=n=a(this,(e=t.__proto__||Object.getPrototypeOf(t)).call.apply(e,[this].concat(s))),n.close=function(){var e=n.props.authActions;e.showDefinitions(!1)},u=r,a(n,u)}return u(t,e),i(t,[{key:"render",value:function(){var e=this.props,t=e.authSelectors,r=e.authActions,n=e.getComponent,o=e.errSelectors,a=e.specSelectors,u=e.fn.AST,i=t.shownDefinitions(),s=n("auths");return l.default.createElement("div",{className:"dialog-ux"},l.default.createElement("div",{className:"backdrop-ux"}),l.default.createElement("div",{className:"modal-ux"},l.default.createElement("div",{className:"modal-dialog-ux"},l.default.createElement("div",{className:"modal-ux-inner"},l.default.createElement("div",{className:"modal-ux-header"},l.default.createElement("h3",null,"Available authorizations"),l.default.createElement("button",{type:"button",className:"close-modal",onClick:this.close},l.default.createElement("svg",{width:"20",height:"20"},l.default.createElement("use",{xlinkHref:"#close"})))),l.default.createElement("div",{className:"modal-ux-content"},i.valueSeq().map(function(e,i){return l.default.createElement(s,{key:i,AST:u,definitions:e,getComponent:n,errSelectors:o,authSelectors:t,authActions:r,specSelectors:a})}))))))}}]),t}(l.default.Component);c.propTypes={fn:s.PropTypes.object.isRequired,getComponent:s.PropTypes.func.isRequired,authSelectors:s.PropTypes.object.isRequired,specSelectors:s.PropTypes.object.isRequired,errSelectors:s.PropTypes.object.isRequired,authActions:s.PropTypes.object.isRequired},t.default=c},function(e,t,r){"use strict";function n(e){return e&&e.__esModule?e:{default:e}}function o(e,t){if(!(e instanceof t))throw new TypeError("Cannot call a class as a function")}function a(e,t){if(!e)throw new ReferenceError("this hasn't been initialised - super() hasn't been called");return!t||"object"!=typeof t&&"function"!=typeof t?e:t}function u(e,t){if("function"!=typeof t&&null!==t)throw new TypeError("Super expression must either be null or a function, not "+typeof t);e.prototype=Object.create(t&&t.prototype,{constructor:{value:e,enumerable:!1,writable:!0,configurable:!0}}),t&&(Object.setPrototypeOf?Object.setPrototypeOf(e,t):e.__proto__=t)}Object.defineProperty(t,"__esModule",{value:!0});var i=function(){function e(e,t){for(var r=0;r<t.length;r++){var n=t[r];n.enumerable=n.enumerable||!1,n.configurable=!0,"value"in n&&(n.writable=!0),Object.defineProperty(e,n.key,n)}}return function(t,r,n){return r&&e(t.prototype,r),n&&e(t,n),t}}(),s=r(187),l=n(s),c=function(e){function t(){var e,r,n,u;o(this,t);for(var i=arguments.length,s=Array(i),l=0;l<i;l++)s[l]=arguments[l];return r=n=a(this,(e=t.__proto__||Object.getPrototypeOf(t)).call.apply(e,[this].concat(s))),n.onClick=function(){var e=n.props,t=e.authActions,r=e.authSelectors,o=r.definitionsToAuthorize();t.showDefinitions(o)},u=r,a(n,u)}return u(t,e),i(t,[{key:"render",value:function(){var e=this.props,t=e.authSelectors,r=e.getComponent,n=r("authorizationPopup",!0),o=!!t.shownDefinitions(),a=!!t.authorized().size;return l.default.createElement("div",{className:"auth-wrapper"},l.default.createElement("button",{className:a?"btn authorize locked":"btn authorize unlocked",onClick:this.onClick},l.default.createElement("span",null,"Authorize"),l.default.createElement("svg",{width:"20",height:"20"},l.default.createElement("use",{xlinkHref:a?"#locked":"#unlocked"}))),o&&l.default.createElement(n,null))}}]),t}(l.default.Component);c.propTypes={className:s.PropTypes.string},c.propTypes={getComponent:s.PropTypes.func.isRequired,authSelectors:s.PropTypes.object.isRequired,errActions:s.PropTypes.object.isRequired,authActions:s.PropTypes.object.isRequired},t.default=c},function(e,t,r){"use strict";function n(e){return e&&e.__esModule?e:{default:e}}function o(e,t){if(!(e instanceof t))throw new TypeError("Cannot call a class as a function")}function a(e,t){if(!e)throw new ReferenceError("this hasn't been initialised - super() hasn't been called");return!t||"object"!=typeof t&&"function"!=typeof t?e:t}function u(e,t){if("function"!=typeof t&&null!==t)throw new TypeError("Super expression must either be null or a function, not "+typeof t);e.prototype=Object.create(t&&t.prototype,{constructor:{value:e,enumerable:!1,writable:!0,configurable:!0}}),t&&(Object.setPrototypeOf?Object.setPrototypeOf(e,t):e.__proto__=t)}Object.defineProperty(t,"__esModule",{value:!0});var i=function(){function e(e,t){for(var r=0;r<t.length;r++){var n=t[r];n.enumerable=n.enumerable||!1,n.configurable=!0,"value"in n&&(n.writable=!0),Object.defineProperty(e,n.key,n)}}return function(t,r,n){return r&&e(t.prototype,r),n&&e(t,n),t}}(),s=r(187),l=n(s),c=r(273),f=n(c),p=function(e){function t(){var e,r,n,u;o(this,t);for(var i=arguments.length,s=Array(i),l=0;l<i;l++)s[l]=arguments[l];return r=n=a(this,(e=t.__proto__||Object.getPrototypeOf(t)).call.apply(e,[this].concat(s))),n.onClick=function(e){e.stopPropagation();var t=n.props,r=t.security,o=t.authActions,a=t.authSelectors,u=a.getDefinitionsByNames(r);o.showDefinitions(u)},u=r,a(n,u)}return u(t,e),i(t,[{key:"render",value:function(){var e=this.props,t=e.security,r=e.authSelectors,n=r.isAuthorized(t);return null===n?null:l.default.createElement("button",{className:n?"authorization__btn locked":"authorization__btn unlocked",onClick:this.onClick},l.default.createElement("svg",{width:"20",height:"20"},l.default.createElement("use",{xlinkHref:n?"#locked":"#unlocked"})))}}]),t}(l.default.Component);p.propTypes={authSelectors:s.PropTypes.object.isRequired,authActions:s.PropTypes.object.isRequired,security:f.default.iterable.isRequired},t.default=p},function(e,t){e.exports=require("react-immutable-proptypes")},function(e,t,r){"use strict";function n(e){return e&&e.__esModule?e:{default:e}}function o(e,t,r){return t in e?Object.defineProperty(e,t,{value:r,enumerable:!0,configurable:!0,writable:!0}):e[t]=r,e}function a(e,t){if(!(e instanceof t))throw new TypeError("Cannot call a class as a function")}function u(e,t){if(!e)throw new ReferenceError("this hasn't been initialised - super() hasn't been called");return!t||"object"!=typeof t&&"function"!=typeof t?e:t}function i(e,t){if("function"!=typeof t&&null!==t)throw new TypeError("Super expression must either be null or a function, not "+typeof t);e.prototype=Object.create(t&&t.prototype,{constructor:{value:e,enumerable:!1,writable:!0,configurable:!0}}),t&&(Object.setPrototypeOf?Object.setPrototypeOf(e,t):e.__proto__=t)}Object.defineProperty(t,"__esModule",{value:!0});var s=function(){function e(e,t){for(var r=0;r<t.length;r++){var n=t[r];n.enumerable=n.enumerable||!1,n.configurable=!0,"value"in n&&(n.writable=!0),Object.defineProperty(e,n.key,n)}}return function(t,r,n){return r&&e(t.prototype,r),n&&e(t,n),t}}(),l=r(187),c=n(l),f=r(273),p=n(f),d=function(e){function t(e,r){a(this,t);var n=u(this,(t.__proto__||Object.getPrototypeOf(t)).call(this,e,r));return n.onAuthChange=function(e){var t=e.name;n.setState(o({},t,e))},n.submitAuth=function(e){e.preventDefault();var t=n.props.authActions;t.authorize(n.state)},n.logoutClick=function(e){e.preventDefault();var t=n.props,r=t.authActions,o=t.definitions,a=o.map(function(e,t){return t}).toArray();r.logout(a)},n.state={},n}return i(t,e),s(t,[{key:"render",value:function(){var e=this,t=this.props,r=t.definitions,n=t.getComponent,o=t.authSelectors,a=t.errSelectors,u=n("apiKeyAuth"),i=n("basicAuth"),s=n("oauth2",!0),l=n("Button"),f=o.authorized(),p=r.filter(function(e,t){return!!f.get(t)}),d=r.filter(function(e){return"oauth2"!==e.get("type")}),h=r.filter(function(e){return"oauth2"===e.get("type")});return c.default.createElement("div",{className:"auth-container"},!!d.size&&c.default.createElement("form",{onSubmit:this.submitAuth},d.map(function(t,r){var o=t.get("type"),s=void 0;switch(o){case"apiKey":s=c.default.createElement(u,{key:r,schema:t,name:r,errSelectors:a,authorized:f,getComponent:n,onChange:e.onAuthChange});break;case"basic":s=c.default.createElement(i,{key:r,schema:t,name:r,errSelectors:a,authorized:f,getComponent:n,onChange:e.onAuthChange});break;default:s=c.default.createElement("div",{key:r},"Unknown security definition type ",o)}return c.default.createElement("div",{key:r+"-jump"},s)}).toArray(),c.default.createElement("div",{className:"auth-btn-wrapper"},d.size===p.size?c.default.createElement(l,{className:"btn modal-btn auth",onClick:this.logoutClick},"Logout"):c.default.createElement(l,{type:"submit",className:"btn modal-btn auth authorize"},"Authorize"))),h&&h.size?c.default.createElement("div",null,c.default.createElement("div",{className:"scope-def"},c.default.createElement("p",null,"Scopes are used to grant an application different levels of access to data on behalf of the end user. Each API may declare one or more scopes."),c.default.createElement("p",null,"API requires the following scopes. Select which ones you want to grant to Swagger UI.")),r.filter(function(e){return"oauth2"===e.get("type")}).map(function(e,t){return c.default.createElement("div",{key:t},c.default.createElement(s,{authorized:f,schema:e,name:t}))}).toArray()):null)}}]),t}(c.default.Component);d.propTypes={definitions:l.PropTypes.object.isRequired,getComponent:l.PropTypes.func.isRequired,authSelectors:l.PropTypes.object.isRequired,authActions:l.PropTypes.object.isRequired,specSelectors:l.PropTypes.object.isRequired},d.propTypes={errSelectors:l.PropTypes.object.isRequired,getComponent:l.PropTypes.func.isRequired,authSelectors:l.PropTypes.object.isRequired,specSelectors:l.PropTypes.object.isRequired,authActions:l.PropTypes.object.isRequired,definitions:p.default.iterable.isRequired},t.default=d},function(e,t,r){"use strict";function n(e){return e&&e.__esModule?e:{default:e}}function o(e,t){if(!(e instanceof t))throw new TypeError("Cannot call a class as a function")}function a(e,t){if(!e)throw new ReferenceError("this hasn't been initialised - super() hasn't been called");return!t||"object"!=typeof t&&"function"!=typeof t?e:t}function u(e,t){if("function"!=typeof t&&null!==t)throw new TypeError("Super expression must either be null or a function, not "+typeof t);e.prototype=Object.create(t&&t.prototype,{constructor:{value:e,enumerable:!1,writable:!0,configurable:!0}}),t&&(Object.setPrototypeOf?Object.setPrototypeOf(e,t):e.__proto__=t)}Object.defineProperty(t,"__esModule",{value:!0});var i=function(){function e(e,t){for(var r=0;r<t.length;r++){var n=t[r];n.enumerable=n.enumerable||!1,n.configurable=!0,"value"in n&&(n.writable=!0),Object.defineProperty(e,n.key,n)}}return function(t,r,n){return r&&e(t.prototype,r),n&&e(t,n),t}}(),s=r(187),l=n(s),c=function(e){function t(){return o(this,t),a(this,(t.__proto__||Object.getPrototypeOf(t)).apply(this,arguments))}return u(t,e),i(t,[{key:"render",value:function(){var e=this.props.error,t=e.get("level"),r=e.get("message"),n=e.get("source");return l.default.createElement("div",{className:"errors",style:{backgroundColor:"#ffeeee",color:"red",margin:"1em"}},l.default.createElement("b",{style:{textTransform:"capitalize",marginRight:"1em"}},n," ",t),l.default.createElement("span",null,r))}}]),t}(l.default.Component);c.propTypes={error:s.PropTypes.object.isRequired},t.default=c},function(e,t,r){"use strict";function n(e){return e&&e.__esModule?e:{default:e}}function o(e,t){if(!(e instanceof t))throw new TypeError("Cannot call a class as a function")}function a(e,t){if(!e)throw new ReferenceError("this hasn't been initialised - super() hasn't been called");return!t||"object"!=typeof t&&"function"!=typeof t?e:t}function u(e,t){if("function"!=typeof t&&null!==t)throw new TypeError("Super expression must either be null or a function, not "+typeof t);e.prototype=Object.create(t&&t.prototype,{constructor:{value:e,enumerable:!1,writable:!0,configurable:!0}}),t&&(Object.setPrototypeOf?Object.setPrototypeOf(e,t):e.__proto__=t)}Object.defineProperty(t,"__esModule",{value:!0});var i=function(){function e(e,t){for(var r=0;r<t.length;r++){var n=t[r];n.enumerable=n.enumerable||!1,n.configurable=!0,"value"in n&&(n.writable=!0),Object.defineProperty(e,n.key,n)}}return function(t,r,n){return r&&e(t.prototype,r),n&&e(t,n),t}}(),s=r(187),l=n(s),c=function(e){function t(e,r){o(this,t);var n=a(this,(t.__proto__||Object.getPrototypeOf(t)).call(this,e,r));f.call(n);var u=n.props,i=u.name,s=u.schema,l=n.getValue();return n.state={name:i,schema:s,value:l},n}return u(t,e),i(t,[{key:"getValue",value:function(){var e=this.props,t=e.name,r=e.authorized;return r&&r.getIn([t,"value"])}},{key:"render",value:function(){var e=this.props,t=e.schema,r=e.getComponent,n=e.errSelectors,o=e.name,a=r("Input"),u=r("Row"),i=r("Col"),s=r("authError"),c=r("Markdown"),f=r("JumpToPath",!0),p=this.getValue(),d=n.allErrors().filter(function(e){return e.get("authId")===o});return l.default.createElement("div",null,l.default.createElement("h4",null,"Api key authorization",l.default.createElement(f,{path:["securityDefinitions",o]})),p&&l.default.createElement("h6",null,"Authorized"),l.default.createElement(u,null,l.default.createElement(c,{source:t.get("description")})),l.default.createElement(u,null,l.default.createElement("p",null,"Name: ",l.default.createElement("code",null,t.get("name")))),l.default.createElement(u,null,l.default.createElement("p",null,"In: ",l.default.createElement("code",null,t.get("in")))),l.default.createElement(u,null,l.default.createElement("label",null,"Value:"),p?l.default.createElement("code",null," ****** "):l.default.createElement(i,null,l.default.createElement(a,{type:"text",onChange:this.onChange}))),d.valueSeq().map(function(e,t){return l.default.createElement(s,{error:e,key:t})}))}}]),t}(l.default.Component);c.propTypes={authorized:s.PropTypes.object,getComponent:s.PropTypes.func.isRequired,errSelectors:s.PropTypes.object.isRequired,schema:s.PropTypes.object.isRequired,name:s.PropTypes.string.isRequired,onChange:s.PropTypes.func};var f=function(){var e=this;this.onChange=function(t){var r=e.props.onChange,n=t.target.value,o=Object.assign({},e.state,{value:n});e.setState(o),r(o)}};t.default=c},function(e,t,r){"use strict";function n(e){return e&&e.__esModule?e:{default:e}}function o(e,t){if(!(e instanceof t))throw new TypeError("Cannot call a class as a function")}function a(e,t){if(!e)throw new ReferenceError("this hasn't been initialised - super() hasn't been called");return!t||"object"!=typeof t&&"function"!=typeof t?e:t}function u(e,t){if("function"!=typeof t&&null!==t)throw new TypeError("Super expression must either be null or a function, not "+typeof t);e.prototype=Object.create(t&&t.prototype,{constructor:{value:e,enumerable:!1,writable:!0,configurable:!0}}),t&&(Object.setPrototypeOf?Object.setPrototypeOf(e,t):e.__proto__=t)}Object.defineProperty(t,"__esModule",{value:!0});var i=function(){function e(e,t){for(var r=0;r<t.length;r++){var n=t[r];n.enumerable=n.enumerable||!1,n.configurable=!0,"value"in n&&(n.writable=!0),Object.defineProperty(e,n.key,n)}}return function(t,r,n){return r&&e(t.prototype,r),n&&e(t,n),t}}(),s=r(187),l=n(s),c=r(273),f=n(c),p=function(e){function t(e,r){o(this,t);var n=a(this,(t.__proto__||Object.getPrototypeOf(t)).call(this,e,r));d.call(n);var u=n.props,i=u.schema,s=u.name,l=n.getValue(),c=l.username;return n.state={name:s,schema:i,value:c?{username:c}:{}},n}return u(t,e),i(t,[{key:"getValue",value:function(){var e=this.props,t=e.authorized,r=e.name;return t&&t.getIn([r,"value"])||{}}},{key:"render",value:function(){var e=this.props,t=e.schema,r=e.getComponent,n=e.name,o=e.errSelectors,a=r("Input"),u=r("Row"),i=r("Col"),s=r("authError"),c=r("JumpToPath",!0),f=r("Markdown"),p=this.getValue().username,d=o.allErrors().filter(function(e){return e.get("authId")===n});return l.default.createElement("div",null,l.default.createElement("h4",null,"Basic authorization",l.default.createElement(c,{path:["securityDefinitions",n]})),p&&l.default.createElement("h6",null,"Authorized"),l.default.createElement(u,null,l.default.createElement(f,{source:t.get("description")})),l.default.createElement(u,null,l.default.createElement("label",null,"Username:"),p?l.default.createElement("code",null," ",p," "):l.default.createElement(i,null,l.default.createElement(a,{type:"text",required:"required",name:"username",onChange:this.onChange}))),l.default.createElement(u,null,l.default.createElement("label",null,"Password:"),p?l.default.createElement("code",null," ****** "):l.default.createElement(i,null,l.default.createElement(a,{required:"required",autoComplete:"new-password",name:"password",type:"password",onChange:this.onChange}))),d.valueSeq().map(function(e,t){return l.default.createElement(s,{error:e,key:t})}))}}]),t}(l.default.Component);p.propTypes={authorized:s.PropTypes.object,getComponent:s.PropTypes.func.isRequired,schema:s.PropTypes.object.isRequired,onChange:s.PropTypes.func.isRequired},p.propTypes={name:s.PropTypes.string.isRequired,errSelectors:s.PropTypes.object.isRequired,getComponent:s.PropTypes.func.isRequired,onChange:s.PropTypes.func,schema:f.default.map,authorized:f.default.map};var d=function(){var e=this;this.onChange=function(t){var r=e.props.onChange,n=t.target,o=n.value,a=n.name,u=e.state.value;u[a]=o,e.setState({value:u}),r(e.state)}};t.default=p},function(e,t,r){"use strict";function n(e){return e&&e.__esModule?e:{default:e}}function o(e,t,r){return t in e?Object.defineProperty(e,t,{value:r,enumerable:!0,configurable:!0,writable:!0}):e[t]=r,e}function a(e,t){if(!(e instanceof t))throw new TypeError("Cannot call a class as a function")}function u(e,t){if(!e)throw new ReferenceError("this hasn't been initialised - super() hasn't been called");return!t||"object"!=typeof t&&"function"!=typeof t?e:t}function i(e,t){if("function"!=typeof t&&null!==t)throw new TypeError("Super expression must either be null or a function, not "+typeof t);e.prototype=Object.create(t&&t.prototype,{constructor:{value:e,enumerable:!1,writable:!0,configurable:!0}}),t&&(Object.setPrototypeOf?Object.setPrototypeOf(e,t):e.__proto__=t)}Object.defineProperty(t,"__esModule",{value:!0});var s=function(){function e(e,t){for(var r=0;r<t.length;r++){var n=t[r];n.enumerable=n.enumerable||!1,n.configurable=!0,"value"in n&&(n.writable=!0),Object.defineProperty(e,n.key,n)}}return function(t,r,n){return r&&e(t.prototype,r),n&&e(t,n),t}}(),l=r(187),c=n(l),f=r(279),p=n(f),d="implicit",h="accessCode",y="password",m="application",v=function(e){ function t(e,r){a(this,t);var n=u(this,(t.__proto__||Object.getPrototypeOf(t)).call(this,e,r));b.call(n);var o=n.props,i=o.name,s=o.schema,l=o.authorized,c=o.authSelectors,f=l&&l.get(i),p=c.getConfigs()||{},d=f&&f.get("username")||"",h=f&&f.get("clientId")||p.clientId||"",y=f&&f.get("clientSecret")||p.clientSecret||"",m=f&&f.get("passwordType")||"request-body";return n.state={appName:p.appName,name:i,schema:s,scopes:[],clientId:h,clientSecret:y,username:d,password:"",passwordType:m},n}return i(t,e),s(t,[{key:"render",value:function(){var e=this,t=this.props,r=t.schema,n=t.getComponent,o=t.authSelectors,a=t.errSelectors,u=t.name,i=n("Input"),s=n("Row"),l=n("Col"),f=n("Button"),p=n("authError"),v=n("JumpToPath",!0),b=n("Markdown"),g=r.get("flow"),_=r.get("allowedScopes")||r.get("scopes"),E=o.authorized().get(u),w=!!E,j=a.allErrors().filter(function(e){return e.get("authId")===u}),P=!j.filter(function(e){return"validation"===e.get("source")}).size,O=r.get("description");return c.default.createElement("div",null,c.default.createElement("h4",null,"OAuth2.0 ",c.default.createElement(v,{path:["securityDefinitions",u]})),this.state.appName?c.default.createElement("h5",null,"Application: ",this.state.appName," "):null,O&&c.default.createElement(b,{source:r.get("description")}),w&&c.default.createElement("h6",null,"Authorized"),(g===d||g===h)&&c.default.createElement("p",null,"Authorization URL: ",c.default.createElement("code",null,r.get("authorizationUrl"))),(g===y||g===h||g===m)&&c.default.createElement("p",null,"Token URL:",c.default.createElement("code",null," ",r.get("tokenUrl"))),c.default.createElement("p",{className:"flow"},"Flow: ",c.default.createElement("code",null,r.get("flow"))),g!==y?null:c.default.createElement(s,null,c.default.createElement(s,null,c.default.createElement("label",{htmlFor:"oauth_username"},"username:"),w?c.default.createElement("code",null," ",this.state.username," "):c.default.createElement(l,{tablet:10,desktop:10},c.default.createElement("input",{id:"oauth_username",type:"text","data-name":"username",onChange:this.onInputChange}))),c.default.createElement(s,null,c.default.createElement("label",{htmlFor:"oauth_password"},"password:"),w?c.default.createElement("code",null," ****** "):c.default.createElement(l,{tablet:10,desktop:10},c.default.createElement("input",{id:"oauth_password",type:"password","data-name":"password",onChange:this.onInputChange}))),c.default.createElement(s,null,c.default.createElement("label",{htmlFor:"password_type"},"type:"),w?c.default.createElement("code",null," ",this.state.passwordType," "):c.default.createElement(l,{tablet:10,desktop:10},c.default.createElement("select",{id:"password_type","data-name":"passwordType",onChange:this.onInputChange},c.default.createElement("option",{value:"request-body"},"Request body"),c.default.createElement("option",{value:"basic"},"Basic auth"),c.default.createElement("option",{value:"query"},"Query parameters"))))),(g===m||g===d||g===h||g===y&&"basic"!==this.state.passwordType)&&(!w||w&&this.state.clientId)&&c.default.createElement(s,null,c.default.createElement("label",{htmlFor:"client_id"},"client_id:"),w?c.default.createElement("code",null," ****** "):c.default.createElement(l,{tablet:10,desktop:10},c.default.createElement("input",{id:"client_id",type:"text",required:g===y,value:this.state.clientId,"data-name":"clientId",onChange:this.onInputChange}))),(g===m||g===h||g===y&&"basic"!==this.state.passwordType)&&c.default.createElement(s,null,c.default.createElement("label",{htmlFor:"client_secret"},"client_secret:"),w?c.default.createElement("code",null," ****** "):c.default.createElement(l,{tablet:10,desktop:10},c.default.createElement("input",{id:"client_secret",value:this.state.clientSecret,type:"text","data-name":"clientSecret",onChange:this.onInputChange}))),!w&&_&&_.size?c.default.createElement("div",{className:"scopes"},c.default.createElement("h2",null,"Scopes:"),_.map(function(t,r){return c.default.createElement(s,{key:r},c.default.createElement("div",{className:"checkbox"},c.default.createElement(i,{"data-value":r,id:r+"-checkbox-"+e.state.name,disabled:w,type:"checkbox",onChange:e.onScopeChange}),c.default.createElement("label",{htmlFor:r+"-checkbox-"+e.state.name},c.default.createElement("span",{className:"item"}),c.default.createElement("div",{className:"text"},c.default.createElement("p",{className:"name"},r),c.default.createElement("p",{className:"description"},t)))))}).toArray()):null,j.valueSeq().map(function(e,t){return c.default.createElement(p,{error:e,key:t})}),c.default.createElement("div",{className:"auth-btn-wrapper"},P&&(w?c.default.createElement(f,{className:"btn modal-btn auth authorize",onClick:this.logout},"Logout"):c.default.createElement(f,{className:"btn modal-btn auth authorize",onClick:this.authorize},"Authorize"))))}}]),t}(c.default.Component);v.propTypes={name:l.PropTypes.string,authorized:l.PropTypes.object,getComponent:l.PropTypes.func.isRequired,schema:l.PropTypes.object.isRequired,authSelectors:l.PropTypes.object.isRequired,authActions:l.PropTypes.object.isRequired,errSelectors:l.PropTypes.object.isRequired,errActions:l.PropTypes.object.isRequired,getConfigs:l.PropTypes.any};var b=function(){var e=this;this.authorize=function(){var t=e.props,r=t.authActions,n=t.errActions,o=t.getConfigs,a=t.authSelectors,u=o(),i=a.getConfigs();n.clear({authId:name,type:"auth",source:"auth"}),(0,p.default)({auth:e.state,authActions:r,errActions:n,configs:u,authConfigs:i})},this.onScopeChange=function(t){var r=t.target,n=r.checked,o=r.dataset.value;if(n&&e.state.scopes.indexOf(o)===-1){var a=e.state.scopes.concat([o]);e.setState({scopes:a})}else!n&&e.state.scopes.indexOf(o)>-1&&e.setState({scopes:e.state.scopes.filter(function(e){return e!==o})})},this.onInputChange=function(t){var r=t.target,n=r.dataset.name,a=r.value,u=o({},n,a);e.setState(u)},this.logout=function(t){t.preventDefault();var r=e.props,n=r.authActions,o=r.errActions,a=r.name;o.clear({authId:a,type:"auth",source:"auth"}),n.logout([a])}};t.default=v},function(e,t,r){"use strict";function n(e){return e&&e.__esModule?e:{default:e}}function o(e){var t=e.auth,r=e.authActions,n=e.errActions,o=e.configs,a=e.authConfigs,s=void 0===a?{}:a,l=t.schema,c=t.scopes,f=t.name,p=t.clientId,d=l.get("flow"),h=[];switch(d){case"password":return void r.authorizePassword(t);case"application":return void r.authorizeApplication(t);case"accessCode":h.push("response_type=code");break;case"implicit":h.push("response_type=token")}"string"==typeof p&&h.push("client_id="+encodeURIComponent(p));var y=o.oauth2RedirectUrl;if("undefined"==typeof y)return void n.newAuthErr({authId:f,source:"validation",level:"error",message:"oauth2RedirectUri configuration is not passed. Oauth2 authorization cannot be performed."});if(h.push("redirect_uri="+encodeURIComponent(y)),Array.isArray(c)&&0<c.length){var m=s.scopeSeparator||" ";h.push("scope="+encodeURIComponent(c.join(m)))}var v=(0,i.btoa)(new Date);h.push("state="+encodeURIComponent(v)),"undefined"!=typeof s.realm&&h.push("realm="+encodeURIComponent(s.realm));var b=s.additionalQueryStringParams;for(var g in b)"undefined"!=typeof b[g]&&h.push([g,b[g]].map(encodeURIComponent).join("="));var _=[l.get("authorizationUrl"),h.join("&")].join("?");u.default.swaggerUIRedirectOauth2={auth:t,state:v,redirectUrl:y,callback:"implicit"===d?r.preAuthorizeImplicit:r.authorizeAccessCode,errCb:n.newAuthErr},u.default.open(_)}Object.defineProperty(t,"__esModule",{value:!0}),t.default=o;var a=r(11),u=n(a),i=r(12)},function(e,t,r){"use strict";function n(e){return e&&e.__esModule?e:{default:e}}function o(e,t){if(!(e instanceof t))throw new TypeError("Cannot call a class as a function")}function a(e,t){if(!e)throw new ReferenceError("this hasn't been initialised - super() hasn't been called");return!t||"object"!=typeof t&&"function"!=typeof t?e:t}function u(e,t){if("function"!=typeof t&&null!==t)throw new TypeError("Super expression must either be null or a function, not "+typeof t);e.prototype=Object.create(t&&t.prototype,{constructor:{value:e,enumerable:!1,writable:!0,configurable:!0}}),t&&(Object.setPrototypeOf?Object.setPrototypeOf(e,t):e.__proto__=t)}Object.defineProperty(t,"__esModule",{value:!0});var i=function(){function e(e,t){for(var r=0;r<t.length;r++){var n=t[r];n.enumerable=n.enumerable||!1,n.configurable=!0,"value"in n&&(n.writable=!0),Object.defineProperty(e,n.key,n)}}return function(t,r,n){return r&&e(t.prototype,r),n&&e(t,n),t}}(),s=r(187),l=n(s),c=function(e){function t(){var e,r,n,u;o(this,t);for(var i=arguments.length,s=Array(i),l=0;l<i;l++)s[l]=arguments[l];return r=n=a(this,(e=t.__proto__||Object.getPrototypeOf(t)).call.apply(e,[this].concat(s))),n.onClick=function(){var e=n.props,t=e.specActions,r=e.path,o=e.method;t.clearResponse(r,o),t.clearRequest(r,o)},u=r,a(n,u)}return u(t,e),i(t,[{key:"render",value:function(){return l.default.createElement("button",{className:"btn btn-clear opblock-control__btn",onClick:this.onClick},"Clear")}}]),t}(s.Component);c.propTypes={specActions:s.PropTypes.object.isRequired,path:s.PropTypes.string.isRequired,method:s.PropTypes.string.isRequired},t.default=c},function(e,t,r){"use strict";function n(e){return e&&e.__esModule?e:{default:e}}function o(e,t){if(!(e instanceof t))throw new TypeError("Cannot call a class as a function")}function a(e,t){if(!e)throw new ReferenceError("this hasn't been initialised - super() hasn't been called");return!t||"object"!=typeof t&&"function"!=typeof t?e:t}function u(e,t){if("function"!=typeof t&&null!==t)throw new TypeError("Super expression must either be null or a function, not "+typeof t);e.prototype=Object.create(t&&t.prototype,{constructor:{value:e,enumerable:!1,writable:!0,configurable:!0}}),t&&(Object.setPrototypeOf?Object.setPrototypeOf(e,t):e.__proto__=t)}Object.defineProperty(t,"__esModule",{value:!0});var i=function(){function e(e,t){for(var r=0;r<t.length;r++){var n=t[r];n.enumerable=n.enumerable||!1,n.configurable=!0,"value"in n&&(n.writable=!0),Object.defineProperty(e,n.key,n)}}return function(t,r,n){return r&&e(t.prototype,r),n&&e(t,n),t}}(),s=r(187),l=n(s),c=r(273),f=n(c),p=function(e){var t=e.headers;return l.default.createElement("div",null,l.default.createElement("h5",null,"Response headers"),l.default.createElement("pre",null,t))};p.propTypes={headers:s.PropTypes.array.isRequired};var d=function(e){function t(){return o(this,t),a(this,(t.__proto__||Object.getPrototypeOf(t)).apply(this,arguments))}return u(t,e),i(t,[{key:"render",value:function(){var e=this.props,t=e.request,r=e.response,n=e.getComponent,o=r.get("status"),a=r.get("url"),u=r.get("headers").toJS(),i=r.get("notDocumented"),s=r.get("error"),c=s?r.get("response").get("text"):r.get("text"),f=Object.keys(u),d=u["content-type"],h=n("curl"),y=n("responseBody"),m=f.map(function(e){return l.default.createElement("span",{className:"headerline",key:e}," ",e,": ",u[e]," ")}),v=0!==m.length;return l.default.createElement("div",null,t&&l.default.createElement(h,{request:t}),l.default.createElement("h4",null,"Server response"),l.default.createElement("table",{className:"responses-table"},l.default.createElement("thead",null,l.default.createElement("tr",{className:"responses-header"},l.default.createElement("td",{className:"col col_header response-col_status"},"Code"),l.default.createElement("td",{className:"col col_header response-col_description"},"Details"))),l.default.createElement("tbody",null,l.default.createElement("tr",{className:"response"},l.default.createElement("td",{className:"col response-col_status"},o,i?l.default.createElement("div",{className:"response-undocumented"},l.default.createElement("i",null," Undocumented ")):null),l.default.createElement("td",{className:"col response-col_description"},s?l.default.createElement("span",null,r.get("name")+": "+r.get("message")):null,c?l.default.createElement(y,{content:c,contentType:d,url:a,headers:u,getComponent:n}):null,v?l.default.createElement(p,{headers:m}):null)))))}}]),t}(l.default.Component);d.propTypes={response:s.PropTypes.object.isRequired,getComponent:s.PropTypes.func.isRequired},d.propTypes={getComponent:s.PropTypes.func.isRequired,request:f.default.map,response:f.default.map},t.default=d},function(e,t,r){"use strict";function n(e){return e&&e.__esModule?e:{default:e}}function o(e,t){if(!(e instanceof t))throw new TypeError("Cannot call a class as a function")}function a(e,t){if(!e)throw new ReferenceError("this hasn't been initialised - super() hasn't been called");return!t||"object"!=typeof t&&"function"!=typeof t?e:t}function u(e,t){if("function"!=typeof t&&null!==t)throw new TypeError("Super expression must either be null or a function, not "+typeof t);e.prototype=Object.create(t&&t.prototype,{constructor:{value:e,enumerable:!1,writable:!0,configurable:!0}}),t&&(Object.setPrototypeOf?Object.setPrototypeOf(e,t):e.__proto__=t)}Object.defineProperty(t,"__esModule",{value:!0});var i="function"==typeof Symbol&&"symbol"==typeof Symbol.iterator?function(e){return typeof e}:function(e){return e&&"function"==typeof Symbol&&e.constructor===Symbol&&e!==Symbol.prototype?"symbol":typeof e},s=function(){function e(e,t){for(var r=0;r<t.length;r++){var n=t[r];n.enumerable=n.enumerable||!1,n.configurable=!0,"value"in n&&(n.writable=!0),Object.defineProperty(e,n.key,n)}}return function(t,r,n){return r&&e(t.prototype,r),n&&e(t,n),t}}(),l=r(187),c=n(l),f=function(e){function t(e,r){o(this,t);var n=a(this,(t.__proto__||Object.getPrototypeOf(t)).call(this,e,r)),u=e.specSelectors,i=e.getConfigs,s=i(),l=s.validatorUrl;return n.state={url:u.url(),validatorUrl:void 0===l?"https://online.swagger.io/validator":l},n}return u(t,e),s(t,[{key:"componentWillReceiveProps",value:function(e){var t=e.specSelectors,r=e.getConfigs,n=r(),o=n.validatorUrl;this.setState({url:t.url(),validatorUrl:void 0===o?"https://online.swagger.io/validator":o})}},{key:"render",value:function(){var e=this.props.getConfigs,t=e(),r=t.spec;return"object"===("undefined"==typeof r?"undefined":i(r))&&Object.keys(r).length?null:!this.state.url||!this.state.validatorUrl||this.state.url.indexOf("localhost")>=0||this.state.url.indexOf("127.0.0.1")>=0?null:c.default.createElement("span",{style:{float:"right"}},c.default.createElement("a",{target:"_blank",href:this.state.validatorUrl+"/debug?url="+this.state.url},c.default.createElement(p,{src:this.state.validatorUrl+"?url="+this.state.url,alt:"Online validator badge"})))}}]),t}(c.default.Component);f.propTypes={getComponent:l.PropTypes.func.isRequired,getConfigs:l.PropTypes.func.isRequired,specSelectors:l.PropTypes.object.isRequired},t.default=f;var p=function(e){function t(e){o(this,t);var r=a(this,(t.__proto__||Object.getPrototypeOf(t)).call(this,e));return r.state={loaded:!1,error:!1},r}return u(t,e),s(t,[{key:"componentDidMount",value:function(){var e=this,t=new Image;t.onload=function(){e.setState({loaded:!0})},t.onerror=function(){e.setState({error:!0})},t.src=this.props.src}},{key:"componentWillReceiveProps",value:function(e){var t=this;if(e.src!==this.props.src){var r=new Image;r.onload=function(){t.setState({loaded:!0})},r.onerror=function(){t.setState({error:!0})},r.src=e.src}}},{key:"render",value:function(){return this.state.error?c.default.createElement("img",{alt:"Error"}):this.state.loaded?c.default.createElement("img",{src:this.props.src,alt:this.props.alt}):c.default.createElement("img",{alt:"Loading..."})}}]),t}(c.default.Component);p.propTypes={src:l.PropTypes.string,alt:l.PropTypes.string}},function(e,t,r){"use strict";function n(e){return e&&e.__esModule?e:{default:e}}function o(e,t){if(!(e instanceof t))throw new TypeError("Cannot call a class as a function")}function a(e,t){if(!e)throw new ReferenceError("this hasn't been initialised - super() hasn't been called");return!t||"object"!=typeof t&&"function"!=typeof t?e:t}function u(e,t){if("function"!=typeof t&&null!==t)throw new TypeError("Super expression must either be null or a function, not "+typeof t);e.prototype=Object.create(t&&t.prototype,{constructor:{value:e,enumerable:!1,writable:!0,configurable:!0}}),t&&(Object.setPrototypeOf?Object.setPrototypeOf(e,t):e.__proto__=t)}Object.defineProperty(t,"__esModule",{value:!0});var i=Object.assign||function(e){for(var t=1;t<arguments.length;t++){var r=arguments[t];for(var n in r)Object.prototype.hasOwnProperty.call(r,n)&&(e[n]=r[n])}return e},s=function(){function e(e,t){for(var r=0;r<t.length;r++){var n=t[r];n.enumerable=n.enumerable||!1,n.configurable=!0,"value"in n&&(n.writable=!0),Object.defineProperty(e,n.key,n)}}return function(t,r,n){return r&&e(t.prototype,r),n&&e(t,n),t}}(),l=r(187),c=n(l),f=function(e){function t(){return o(this,t),a(this,(t.__proto__||Object.getPrototypeOf(t)).apply(this,arguments))}return u(t,e),s(t,[{key:"render",value:function(){var e=this.props,t=e.specSelectors,r=e.specActions,n=e.getComponent,o=e.layoutSelectors,a=e.layoutActions,u=e.authActions,s=e.authSelectors,l=e.getConfigs,f=e.fn,p=t.taggedOperations(),d=n("operation"),h=n("Collapse"),y=o.showSummary(),m=l(),v=m.docExpansion,b=m.displayOperationId;return c.default.createElement("div",null,p.map(function(e,p){var m=e.get("operations"),g=e.getIn(["tagDetails","description"],null),_=["operations-tag",p],E=o.isShown(_,"full"===v||"list"===v);return c.default.createElement("div",{className:E?"opblock-tag-section is-open":"opblock-tag-section",key:"operation-"+p},c.default.createElement("h4",{onClick:function(){return a.show(_,!E)},className:g?"opblock-tag":"opblock-tag no-desc"},c.default.createElement("span",null,p),g?c.default.createElement("small",null,g):null,c.default.createElement("button",{className:"expand-operation",title:"Expand operation",onClick:function(){return a.show(_,!E)}},c.default.createElement("svg",{className:"arrow",width:"20",height:"20"},c.default.createElement("use",{xlinkHref:E?"#large-arrow-down":"#large-arrow"})))),c.default.createElement(h,{isOpened:E},m.map(function(e){var h=["operations",e.get("id"),p],m=e.get("path",""),v=e.get("method",""),g="paths."+m+"."+v,_=t.allowTryItOutFor(e.get("path"),e.get("method")),E=t.responseFor(e.get("path"),e.get("method")),w=t.requestFor(e.get("path"),e.get("method"));return c.default.createElement(d,i({},e.toObject(),{isShownKey:h,jumpToKey:g,showSummary:y,key:h,response:E,request:w,allowTryItOut:_,displayOperationId:b,specActions:r,specSelectors:t,layoutActions:a,layoutSelectors:o,authActions:u,authSelectors:s,getComponent:n,fn:f,getConfigs:l}))}).toArray()))}).toArray(),p.size<1?c.default.createElement("h3",null," No operations defined in spec! "):null)}}]),t}(c.default.Component);f.propTypes={specSelectors:l.PropTypes.object.isRequired,specActions:l.PropTypes.object.isRequired,getComponent:l.PropTypes.func.isRequired,layoutSelectors:l.PropTypes.object.isRequired,layoutActions:l.PropTypes.object.isRequired,authActions:l.PropTypes.object.isRequired,authSelectors:l.PropTypes.object.isRequired,getConfigs:l.PropTypes.func.isRequired},t.default=f,f.propTypes={layoutActions:l.PropTypes.object.isRequired,specSelectors:l.PropTypes.object.isRequired,specActions:l.PropTypes.object.isRequired,layoutSelectors:l.PropTypes.object.isRequired,getComponent:l.PropTypes.func.isRequired,fn:l.PropTypes.object.isRequired}},function(e,t,r){"use strict";function n(e){if(e&&e.__esModule)return e;var t={};if(null!=e)for(var r in e)Object.prototype.hasOwnProperty.call(e,r)&&(t[r]=e[r]);return t.default=e,t}function o(e){return e&&e.__esModule?e:{default:e}}function a(e,t){if(!(e instanceof t))throw new TypeError("Cannot call a class as a function")}function u(e,t){if(!e)throw new ReferenceError("this hasn't been initialised - super() hasn't been called");return!t||"object"!=typeof t&&"function"!=typeof t?e:t}function i(e,t){if("function"!=typeof t&&null!==t)throw new TypeError("Super expression must either be null or a function, not "+typeof t);e.prototype=Object.create(t&&t.prototype,{constructor:{value:e,enumerable:!1,writable:!0,configurable:!0}}),t&&(Object.setPrototypeOf?Object.setPrototypeOf(e,t):e.__proto__=t)}Object.defineProperty(t,"__esModule",{value:!0});var s=function(){function e(e,t){for(var r=0;r<t.length;r++){var n=t[r];n.enumerable=n.enumerable||!1,n.configurable=!0,"value"in n&&(n.writable=!0),Object.defineProperty(e,n.key,n)}}return function(t,r,n){return r&&e(t.prototype,r),n&&e(t,n),t}}(),l=r(187),c=o(l),f=r(285),p=o(f),d=r(12),h=r(286),y=n(h),m=function(e){function t(e,r){a(this,t);var n=u(this,(t.__proto__||Object.getPrototypeOf(t)).call(this,e,r));return n.toggleShown=function(){var e=n.props,t=e.layoutActions,r=e.isShownKey;t.show(r,!n.isShown())},n.isShown=function(){var e=n.props,t=e.layoutSelectors,r=e.isShownKey,o=e.getConfigs,a=o(),u=a.docExpansion;return t.isShown(r,"full"===u)},n.onTryoutClick=function(){n.setState({tryItOutEnabled:!n.state.tryItOutEnabled})},n.onCancelClick=function(){var e=n.props,t=e.specActions,r=e.path,o=e.method;n.setState({tryItOutEnabled:!n.state.tryItOutEnabled}),t.clearValidateParams([r,o])},n.onExecute=function(){n.setState({executeInProgress:!0})},n.state={tryItOutEnabled:!1},n}return i(t,e),s(t,[{key:"componentWillReceiveProps",value:function(e){var t="application/json",r=e.specActions,n=e.path,o=e.method,a=e.operation,u=a.get("produces_value"),i=a.get("produces"),s=a.get("consumes"),l=a.get("consumes_value");e.response!==this.props.response&&this.setState({executeInProgress:!1}),void 0===u&&(u=i&&i.size?i.first():t,r.changeProducesValue([n,o],u)),void 0===l&&(l=s&&s.size?s.first():t,r.changeConsumesValue([n,o],l))}},{key:"shouldComponentUpdate",value:function(e,t){return(0,p.default)(this,e,t)}},{key:"render",value:function(){var e=this.props,t=e.isShownKey,r=e.jumpToKey,n=e.path,o=e.method,a=e.operation,u=e.showSummary,i=e.response,s=e.request,l=e.allowTryItOut,f=e.displayOperationId,p=e.fn,h=e.getComponent,y=e.specActions,m=e.specSelectors,v=e.authActions,b=e.authSelectors,g=a.get("summary"),_=a.get("description"),E=a.get("deprecated"),w=a.get("externalDocs"),j=a.get("responses"),P=a.get("security")||m.security(),O=a.get("produces"),T=a.get("schemes"),S=(0,d.getList)(a,["parameters"]),x=a.get("__originalOperationId"),C=h("responses"),A=h("parameters"),R=h("execute"),k=h("clear"),q=h("authorizeOperationBtn"),M=h("JumpToPath",!0),N=h("Collapse"),I=h("Markdown"),U=h("schemes");if(i&&i.size>0){var z=!j.get(String(i.get("status")));i=i.set("notDocumented",z)}var D=this.state.tryItOutEnabled,L=this.isShown(),B=[n,o];return c.default.createElement("div",{className:E?"opblock opblock-deprecated":L?"opblock opblock-"+o+" is-open":"opblock opblock-"+o,id:t},c.default.createElement("div",{className:"opblock-summary opblock-summary-"+o,onClick:this.toggleShown},c.default.createElement("span",{className:"opblock-summary-method"},o.toUpperCase()),c.default.createElement("span",{className:E?"opblock-summary-path__deprecated":"opblock-summary-path"},c.default.createElement("span",null,n),c.default.createElement(M,{path:r})),u?c.default.createElement("div",{className:"opblock-summary-description"},g):null,f&&x?c.default.createElement("span",{className:"opblock-summary-operation-id"},x):null,P&&P.count()?c.default.createElement(q,{authActions:v,security:P,authSelectors:b}):null),c.default.createElement(N,{isOpened:L,animated:!0},c.default.createElement("div",{className:"opblock-body"},E&&c.default.createElement("h4",{className:"opblock-title_normal"}," Warning: Deprecated"),_&&c.default.createElement("div",{className:"opblock-description-wrapper"},c.default.createElement("div",{className:"opblock-description"},c.default.createElement(I,{source:_}))),w&&w.get("url")?c.default.createElement("div",{className:"opblock-external-docs-wrapper"},c.default.createElement("h4",{className:"opblock-title_normal"},"Find more details"),c.default.createElement("div",{className:"opblock-external-docs"},c.default.createElement("span",{className:"opblock-external-docs__description"},w.get("description")),c.default.createElement("a",{className:"opblock-external-docs__link",href:w.get("url")},w.get("url")))):null,c.default.createElement(A,{parameters:S,onChangeKey:B,onTryoutClick:this.onTryoutClick,onCancelClick:this.onCancelClick,tryItOutEnabled:D,allowTryItOut:l,fn:p,getComponent:h,specActions:y,specSelectors:m,pathMethod:[n,o]}),D&&l&&T&&T.size?c.default.createElement("div",{className:"opblock-schemes"},c.default.createElement(U,{schemes:T,path:n,method:o,specActions:y})):null,c.default.createElement("div",{className:D&&i&&l?"btn-group":"execute-wrapper"},D&&l?c.default.createElement(R,{getComponent:h,operation:a,specActions:y,specSelectors:m,path:n,method:o,onExecute:this.onExecute}):null,D&&i&&l?c.default.createElement(k,{onClick:this.onClearClick,specActions:y,path:n,method:o}):null),this.state.executeInProgress?c.default.createElement("div",{className:"loading-container"},c.default.createElement("div",{className:"loading"})):null,j?c.default.createElement(C,{responses:j,request:s,tryItOutResponse:i,getComponent:h,specSelectors:m,specActions:y,produces:O,producesValue:a.get("produces_value"),pathMethod:[n,o],fn:p}):null)))}}]),t}(c.default.Component);m.propTypes={path:l.PropTypes.string.isRequired,method:l.PropTypes.string.isRequired,operation:l.PropTypes.object.isRequired,showSummary:l.PropTypes.bool,isShownKey:y.arrayOrString.isRequired,jumpToKey:y.arrayOrString.isRequired,allowTryItOut:l.PropTypes.bool,displayOperationId:l.PropTypes.bool,response:l.PropTypes.object,request:l.PropTypes.object,getComponent:l.PropTypes.func.isRequired,authActions:l.PropTypes.object,authSelectors:l.PropTypes.object,specActions:l.PropTypes.object.isRequired,specSelectors:l.PropTypes.object.isRequired,layoutActions:l.PropTypes.object.isRequired,layoutSelectors:l.PropTypes.object.isRequired,fn:l.PropTypes.object.isRequired,getConfigs:l.PropTypes.func.isRequired},m.defaultProps={showSummary:!0,response:null,allowTryItOut:!0,displayOperationId:!1},t.default=m},function(e,t){e.exports=require("react-addons-shallow-compare")},function(e,t,r){"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.objectWithFuncs=t.arrayOrString=void 0;var n=r(187),o=function(e,t){return n.PropTypes.shape(e.reduce(function(e,r){return e[r]=t,e},{}))};t.arrayOrString=n.PropTypes.oneOfType([n.PropTypes.arrayOf(n.PropTypes.string),n.PropTypes.string]),t.objectWithFuncs=function(e){return o(e,n.PropTypes.func.isRequired)}},function(e,t,r){"use strict";function n(e){return e&&e.__esModule?e:{default:e}}function o(e,t){if(!(e instanceof t))throw new TypeError("Cannot call a class as a function")}function a(e,t){if(!e)throw new ReferenceError("this hasn't been initialised - super() hasn't been called");return!t||"object"!=typeof t&&"function"!=typeof t?e:t}function u(e,t){if("function"!=typeof t&&null!==t)throw new TypeError("Super expression must either be null or a function, not "+typeof t);e.prototype=Object.create(t&&t.prototype,{constructor:{value:e,enumerable:!1,writable:!0,configurable:!0}}),t&&(Object.setPrototypeOf?Object.setPrototypeOf(e,t):e.__proto__=t)}Object.defineProperty(t,"__esModule",{value:!0});var i=function(){function e(e,t){for(var r=0;r<t.length;r++){var n=t[r];n.enumerable=n.enumerable||!1,n.configurable=!0,"value"in n&&(n.writable=!0),Object.defineProperty(e,n.key,n)}}return function(t,r,n){return r&&e(t.prototype,r),n&&e(t,n),t}}(),s=r(187),l=n(s),c=r(12),f=function(e){function t(){return o(this,t),a(this,(t.__proto__||Object.getPrototypeOf(t)).apply(this,arguments))}return u(t,e),i(t,[{key:"componentDidMount",value:function(){(0,c.highlight)(this.refs.el)}},{key:"componentDidUpdate",value:function(){(0,c.highlight)(this.refs.el)}},{key:"render",value:function(){var e=this.props,t=e.value,r=e.className;return r=r||"",l.default.createElement("pre",{ref:"el",className:r+" microlight"},t)}}]),t}(s.Component);f.propTypes={value:s.PropTypes.string.isRequired,className:s.PropTypes.string},t.default=f},function(e,t,r){"use strict";function n(e){return e&&e.__esModule?e:{default:e}}function o(e,t){if(!(e instanceof t))throw new TypeError("Cannot call a class as a function")}function a(e,t){if(!e)throw new ReferenceError("this hasn't been initialised - super() hasn't been called");return!t||"object"!=typeof t&&"function"!=typeof t?e:t}function u(e,t){if("function"!=typeof t&&null!==t)throw new TypeError("Super expression must either be null or a function, not "+typeof t);e.prototype=Object.create(t&&t.prototype,{constructor:{value:e,enumerable:!1,writable:!0,configurable:!0}}),t&&(Object.setPrototypeOf?Object.setPrototypeOf(e,t):e.__proto__=t)}Object.defineProperty(t,"__esModule",{value:!0});var i=function(){function e(e,t){var r=[],n=!0,o=!1,a=void 0;try{for(var u,i=e[Symbol.iterator]();!(n=(u=i.next()).done)&&(r.push(u.value),!t||r.length!==t);n=!0);}catch(e){o=!0,a=e}finally{try{!n&&i.return&&i.return()}finally{if(o)throw a}}return r}return function(t,r){if(Array.isArray(t))return t;if(Symbol.iterator in Object(t))return e(t,r);throw new TypeError("Invalid attempt to destructure non-iterable instance")}}(),s=function(){function e(e,t){for(var r=0;r<t.length;r++){var n=t[r];n.enumerable=n.enumerable||!1,n.configurable=!0,"value"in n&&(n.writable=!0),Object.defineProperty(e,n.key,n)}}return function(t,r,n){return r&&e(t.prototype,r),n&&e(t,n),t}}(),l=r(187),c=n(l),f=r(7),p=r(12),d=function(e){function t(){var e,r,n,u;o(this,t);for(var i=arguments.length,s=Array(i),l=0;l<i;l++)s[l]=arguments[l];return r=n=a(this,(e=t.__proto__||Object.getPrototypeOf(t)).call.apply(e,[this].concat(s))),n.onChangeProducesWrapper=function(e){return n.props.specActions.changeProducesValue(n.props.pathMethod,e)},u=r,a(n,u)}return u(t,e),s(t,[{key:"render",value:function(){var e=this.props,r=e.responses,n=e.request,o=e.tryItOutResponse,a=e.getComponent,u=e.specSelectors,s=e.fn,l=e.producesValue,f=(0,p.defaultStatusCode)(r),d=a("contentType"),h=a("liveResponse"),y=a("response"),m=this.props.produces&&this.props.produces.size?this.props.produces:t.defaultProps.produces;return c.default.createElement("div",{className:"responses-wrapper"},c.default.createElement("div",{className:"opblock-section-header"},c.default.createElement("h4",null,"Responses"),c.default.createElement("label",null,c.default.createElement("span",null,"Response content type"),c.default.createElement(d,{value:l,onChange:this.onChangeProducesWrapper,contentTypes:m,className:"execute-content-type"}))),c.default.createElement("div",{className:"responses-inner"},o?c.default.createElement("div",null,c.default.createElement(h,{request:n,response:o,getComponent:a}),c.default.createElement("h4",null,"Responses")):null,c.default.createElement("table",{className:"responses-table"},c.default.createElement("thead",null,c.default.createElement("tr",{className:"responses-header"},c.default.createElement("td",{className:"col col_header response-col_status"},"Code"),c.default.createElement("td",{className:"col col_header response-col_description"},"Description"))),c.default.createElement("tbody",null,r.entrySeq().map(function(e){var t=i(e,2),r=t[0],n=t[1],p=o&&o.get("status")==r?"response_current":"";return c.default.createElement(y,{key:r,isDefault:f===r,fn:s,className:p,code:r,response:n,specSelectors:u,contentType:l,getComponent:a})}).toArray()))))}}]),t}(c.default.Component);d.propTypes={request:l.PropTypes.object,tryItOutResponse:l.PropTypes.object,responses:l.PropTypes.object.isRequired,produces:l.PropTypes.object,producesValue:l.PropTypes.any,getComponent:l.PropTypes.func.isRequired,specSelectors:l.PropTypes.object.isRequired,specActions:l.PropTypes.object.isRequired,pathMethod:l.PropTypes.array.isRequired,fn:l.PropTypes.object.isRequired},d.defaultProps={request:null,tryItOutResponse:null,produces:(0,f.fromJS)(["application/json"])},t.default=d},function(e,t,r){"use strict";function n(e){return e&&e.__esModule?e:{default:e}}function o(e,t){if(!(e instanceof t))throw new TypeError("Cannot call a class as a function")}function a(e,t){if(!e)throw new ReferenceError("this hasn't been initialised - super() hasn't been called"); return!t||"object"!=typeof t&&"function"!=typeof t?e:t}function u(e,t){if("function"!=typeof t&&null!==t)throw new TypeError("Super expression must either be null or a function, not "+typeof t);e.prototype=Object.create(t&&t.prototype,{constructor:{value:e,enumerable:!1,writable:!0,configurable:!0}}),t&&(Object.setPrototypeOf?Object.setPrototypeOf(e,t):e.__proto__=t)}Object.defineProperty(t,"__esModule",{value:!0});var i=function(){function e(e,t){for(var r=0;r<t.length;r++){var n=t[r];n.enumerable=n.enumerable||!1,n.configurable=!0,"value"in n&&(n.writable=!0),Object.defineProperty(e,n.key,n)}}return function(t,r,n){return r&&e(t.prototype,r),n&&e(t,n),t}}(),s=function(){function e(e,t){var r=[],n=!0,o=!1,a=void 0;try{for(var u,i=e[Symbol.iterator]();!(n=(u=i.next()).done)&&(r.push(u.value),!t||r.length!==t);n=!0);}catch(e){o=!0,a=e}finally{try{!n&&i.return&&i.return()}finally{if(o)throw a}}return r}return function(t,r){if(Array.isArray(t))return t;if(Symbol.iterator in Object(t))return e(t,r);throw new TypeError("Invalid attempt to destructure non-iterable instance")}}(),l=r(187),c=n(l),f=r(7),p=r(12),d=function(e,t,r){return t&&t.size?t.entrySeq().map(function(e){var t=s(e,2),n=t[0],o=t[1],a=void 0;try{a=o&&o.toJS?o.toJS():o,a=JSON.stringify(a,null,2)}catch(e){a=String(o)}return c.default.createElement("div",{key:n},c.default.createElement("h5",null,n),c.default.createElement(r,{className:"example",value:a}))}).toArray():e?c.default.createElement("div",null,c.default.createElement(r,{className:"example",value:e})):null},h=function(e){function t(){return o(this,t),a(this,(t.__proto__||Object.getPrototypeOf(t)).apply(this,arguments))}return u(t,e),i(t,[{key:"render",value:function(){var e=this.props,t=e.code,r=e.response,n=e.className,o=e.fn,a=e.getComponent,u=e.specSelectors,i=e.contentType,s=o.inferSchema,l=s(r.toJS()),h=r.get("headers"),y=r.get("examples"),m=a("headers"),v=a("highlightCode"),b=a("modelExample"),g=a("Markdown"),_=l?(0,p.getSampleSchema)(l,i,{includeReadOnly:!0}):null,E=d(_,y,v);return c.default.createElement("tr",{className:"response "+(n||"")},c.default.createElement("td",{className:"col response-col_status"},t),c.default.createElement("td",{className:"col response-col_description"},c.default.createElement("div",{className:"response-col_description__inner"},c.default.createElement(g,{source:r.get("description")})),E?c.default.createElement(b,{getComponent:a,specSelectors:u,schema:(0,f.fromJS)(l),example:E}):null,h?c.default.createElement(m,{headers:h}):null))}}]),t}(c.default.Component);h.propTypes={code:l.PropTypes.string.isRequired,response:l.PropTypes.object,className:l.PropTypes.string,getComponent:l.PropTypes.func.isRequired,specSelectors:l.PropTypes.object.isRequired,fn:l.PropTypes.object.isRequired,contentType:l.PropTypes.string},h.defaultProps={response:(0,f.fromJS)({})},t.default=h},function(e,t,r){"use strict";function n(e){return e&&e.__esModule?e:{default:e}}function o(e,t){if(!(e instanceof t))throw new TypeError("Cannot call a class as a function")}function a(e,t){if(!e)throw new ReferenceError("this hasn't been initialised - super() hasn't been called");return!t||"object"!=typeof t&&"function"!=typeof t?e:t}function u(e,t){if("function"!=typeof t&&null!==t)throw new TypeError("Super expression must either be null or a function, not "+typeof t);e.prototype=Object.create(t&&t.prototype,{constructor:{value:e,enumerable:!1,writable:!0,configurable:!0}}),t&&(Object.setPrototypeOf?Object.setPrototypeOf(e,t):e.__proto__=t)}Object.defineProperty(t,"__esModule",{value:!0});var i=function(){function e(e,t){for(var r=0;r<t.length;r++){var n=t[r];n.enumerable=n.enumerable||!1,n.configurable=!0,"value"in n&&(n.writable=!0),Object.defineProperty(e,n.key,n)}}return function(t,r,n){return r&&e(t.prototype,r),n&&e(t,n),t}}(),s=r(187),l=n(s),c=r(12),f=r(291),p=n(f),d=function(e){function t(){return o(this,t),a(this,(t.__proto__||Object.getPrototypeOf(t)).apply(this,arguments))}return u(t,e),i(t,[{key:"render",value:function(){var e=this.props,t=e.content,r=e.contentType,n=e.url,o=e.headers,a=void 0===o?{}:o,u=e.getComponent,i=u("highlightCode"),s=void 0,f=void 0;if(n=n||"",/json/i.test(r)){try{s=JSON.stringify(JSON.parse(t),null," ")}catch(e){s="can't parse JSON. Raw result:\n\n"+t}f=l.default.createElement(i,{value:s})}else if(/xml/i.test(r))s=(0,c.formatXml)(t),f=l.default.createElement(i,{value:s});else if("text/html"===(0,p.default)(r)||/text\/plain/.test(r))f=l.default.createElement(i,{value:t});else if(/^image\//i.test(r))f=l.default.createElement("img",{src:n});else if(/^audio\//i.test(r))f=l.default.createElement("pre",null,l.default.createElement("audio",{controls:!0},l.default.createElement("source",{src:n,type:r})));else if(/^application\/octet-stream/i.test(r)||a["Content-Disposition"]&&/attachment/i.test(a["Content-Disposition"])||a["content-disposition"]&&/attachment/i.test(a["content-disposition"])||a["Content-Description"]&&/File Transfer/i.test(a["Content-Description"])||a["content-description"]&&/File Transfer/i.test(a["content-description"])){var d=a["content-length"]||a["Content-Length"];if(!+d)return null;var h=/^((?!chrome|android).)*safari/i.test(navigator.userAgent);if(!h&&"Blob"in window){var y=r||"text/html",m=t instanceof Blob?t:new Blob([t],{type:y}),v=window.URL.createObjectURL(m),b=n.substr(n.lastIndexOf("/")+1),g=[y,b,v].join(":"),_=a["content-disposition"]||a["Content-Disposition"];if("undefined"!=typeof _){var E=/filename=([^;]*);?/i.exec(_);null!==E&&E.length>1&&(g=E[1])}f=l.default.createElement("div",null,l.default.createElement("a",{href:v,download:g},"Download file"))}else f=l.default.createElement("pre",null,"Download headers detected but your browser does not support downloading binary via XHR (Blob).")}else f="string"==typeof t?l.default.createElement(i,{value:t}):l.default.createElement("div",null,"Unknown response type");return f?l.default.createElement("div",null,l.default.createElement("h5",null,"Response body"),f):null}}]),t}(l.default.Component);d.propTypes={content:s.PropTypes.any.isRequired,contentType:s.PropTypes.string.isRequired,getComponent:s.PropTypes.func.isRequired,headers:s.PropTypes.object,url:s.PropTypes.string},t.default=d},function(e,t,r){var n=r(40),o=n(function(e,t,r){return e+(r?" ":"")+t.toLowerCase()});e.exports=o},function(e,t,r){"use strict";function n(e){return e&&e.__esModule?e:{default:e}}function o(e,t){if(!(e instanceof t))throw new TypeError("Cannot call a class as a function")}function a(e,t){if(!e)throw new ReferenceError("this hasn't been initialised - super() hasn't been called");return!t||"object"!=typeof t&&"function"!=typeof t?e:t}function u(e,t){if("function"!=typeof t&&null!==t)throw new TypeError("Super expression must either be null or a function, not "+typeof t);e.prototype=Object.create(t&&t.prototype,{constructor:{value:e,enumerable:!1,writable:!0,configurable:!0}}),t&&(Object.setPrototypeOf?Object.setPrototypeOf(e,t):e.__proto__=t)}Object.defineProperty(t,"__esModule",{value:!0});var i=function(){function e(e,t){for(var r=0;r<t.length;r++){var n=t[r];n.enumerable=n.enumerable||!1,n.configurable=!0,"value"in n&&(n.writable=!0),Object.defineProperty(e,n.key,n)}}return function(t,r,n){return r&&e(t.prototype,r),n&&e(t,n),t}}(),s=r(187),l=n(s),c=r(273),f=n(c),p=r(7),d=n(p),h=function(e,t){return e.valueSeq().filter(d.default.Map.isMap).map(t)},y=function(e){function t(){var e,r,n,u;o(this,t);for(var i=arguments.length,s=Array(i),l=0;l<i;l++)s[l]=arguments[l];return r=n=a(this,(e=t.__proto__||Object.getPrototypeOf(t)).call.apply(e,[this].concat(s))),n.onChange=function(e,t,r){var o=n.props,a=o.specActions.changeParam,u=o.onChangeKey;a(u,e.get("name"),t,r)},n.onChangeConsumesWrapper=function(e){var t=n.props,r=t.specActions.changeConsumesValue,o=t.onChangeKey;r(o,e)},u=r,a(n,u)}return u(t,e),i(t,[{key:"render",value:function(){var e=this,t=this.props,r=t.onTryoutClick,n=t.onCancelClick,o=t.parameters,a=t.allowTryItOut,u=t.tryItOutEnabled,i=t.fn,s=t.getComponent,c=t.specSelectors,f=t.pathMethod,p=s("parameterRow"),d=s("TryItOutButton"),y=u&&a;return l.default.createElement("div",{className:"opblock-section"},l.default.createElement("div",{className:"opblock-section-header"},l.default.createElement("h4",{className:"opblock-title"},"Parameters"),a?l.default.createElement(d,{enabled:u,onCancelClick:n,onTryoutClick:r}):null),o.count()?l.default.createElement("div",{className:"table-container"},l.default.createElement("table",{className:"parameters"},l.default.createElement("thead",null,l.default.createElement("tr",null,l.default.createElement("th",{className:"col col_header parameters-col_name"},"Name"),l.default.createElement("th",{className:"col col_header parameters-col_description"},"Description"))),l.default.createElement("tbody",null,h(o,function(t){return l.default.createElement(p,{fn:i,getComponent:s,param:t,key:t.get("name"),onChange:e.onChange,onChangeConsumes:e.onChangeConsumesWrapper,specSelectors:c,pathMethod:f,isExecute:y})}).toArray()))):l.default.createElement("div",{className:"opblock-description-wrapper"},l.default.createElement("p",null,"No parameters")))}}]),t}(s.Component);y.propTypes={parameters:f.default.list.isRequired,specActions:s.PropTypes.object.isRequired,getComponent:s.PropTypes.func.isRequired,specSelectors:s.PropTypes.object.isRequired,fn:s.PropTypes.object.isRequired,tryItOutEnabled:s.PropTypes.bool,allowTryItOut:s.PropTypes.bool,onTryoutClick:s.PropTypes.func,onCancelClick:s.PropTypes.func,onChangeKey:s.PropTypes.array,pathMethod:s.PropTypes.array.isRequired},y.defaultProps={onTryoutClick:Function.prototype,onCancelClick:Function.prototype,tryItOutEnabled:!1,allowTryItOut:!0,onChangeKey:[]},t.default=y},function(e,t,r){"use strict";function n(e){return e&&e.__esModule?e:{default:e}}function o(e,t){if(!(e instanceof t))throw new TypeError("Cannot call a class as a function")}function a(e,t){if(!e)throw new ReferenceError("this hasn't been initialised - super() hasn't been called");return!t||"object"!=typeof t&&"function"!=typeof t?e:t}function u(e,t){if("function"!=typeof t&&null!==t)throw new TypeError("Super expression must either be null or a function, not "+typeof t);e.prototype=Object.create(t&&t.prototype,{constructor:{value:e,enumerable:!1,writable:!0,configurable:!0}}),t&&(Object.setPrototypeOf?Object.setPrototypeOf(e,t):e.__proto__=t)}Object.defineProperty(t,"__esModule",{value:!0});var i=function(){function e(e,t){for(var r=0;r<t.length;r++){var n=t[r];n.enumerable=n.enumerable||!1,n.configurable=!0,"value"in n&&(n.writable=!0),Object.defineProperty(e,n.key,n)}}return function(t,r,n){return r&&e(t.prototype,r),n&&e(t,n),t}}(),s=r(187),l=n(s),c=r(11),f=n(c),p=function(e){function t(e,r){o(this,t);var n=a(this,(t.__proto__||Object.getPrototypeOf(t)).call(this,e,r));d.call(n);var u=e.specSelectors,i=e.pathMethod,s=e.param,l=s.get("default"),c=u.getParameter(i,s.get("name")),f=c?c.get("value"):"";return void 0!==l&&void 0===f&&n.onChangeWrapper(l),n}return u(t,e),i(t,[{key:"componentWillReceiveProps",value:function(e){var t=e.specSelectors,r=e.pathMethod,n=e.param,o=n.get("example"),a=n.get("default"),u=t.getParameter(r,n.get("name")),i=u?u.get("value"):void 0,s=u?u.get("enum"):void 0,l=void 0;void 0!==i?l=i:void 0!==o?l=o:void 0!==a?l=a:n.get("required")&&s&&s.size&&(l=s.first()),void 0!==l&&this.onChangeWrapper(l)}},{key:"render",value:function(){var e=this.props,t=e.param,r=e.onChange,n=e.getComponent,o=e.isExecute,a=e.fn,u=e.onChangeConsumes,i=e.specSelectors,s=e.pathMethod,c=n("JsonSchemaForm"),p=n("ParamBody"),d=t.get("in"),h="body"!==d?null:l.default.createElement(p,{getComponent:n,fn:a,param:t,consumes:i.operationConsumes(s),consumesValue:i.contentTypeValues(s).get("requestContentType"),onChange:r,onChangeConsumes:u,isExecute:o,specSelectors:i,pathMethod:s}),y=n("modelExample"),m=n("Markdown"),v=t.get("schema"),b="formData"===d,g="FormData"in f.default,_=t.get("required"),E=t.getIn(["items","type"]),w=i.getParameter(s,t.get("name")),j=w?w.get("value"):"";return l.default.createElement("tr",null,l.default.createElement("td",{className:"col parameters-col_name"},l.default.createElement("div",{className:_?"parameter__name required":"parameter__name"},t.get("name"),_?l.default.createElement("span",{style:{color:"red"}}," *"):null),l.default.createElement("div",{className:"parаmeter__type"},t.get("type")," ",E&&"["+E+"]"),l.default.createElement("div",{className:"parameter__in"},"(",t.get("in"),")")),l.default.createElement("td",{className:"col parameters-col_description"},l.default.createElement(m,{source:t.get("description")}),b&&!g&&l.default.createElement("div",null,"Error: your browser does not support FormData"),h||!o?null:l.default.createElement(c,{fn:a,getComponent:n,value:j,required:_,description:t.get("description")?t.get("name")+" - "+t.get("description"):""+t.get("name"),onChange:this.onChangeWrapper,schema:t}),h&&v?l.default.createElement(y,{getComponent:n,isExecute:o,specSelectors:i,schema:v,example:h}):null))}}]),t}(s.Component);p.propTypes={onChange:s.PropTypes.func.isRequired,param:s.PropTypes.object.isRequired,getComponent:s.PropTypes.func.isRequired,fn:s.PropTypes.object.isRequired,isExecute:s.PropTypes.bool,onChangeConsumes:s.PropTypes.func.isRequired,specSelectors:s.PropTypes.object.isRequired,pathMethod:s.PropTypes.array.isRequired};var d=function(){var e=this;this.onChangeWrapper=function(t){var r=e.props,n=r.onChange,o=r.param;return n(o,t)}};t.default=p},function(e,t,r){"use strict";function n(e){return e&&e.__esModule?e:{default:e}}function o(e,t){if(!(e instanceof t))throw new TypeError("Cannot call a class as a function")}function a(e,t){if(!e)throw new ReferenceError("this hasn't been initialised - super() hasn't been called");return!t||"object"!=typeof t&&"function"!=typeof t?e:t}function u(e,t){if("function"!=typeof t&&null!==t)throw new TypeError("Super expression must either be null or a function, not "+typeof t);e.prototype=Object.create(t&&t.prototype,{constructor:{value:e,enumerable:!1,writable:!0,configurable:!0}}),t&&(Object.setPrototypeOf?Object.setPrototypeOf(e,t):e.__proto__=t)}Object.defineProperty(t,"__esModule",{value:!0});var i=function(){function e(e,t){for(var r=0;r<t.length;r++){var n=t[r];n.enumerable=n.enumerable||!1,n.configurable=!0,"value"in n&&(n.writable=!0),Object.defineProperty(e,n.key,n)}}return function(t,r,n){return r&&e(t.prototype,r),n&&e(t,n),t}}(),s=r(187),l=n(s),c=function(e){function t(){var e,r,n,u;o(this,t);for(var i=arguments.length,s=Array(i),l=0;l<i;l++)s[l]=arguments[l];return r=n=a(this,(e=t.__proto__||Object.getPrototypeOf(t)).call.apply(e,[this].concat(s))),n.onClick=function(){var e=n.props,t=e.specSelectors,r=e.specActions,o=e.operation,a=e.path,u=e.method;r.validateParams([a,u]),t.validateBeforeExecute([a,u])&&(n.props.onExecute&&n.props.onExecute(),r.execute({operation:o,path:a,method:u}))},n.onChangeProducesWrapper=function(e){return n.props.specActions.changeProducesValue([n.props.path,n.props.method],e)},u=r,a(n,u)}return u(t,e),i(t,[{key:"render",value:function(){return l.default.createElement("button",{className:"btn execute opblock-control__btn",onClick:this.onClick},"Execute")}}]),t}(s.Component);c.propTypes={specSelectors:s.PropTypes.object.isRequired,specActions:s.PropTypes.object.isRequired,operation:s.PropTypes.object.isRequired,path:s.PropTypes.string.isRequired,getComponent:s.PropTypes.func.isRequired,method:s.PropTypes.string.isRequired,onExecute:s.PropTypes.func},t.default=c},function(e,t,r){"use strict";function n(e){return e&&e.__esModule?e:{default:e}}function o(e,t){if(!(e instanceof t))throw new TypeError("Cannot call a class as a function")}function a(e,t){if(!e)throw new ReferenceError("this hasn't been initialised - super() hasn't been called");return!t||"object"!=typeof t&&"function"!=typeof t?e:t}function u(e,t){if("function"!=typeof t&&null!==t)throw new TypeError("Super expression must either be null or a function, not "+typeof t);e.prototype=Object.create(t&&t.prototype,{constructor:{value:e,enumerable:!1,writable:!0,configurable:!0}}),t&&(Object.setPrototypeOf?Object.setPrototypeOf(e,t):e.__proto__=t)}Object.defineProperty(t,"__esModule",{value:!0});var i=function(){function e(e,t){var r=[],n=!0,o=!1,a=void 0;try{for(var u,i=e[Symbol.iterator]();!(n=(u=i.next()).done)&&(r.push(u.value),!t||r.length!==t);n=!0);}catch(e){o=!0,a=e}finally{try{!n&&i.return&&i.return()}finally{if(o)throw a}}return r}return function(t,r){if(Array.isArray(t))return t;if(Symbol.iterator in Object(t))return e(t,r);throw new TypeError("Invalid attempt to destructure non-iterable instance")}}(),s=function(){function e(e,t){for(var r=0;r<t.length;r++){var n=t[r];n.enumerable=n.enumerable||!1,n.configurable=!0,"value"in n&&(n.writable=!0),Object.defineProperty(e,n.key,n)}}return function(t,r,n){return r&&e(t.prototype,r),n&&e(t,n),t}}(),l=r(187),c=n(l),f=r(7),p=n(f),d=function(e){function t(){return o(this,t),a(this,(t.__proto__||Object.getPrototypeOf(t)).apply(this,arguments))}return u(t,e),s(t,[{key:"render",value:function(){var e=this.props.headers;return e&&e.size?c.default.createElement("div",{className:"headers-wrapper"},c.default.createElement("h4",{className:"headers__title"},"Headers:"),c.default.createElement("table",{className:"headers"},c.default.createElement("thead",null,c.default.createElement("tr",{className:"header-row"},c.default.createElement("th",{className:"header-col"},"Name"),c.default.createElement("th",{className:"header-col"},"Description"),c.default.createElement("th",{className:"header-col"},"Type"))),c.default.createElement("tbody",null,e.entrySeq().map(function(e){var t=i(e,2),r=t[0],n=t[1];return p.default.Map.isMap(n)?c.default.createElement("tr",{key:r},c.default.createElement("td",{className:"header-col"},r),c.default.createElement("td",{className:"header-col"},n.get("description")),c.default.createElement("td",{className:"header-col"},n.get("type"))):null}).toArray()))):null}}]),t}(c.default.Component);d.propTypes={headers:l.PropTypes.object.isRequired},t.default=d},function(e,t,r){"use strict";function n(e){return e&&e.__esModule?e:{default:e}}function o(e,t){if(!(e instanceof t))throw new TypeError("Cannot call a class as a function")}function a(e,t){if(!e)throw new ReferenceError("this hasn't been initialised - super() hasn't been called");return!t||"object"!=typeof t&&"function"!=typeof t?e:t}function u(e,t){if("function"!=typeof t&&null!==t)throw new TypeError("Super expression must either be null or a function, not "+typeof t);e.prototype=Object.create(t&&t.prototype,{constructor:{value:e,enumerable:!1,writable:!0,configurable:!0}}),t&&(Object.setPrototypeOf?Object.setPrototypeOf(e,t):e.__proto__=t)}function i(e){return e.split(" ").map(function(e){return e[0].toUpperCase()+e.slice(1)}).join(" ")}Object.defineProperty(t,"__esModule",{value:!0});var s=function(){function e(e,t){for(var r=0;r<t.length;r++){var n=t[r];n.enumerable=n.enumerable||!1,n.configurable=!0,"value"in n&&(n.writable=!0),Object.defineProperty(e,n.key,n)}}return function(t,r,n){return r&&e(t.prototype,r),n&&e(t,n),t}}(),l=r(187),c=n(l),f=r(7),p=r(297),d=n(p),h=function(e){function t(){return o(this,t),a(this,(t.__proto__||Object.getPrototypeOf(t)).apply(this,arguments))}return u(t,e),s(t,[{key:"render",value:function(){var e=this.props,t=e.editorActions,r=e.errSelectors,n=e.layoutSelectors,o=e.layoutActions;if(t&&t.jumpToLine)var a=t.jumpToLine;var u=r.allErrors(),i=u.filter(function(e){return"thrown"===e.get("type")||"error"===e.get("level")});if(!i||i.count()<1)return null;var s=n.isShown(["errorPane"],!0),l=function(){return o.show(["errorPane"],!s)},f=i.sortBy(function(e){return e.get("line")});return c.default.createElement("pre",{className:"errors-wrapper"},c.default.createElement("hgroup",{className:"error"},c.default.createElement("h4",{className:"errors__title"},"Errors"),c.default.createElement("button",{className:"btn errors__clear-btn",onClick:l},s?"Hide":"Show")),c.default.createElement(d.default,{isOpened:s,animated:!0},c.default.createElement("div",{className:"errors"},f.map(function(e,t){var r=e.get("type");return"thrown"===r||"auth"===r?c.default.createElement(y,{key:t,error:e.get("error")||e,jumpToLine:a}):"spec"===r?c.default.createElement(m,{key:t,error:e,jumpToLine:a}):void 0}))))}}]),t}(c.default.Component);h.propTypes={editorActions:l.PropTypes.object,errSelectors:l.PropTypes.object.isRequired,layoutSelectors:l.PropTypes.object.isRequired,layoutActions:l.PropTypes.object.isRequired},t.default=h;var y=function(e){var t=e.error,r=e.jumpToLine;if(!t)return null;var n=t.get("line");return c.default.createElement("div",{className:"error-wrapper"},t?c.default.createElement("div",null,c.default.createElement("h4",null,t.get("source")&&t.get("level")?i(t.get("source"))+" "+t.get("level"):"",t.get("path")?c.default.createElement("small",null," at ",t.get("path")):null),c.default.createElement("span",{style:{whiteSpace:"pre-line",maxWidth:"100%"}},t.get("message")),c.default.createElement("div",null,n&&r?c.default.createElement("a",{onClick:r.bind(null,n)},"Jump to line ",n):null)):null)},m=function(e){var t=e.error,r=e.jumpToLine,n=null;return t.get("path")?n=f.List.isList(t.get("path"))?c.default.createElement("small",null,"at ",t.get("path").join(".")):c.default.createElement("small",null,"at ",t.get("path")):t.get("line")&&!r&&(n=c.default.createElement("small",null,"on line ",t.get("line"))),c.default.createElement("div",{className:"error-wrapper"},t?c.default.createElement("div",null,c.default.createElement("h4",null,i(t.get("source"))+" "+t.get("level")," ",n),c.default.createElement("span",{style:{whiteSpace:"pre-line"}},t.get("message")),c.default.createElement("div",{style:{"text-decoration":"underline",cursor:"pointer"}},r?c.default.createElement("a",{onClick:r.bind(null,t.get("line"))},"Jump to line ",t.get("line")):null)):null)};y.propTypes={error:l.PropTypes.object.isRequired,jumpToLine:l.PropTypes.func},y.defaultProps={jumpToLine:null},m.propTypes={error:l.PropTypes.object.isRequired,jumpToLine:l.PropTypes.func}},function(e,t){e.exports=require("react-collapse")},function(e,t,r){"use strict";function n(e){return e&&e.__esModule?e:{default:e}}function o(e,t){if(!(e instanceof t))throw new TypeError("Cannot call a class as a function")}function a(e,t){if(!e)throw new ReferenceError("this hasn't been initialised - super() hasn't been called");return!t||"object"!=typeof t&&"function"!=typeof t?e:t}function u(e,t){if("function"!=typeof t&&null!==t)throw new TypeError("Super expression must either be null or a function, not "+typeof t);e.prototype=Object.create(t&&t.prototype,{constructor:{value:e,enumerable:!1,writable:!0,configurable:!0}}),t&&(Object.setPrototypeOf?Object.setPrototypeOf(e,t):e.__proto__=t)}Object.defineProperty(t,"__esModule",{value:!0});var i=function(){function e(e,t){for(var r=0;r<t.length;r++){var n=t[r];n.enumerable=n.enumerable||!1,n.configurable=!0,"value"in n&&(n.writable=!0),Object.defineProperty(e,n.key,n)}}return function(t,r,n){return r&&e(t.prototype,r),n&&e(t,n),t}}(),s=r(187),l=n(s),c=r(273),f=n(c),p=r(7),d=function(){},h=function(e){function t(){var e,r,n,u;o(this,t);for(var i=arguments.length,s=Array(i),l=0;l<i;l++)s[l]=arguments[l];return r=n=a(this,(e=t.__proto__||Object.getPrototypeOf(t)).call.apply(e,[this].concat(s))),n.onChangeWrapper=function(e){return n.props.onChange(e.target.value)},u=r,a(n,u)}return u(t,e),i(t,[{key:"componentDidMount",value:function(){this.props.onChange(this.props.contentTypes.first())}},{key:"render",value:function(){var e=this.props,t=e.contentTypes,r=e.className,n=e.value;return t&&t.size?l.default.createElement("div",{className:"content-type-wrapper "+(r||"")},l.default.createElement("select",{className:"content-type",value:n,onChange:this.onChangeWrapper},t.map(function(e){return l.default.createElement("option",{key:e,value:e},e)}).toArray())):null}}]),t}(l.default.Component);h.propTypes={contentTypes:s.PropTypes.oneOfType([f.default.list,f.default.set]),value:s.PropTypes.string,onChange:s.PropTypes.func,className:s.PropTypes.string},h.defaultProps={onChange:d,value:null,contentTypes:(0,p.fromJS)(["application/json"])},t.default=h},function(e,t,r){"use strict";function n(e){return e&&e.__esModule?e:{default:e}}function o(e,t){if(!(e instanceof t))throw new TypeError("Cannot call a class as a function")}function a(e,t){if(!e)throw new ReferenceError("this hasn't been initialised - super() hasn't been called");return!t||"object"!=typeof t&&"function"!=typeof t?e:t}function u(e,t){if("function"!=typeof t&&null!==t)throw new TypeError("Super expression must either be null or a function, not "+typeof t);e.prototype=Object.create(t&&t.prototype,{constructor:{value:e,enumerable:!1,writable:!0,configurable:!0}}),t&&(Object.setPrototypeOf?Object.setPrototypeOf(e,t):e.__proto__=t)}Object.defineProperty(t,"__esModule",{value:!0}),t.OperationLink=void 0;var i=function(){function e(e,t){for(var r=0;r<t.length;r++){var n=t[r];n.enumerable=n.enumerable||!1,n.configurable=!0,"value"in n&&(n.writable=!0),Object.defineProperty(e,n.key,n)}}return function(t,r,n){return r&&e(t.prototype,r),n&&e(t,n),t}}(),s=r(187),l=n(s),c=r(300),f=function(e){function t(){var e;o(this,t);for(var r=arguments.length,n=Array(r),u=0;u<r;u++)n[u]=arguments[u];var i=a(this,(e=t.__proto__||Object.getPrototypeOf(t)).call.apply(e,[this].concat(n)));return i.setTagShown=i._setTagShown.bind(i),i}return u(t,e),i(t,[{key:"_setTagShown",value:function(e,t){this.props.layoutActions.show(e,t)}},{key:"showOp",value:function(e,t){var r=this.props.layoutActions;r.show(e,t)}},{key:"render",value:function(){var e=this.props,t=e.specSelectors,r=e.layoutSelectors,n=e.layoutActions,o=e.getComponent,a=t.taggedOperations(),u=o("Collapse");return l.default.createElement("div",null,l.default.createElement("h4",{className:"overview-title"},"Overview"),a.map(function(e,t){var o=e.get("operations"),a=["overview-tags",t],i=r.isShown(a,!0),s=function(){return n.show(a,!i)};return l.default.createElement("div",{key:"overview-"+t},l.default.createElement("h4",{onClick:s,className:"link overview-tag"}," ",i?"-":"+",t),l.default.createElement(u,{isOpened:i,animated:!0},o.map(function(e){var t=e.toObject(),o=t.path,a=t.method,u=t.id,i="operations",s=u,c=r.isShown([i,s]);return l.default.createElement(p,{key:u,path:o,method:a,id:o+"-"+a,shown:c,showOpId:s,showOpIdPrefix:i,href:"#operation-"+s,onClick:n.show})}).toArray()))}).toArray(),a.size<1&&l.default.createElement("h3",null," No operations defined in spec! "))}}]),t}(l.default.Component);t.default=f,f.propTypes={layoutSelectors:s.PropTypes.object.isRequired,specSelectors:s.PropTypes.object.isRequired,layoutActions:s.PropTypes.object.isRequired,getComponent:s.PropTypes.func.isRequired};var p=t.OperationLink=function(e){function t(e){o(this,t);var r=a(this,(t.__proto__||Object.getPrototypeOf(t)).call(this,e));return r.onClick=r._onClick.bind(r),r}return u(t,e),i(t,[{key:"_onClick",value:function(){var e=this.props,t=e.showOpId,r=e.showOpIdPrefix,n=e.onClick,o=e.shown;n([r,t],!o)}},{key:"render",value:function(){var e=this.props,t=e.id,r=e.method,n=e.shown,o=e.href;return l.default.createElement(c.Link,{href:o,style:{fontWeight:n?"bold":"normal"},onClick:this.onClick,className:"block opblock-link"},l.default.createElement("div",null,l.default.createElement("small",{className:"bold-label-"+r},r.toUpperCase()),l.default.createElement("span",{className:"bold-label"},t)))}}]),t}(l.default.Component);p.propTypes={href:s.PropTypes.string,onClick:s.PropTypes.func,id:s.PropTypes.string.isRequired,method:s.PropTypes.string.isRequired,shown:s.PropTypes.bool.isRequired,showOpId:s.PropTypes.string.isRequired,showOpIdPrefix:s.PropTypes.string.isRequired}},function(e,t,r){"use strict";function n(e){return e&&e.__esModule?e:{default:e}}function o(e,t){var r={};for(var n in e)t.indexOf(n)>=0||Object.prototype.hasOwnProperty.call(e,n)&&(r[n]=e[n]);return r}function a(e,t){if(!(e instanceof t))throw new TypeError("Cannot call a class as a function")}function u(e,t){if(!e)throw new ReferenceError("this hasn't been initialised - super() hasn't been called");return!t||"object"!=typeof t&&"function"!=typeof t?e:t}function i(e,t){if("function"!=typeof t&&null!==t)throw new TypeError("Super expression must either be null or a function, not "+typeof t);e.prototype=Object.create(t&&t.prototype,{constructor:{value:e,enumerable:!1,writable:!0,configurable:!0}}),t&&(Object.setPrototypeOf?Object.setPrototypeOf(e,t):e.__proto__=t)}function s(){for(var e=arguments.length,t=Array(e),r=0;r<e;r++)t[r]=arguments[r];return t.filter(function(e){return!!e}).join(" ").trim()}Object.defineProperty(t,"__esModule",{value:!0}),t.Collapse=t.Link=t.Select=t.Input=t.TextArea=t.Button=t.Row=t.Col=t.Container=void 0;var l=Object.assign||function(e){for(var t=1;t<arguments.length;t++){var r=arguments[t];for(var n in r)Object.prototype.hasOwnProperty.call(r,n)&&(e[n]=r[n])}return e},c=function(){function e(e,t){for(var r=0;r<t.length;r++){var n=t[r];n.enumerable=n.enumerable||!1,n.configurable=!0,"value"in n&&(n.writable=!0),Object.defineProperty(e,n.key,n)}}return function(t,r,n){return r&&e(t.prototype,r),n&&e(t,n),t}}(),f=r(187),p=n(f),d=r(297),h=n(d),y=t.Container=function(e){function t(){return a(this,t),u(this,(t.__proto__||Object.getPrototypeOf(t)).apply(this,arguments))}return i(t,e),c(t,[{key:"render",value:function(){var e=this.props,t=e.fullscreen,r=e.full,n=o(e,["fullscreen","full"]);if(t)return p.default.createElement("section",n);var a="swagger-container"+(r?"-full":"");return p.default.createElement("section",l({},n,{className:s(n.className,a)}))}}]),t}(p.default.Component);y.propTypes={fullscreen:f.PropTypes.bool,full:f.PropTypes.bool,className:f.PropTypes.string};var m={mobile:"",tablet:"-tablet",desktop:"-desktop",large:"-hd"},v=t.Col=function(e){function t(){return a(this,t),u(this,(t.__proto__||Object.getPrototypeOf(t)).apply(this,arguments))}return i(t,e),c(t,[{key:"render",value:function(){var e=this.props,t=e.hide,r=e.keepContents,n=(e.mobile,e.tablet,e.desktop,e.large,o(e,["hide","keepContents","mobile","tablet","desktop","large"]));if(t&&!r)return p.default.createElement("span",null);var a=[];for(var u in m){var i=m[u];if(u in this.props){var c=this.props[u];if(c<1){a.push("none"+i);continue}a.push("block"+i),a.push("col-"+c+i)}}var f=s.apply(void 0,[n.className].concat(a));return p.default.createElement("section",l({},n,{style:{display:t?"none":null},className:f}))}}]),t}(p.default.Component);v.propTypes={hide:f.PropTypes.bool,keepContents:f.PropTypes.bool,mobile:f.PropTypes.number,tablet:f.PropTypes.number,desktop:f.PropTypes.number,large:f.PropTypes.number,className:f.PropTypes.string};var b=t.Row=function(e){function t(){return a(this,t),u(this,(t.__proto__||Object.getPrototypeOf(t)).apply(this,arguments))}return i(t,e),c(t,[{key:"render",value:function(){return p.default.createElement("div",l({},this.props,{className:s(this.props.className,"wrapper")}))}}]),t}(p.default.Component);b.propTypes={className:f.PropTypes.string};var g=t.Button=function(e){function t(){return a(this,t),u(this,(t.__proto__||Object.getPrototypeOf(t)).apply(this,arguments))}return i(t,e),c(t,[{key:"render",value:function(){return p.default.createElement("button",l({},this.props,{className:s(this.props.className,"button")}))}}]),t}(p.default.Component);g.propTypes={className:f.PropTypes.string},g.defaultProps={className:""};var _=(t.TextArea=function(e){return p.default.createElement("textarea",e)},t.Input=function(e){return p.default.createElement("input",e)},t.Select=function(e){function t(e,r){a(this,t);var n=u(this,(t.__proto__||Object.getPrototypeOf(t)).call(this,e,r));E.call(n);var o=void 0;return o=void 0!==e.value?e.value:e.multiple?[""]:"",n.state={value:o},n}return i(t,e),c(t,[{key:"render",value:function(){var e=this.props,t=e.allowedValues,r=e.multiple,n=e.allowEmptyValue,o=this.state.value.toJS?this.state.value.toJS():this.state.value; return p.default.createElement("select",{multiple:r,value:o,onChange:this.onChange},n?p.default.createElement("option",{value:""},"--"):null,t.map(function(e,t){return p.default.createElement("option",{key:t,value:String(e)},e)}))}}]),t}(p.default.Component));_.propTypes={allowedValues:f.PropTypes.array,value:f.PropTypes.any,onChange:f.PropTypes.func,multiple:f.PropTypes.bool,allowEmptyValue:f.PropTypes.bool},_.defaultProps={multiple:!1,allowEmptyValue:!0};var E=function(){var e=this;this.onChange=function(t){var r=e.props,n=r.onChange,o=r.multiple,a=[].slice.call(t.target.options),u=void 0;u=o?a.filter(function(e){return e.selected}).map(function(e){return e.value}):t.target.value,e.setState({value:u}),n&&n(u)}},w=t.Link=function(e){function t(){return a(this,t),u(this,(t.__proto__||Object.getPrototypeOf(t)).apply(this,arguments))}return i(t,e),c(t,[{key:"render",value:function(){return p.default.createElement("a",l({},this.props,{className:s(this.props.className,"link")}))}}]),t}(p.default.Component);w.propTypes={className:f.PropTypes.string};var j=function(e){var t=e.children;return p.default.createElement("div",{style:{height:"auto",border:"none",margin:0,padding:0}}," ",t," ")};j.propTypes={children:f.PropTypes.node};var P=t.Collapse=function(e){function t(){return a(this,t),u(this,(t.__proto__||Object.getPrototypeOf(t)).apply(this,arguments))}return i(t,e),c(t,[{key:"renderNotAnimated",value:function(){return this.props.isOpened?p.default.createElement(j,null,this.props.children):p.default.createElement("noscript",null)}},{key:"render",value:function(){var e=this.props,t=e.animated,r=e.isOpened,n=e.children;return t?(n=r?n:null,p.default.createElement(h.default,{isOpened:r},p.default.createElement(j,null,n))):this.renderNotAnimated()}}]),t}(p.default.Component);P.propTypes={isOpened:f.PropTypes.bool,children:f.PropTypes.node.isRequired,animated:f.PropTypes.bool},P.defaultProps={isOpened:!1,animated:!1}},function(e,t,r){"use strict";function n(e){return e&&e.__esModule?e:{default:e}}function o(e,t){if(!(e instanceof t))throw new TypeError("Cannot call a class as a function")}function a(e,t){if(!e)throw new ReferenceError("this hasn't been initialised - super() hasn't been called");return!t||"object"!=typeof t&&"function"!=typeof t?e:t}function u(e,t){if("function"!=typeof t&&null!==t)throw new TypeError("Super expression must either be null or a function, not "+typeof t);e.prototype=Object.create(t&&t.prototype,{constructor:{value:e,enumerable:!1,writable:!0,configurable:!0}}),t&&(Object.setPrototypeOf?Object.setPrototypeOf(e,t):e.__proto__=t)}Object.defineProperty(t,"__esModule",{value:!0});var i=function(){function e(e,t){for(var r=0;r<t.length;r++){var n=t[r];n.enumerable=n.enumerable||!1,n.configurable=!0,"value"in n&&(n.writable=!0),Object.defineProperty(e,n.key,n)}}return function(t,r,n){return r&&e(t.prototype,r),n&&e(t,n),t}}(),s=r(187),l=n(s),c=r(7),f=r(273),p=n(f),d=function(e){function t(){return o(this,t),a(this,(t.__proto__||Object.getPrototypeOf(t)).apply(this,arguments))}return u(t,e),i(t,[{key:"render",value:function(){var e=this.props,t=e.host,r=e.basePath;return l.default.createElement("pre",{className:"base-url"},"[ Base url: ",t,r,"]")}}]),t}(l.default.Component);d.propTypes={host:s.PropTypes.string,basePath:s.PropTypes.string};var h=function(e){function t(){return o(this,t),a(this,(t.__proto__||Object.getPrototypeOf(t)).apply(this,arguments))}return u(t,e),i(t,[{key:"render",value:function(){var e=this.props.data,t=e.get("name")||"the developer",r=e.get("url"),n=e.get("email");return l.default.createElement("div",null,r&&l.default.createElement("div",null,l.default.createElement("a",{href:r,target:"_blank"},t," - Website")),n&&l.default.createElement("a",{href:"mailto:"+n},r?"Send email to "+t:"Contact "+t))}}]),t}(l.default.Component);h.propTypes={data:s.PropTypes.object};var y=function(e){function t(){return o(this,t),a(this,(t.__proto__||Object.getPrototypeOf(t)).apply(this,arguments))}return u(t,e),i(t,[{key:"render",value:function(){var e=this.props.license,t=e.get("name")||"License",r=e.get("url");return l.default.createElement("div",null,r?l.default.createElement("a",{target:"_blank",href:r},t):l.default.createElement("span",null,t))}}]),t}(l.default.Component);y.propTypes={license:s.PropTypes.object};var m=function(e){function t(){return o(this,t),a(this,(t.__proto__||Object.getPrototypeOf(t)).apply(this,arguments))}return u(t,e),i(t,[{key:"render",value:function(){var e=this.props,t=e.info,r=e.url,n=e.host,o=e.basePath,a=e.getComponent,u=e.externalDocs,i=t.get("version"),s=t.get("description"),f=t.get("title"),p=t.get("termsOfService"),m=t.get("contact"),v=t.get("license"),b=(u||(0,c.fromJS)({})).toJS(),g=b.url,_=b.description,E=a("Markdown");return l.default.createElement("div",{className:"info"},l.default.createElement("hgroup",{className:"main"},l.default.createElement("h2",{className:"title"},f,i&&l.default.createElement("small",null,l.default.createElement("pre",{className:"version"}," ",i," "))),n||o?l.default.createElement(d,{host:n,basePath:o}):null,r&&l.default.createElement("a",{target:"_blank",href:r},l.default.createElement("span",{className:"url"}," ",r," "))),l.default.createElement("div",{className:"description"},l.default.createElement(E,{source:s})),p&&l.default.createElement("div",null,l.default.createElement("a",{target:"_blank",href:p},"Terms of service")),m&&m.size?l.default.createElement(h,{data:m}):null,v&&v.size?l.default.createElement(y,{license:v}):null,g?l.default.createElement("a",{target:"_blank",href:g},_||g):null)}}]),t}(l.default.Component);m.propTypes={info:s.PropTypes.object,url:s.PropTypes.string,host:s.PropTypes.string,basePath:s.PropTypes.string,externalDocs:p.default.map,getComponent:s.PropTypes.func.isRequired},t.default=m,m.propTypes={title:s.PropTypes.any,description:s.PropTypes.any,version:s.PropTypes.any,url:s.PropTypes.string}},function(e,t,r){"use strict";function n(e){return e&&e.__esModule?e:{default:e}}function o(e,t){if(!(e instanceof t))throw new TypeError("Cannot call a class as a function")}function a(e,t){if(!e)throw new ReferenceError("this hasn't been initialised - super() hasn't been called");return!t||"object"!=typeof t&&"function"!=typeof t?e:t}function u(e,t){if("function"!=typeof t&&null!==t)throw new TypeError("Super expression must either be null or a function, not "+typeof t);e.prototype=Object.create(t&&t.prototype,{constructor:{value:e,enumerable:!1,writable:!0,configurable:!0}}),t&&(Object.setPrototypeOf?Object.setPrototypeOf(e,t):e.__proto__=t)}Object.defineProperty(t,"__esModule",{value:!0});var i=function(){function e(e,t){for(var r=0;r<t.length;r++){var n=t[r];n.enumerable=n.enumerable||!1,n.configurable=!0,"value"in n&&(n.writable=!0),Object.defineProperty(e,n.key,n)}}return function(t,r,n){return r&&e(t.prototype,r),n&&e(t,n),t}}(),s=r(187),l=n(s),c=function(e){function t(){return o(this,t),a(this,(t.__proto__||Object.getPrototypeOf(t)).apply(this,arguments))}return u(t,e),i(t,[{key:"render",value:function(){return l.default.createElement("div",{className:"footer"})}}]),t}(l.default.Component);t.default=c},function(e,t,r){"use strict";function n(e){return e&&e.__esModule?e:{default:e}}function o(e,t){if(!(e instanceof t))throw new TypeError("Cannot call a class as a function")}function a(e,t){if(!e)throw new ReferenceError("this hasn't been initialised - super() hasn't been called");return!t||"object"!=typeof t&&"function"!=typeof t?e:t}function u(e,t){if("function"!=typeof t&&null!==t)throw new TypeError("Super expression must either be null or a function, not "+typeof t);e.prototype=Object.create(t&&t.prototype,{constructor:{value:e,enumerable:!1,writable:!0,configurable:!0}}),t&&(Object.setPrototypeOf?Object.setPrototypeOf(e,t):e.__proto__=t)}Object.defineProperty(t,"__esModule",{value:!0});var i=function(){function e(e,t){for(var r=0;r<t.length;r++){var n=t[r];n.enumerable=n.enumerable||!1,n.configurable=!0,"value"in n&&(n.writable=!0),Object.defineProperty(e,n.key,n)}}return function(t,r,n){return r&&e(t.prototype,r),n&&e(t,n),t}}(),s=r(187),l=n(s),c=r(285),f=n(c),p=r(7),d=r(12),h=Function.prototype,y=function(e){function t(e,r){o(this,t);var n=a(this,(t.__proto__||Object.getPrototypeOf(t)).call(this,e,r));return m.call(n),n.state={isEditBox:!1,value:""},n}return u(t,e),i(t,[{key:"componentDidMount",value:function(){this.updateValues.call(this,this.props)}},{key:"shouldComponentUpdate",value:function(e,t){return(0,f.default)(this,e,t)}},{key:"componentWillReceiveProps",value:function(e){this.updateValues.call(this,e)}},{key:"render",value:function(){var e=this.props,r=e.onChangeConsumes,n=e.param,o=e.isExecute,a=e.specSelectors,u=e.pathMethod,i=e.getComponent,s=i("Button"),c=i("TextArea"),f=i("highlightCode"),d=i("contentType"),h=a?a.getParameter(u,n.get("name")):n,y=h.get("errors",(0,p.List)()),m=a.contentTypeValues(u).get("requestContentType"),v=this.props.consumes&&this.props.consumes.size?this.props.consumes:t.defaultProp.consumes,b=this.state,g=b.value,_=b.isEditBox;return l.default.createElement("div",{className:"body-param"},_&&o?l.default.createElement(c,{className:"body-param__text"+(y.count()?" invalid":""),value:g,onChange:this.handleOnChange}):g&&l.default.createElement(f,{className:"body-param__example",value:g}),l.default.createElement("div",{className:"body-param-options"},o?l.default.createElement("div",{className:"body-param-edit"},l.default.createElement(s,{className:_?"btn cancel body-param__example-edit":"btn edit body-param__example-edit",onClick:this.toggleIsEditBox},_?"Cancel":"Edit")):null,l.default.createElement("label",{htmlFor:""},l.default.createElement("span",null,"Parameter content type"),l.default.createElement(d,{value:m,contentTypes:v,onChange:r,className:"body-param-content-type"}))))}}]),t}(s.Component);y.propTypes={param:s.PropTypes.object,onChange:s.PropTypes.func,onChangeConsumes:s.PropTypes.func,consumes:s.PropTypes.object,consumesValue:s.PropTypes.string,fn:s.PropTypes.object.isRequired,getComponent:s.PropTypes.func.isRequired,isExecute:s.PropTypes.bool,specSelectors:s.PropTypes.object.isRequired,pathMethod:s.PropTypes.array.isRequired},y.defaultProp={consumes:(0,p.fromJS)(["application/json"]),param:(0,p.fromJS)({}),onChange:h,onChangeConsumes:h};var m=function(){var e=this;this.updateValues=function(t){var r=t.specSelectors,n=t.pathMethod,o=t.param,a=t.isExecute,u=t.consumesValue,i=void 0===u?"":u,s=r?r.getParameter(n,o.get("name")):{},l=/xml/i.test(i),c=l?s.get("value_xml"):s.get("value");if(void 0!==c){var f=c||l?c:"{}";e.setState({value:f}),e.onChange(f,{isXml:l,isEditBox:a})}else l?e.onChange(e.sample("xml"),{isXml:l,isEditBox:a}):e.onChange(e.sample(),{isEditBox:a})},this.sample=function(t){var r=e.props,n=r.param,o=r.fn.inferSchema,a=o(n.toJS());return(0,d.getSampleSchema)(a,t)},this.onChange=function(t,r){var n=r.isEditBox,o=r.isXml;e.setState({value:t,isEditBox:n}),e._onChange(t,o)},this._onChange=function(t,r){(e.props.onChange||h)(e.props.param,t,r)},this.handleOnChange=function(t){var r=e.props.consumesValue;e.onChange(t.target.value.trim(),{isXml:/xml/i.test(r)})},this.toggleIsEditBox=function(){return e.setState(function(e){return{isEditBox:!e.isEditBox}})}};t.default=y},function(e,t,r){"use strict";function n(e){return e&&e.__esModule?e:{default:e}}function o(e,t){if(!(e instanceof t))throw new TypeError("Cannot call a class as a function")}function a(e,t){if(!e)throw new ReferenceError("this hasn't been initialised - super() hasn't been called");return!t||"object"!=typeof t&&"function"!=typeof t?e:t}function u(e,t){if("function"!=typeof t&&null!==t)throw new TypeError("Super expression must either be null or a function, not "+typeof t);e.prototype=Object.create(t&&t.prototype,{constructor:{value:e,enumerable:!1,writable:!0,configurable:!0}}),t&&(Object.setPrototypeOf?Object.setPrototypeOf(e,t):e.__proto__=t)}Object.defineProperty(t,"__esModule",{value:!0});var i=function(){function e(e,t){for(var r=0;r<t.length;r++){var n=t[r];n.enumerable=n.enumerable||!1,n.configurable=!0,"value"in n&&(n.writable=!0),Object.defineProperty(e,n.key,n)}}return function(t,r,n){return r&&e(t.prototype,r),n&&e(t,n),t}}(),s=r(187),l=n(s),c=r(305),f=n(c),p=function(e){function t(){return o(this,t),a(this,(t.__proto__||Object.getPrototypeOf(t)).apply(this,arguments))}return u(t,e),i(t,[{key:"handleFocus",value:function(e){e.target.select(),document.execCommand("copy")}},{key:"render",value:function(){var e=this.props.request,t=(0,f.default)(e);return l.default.createElement("div",null,l.default.createElement("h4",null,"Curl"),l.default.createElement("div",{className:"copy-paste"},l.default.createElement("textarea",{onFocus:this.handleFocus,readOnly:"true",className:"curl",style:{whiteSpace:"normal"},value:t})))}}]),t}(l.default.Component);p.propTypes={request:s.PropTypes.object.isRequired},t.default=p},function(e,t,r){"use strict";function n(e){return e&&e.__esModule?e:{default:e}}function o(e){var t=[],r="",n=e.get("headers");if(t.push("curl"),t.push("-X",e.get("method")),t.push('"'+e.get("url")+'"'),n&&n.size){var o=!0,u=!1,s=void 0;try{for(var l,c=e.get("headers").entries()[Symbol.iterator]();!(o=(l=c.next()).done);o=!0){var f=l.value,p=a(f,2),d=p[0],h=p[1];r=h,t.push("-H "),t.push('"'+d+": "+h+'"')}}catch(e){u=!0,s=e}finally{try{!o&&c.return&&c.return()}finally{if(u)throw s}}}if(e.get("body"))if("multipart/form-data"===r&&"POST"===e.get("method")){var y=!0,m=!1,v=void 0;try{for(var b,g=e.get("body").values()[Symbol.iterator]();!(y=(b=g.next()).done);y=!0){var _=a(b.value,2),E=_[0],h=_[1];t.push("-F"),h instanceof i.default.File?t.push('"'+E+"=@"+h.name+";type="+h.type+'"'):t.push('"'+E+"="+h+'"')}}catch(e){m=!0,v=e}finally{try{!y&&g.return&&g.return()}finally{if(m)throw v}}}else t.push("-d"),t.push(JSON.stringify(e.get("body")).replace(/\\n/g,""));return t.join(" ")}Object.defineProperty(t,"__esModule",{value:!0});var a=function(){function e(e,t){var r=[],n=!0,o=!1,a=void 0;try{for(var u,i=e[Symbol.iterator]();!(n=(u=i.next()).done)&&(r.push(u.value),!t||r.length!==t);n=!0);}catch(e){o=!0,a=e}finally{try{!n&&i.return&&i.return()}finally{if(o)throw a}}return r}return function(t,r){if(Array.isArray(t))return t;if(Symbol.iterator in Object(t))return e(t,r);throw new TypeError("Invalid attempt to destructure non-iterable instance")}}();t.default=o;var u=r(11),i=n(u)},function(e,t,r){"use strict";function n(e){return e&&e.__esModule?e:{default:e}}function o(e,t){if(!(e instanceof t))throw new TypeError("Cannot call a class as a function")}function a(e,t){if(!e)throw new ReferenceError("this hasn't been initialised - super() hasn't been called");return!t||"object"!=typeof t&&"function"!=typeof t?e:t}function u(e,t){if("function"!=typeof t&&null!==t)throw new TypeError("Super expression must either be null or a function, not "+typeof t);e.prototype=Object.create(t&&t.prototype,{constructor:{value:e,enumerable:!1,writable:!0,configurable:!0}}),t&&(Object.setPrototypeOf?Object.setPrototypeOf(e,t):e.__proto__=t)}Object.defineProperty(t,"__esModule",{value:!0});var i=function(){function e(e,t){for(var r=0;r<t.length;r++){var n=t[r];n.enumerable=n.enumerable||!1,n.configurable=!0,"value"in n&&(n.writable=!0),Object.defineProperty(e,n.key,n)}}return function(t,r,n){return r&&e(t.prototype,r),n&&e(t,n),t}}(),s=r(187),l=n(s),c=function(e){function t(){var e,r,n,u;o(this,t);for(var i=arguments.length,s=Array(i),l=0;l<i;l++)s[l]=arguments[l];return r=n=a(this,(e=t.__proto__||Object.getPrototypeOf(t)).call.apply(e,[this].concat(s))),n.onChange=function(e){n.setScheme(e.target.value)},n.setScheme=function(e){var t=n.props,r=t.path,o=t.method,a=t.specActions;a.setScheme(e,r,o)},u=r,a(n,u)}return u(t,e),i(t,[{key:"componentWillMount",value:function(){var e=this.props.schemes;this.setScheme(e.first())}},{key:"render",value:function(){var e=this.props.schemes;return l.default.createElement("label",{htmlFor:"schemes"},l.default.createElement("span",{className:"schemes-title"},"Schemes"),l.default.createElement("select",{onChange:this.onChange},e.valueSeq().map(function(e){return l.default.createElement("option",{value:e,key:e},e)}).toArray()))}}]),t}(l.default.Component);c.propTypes={specActions:s.PropTypes.object.isRequired,schemes:s.PropTypes.object.isRequired,path:s.PropTypes.string,method:s.PropTypes.string},t.default=c},function(e,t,r){"use strict";function n(e){return e&&e.__esModule?e:{default:e}}function o(e,t){if(!(e instanceof t))throw new TypeError("Cannot call a class as a function")}function a(e,t){if(!e)throw new ReferenceError("this hasn't been initialised - super() hasn't been called");return!t||"object"!=typeof t&&"function"!=typeof t?e:t}function u(e,t){if("function"!=typeof t&&null!==t)throw new TypeError("Super expression must either be null or a function, not "+typeof t);e.prototype=Object.create(t&&t.prototype,{constructor:{value:e,enumerable:!1,writable:!0,configurable:!0}}),t&&(Object.setPrototypeOf?Object.setPrototypeOf(e,t):e.__proto__=t)}Object.defineProperty(t,"__esModule",{value:!0});var i=function(){function e(e,t){for(var r=0;r<t.length;r++){var n=t[r];n.enumerable=n.enumerable||!1,n.configurable=!0,"value"in n&&(n.writable=!0),Object.defineProperty(e,n.key,n)}}return function(t,r,n){return r&&e(t.prototype,r),n&&e(t,n),t}}(),s=r(187),l=n(s),c=function(e){function t(e,r){o(this,t);var n=a(this,(t.__proto__||Object.getPrototypeOf(t)).call(this,e,r));return n.activeTab=function(e){var t=e.target.dataset.name;n.setState({activeTab:t})},n.state={activeTab:"example"},n}return u(t,e),i(t,[{key:"render",value:function(){var e=this.props,t=e.getComponent,r=e.specSelectors,n=e.schema,o=e.example,a=e.isExecute,u=t("model");return l.default.createElement("div",null,l.default.createElement("ul",{className:"tab"},l.default.createElement("li",{className:"tabitem"+(a||"example"===this.state.activeTab?" active":"")},l.default.createElement("a",{className:"tablinks","data-name":"example",onClick:this.activeTab},"Example Value")),l.default.createElement("li",{className:"tabitem"+(a||"model"!==this.state.activeTab?"":" active")},l.default.createElement("a",{className:"tablinks"+(a?" inactive":""),"data-name":"model",onClick:this.activeTab},"Model"))),l.default.createElement("div",null,(a||"example"===this.state.activeTab)&&o,!a&&"model"===this.state.activeTab&&l.default.createElement(u,{schema:n,getComponent:t,specSelectors:r,expandDepth:1})))}}]),t}(l.default.Component);c.propTypes={getComponent:s.PropTypes.func.isRequired,specSelectors:s.PropTypes.object.isRequired,schema:s.PropTypes.object.isRequired,example:s.PropTypes.any.isRequired,isExecute:s.PropTypes.bool},t.default=c},function(e,t,r){"use strict";function n(e){return e&&e.__esModule?e:{default:e}}function o(e,t){var r={};for(var n in e)t.indexOf(n)>=0||Object.prototype.hasOwnProperty.call(e,n)&&(r[n]=e[n]);return r}function a(e,t){if(!(e instanceof t))throw new TypeError("Cannot call a class as a function")}function u(e,t){if(!e)throw new ReferenceError("this hasn't been initialised - super() hasn't been called");return!t||"object"!=typeof t&&"function"!=typeof t?e:t}function i(e,t){if("function"!=typeof t&&null!==t)throw new TypeError("Super expression must either be null or a function, not "+typeof t);e.prototype=Object.create(t&&t.prototype,{constructor:{value:e,enumerable:!1,writable:!0,configurable:!0}}),t&&(Object.setPrototypeOf?Object.setPrototypeOf(e,t):e.__proto__=t)}Object.defineProperty(t,"__esModule",{value:!0});var s=Object.assign||function(e){for(var t=1;t<arguments.length;t++){var r=arguments[t];for(var n in r)Object.prototype.hasOwnProperty.call(r,n)&&(e[n]=r[n])}return e},l=function(){function e(e,t){var r=[],n=!0,o=!1,a=void 0;try{for(var u,i=e[Symbol.iterator]();!(n=(u=i.next()).done)&&(r.push(u.value),!t||r.length!==t);n=!0);}catch(e){o=!0,a=e}finally{try{!n&&i.return&&i.return()}finally{if(o)throw a}}return r}return function(t,r){if(Array.isArray(t))return t;if(Symbol.iterator in Object(t))return e(t,r);throw new TypeError("Invalid attempt to destructure non-iterable instance")}}(),c=function(){function e(e,t){for(var r=0;r<t.length;r++){var n=t[r];n.enumerable=n.enumerable||!1,n.configurable=!0,"value"in n&&(n.writable=!0),Object.defineProperty(e,n.key,n)}}return function(t,r,n){return r&&e(t.prototype,r),n&&e(t,n),t}}(),f=r(187),p=n(f),d=r(273),h=n(d),y=r(7),m="{",v="}",b={color:"#999",fontStyle:"italic"},g=function(e){var t=e.value,r=p.default.createElement("span",null,"Array [ ",t.count()," ]");return p.default.createElement("span",{className:"prop-enum"},"Enum:",p.default.createElement("br",null),p.default.createElement(O,{collapsedContent:r},"[ ",t.join(", ")," ]"))};g.propTypes={value:h.default.iterable};var _=function(e){function t(){return a(this,t),u(this,(t.__proto__||Object.getPrototypeOf(t)).apply(this,arguments))}return i(t,e),c(t,[{key:"render",value:function(){var e=this.props,t=e.schema,r=e.name,n=e.isRef,a=e.getComponent,u=e.depth,i=o(e,["schema","name","isRef","getComponent","depth"]),c=this.props.expandDepth,f=a("JumpToPath",!0),d=t.get("description"),h=t.get("properties"),b=t.get("additionalProperties"),g=t.get("title")||r,_=t.get("required"),E=a("Markdown"),w=function(e){var t=e.name;return p.default.createElement("span",{className:"model-jump-to-path"},p.default.createElement(f,{path:"definitions."+t}))},P=p.default.createElement("span",null,p.default.createElement("span",null,m),"...",p.default.createElement("span",null,v),n?p.default.createElement(w,{name:r}):"");return p.default.createElement("span",{className:"model"},g&&p.default.createElement("span",{className:"model-title"},n&&t.get("$$ref")&&p.default.createElement("span",{className:"model-hint"},t.get("$$ref")),p.default.createElement("span",{className:"model-title__text"},g)),p.default.createElement(O,{collapsed:u>c,collapsedContent:P},p.default.createElement("span",{className:"brace-open object"},m),n?p.default.createElement(w,{name:r}):null,p.default.createElement("span",{className:"inner-object"},p.default.createElement("table",{className:"model",style:{marginLeft:"2em"}},p.default.createElement("tbody",null,d?p.default.createElement("tr",{style:{color:"#999",fontStyle:"italic"}},p.default.createElement("td",null,"description:"),p.default.createElement("td",null,p.default.createElement(E,{source:d}))):null,h&&h.size?h.entrySeq().map(function(e){var t=l(e,2),n=t[0],o=t[1],c=y.List.isList(_)&&_.contains(n),f={verticalAlign:"top",paddingRight:"0.2em"};return c&&(f.fontWeight="bold"),p.default.createElement("tr",{key:n},p.default.createElement("td",{style:f},n,":"),p.default.createElement("td",{style:{verticalAlign:"top"}},p.default.createElement(j,s({key:"object-"+r+"-"+n+"_"+o},i,{required:c,getComponent:a,schema:o,depth:u+1}))))}).toArray():null,b&&b.size?p.default.createElement("tr",null,p.default.createElement("td",null,"< * >:"),p.default.createElement("td",null,p.default.createElement(j,s({},i,{required:!1,getComponent:a,schema:b,depth:u+1})))):null))),p.default.createElement("span",{className:"brace-close"},v)))}}]),t}(f.Component);_.propTypes={schema:f.PropTypes.object.isRequired,getComponent:f.PropTypes.func.isRequired,specSelectors:f.PropTypes.object.isRequired,name:f.PropTypes.string,isRef:f.PropTypes.bool,expandDepth:f.PropTypes.number,depth:f.PropTypes.number};var E=function(e){function t(){return a(this,t),u(this,(t.__proto__||Object.getPrototypeOf(t)).apply(this,arguments))}return i(t,e),c(t,[{key:"render",value:function(){var e=this.props,t=e.schema,r=e.getComponent,n=e.required;if(!t||!t.get)return p.default.createElement("div",null);var o=t.get("type"),a=t.get("format"),u=t.get("xml"),i=t.get("enum"),s=t.get("description"),c=t.filter(function(e,t){return["enum","type","format","description","$$ref"].indexOf(t)===-1}),f=n?{fontWeight:"bold"}:{},d=r("Markdown");return p.default.createElement("span",{className:"prop"},p.default.createElement("span",{className:"prop-type",style:f},o)," ",n&&p.default.createElement("span",{style:{color:"red"}},"*"),a&&p.default.createElement("span",{className:"prop-format"},"($",a,")"),c.size?c.entrySeq().map(function(e){var t=l(e,2),r=t[0],n=t[1];return p.default.createElement("span",{key:r+"-"+n,style:b},p.default.createElement("br",null),r,": ",String(n))}):null,s?p.default.createElement(d,{source:s}):null,u&&u.size?p.default.createElement("span",null,p.default.createElement("br",null),p.default.createElement("span",{style:b},"xml:"),u.entrySeq().map(function(e){var t=l(e,2),r=t[0],n=t[1];return p.default.createElement("span",{key:r+"-"+n,style:b},p.default.createElement("br",null),"   ",r,": ",String(n))}).toArray()):null,i&&p.default.createElement(g,{value:i}))}}]),t}(f.Component);E.propTypes={schema:f.PropTypes.object.isRequired,getComponent:f.PropTypes.func.isRequired,required:f.PropTypes.bool};var w=function(e){function t(){return a(this,t),u(this,(t.__proto__||Object.getPrototypeOf(t)).apply(this,arguments))}return i(t,e),c(t,[{key:"render",value:function(){var e=this.props,t=e.required,r=e.schema,n=e.depth,o=e.expandDepth,a=r.get("items"),u=r.filter(function(e,t){return["type","items","$$ref"].indexOf(t)===-1});return p.default.createElement("span",{className:"model"},p.default.createElement("span",{className:"model-title"},p.default.createElement("span",{className:"model-title__text"},r.get("title"))),p.default.createElement(O,{collapsed:n>o,collapsedContent:"[...]"},"[",p.default.createElement("span",null,p.default.createElement(j,s({},this.props,{schema:a,required:!1}))),"]",u.size?p.default.createElement("span",null,u.entrySeq().map(function(e){var t=l(e,2),r=t[0],n=t[1];return p.default.createElement("span",{key:r+"-"+n,style:b},p.default.createElement("br",null),r+":",String(n))}),p.default.createElement("br",null)):null),t&&p.default.createElement("span",{style:{color:"red"}},"*"))}}]),t}(f.Component);w.propTypes={schema:f.PropTypes.object.isRequired,getComponent:f.PropTypes.func.isRequired,specSelectors:f.PropTypes.object.isRequired,name:f.PropTypes.string,required:f.PropTypes.bool,expandDepth:f.PropTypes.number,depth:f.PropTypes.number};var j=function(e){function t(){var e,r,n,o;a(this,t);for(var i=arguments.length,s=Array(i),l=0;l<i;l++)s[l]=arguments[l];return r=n=u(this,(e=t.__proto__||Object.getPrototypeOf(t)).call.apply(e,[this].concat(s))),n.getModelName=function(e){if(e.indexOf("#/definitions/")!==-1)return e.replace(/^.*#\/definitions\//,"")},n.getRefSchema=function(e){var t=n.props.specSelectors;return t.findDefinition(e)},o=r,u(n,o)}return i(t,e),c(t,[{key:"render",value:function(){var e=this.props,t=e.schema,r=e.getComponent,n=e.required,o=e.name,a=e.isRef,u=t&&t.get("$$ref"),i=u&&this.getModelName(u),l=void 0,c=void 0;switch(t&&(t.get("type")||t.get("properties"))?l=t:u&&(l=this.getRefSchema(i)),c=l&&l.get("type"),!c&&l&&l.get("properties")&&(c="object"),c){case"object":return p.default.createElement(_,s({className:"object"},this.props,{schema:l,name:o||i,isRef:void 0!==a?a:!!u}));case"array":return p.default.createElement(w,s({className:"array"},this.props,{schema:l,required:n}));case"string":case"number":case"integer":case"boolean":default:return p.default.createElement(E,{getComponent:r,schema:l,required:n})}}}]),t}(f.Component);j.propTypes={schema:f.PropTypes.object.isRequired,getComponent:f.PropTypes.func.isRequired,specSelectors:f.PropTypes.object.isRequired,name:f.PropTypes.string,isRef:f.PropTypes.bool,required:f.PropTypes.bool,expandDepth:f.PropTypes.number,depth:f.PropTypes.number};var P=function(e){function t(){return a(this,t),u(this,(t.__proto__||Object.getPrototypeOf(t)).apply(this,arguments))}return i(t,e),c(t,[{key:"render",value:function(){return p.default.createElement("div",{className:"model-box"},p.default.createElement(j,s({},this.props,{depth:1,expandDepth:this.props.expandDepth||0})))}}]),t}(f.Component);P.propTypes={schema:f.PropTypes.object.isRequired,name:f.PropTypes.string,getComponent:f.PropTypes.func.isRequired,specSelectors:f.PropTypes.object.isRequired,expandDepth:f.PropTypes.number},t.default=P;var O=function(e){function t(e,r){a(this,t);var n=u(this,(t.__proto__||Object.getPrototypeOf(t)).call(this,e,r));n.toggleCollapsed=function(){n.setState({collapsed:!n.state.collapsed})};var o=n.props,i=o.collapsed,s=o.collapsedContent;return n.state={collapsed:void 0!==i?i:t.defaultProps.collapsed,collapsedContent:s||t.defaultProps.collapsedContent},n}return i(t,e),c(t,[{key:"render",value:function(){return p.default.createElement("span",null,p.default.createElement("span",{onClick:this.toggleCollapsed,style:{cursor:"pointer"}},p.default.createElement("span",{className:"model-toggle"+(this.state.collapsed?" collapsed":"")})),this.state.collapsed?this.state.collapsedContent:this.props.children)}}]),t}(f.Component);O.propTypes={collapsedContent:f.PropTypes.any,collapsed:f.PropTypes.bool,children:f.PropTypes.any},O.defaultProps={collapsedContent:"{...}",collapsed:!0}},function(e,t,r){"use strict";function n(e){return e&&e.__esModule?e:{default:e}}function o(e,t){if(!(e instanceof t))throw new TypeError("Cannot call a class as a function")}function a(e,t){if(!e)throw new ReferenceError("this hasn't been initialised - super() hasn't been called");return!t||"object"!=typeof t&&"function"!=typeof t?e:t}function u(e,t){if("function"!=typeof t&&null!==t)throw new TypeError("Super expression must either be null or a function, not "+typeof t);e.prototype=Object.create(t&&t.prototype,{constructor:{value:e,enumerable:!1,writable:!0,configurable:!0}}),t&&(Object.setPrototypeOf?Object.setPrototypeOf(e,t):e.__proto__=t)}Object.defineProperty(t,"__esModule",{value:!0});var i=function(){function e(e,t){var r=[],n=!0,o=!1,a=void 0;try{for(var u,i=e[Symbol.iterator]();!(n=(u=i.next()).done)&&(r.push(u.value),!t||r.length!==t);n=!0);}catch(e){o=!0,a=e}finally{try{!n&&i.return&&i.return()}finally{if(o)throw a}}return r}return function(t,r){if(Array.isArray(t))return t;if(Symbol.iterator in Object(t))return e(t,r);throw new TypeError("Invalid attempt to destructure non-iterable instance")}}(),s=function(){function e(e,t){for(var r=0;r<t.length;r++){var n=t[r];n.enumerable=n.enumerable||!1,n.configurable=!0,"value"in n&&(n.writable=!0),Object.defineProperty(e,n.key,n)}}return function(t,r,n){return r&&e(t.prototype,r),n&&e(t,n),t}}(),l=r(187),c=n(l),f=function(e){function t(){return o(this,t),a(this,(t.__proto__||Object.getPrototypeOf(t)).apply(this,arguments))}return u(t,e),s(t,[{key:"render",value:function(){var e=this.props,t=e.specSelectors,r=e.getComponent,n=e.layoutSelectors,o=e.layoutActions,a=e.getConfigs,u=t.definitions(),s=a(),l=s.docExpansion,f=n.isShown("models","full"===l||"list"===l),p=r("model"),d=r("Collapse");return u.size?c.default.createElement("section",{className:f?"models is-open":"models"},c.default.createElement("h4",{onClick:function(){return o.show("models",!f)}},c.default.createElement("span",null,"Models"),c.default.createElement("svg",{width:"20",height:"20"},c.default.createElement("use",{xlinkHref:"#large-arrow"}))),c.default.createElement(d,{isOpened:f,animated:!0},u.entrySeq().map(function(e){var n=i(e,2),o=n[0],a=n[1];return c.default.createElement("div",{className:"model-container",key:"models-section-"+o},c.default.createElement(p,{name:o,schema:a,isRef:!0,getComponent:r,specSelectors:t}))}).toArray())):null}}]),t}(l.Component);f.propTypes={getComponent:l.PropTypes.func,specSelectors:l.PropTypes.object,layoutSelectors:l.PropTypes.object,layoutActions:l.PropTypes.object,getConfigs:l.PropTypes.func.isRequired},t.default=f},function(e,t,r){"use strict";function n(e){return e&&e.__esModule?e:{default:e}}function o(e,t){if(!(e instanceof t))throw new TypeError("Cannot call a class as a function")}function a(e,t){if(!e)throw new ReferenceError("this hasn't been initialised - super() hasn't been called");return!t||"object"!=typeof t&&"function"!=typeof t?e:t}function u(e,t){if("function"!=typeof t&&null!==t)throw new TypeError("Super expression must either be null or a function, not "+typeof t); e.prototype=Object.create(t&&t.prototype,{constructor:{value:e,enumerable:!1,writable:!0,configurable:!0}}),t&&(Object.setPrototypeOf?Object.setPrototypeOf(e,t):e.__proto__=t)}Object.defineProperty(t,"__esModule",{value:!0});var i=function(){function e(e,t){for(var r=0;r<t.length;r++){var n=t[r];n.enumerable=n.enumerable||!1,n.configurable=!0,"value"in n&&(n.writable=!0),Object.defineProperty(e,n.key,n)}}return function(t,r,n){return r&&e(t.prototype,r),n&&e(t,n),t}}(),s=r(187),l=n(s),c=function(e){function t(){return o(this,t),a(this,(t.__proto__||Object.getPrototypeOf(t)).apply(this,arguments))}return u(t,e),i(t,[{key:"render",value:function(){var e=this.props,t=e.onTryoutClick,r=e.onCancelClick,n=e.enabled;return l.default.createElement("div",{className:"try-out"},n?l.default.createElement("button",{className:"btn try-out__btn cancel",onClick:t},"Cancel"):l.default.createElement("button",{className:"btn try-out__btn",onClick:r},"Try it out "))}}]),t}(l.default.Component);c.propTypes={onTryoutClick:s.PropTypes.func,onCancelClick:s.PropTypes.func,enabled:s.PropTypes.bool},c.defaultProps={onTryoutClick:Function.prototype,onCancelClick:Function.prototype,enabled:!1},t.default=c},function(e,t,r){"use strict";function n(e){return e&&e.__esModule?e:{default:e}}function o(e){var t=e.source,r=(0,c.default)(t,f);return u.default.createElement(s.default,{options:{html:!0,typographer:!0,linkify:!0,linkTarget:"_blank"},source:r})}Object.defineProperty(t,"__esModule",{value:!0});var a=r(187),u=n(a),i=r(312),s=n(i),l=r(313),c=n(l),f={textFilter:function(e){return e.replace(/&quot;/g,'"')}};o.propTypes={source:a.PropTypes.string.isRequired},t.default=o},function(e,t){e.exports=require("react-remarkable")},function(e,t){e.exports=require("sanitize-html")},function(e,t,r){"use strict";function n(e){return e&&e.__esModule?e:{default:e}}function o(e,t){if(!(e instanceof t))throw new TypeError("Cannot call a class as a function")}function a(e,t){if(!e)throw new ReferenceError("this hasn't been initialised - super() hasn't been called");return!t||"object"!=typeof t&&"function"!=typeof t?e:t}function u(e,t){if("function"!=typeof t&&null!==t)throw new TypeError("Super expression must either be null or a function, not "+typeof t);e.prototype=Object.create(t&&t.prototype,{constructor:{value:e,enumerable:!1,writable:!0,configurable:!0}}),t&&(Object.setPrototypeOf?Object.setPrototypeOf(e,t):e.__proto__=t)}Object.defineProperty(t,"__esModule",{value:!0});var i=function(){function e(e,t){for(var r=0;r<t.length;r++){var n=t[r];n.enumerable=n.enumerable||!1,n.configurable=!0,"value"in n&&(n.writable=!0),Object.defineProperty(e,n.key,n)}}return function(t,r,n){return r&&e(t.prototype,r),n&&e(t,n),t}}(),s=r(187),l=n(s),c=function(e){function t(){return o(this,t),a(this,(t.__proto__||Object.getPrototypeOf(t)).apply(this,arguments))}return u(t,e),i(t,[{key:"render",value:function(){var e=this.props,t=e.specSelectors,r=e.specActions,n=e.getComponent,o=t.info(),a=t.url(),u=t.basePath(),i=t.host(),s=t.securityDefinitions(),c=t.externalDocs(),f=t.schemes(),p=n("info"),d=n("operations",!0),h=n("models",!0),y=n("authorizeBtn",!0),m=n("Row"),v=n("Col"),b=n("errors",!0),g=n("schemes"),_=!t.specStr();return _?l.default.createElement("h4",null,"No spec provided."):l.default.createElement("div",{className:"swagger-ui"},l.default.createElement("div",null,l.default.createElement(b,null),l.default.createElement(m,{className:"information-container"},l.default.createElement(v,{mobile:12},o.count()?l.default.createElement(p,{info:o,url:a,host:i,basePath:u,externalDocs:c,getComponent:n}):null)),f&&f.size||s?l.default.createElement("div",{className:"scheme-container"},l.default.createElement(v,{className:"schemes wrapper",mobile:12},f&&f.size?l.default.createElement(g,{schemes:f,specActions:r}):null,s?l.default.createElement(y,null):null)):null,l.default.createElement(m,null,l.default.createElement(v,{mobile:12,desktop:12},l.default.createElement(d,null))),l.default.createElement(m,null,l.default.createElement(v,{mobile:12,desktop:12},l.default.createElement(h,null)))))}}]),t}(l.default.Component);c.propTypes={errSelectors:s.PropTypes.object.isRequired,errActions:s.PropTypes.object.isRequired,specActions:s.PropTypes.object.isRequired,specSelectors:s.PropTypes.object.isRequired,layoutSelectors:s.PropTypes.object.isRequired,layoutActions:s.PropTypes.object.isRequired,getComponent:s.PropTypes.func.isRequired},t.default=c},function(e,t,r){"use strict";function n(e){return e&&e.__esModule?e:{default:e}}function o(e,t){if(!(e instanceof t))throw new TypeError("Cannot call a class as a function")}function a(e,t){if(!e)throw new ReferenceError("this hasn't been initialised - super() hasn't been called");return!t||"object"!=typeof t&&"function"!=typeof t?e:t}function u(e,t){if("function"!=typeof t&&null!==t)throw new TypeError("Super expression must either be null or a function, not "+typeof t);e.prototype=Object.create(t&&t.prototype,{constructor:{value:e,enumerable:!1,writable:!0,configurable:!0}}),t&&(Object.setPrototypeOf?Object.setPrototypeOf(e,t):e.__proto__=t)}Object.defineProperty(t,"__esModule",{value:!0}),t.JsonSchema_boolean=t.JsonSchema_array=t.JsonSchema_string=t.JsonSchemaForm=void 0;var i=Object.assign||function(e){for(var t=1;t<arguments.length;t++){var r=arguments[t];for(var n in r)Object.prototype.hasOwnProperty.call(r,n)&&(e[n]=r[n])}return e},s=function(){function e(e,t){for(var r=0;r<t.length;r++){var n=t[r];n.enumerable=n.enumerable||!1,n.configurable=!0,"value"in n&&(n.writable=!0),Object.defineProperty(e,n.key,n)}}return function(t,r,n){return r&&e(t.prototype,r),n&&e(t,n),t}}(),l=r(187),c=n(l),f=r(285),p=n(f),d=r(7),h=function(){},y={getComponent:l.PropTypes.func.isRequired,value:l.PropTypes.any,onChange:l.PropTypes.func,keyName:l.PropTypes.any,fn:l.PropTypes.object.isRequired,schema:l.PropTypes.object,required:l.PropTypes.bool,description:l.PropTypes.any},m={value:"",onChange:h,schema:{},keyName:"",required:!1},v=t.JsonSchemaForm=function(e){function t(){return o(this,t),a(this,(t.__proto__||Object.getPrototypeOf(t)).apply(this,arguments))}return u(t,e),s(t,[{key:"render",value:function(){var e=this.props,t=e.schema,r=e.value,n=e.onChange,o=e.getComponent,a=e.fn;t.toJS&&(t=t.toJS());var u=t,s=u.type,l=u.format,f=void 0===l?"":l,p=o("JsonSchema_"+s+"_"+f)||o("JsonSchema_"+s)||o("JsonSchema_string");return c.default.createElement(p,i({},this.props,{fn:a,getComponent:o,value:r,onChange:n,schema:t}))}}]),t}(l.Component);v.propTypes=y,v.defaultProps=m;var b=t.JsonSchema_string=function(e){function t(){var e,r,n,u;o(this,t);for(var i=arguments.length,s=Array(i),l=0;l<i;l++)s[l]=arguments[l];return r=n=a(this,(e=t.__proto__||Object.getPrototypeOf(t)).call.apply(e,[this].concat(s))),n.onChange=function(e){var t="file"===n.props.schema.type?e.target.files[0]:e.target.value;n.props.onChange(t,n.props.keyName)},n.onEnumChange=function(e){return n.props.onChange(e)},u=r,a(n,u)}return u(t,e),s(t,[{key:"render",value:function(){var e=this.props,t=e.getComponent,r=e.value,n=e.schema,o=e.required,a=e.description,u=n.enum,i=n.errors||[];if(u){var s=t("Select");return c.default.createElement(s,{allowedValues:u,value:r,allowEmptyValue:!o,onChange:this.onEnumChange})}var l="formData"===n.in&&!("FormData"in window),f=t("Input");return"file"===n.type?c.default.createElement(f,{type:"file",className:i.length?"invalid":"",onChange:this.onChange,disabled:l}):c.default.createElement(f,{type:"password"===n.format?"password":"text",className:i.length?"invalid":"",value:r,placeholder:a,onChange:this.onChange,disabled:l})}}]),t}(l.Component);b.propTypes=y,b.defaultProps=m;var g=t.JsonSchema_array=function(e){function t(e,r){o(this,t);var n=a(this,(t.__proto__||Object.getPrototypeOf(t)).call(this,e,r));return n.onChange=function(){return n.props.onChange(n.state.value)},n.onItemChange=function(e,t){n.setState(function(r){return{value:r.value.set(t,e)}},n.onChange)},n.removeItem=function(e){n.setState(function(t){return{value:t.value.remove(e)}},n.onChange)},n.addItem=function(){n.setState(function(e){return e.value=e.value||(0,d.List)(),{value:e.value.push("")}},n.onChange)},n.onEnumChange=function(e){n.setState(function(){return{value:e}},n.onChange)},n.state={value:e.value},n}return u(t,e),s(t,[{key:"componentWillReceiveProps",value:function(e){e.value!==this.state.value&&this.setState({value:e.value})}},{key:"shouldComponentUpdate",value:function(e,t){return(0,p.default)(this,e,t)}},{key:"render",value:function(){var e=this,t=this.props,r=t.getComponent,n=t.required,o=t.schema,a=t.fn,u=a.inferSchema(o.items),i=r("JsonSchemaForm"),s=r("Button"),l=u.enum,f=this.state.value;if(l){var p=r("Select");return c.default.createElement(p,{multiple:!0,value:f,allowedValues:l,allowEmptyValue:!n,onChange:this.onEnumChange})}var d=o.errors||[];return c.default.createElement("div",null,!f||f.count()<1?d.length?c.default.createElement("span",{style:{color:"red",fortWeight:"bold"}},d[0]):null:f.map(function(t,n){var o=Object.assign({},u);if(d.length){var l=d.filter(function(e){return e.index===n});l.length&&(o.errors=[l[0].error+n])}return c.default.createElement("div",{key:n,className:"json-schema-form-item"},c.default.createElement(i,{fn:a,getComponent:r,value:t,onChange:function(t){return e.onItemChange(t,n)},schema:o}),c.default.createElement(s,{className:"json-schema-form-item-remove",onClick:function(){return e.removeItem(n)}}," - "))}).toArray(),c.default.createElement(s,{className:"json-schema-form-item-add",onClick:this.addItem}," Add item "))}}]),t}(l.Component);g.propTypes=y,g.defaultProps=m;var _=t.JsonSchema_boolean=function(e){function t(){var e,r,n,u;o(this,t);for(var i=arguments.length,s=Array(i),l=0;l<i;l++)s[l]=arguments[l];return r=n=a(this,(e=t.__proto__||Object.getPrototypeOf(t)).call.apply(e,[this].concat(s))),n.onEnumChange=function(e){return n.props.onChange(e)},u=r,a(n,u)}return u(t,e),s(t,[{key:"render",value:function(){var e=this.props,t=e.getComponent,r=e.required,n=e.value,o=t("Select");return c.default.createElement(o,{value:String(n),allowedValues:(0,d.fromJS)(["true","false"]),allowEmptyValue:!r,onChange:this.onEnumChange})}}]),t}(l.Component);_.propTypes=y,_.defaultProps=m},function(e,t,r){"use strict";var n=r(12),o=r(317);o.keys().forEach(function(t){if("./index.js"!==t){var r=o(t);e.exports[(0,n.pascalCaseFilename)(t)]=r.default?r.default:r}})},function(e,t,r){function n(e){return r(o(e))}function o(e){return a[e]||function(){throw new Error("Cannot find module '"+e+"'.")}()}var a={"./all.js":316,"./ast/ast.js":243,"./ast/index.js":242,"./ast/jump-to-path.jsx":252,"./auth/actions.js":257,"./auth/index.js":255,"./auth/reducers.js":256,"./auth/selectors.js":258,"./auth/spec-wrap-actions.js":259,"./download-url.js":268,"./err/actions.js":10,"./err/error-transformers/hook.js":165,"./err/error-transformers/transformers/not-of-type.js":169,"./err/error-transformers/transformers/parameter-oneof.js":170,"./err/error-transformers/transformers/strip-instance.js":171,"./err/index.js":159,"./err/reducers.js":160,"./err/selectors.js":172,"./layout/actions.js":176,"./layout/index.js":174,"./layout/reducers.js":175,"./layout/selectors.js":177,"./logs/index.js":241,"./samples/fn.js":154,"./samples/index.js":240,"./spec/actions.js":180,"./spec/index.js":178,"./spec/reducers.js":179,"./spec/selectors.js":183,"./spec/wrap-actions.js":184,"./split-pane-mode/components/index.js":263,"./split-pane-mode/components/split-pane-mode.jsx":265,"./split-pane-mode/index.js":262,"./swagger-js/index.js":253,"./util/index.js":260,"./view/index.js":185,"./view/root-injects.js":186};n.keys=function(){return Object.keys(a)},n.resolve=o,e.exports=n,n.id=317}]))}); //# sourceMappingURL=swagger-ui.js.map
Python/Templates/Web/ProjectTemplates/Python/Web/StarterBottleProject/jquery-1.10.2.min.js
zooba/PTVS
/* NUGET: BEGIN LICENSE TEXT * * Microsoft grants you the right to use these script files for the sole * purpose of either: (i) interacting through your browser with the Microsoft * website or online service, subject to the applicable licensing or use * terms; or (ii) using the files as included with a Microsoft product subject * to that product's license terms. Microsoft reserves all other rights to the * files not expressly granted by Microsoft, whether by implication, estoppel * or otherwise. Insofar as a script file is dual licensed under GPL, * Microsoft neither took the code under GPL nor distributes it thereunder but * under the terms set out in this paragraph. All notices and licenses * below are for informational purposes only. * * JQUERY CORE 1.10.2; Copyright 2005, 2013 jQuery Foundation, Inc. and other contributors; http://jquery.org/license * Includes Sizzle.js; Copyright 2013 jQuery Foundation, Inc. and other contributors; http://opensource.org/licenses/MIT * * NUGET: END LICENSE TEXT */ /*! jQuery v1.10.2 | (c) 2005, 2013 jQuery Foundation, Inc. | jquery.org/license //@ sourceMappingURL=jquery-1.10.2.min.map */ (function(e,t){var n,r,i=typeof t,o=e.location,a=e.document,s=a.documentElement,l=e.jQuery,u=e.$,c={},p=[],f="1.10.2",d=p.concat,h=p.push,g=p.slice,m=p.indexOf,y=c.toString,v=c.hasOwnProperty,b=f.trim,x=function(e,t){return new x.fn.init(e,t,r)},w=/[+-]?(?:\d*\.|)\d+(?:[eE][+-]?\d+|)/.source,T=/\S+/g,C=/^[\s\uFEFF\xA0]+|[\s\uFEFF\xA0]+$/g,N=/^(?:\s*(<[\w\W]+>)[^>]*|#([\w-]*))$/,k=/^<(\w+)\s*\/?>(?:<\/\1>|)$/,E=/^[\],:{}\s]*$/,S=/(?:^|:|,)(?:\s*\[)+/g,A=/\\(?:["\\\/bfnrt]|u[\da-fA-F]{4})/g,j=/"[^"\\\r\n]*"|true|false|null|-?(?:\d+\.|)\d+(?:[eE][+-]?\d+|)/g,D=/^-ms-/,L=/-([\da-z])/gi,H=function(e,t){return t.toUpperCase()},q=function(e){(a.addEventListener||"load"===e.type||"complete"===a.readyState)&&(_(),x.ready())},_=function(){a.addEventListener?(a.removeEventListener("DOMContentLoaded",q,!1),e.removeEventListener("load",q,!1)):(a.detachEvent("onreadystatechange",q),e.detachEvent("onload",q))};x.fn=x.prototype={jquery:f,constructor:x,init:function(e,n,r){var i,o;if(!e)return this;if("string"==typeof e){if(i="<"===e.charAt(0)&&">"===e.charAt(e.length-1)&&e.length>=3?[null,e,null]:N.exec(e),!i||!i[1]&&n)return!n||n.jquery?(n||r).find(e):this.constructor(n).find(e);if(i[1]){if(n=n instanceof x?n[0]:n,x.merge(this,x.parseHTML(i[1],n&&n.nodeType?n.ownerDocument||n:a,!0)),k.test(i[1])&&x.isPlainObject(n))for(i in n)x.isFunction(this[i])?this[i](n[i]):this.attr(i,n[i]);return this}if(o=a.getElementById(i[2]),o&&o.parentNode){if(o.id!==i[2])return r.find(e);this.length=1,this[0]=o}return this.context=a,this.selector=e,this}return e.nodeType?(this.context=this[0]=e,this.length=1,this):x.isFunction(e)?r.ready(e):(e.selector!==t&&(this.selector=e.selector,this.context=e.context),x.makeArray(e,this))},selector:"",length:0,toArray:function(){return g.call(this)},get:function(e){return null==e?this.toArray():0>e?this[this.length+e]:this[e]},pushStack:function(e){var t=x.merge(this.constructor(),e);return t.prevObject=this,t.context=this.context,t},each:function(e,t){return x.each(this,e,t)},ready:function(e){return x.ready.promise().done(e),this},slice:function(){return this.pushStack(g.apply(this,arguments))},first:function(){return this.eq(0)},last:function(){return this.eq(-1)},eq:function(e){var t=this.length,n=+e+(0>e?t:0);return this.pushStack(n>=0&&t>n?[this[n]]:[])},map:function(e){return this.pushStack(x.map(this,function(t,n){return e.call(t,n,t)}))},end:function(){return this.prevObject||this.constructor(null)},push:h,sort:[].sort,splice:[].splice},x.fn.init.prototype=x.fn,x.extend=x.fn.extend=function(){var e,n,r,i,o,a,s=arguments[0]||{},l=1,u=arguments.length,c=!1;for("boolean"==typeof s&&(c=s,s=arguments[1]||{},l=2),"object"==typeof s||x.isFunction(s)||(s={}),u===l&&(s=this,--l);u>l;l++)if(null!=(o=arguments[l]))for(i in o)e=s[i],r=o[i],s!==r&&(c&&r&&(x.isPlainObject(r)||(n=x.isArray(r)))?(n?(n=!1,a=e&&x.isArray(e)?e:[]):a=e&&x.isPlainObject(e)?e:{},s[i]=x.extend(c,a,r)):r!==t&&(s[i]=r));return s},x.extend({expando:"jQuery"+(f+Math.random()).replace(/\D/g,""),noConflict:function(t){return e.$===x&&(e.$=u),t&&e.jQuery===x&&(e.jQuery=l),x},isReady:!1,readyWait:1,holdReady:function(e){e?x.readyWait++:x.ready(!0)},ready:function(e){if(e===!0?!--x.readyWait:!x.isReady){if(!a.body)return setTimeout(x.ready);x.isReady=!0,e!==!0&&--x.readyWait>0||(n.resolveWith(a,[x]),x.fn.trigger&&x(a).trigger("ready").off("ready"))}},isFunction:function(e){return"function"===x.type(e)},isArray:Array.isArray||function(e){return"array"===x.type(e)},isWindow:function(e){return null!=e&&e==e.window},isNumeric:function(e){return!isNaN(parseFloat(e))&&isFinite(e)},type:function(e){return null==e?e+"":"object"==typeof e||"function"==typeof e?c[y.call(e)]||"object":typeof e},isPlainObject:function(e){var n;if(!e||"object"!==x.type(e)||e.nodeType||x.isWindow(e))return!1;try{if(e.constructor&&!v.call(e,"constructor")&&!v.call(e.constructor.prototype,"isPrototypeOf"))return!1}catch(r){return!1}if(x.support.ownLast)for(n in e)return v.call(e,n);for(n in e);return n===t||v.call(e,n)},isEmptyObject:function(e){var t;for(t in e)return!1;return!0},error:function(e){throw Error(e)},parseHTML:function(e,t,n){if(!e||"string"!=typeof e)return null;"boolean"==typeof t&&(n=t,t=!1),t=t||a;var r=k.exec(e),i=!n&&[];return r?[t.createElement(r[1])]:(r=x.buildFragment([e],t,i),i&&x(i).remove(),x.merge([],r.childNodes))},parseJSON:function(n){return e.JSON&&e.JSON.parse?e.JSON.parse(n):null===n?n:"string"==typeof n&&(n=x.trim(n),n&&E.test(n.replace(A,"@").replace(j,"]").replace(S,"")))?Function("return "+n)():(x.error("Invalid JSON: "+n),t)},parseXML:function(n){var r,i;if(!n||"string"!=typeof n)return null;try{e.DOMParser?(i=new DOMParser,r=i.parseFromString(n,"text/xml")):(r=new ActiveXObject("Microsoft.XMLDOM"),r.async="false",r.loadXML(n))}catch(o){r=t}return r&&r.documentElement&&!r.getElementsByTagName("parsererror").length||x.error("Invalid XML: "+n),r},noop:function(){},globalEval:function(t){t&&x.trim(t)&&(e.execScript||function(t){e.eval.call(e,t)})(t)},camelCase:function(e){return e.replace(D,"ms-").replace(L,H)},nodeName:function(e,t){return e.nodeName&&e.nodeName.toLowerCase()===t.toLowerCase()},each:function(e,t,n){var r,i=0,o=e.length,a=M(e);if(n){if(a){for(;o>i;i++)if(r=t.apply(e[i],n),r===!1)break}else for(i in e)if(r=t.apply(e[i],n),r===!1)break}else if(a){for(;o>i;i++)if(r=t.call(e[i],i,e[i]),r===!1)break}else for(i in e)if(r=t.call(e[i],i,e[i]),r===!1)break;return e},trim:b&&!b.call("\ufeff\u00a0")?function(e){return null==e?"":b.call(e)}:function(e){return null==e?"":(e+"").replace(C,"")},makeArray:function(e,t){var n=t||[];return null!=e&&(M(Object(e))?x.merge(n,"string"==typeof e?[e]:e):h.call(n,e)),n},inArray:function(e,t,n){var r;if(t){if(m)return m.call(t,e,n);for(r=t.length,n=n?0>n?Math.max(0,r+n):n:0;r>n;n++)if(n in t&&t[n]===e)return n}return-1},merge:function(e,n){var r=n.length,i=e.length,o=0;if("number"==typeof r)for(;r>o;o++)e[i++]=n[o];else while(n[o]!==t)e[i++]=n[o++];return e.length=i,e},grep:function(e,t,n){var r,i=[],o=0,a=e.length;for(n=!!n;a>o;o++)r=!!t(e[o],o),n!==r&&i.push(e[o]);return i},map:function(e,t,n){var r,i=0,o=e.length,a=M(e),s=[];if(a)for(;o>i;i++)r=t(e[i],i,n),null!=r&&(s[s.length]=r);else for(i in e)r=t(e[i],i,n),null!=r&&(s[s.length]=r);return d.apply([],s)},guid:1,proxy:function(e,n){var r,i,o;return"string"==typeof n&&(o=e[n],n=e,e=o),x.isFunction(e)?(r=g.call(arguments,2),i=function(){return e.apply(n||this,r.concat(g.call(arguments)))},i.guid=e.guid=e.guid||x.guid++,i):t},access:function(e,n,r,i,o,a,s){var l=0,u=e.length,c=null==r;if("object"===x.type(r)){o=!0;for(l in r)x.access(e,n,l,r[l],!0,a,s)}else if(i!==t&&(o=!0,x.isFunction(i)||(s=!0),c&&(s?(n.call(e,i),n=null):(c=n,n=function(e,t,n){return c.call(x(e),n)})),n))for(;u>l;l++)n(e[l],r,s?i:i.call(e[l],l,n(e[l],r)));return o?e:c?n.call(e):u?n(e[0],r):a},now:function(){return(new Date).getTime()},swap:function(e,t,n,r){var i,o,a={};for(o in t)a[o]=e.style[o],e.style[o]=t[o];i=n.apply(e,r||[]);for(o in t)e.style[o]=a[o];return i}}),x.ready.promise=function(t){if(!n)if(n=x.Deferred(),"complete"===a.readyState)setTimeout(x.ready);else if(a.addEventListener)a.addEventListener("DOMContentLoaded",q,!1),e.addEventListener("load",q,!1);else{a.attachEvent("onreadystatechange",q),e.attachEvent("onload",q);var r=!1;try{r=null==e.frameElement&&a.documentElement}catch(i){}r&&r.doScroll&&function o(){if(!x.isReady){try{r.doScroll("left")}catch(e){return setTimeout(o,50)}_(),x.ready()}}()}return n.promise(t)},x.each("Boolean Number String Function Array Date RegExp Object Error".split(" "),function(e,t){c["[object "+t+"]"]=t.toLowerCase()});function M(e){var t=e.length,n=x.type(e);return x.isWindow(e)?!1:1===e.nodeType&&t?!0:"array"===n||"function"!==n&&(0===t||"number"==typeof t&&t>0&&t-1 in e)}r=x(a),function(e,t){var n,r,i,o,a,s,l,u,c,p,f,d,h,g,m,y,v,b="sizzle"+-new Date,w=e.document,T=0,C=0,N=st(),k=st(),E=st(),S=!1,A=function(e,t){return e===t?(S=!0,0):0},j=typeof t,D=1<<31,L={}.hasOwnProperty,H=[],q=H.pop,_=H.push,M=H.push,O=H.slice,F=H.indexOf||function(e){var t=0,n=this.length;for(;n>t;t++)if(this[t]===e)return t;return-1},B="checked|selected|async|autofocus|autoplay|controls|defer|disabled|hidden|ismap|loop|multiple|open|readonly|required|scoped",P="[\\x20\\t\\r\\n\\f]",R="(?:\\\\.|[\\w-]|[^\\x00-\\xa0])+",W=R.replace("w","w#"),$="\\["+P+"*("+R+")"+P+"*(?:([*^$|!~]?=)"+P+"*(?:(['\"])((?:\\\\.|[^\\\\])*?)\\3|("+W+")|)|)"+P+"*\\]",I=":("+R+")(?:\\(((['\"])((?:\\\\.|[^\\\\])*?)\\3|((?:\\\\.|[^\\\\()[\\]]|"+$.replace(3,8)+")*)|.*)\\)|)",z=RegExp("^"+P+"+|((?:^|[^\\\\])(?:\\\\.)*)"+P+"+$","g"),X=RegExp("^"+P+"*,"+P+"*"),U=RegExp("^"+P+"*([>+~]|"+P+")"+P+"*"),V=RegExp(P+"*[+~]"),Y=RegExp("="+P+"*([^\\]'\"]*)"+P+"*\\]","g"),J=RegExp(I),G=RegExp("^"+W+"$"),Q={ID:RegExp("^#("+R+")"),CLASS:RegExp("^\\.("+R+")"),TAG:RegExp("^("+R.replace("w","w*")+")"),ATTR:RegExp("^"+$),PSEUDO:RegExp("^"+I),CHILD:RegExp("^:(only|first|last|nth|nth-last)-(child|of-type)(?:\\("+P+"*(even|odd|(([+-]|)(\\d*)n|)"+P+"*(?:([+-]|)"+P+"*(\\d+)|))"+P+"*\\)|)","i"),bool:RegExp("^(?:"+B+")$","i"),needsContext:RegExp("^"+P+"*[>+~]|:(even|odd|eq|gt|lt|nth|first|last)(?:\\("+P+"*((?:-\\d)?\\d*)"+P+"*\\)|)(?=[^-]|$)","i")},K=/^[^{]+\{\s*\[native \w/,Z=/^(?:#([\w-]+)|(\w+)|\.([\w-]+))$/,et=/^(?:input|select|textarea|button)$/i,tt=/^h\d$/i,nt=/'|\\/g,rt=RegExp("\\\\([\\da-f]{1,6}"+P+"?|("+P+")|.)","ig"),it=function(e,t,n){var r="0x"+t-65536;return r!==r||n?t:0>r?String.fromCharCode(r+65536):String.fromCharCode(55296|r>>10,56320|1023&r)};try{M.apply(H=O.call(w.childNodes),w.childNodes),H[w.childNodes.length].nodeType}catch(ot){M={apply:H.length?function(e,t){_.apply(e,O.call(t))}:function(e,t){var n=e.length,r=0;while(e[n++]=t[r++]);e.length=n-1}}}function at(e,t,n,i){var o,a,s,l,u,c,d,m,y,x;if((t?t.ownerDocument||t:w)!==f&&p(t),t=t||f,n=n||[],!e||"string"!=typeof e)return n;if(1!==(l=t.nodeType)&&9!==l)return[];if(h&&!i){if(o=Z.exec(e))if(s=o[1]){if(9===l){if(a=t.getElementById(s),!a||!a.parentNode)return n;if(a.id===s)return n.push(a),n}else if(t.ownerDocument&&(a=t.ownerDocument.getElementById(s))&&v(t,a)&&a.id===s)return n.push(a),n}else{if(o[2])return M.apply(n,t.getElementsByTagName(e)),n;if((s=o[3])&&r.getElementsByClassName&&t.getElementsByClassName)return M.apply(n,t.getElementsByClassName(s)),n}if(r.qsa&&(!g||!g.test(e))){if(m=d=b,y=t,x=9===l&&e,1===l&&"object"!==t.nodeName.toLowerCase()){c=mt(e),(d=t.getAttribute("id"))?m=d.replace(nt,"\\$&"):t.setAttribute("id",m),m="[id='"+m+"'] ",u=c.length;while(u--)c[u]=m+yt(c[u]);y=V.test(e)&&t.parentNode||t,x=c.join(",")}if(x)try{return M.apply(n,y.querySelectorAll(x)),n}catch(T){}finally{d||t.removeAttribute("id")}}}return kt(e.replace(z,"$1"),t,n,i)}function st(){var e=[];function t(n,r){return e.push(n+=" ")>o.cacheLength&&delete t[e.shift()],t[n]=r}return t}function lt(e){return e[b]=!0,e}function ut(e){var t=f.createElement("div");try{return!!e(t)}catch(n){return!1}finally{t.parentNode&&t.parentNode.removeChild(t),t=null}}function ct(e,t){var n=e.split("|"),r=e.length;while(r--)o.attrHandle[n[r]]=t}function pt(e,t){var n=t&&e,r=n&&1===e.nodeType&&1===t.nodeType&&(~t.sourceIndex||D)-(~e.sourceIndex||D);if(r)return r;if(n)while(n=n.nextSibling)if(n===t)return-1;return e?1:-1}function ft(e){return function(t){var n=t.nodeName.toLowerCase();return"input"===n&&t.type===e}}function dt(e){return function(t){var n=t.nodeName.toLowerCase();return("input"===n||"button"===n)&&t.type===e}}function ht(e){return lt(function(t){return t=+t,lt(function(n,r){var i,o=e([],n.length,t),a=o.length;while(a--)n[i=o[a]]&&(n[i]=!(r[i]=n[i]))})})}s=at.isXML=function(e){var t=e&&(e.ownerDocument||e).documentElement;return t?"HTML"!==t.nodeName:!1},r=at.support={},p=at.setDocument=function(e){var n=e?e.ownerDocument||e:w,i=n.defaultView;return n!==f&&9===n.nodeType&&n.documentElement?(f=n,d=n.documentElement,h=!s(n),i&&i.attachEvent&&i!==i.top&&i.attachEvent("onbeforeunload",function(){p()}),r.attributes=ut(function(e){return e.className="i",!e.getAttribute("className")}),r.getElementsByTagName=ut(function(e){return e.appendChild(n.createComment("")),!e.getElementsByTagName("*").length}),r.getElementsByClassName=ut(function(e){return e.innerHTML="<div class='a'></div><div class='a i'></div>",e.firstChild.className="i",2===e.getElementsByClassName("i").length}),r.getById=ut(function(e){return d.appendChild(e).id=b,!n.getElementsByName||!n.getElementsByName(b).length}),r.getById?(o.find.ID=function(e,t){if(typeof t.getElementById!==j&&h){var n=t.getElementById(e);return n&&n.parentNode?[n]:[]}},o.filter.ID=function(e){var t=e.replace(rt,it);return function(e){return e.getAttribute("id")===t}}):(delete o.find.ID,o.filter.ID=function(e){var t=e.replace(rt,it);return function(e){var n=typeof e.getAttributeNode!==j&&e.getAttributeNode("id");return n&&n.value===t}}),o.find.TAG=r.getElementsByTagName?function(e,n){return typeof n.getElementsByTagName!==j?n.getElementsByTagName(e):t}:function(e,t){var n,r=[],i=0,o=t.getElementsByTagName(e);if("*"===e){while(n=o[i++])1===n.nodeType&&r.push(n);return r}return o},o.find.CLASS=r.getElementsByClassName&&function(e,n){return typeof n.getElementsByClassName!==j&&h?n.getElementsByClassName(e):t},m=[],g=[],(r.qsa=K.test(n.querySelectorAll))&&(ut(function(e){e.innerHTML="<select><option selected=''></option></select>",e.querySelectorAll("[selected]").length||g.push("\\["+P+"*(?:value|"+B+")"),e.querySelectorAll(":checked").length||g.push(":checked")}),ut(function(e){var t=n.createElement("input");t.setAttribute("type","hidden"),e.appendChild(t).setAttribute("t",""),e.querySelectorAll("[t^='']").length&&g.push("[*^$]="+P+"*(?:''|\"\")"),e.querySelectorAll(":enabled").length||g.push(":enabled",":disabled"),e.querySelectorAll("*,:x"),g.push(",.*:")})),(r.matchesSelector=K.test(y=d.webkitMatchesSelector||d.mozMatchesSelector||d.oMatchesSelector||d.msMatchesSelector))&&ut(function(e){r.disconnectedMatch=y.call(e,"div"),y.call(e,"[s!='']:x"),m.push("!=",I)}),g=g.length&&RegExp(g.join("|")),m=m.length&&RegExp(m.join("|")),v=K.test(d.contains)||d.compareDocumentPosition?function(e,t){var n=9===e.nodeType?e.documentElement:e,r=t&&t.parentNode;return e===r||!(!r||1!==r.nodeType||!(n.contains?n.contains(r):e.compareDocumentPosition&&16&e.compareDocumentPosition(r)))}:function(e,t){if(t)while(t=t.parentNode)if(t===e)return!0;return!1},A=d.compareDocumentPosition?function(e,t){if(e===t)return S=!0,0;var i=t.compareDocumentPosition&&e.compareDocumentPosition&&e.compareDocumentPosition(t);return i?1&i||!r.sortDetached&&t.compareDocumentPosition(e)===i?e===n||v(w,e)?-1:t===n||v(w,t)?1:c?F.call(c,e)-F.call(c,t):0:4&i?-1:1:e.compareDocumentPosition?-1:1}:function(e,t){var r,i=0,o=e.parentNode,a=t.parentNode,s=[e],l=[t];if(e===t)return S=!0,0;if(!o||!a)return e===n?-1:t===n?1:o?-1:a?1:c?F.call(c,e)-F.call(c,t):0;if(o===a)return pt(e,t);r=e;while(r=r.parentNode)s.unshift(r);r=t;while(r=r.parentNode)l.unshift(r);while(s[i]===l[i])i++;return i?pt(s[i],l[i]):s[i]===w?-1:l[i]===w?1:0},n):f},at.matches=function(e,t){return at(e,null,null,t)},at.matchesSelector=function(e,t){if((e.ownerDocument||e)!==f&&p(e),t=t.replace(Y,"='$1']"),!(!r.matchesSelector||!h||m&&m.test(t)||g&&g.test(t)))try{var n=y.call(e,t);if(n||r.disconnectedMatch||e.document&&11!==e.document.nodeType)return n}catch(i){}return at(t,f,null,[e]).length>0},at.contains=function(e,t){return(e.ownerDocument||e)!==f&&p(e),v(e,t)},at.attr=function(e,n){(e.ownerDocument||e)!==f&&p(e);var i=o.attrHandle[n.toLowerCase()],a=i&&L.call(o.attrHandle,n.toLowerCase())?i(e,n,!h):t;return a===t?r.attributes||!h?e.getAttribute(n):(a=e.getAttributeNode(n))&&a.specified?a.value:null:a},at.error=function(e){throw Error("Syntax error, unrecognized expression: "+e)},at.uniqueSort=function(e){var t,n=[],i=0,o=0;if(S=!r.detectDuplicates,c=!r.sortStable&&e.slice(0),e.sort(A),S){while(t=e[o++])t===e[o]&&(i=n.push(o));while(i--)e.splice(n[i],1)}return e},a=at.getText=function(e){var t,n="",r=0,i=e.nodeType;if(i){if(1===i||9===i||11===i){if("string"==typeof e.textContent)return e.textContent;for(e=e.firstChild;e;e=e.nextSibling)n+=a(e)}else if(3===i||4===i)return e.nodeValue}else for(;t=e[r];r++)n+=a(t);return n},o=at.selectors={cacheLength:50,createPseudo:lt,match:Q,attrHandle:{},find:{},relative:{">":{dir:"parentNode",first:!0}," ":{dir:"parentNode"},"+":{dir:"previousSibling",first:!0},"~":{dir:"previousSibling"}},preFilter:{ATTR:function(e){return e[1]=e[1].replace(rt,it),e[3]=(e[4]||e[5]||"").replace(rt,it),"~="===e[2]&&(e[3]=" "+e[3]+" "),e.slice(0,4)},CHILD:function(e){return e[1]=e[1].toLowerCase(),"nth"===e[1].slice(0,3)?(e[3]||at.error(e[0]),e[4]=+(e[4]?e[5]+(e[6]||1):2*("even"===e[3]||"odd"===e[3])),e[5]=+(e[7]+e[8]||"odd"===e[3])):e[3]&&at.error(e[0]),e},PSEUDO:function(e){var n,r=!e[5]&&e[2];return Q.CHILD.test(e[0])?null:(e[3]&&e[4]!==t?e[2]=e[4]:r&&J.test(r)&&(n=mt(r,!0))&&(n=r.indexOf(")",r.length-n)-r.length)&&(e[0]=e[0].slice(0,n),e[2]=r.slice(0,n)),e.slice(0,3))}},filter:{TAG:function(e){var t=e.replace(rt,it).toLowerCase();return"*"===e?function(){return!0}:function(e){return e.nodeName&&e.nodeName.toLowerCase()===t}},CLASS:function(e){var t=N[e+" "];return t||(t=RegExp("(^|"+P+")"+e+"("+P+"|$)"))&&N(e,function(e){return t.test("string"==typeof e.className&&e.className||typeof e.getAttribute!==j&&e.getAttribute("class")||"")})},ATTR:function(e,t,n){return function(r){var i=at.attr(r,e);return null==i?"!="===t:t?(i+="","="===t?i===n:"!="===t?i!==n:"^="===t?n&&0===i.indexOf(n):"*="===t?n&&i.indexOf(n)>-1:"$="===t?n&&i.slice(-n.length)===n:"~="===t?(" "+i+" ").indexOf(n)>-1:"|="===t?i===n||i.slice(0,n.length+1)===n+"-":!1):!0}},CHILD:function(e,t,n,r,i){var o="nth"!==e.slice(0,3),a="last"!==e.slice(-4),s="of-type"===t;return 1===r&&0===i?function(e){return!!e.parentNode}:function(t,n,l){var u,c,p,f,d,h,g=o!==a?"nextSibling":"previousSibling",m=t.parentNode,y=s&&t.nodeName.toLowerCase(),v=!l&&!s;if(m){if(o){while(g){p=t;while(p=p[g])if(s?p.nodeName.toLowerCase()===y:1===p.nodeType)return!1;h=g="only"===e&&!h&&"nextSibling"}return!0}if(h=[a?m.firstChild:m.lastChild],a&&v){c=m[b]||(m[b]={}),u=c[e]||[],d=u[0]===T&&u[1],f=u[0]===T&&u[2],p=d&&m.childNodes[d];while(p=++d&&p&&p[g]||(f=d=0)||h.pop())if(1===p.nodeType&&++f&&p===t){c[e]=[T,d,f];break}}else if(v&&(u=(t[b]||(t[b]={}))[e])&&u[0]===T)f=u[1];else while(p=++d&&p&&p[g]||(f=d=0)||h.pop())if((s?p.nodeName.toLowerCase()===y:1===p.nodeType)&&++f&&(v&&((p[b]||(p[b]={}))[e]=[T,f]),p===t))break;return f-=i,f===r||0===f%r&&f/r>=0}}},PSEUDO:function(e,t){var n,r=o.pseudos[e]||o.setFilters[e.toLowerCase()]||at.error("unsupported pseudo: "+e);return r[b]?r(t):r.length>1?(n=[e,e,"",t],o.setFilters.hasOwnProperty(e.toLowerCase())?lt(function(e,n){var i,o=r(e,t),a=o.length;while(a--)i=F.call(e,o[a]),e[i]=!(n[i]=o[a])}):function(e){return r(e,0,n)}):r}},pseudos:{not:lt(function(e){var t=[],n=[],r=l(e.replace(z,"$1"));return r[b]?lt(function(e,t,n,i){var o,a=r(e,null,i,[]),s=e.length;while(s--)(o=a[s])&&(e[s]=!(t[s]=o))}):function(e,i,o){return t[0]=e,r(t,null,o,n),!n.pop()}}),has:lt(function(e){return function(t){return at(e,t).length>0}}),contains:lt(function(e){return function(t){return(t.textContent||t.innerText||a(t)).indexOf(e)>-1}}),lang:lt(function(e){return G.test(e||"")||at.error("unsupported lang: "+e),e=e.replace(rt,it).toLowerCase(),function(t){var n;do if(n=h?t.lang:t.getAttribute("xml:lang")||t.getAttribute("lang"))return n=n.toLowerCase(),n===e||0===n.indexOf(e+"-");while((t=t.parentNode)&&1===t.nodeType);return!1}}),target:function(t){var n=e.location&&e.location.hash;return n&&n.slice(1)===t.id},root:function(e){return e===d},focus:function(e){return e===f.activeElement&&(!f.hasFocus||f.hasFocus())&&!!(e.type||e.href||~e.tabIndex)},enabled:function(e){return e.disabled===!1},disabled:function(e){return e.disabled===!0},checked:function(e){var t=e.nodeName.toLowerCase();return"input"===t&&!!e.checked||"option"===t&&!!e.selected},selected:function(e){return e.parentNode&&e.parentNode.selectedIndex,e.selected===!0},empty:function(e){for(e=e.firstChild;e;e=e.nextSibling)if(e.nodeName>"@"||3===e.nodeType||4===e.nodeType)return!1;return!0},parent:function(e){return!o.pseudos.empty(e)},header:function(e){return tt.test(e.nodeName)},input:function(e){return et.test(e.nodeName)},button:function(e){var t=e.nodeName.toLowerCase();return"input"===t&&"button"===e.type||"button"===t},text:function(e){var t;return"input"===e.nodeName.toLowerCase()&&"text"===e.type&&(null==(t=e.getAttribute("type"))||t.toLowerCase()===e.type)},first:ht(function(){return[0]}),last:ht(function(e,t){return[t-1]}),eq:ht(function(e,t,n){return[0>n?n+t:n]}),even:ht(function(e,t){var n=0;for(;t>n;n+=2)e.push(n);return e}),odd:ht(function(e,t){var n=1;for(;t>n;n+=2)e.push(n);return e}),lt:ht(function(e,t,n){var r=0>n?n+t:n;for(;--r>=0;)e.push(r);return e}),gt:ht(function(e,t,n){var r=0>n?n+t:n;for(;t>++r;)e.push(r);return e})}},o.pseudos.nth=o.pseudos.eq;for(n in{radio:!0,checkbox:!0,file:!0,password:!0,image:!0})o.pseudos[n]=ft(n);for(n in{submit:!0,reset:!0})o.pseudos[n]=dt(n);function gt(){}gt.prototype=o.filters=o.pseudos,o.setFilters=new gt;function mt(e,t){var n,r,i,a,s,l,u,c=k[e+" "];if(c)return t?0:c.slice(0);s=e,l=[],u=o.preFilter;while(s){(!n||(r=X.exec(s)))&&(r&&(s=s.slice(r[0].length)||s),l.push(i=[])),n=!1,(r=U.exec(s))&&(n=r.shift(),i.push({value:n,type:r[0].replace(z," ")}),s=s.slice(n.length));for(a in o.filter)!(r=Q[a].exec(s))||u[a]&&!(r=u[a](r))||(n=r.shift(),i.push({value:n,type:a,matches:r}),s=s.slice(n.length));if(!n)break}return t?s.length:s?at.error(e):k(e,l).slice(0)}function yt(e){var t=0,n=e.length,r="";for(;n>t;t++)r+=e[t].value;return r}function vt(e,t,n){var r=t.dir,o=n&&"parentNode"===r,a=C++;return t.first?function(t,n,i){while(t=t[r])if(1===t.nodeType||o)return e(t,n,i)}:function(t,n,s){var l,u,c,p=T+" "+a;if(s){while(t=t[r])if((1===t.nodeType||o)&&e(t,n,s))return!0}else while(t=t[r])if(1===t.nodeType||o)if(c=t[b]||(t[b]={}),(u=c[r])&&u[0]===p){if((l=u[1])===!0||l===i)return l===!0}else if(u=c[r]=[p],u[1]=e(t,n,s)||i,u[1]===!0)return!0}}function bt(e){return e.length>1?function(t,n,r){var i=e.length;while(i--)if(!e[i](t,n,r))return!1;return!0}:e[0]}function xt(e,t,n,r,i){var o,a=[],s=0,l=e.length,u=null!=t;for(;l>s;s++)(o=e[s])&&(!n||n(o,r,i))&&(a.push(o),u&&t.push(s));return a}function wt(e,t,n,r,i,o){return r&&!r[b]&&(r=wt(r)),i&&!i[b]&&(i=wt(i,o)),lt(function(o,a,s,l){var u,c,p,f=[],d=[],h=a.length,g=o||Nt(t||"*",s.nodeType?[s]:s,[]),m=!e||!o&&t?g:xt(g,f,e,s,l),y=n?i||(o?e:h||r)?[]:a:m;if(n&&n(m,y,s,l),r){u=xt(y,d),r(u,[],s,l),c=u.length;while(c--)(p=u[c])&&(y[d[c]]=!(m[d[c]]=p))}if(o){if(i||e){if(i){u=[],c=y.length;while(c--)(p=y[c])&&u.push(m[c]=p);i(null,y=[],u,l)}c=y.length;while(c--)(p=y[c])&&(u=i?F.call(o,p):f[c])>-1&&(o[u]=!(a[u]=p))}}else y=xt(y===a?y.splice(h,y.length):y),i?i(null,a,y,l):M.apply(a,y)})}function Tt(e){var t,n,r,i=e.length,a=o.relative[e[0].type],s=a||o.relative[" "],l=a?1:0,c=vt(function(e){return e===t},s,!0),p=vt(function(e){return F.call(t,e)>-1},s,!0),f=[function(e,n,r){return!a&&(r||n!==u)||((t=n).nodeType?c(e,n,r):p(e,n,r))}];for(;i>l;l++)if(n=o.relative[e[l].type])f=[vt(bt(f),n)];else{if(n=o.filter[e[l].type].apply(null,e[l].matches),n[b]){for(r=++l;i>r;r++)if(o.relative[e[r].type])break;return wt(l>1&&bt(f),l>1&&yt(e.slice(0,l-1).concat({value:" "===e[l-2].type?"*":""})).replace(z,"$1"),n,r>l&&Tt(e.slice(l,r)),i>r&&Tt(e=e.slice(r)),i>r&&yt(e))}f.push(n)}return bt(f)}function Ct(e,t){var n=0,r=t.length>0,a=e.length>0,s=function(s,l,c,p,d){var h,g,m,y=[],v=0,b="0",x=s&&[],w=null!=d,C=u,N=s||a&&o.find.TAG("*",d&&l.parentNode||l),k=T+=null==C?1:Math.random()||.1;for(w&&(u=l!==f&&l,i=n);null!=(h=N[b]);b++){if(a&&h){g=0;while(m=e[g++])if(m(h,l,c)){p.push(h);break}w&&(T=k,i=++n)}r&&((h=!m&&h)&&v--,s&&x.push(h))}if(v+=b,r&&b!==v){g=0;while(m=t[g++])m(x,y,l,c);if(s){if(v>0)while(b--)x[b]||y[b]||(y[b]=q.call(p));y=xt(y)}M.apply(p,y),w&&!s&&y.length>0&&v+t.length>1&&at.uniqueSort(p)}return w&&(T=k,u=C),x};return r?lt(s):s}l=at.compile=function(e,t){var n,r=[],i=[],o=E[e+" "];if(!o){t||(t=mt(e)),n=t.length;while(n--)o=Tt(t[n]),o[b]?r.push(o):i.push(o);o=E(e,Ct(i,r))}return o};function Nt(e,t,n){var r=0,i=t.length;for(;i>r;r++)at(e,t[r],n);return n}function kt(e,t,n,i){var a,s,u,c,p,f=mt(e);if(!i&&1===f.length){if(s=f[0]=f[0].slice(0),s.length>2&&"ID"===(u=s[0]).type&&r.getById&&9===t.nodeType&&h&&o.relative[s[1].type]){if(t=(o.find.ID(u.matches[0].replace(rt,it),t)||[])[0],!t)return n;e=e.slice(s.shift().value.length)}a=Q.needsContext.test(e)?0:s.length;while(a--){if(u=s[a],o.relative[c=u.type])break;if((p=o.find[c])&&(i=p(u.matches[0].replace(rt,it),V.test(s[0].type)&&t.parentNode||t))){if(s.splice(a,1),e=i.length&&yt(s),!e)return M.apply(n,i),n;break}}}return l(e,f)(i,t,!h,n,V.test(e)),n}r.sortStable=b.split("").sort(A).join("")===b,r.detectDuplicates=S,p(),r.sortDetached=ut(function(e){return 1&e.compareDocumentPosition(f.createElement("div"))}),ut(function(e){return e.innerHTML="<a href='#'></a>","#"===e.firstChild.getAttribute("href")})||ct("type|href|height|width",function(e,n,r){return r?t:e.getAttribute(n,"type"===n.toLowerCase()?1:2)}),r.attributes&&ut(function(e){return e.innerHTML="<input/>",e.firstChild.setAttribute("value",""),""===e.firstChild.getAttribute("value")})||ct("value",function(e,n,r){return r||"input"!==e.nodeName.toLowerCase()?t:e.defaultValue}),ut(function(e){return null==e.getAttribute("disabled")})||ct(B,function(e,n,r){var i;return r?t:(i=e.getAttributeNode(n))&&i.specified?i.value:e[n]===!0?n.toLowerCase():null}),x.find=at,x.expr=at.selectors,x.expr[":"]=x.expr.pseudos,x.unique=at.uniqueSort,x.text=at.getText,x.isXMLDoc=at.isXML,x.contains=at.contains}(e);var O={};function F(e){var t=O[e]={};return x.each(e.match(T)||[],function(e,n){t[n]=!0}),t}x.Callbacks=function(e){e="string"==typeof e?O[e]||F(e):x.extend({},e);var n,r,i,o,a,s,l=[],u=!e.once&&[],c=function(t){for(r=e.memory&&t,i=!0,a=s||0,s=0,o=l.length,n=!0;l&&o>a;a++)if(l[a].apply(t[0],t[1])===!1&&e.stopOnFalse){r=!1;break}n=!1,l&&(u?u.length&&c(u.shift()):r?l=[]:p.disable())},p={add:function(){if(l){var t=l.length;(function i(t){x.each(t,function(t,n){var r=x.type(n);"function"===r?e.unique&&p.has(n)||l.push(n):n&&n.length&&"string"!==r&&i(n)})})(arguments),n?o=l.length:r&&(s=t,c(r))}return this},remove:function(){return l&&x.each(arguments,function(e,t){var r;while((r=x.inArray(t,l,r))>-1)l.splice(r,1),n&&(o>=r&&o--,a>=r&&a--)}),this},has:function(e){return e?x.inArray(e,l)>-1:!(!l||!l.length)},empty:function(){return l=[],o=0,this},disable:function(){return l=u=r=t,this},disabled:function(){return!l},lock:function(){return u=t,r||p.disable(),this},locked:function(){return!u},fireWith:function(e,t){return!l||i&&!u||(t=t||[],t=[e,t.slice?t.slice():t],n?u.push(t):c(t)),this},fire:function(){return p.fireWith(this,arguments),this},fired:function(){return!!i}};return p},x.extend({Deferred:function(e){var t=[["resolve","done",x.Callbacks("once memory"),"resolved"],["reject","fail",x.Callbacks("once memory"),"rejected"],["notify","progress",x.Callbacks("memory")]],n="pending",r={state:function(){return n},always:function(){return i.done(arguments).fail(arguments),this},then:function(){var e=arguments;return x.Deferred(function(n){x.each(t,function(t,o){var a=o[0],s=x.isFunction(e[t])&&e[t];i[o[1]](function(){var e=s&&s.apply(this,arguments);e&&x.isFunction(e.promise)?e.promise().done(n.resolve).fail(n.reject).progress(n.notify):n[a+"With"](this===r?n.promise():this,s?[e]:arguments)})}),e=null}).promise()},promise:function(e){return null!=e?x.extend(e,r):r}},i={};return r.pipe=r.then,x.each(t,function(e,o){var a=o[2],s=o[3];r[o[1]]=a.add,s&&a.add(function(){n=s},t[1^e][2].disable,t[2][2].lock),i[o[0]]=function(){return i[o[0]+"With"](this===i?r:this,arguments),this},i[o[0]+"With"]=a.fireWith}),r.promise(i),e&&e.call(i,i),i},when:function(e){var t=0,n=g.call(arguments),r=n.length,i=1!==r||e&&x.isFunction(e.promise)?r:0,o=1===i?e:x.Deferred(),a=function(e,t,n){return function(r){t[e]=this,n[e]=arguments.length>1?g.call(arguments):r,n===s?o.notifyWith(t,n):--i||o.resolveWith(t,n)}},s,l,u;if(r>1)for(s=Array(r),l=Array(r),u=Array(r);r>t;t++)n[t]&&x.isFunction(n[t].promise)?n[t].promise().done(a(t,u,n)).fail(o.reject).progress(a(t,l,s)):--i;return i||o.resolveWith(u,n),o.promise()}}),x.support=function(t){var n,r,o,s,l,u,c,p,f,d=a.createElement("div");if(d.setAttribute("className","t"),d.innerHTML=" <link/><table></table><a href='/a'>a</a><input type='checkbox'/>",n=d.getElementsByTagName("*")||[],r=d.getElementsByTagName("a")[0],!r||!r.style||!n.length)return t;s=a.createElement("select"),u=s.appendChild(a.createElement("option")),o=d.getElementsByTagName("input")[0],r.style.cssText="top:1px;float:left;opacity:.5",t.getSetAttribute="t"!==d.className,t.leadingWhitespace=3===d.firstChild.nodeType,t.tbody=!d.getElementsByTagName("tbody").length,t.htmlSerialize=!!d.getElementsByTagName("link").length,t.style=/top/.test(r.getAttribute("style")),t.hrefNormalized="/a"===r.getAttribute("href"),t.opacity=/^0.5/.test(r.style.opacity),t.cssFloat=!!r.style.cssFloat,t.checkOn=!!o.value,t.optSelected=u.selected,t.enctype=!!a.createElement("form").enctype,t.html5Clone="<:nav></:nav>"!==a.createElement("nav").cloneNode(!0).outerHTML,t.inlineBlockNeedsLayout=!1,t.shrinkWrapBlocks=!1,t.pixelPosition=!1,t.deleteExpando=!0,t.noCloneEvent=!0,t.reliableMarginRight=!0,t.boxSizingReliable=!0,o.checked=!0,t.noCloneChecked=o.cloneNode(!0).checked,s.disabled=!0,t.optDisabled=!u.disabled;try{delete d.test}catch(h){t.deleteExpando=!1}o=a.createElement("input"),o.setAttribute("value",""),t.input=""===o.getAttribute("value"),o.value="t",o.setAttribute("type","radio"),t.radioValue="t"===o.value,o.setAttribute("checked","t"),o.setAttribute("name","t"),l=a.createDocumentFragment(),l.appendChild(o),t.appendChecked=o.checked,t.checkClone=l.cloneNode(!0).cloneNode(!0).lastChild.checked,d.attachEvent&&(d.attachEvent("onclick",function(){t.noCloneEvent=!1}),d.cloneNode(!0).click());for(f in{submit:!0,change:!0,focusin:!0})d.setAttribute(c="on"+f,"t"),t[f+"Bubbles"]=c in e||d.attributes[c].expando===!1;d.style.backgroundClip="content-box",d.cloneNode(!0).style.backgroundClip="",t.clearCloneStyle="content-box"===d.style.backgroundClip;for(f in x(t))break;return t.ownLast="0"!==f,x(function(){var n,r,o,s="padding:0;margin:0;border:0;display:block;box-sizing:content-box;-moz-box-sizing:content-box;-webkit-box-sizing:content-box;",l=a.getElementsByTagName("body")[0];l&&(n=a.createElement("div"),n.style.cssText="border:0;width:0;height:0;position:absolute;top:0;left:-9999px;margin-top:1px",l.appendChild(n).appendChild(d),d.innerHTML="<table><tr><td></td><td>t</td></tr></table>",o=d.getElementsByTagName("td"),o[0].style.cssText="padding:0;margin:0;border:0;display:none",p=0===o[0].offsetHeight,o[0].style.display="",o[1].style.display="none",t.reliableHiddenOffsets=p&&0===o[0].offsetHeight,d.innerHTML="",d.style.cssText="box-sizing:border-box;-moz-box-sizing:border-box;-webkit-box-sizing:border-box;padding:1px;border:1px;display:block;width:4px;margin-top:1%;position:absolute;top:1%;",x.swap(l,null!=l.style.zoom?{zoom:1}:{},function(){t.boxSizing=4===d.offsetWidth}),e.getComputedStyle&&(t.pixelPosition="1%"!==(e.getComputedStyle(d,null)||{}).top,t.boxSizingReliable="4px"===(e.getComputedStyle(d,null)||{width:"4px"}).width,r=d.appendChild(a.createElement("div")),r.style.cssText=d.style.cssText=s,r.style.marginRight=r.style.width="0",d.style.width="1px",t.reliableMarginRight=!parseFloat((e.getComputedStyle(r,null)||{}).marginRight)),typeof d.style.zoom!==i&&(d.innerHTML="",d.style.cssText=s+"width:1px;padding:1px;display:inline;zoom:1",t.inlineBlockNeedsLayout=3===d.offsetWidth,d.style.display="block",d.innerHTML="<div></div>",d.firstChild.style.width="5px",t.shrinkWrapBlocks=3!==d.offsetWidth,t.inlineBlockNeedsLayout&&(l.style.zoom=1)),l.removeChild(n),n=d=o=r=null)}),n=s=l=u=r=o=null,t }({});var B=/(?:\{[\s\S]*\}|\[[\s\S]*\])$/,P=/([A-Z])/g;function R(e,n,r,i){if(x.acceptData(e)){var o,a,s=x.expando,l=e.nodeType,u=l?x.cache:e,c=l?e[s]:e[s]&&s;if(c&&u[c]&&(i||u[c].data)||r!==t||"string"!=typeof n)return c||(c=l?e[s]=p.pop()||x.guid++:s),u[c]||(u[c]=l?{}:{toJSON:x.noop}),("object"==typeof n||"function"==typeof n)&&(i?u[c]=x.extend(u[c],n):u[c].data=x.extend(u[c].data,n)),a=u[c],i||(a.data||(a.data={}),a=a.data),r!==t&&(a[x.camelCase(n)]=r),"string"==typeof n?(o=a[n],null==o&&(o=a[x.camelCase(n)])):o=a,o}}function W(e,t,n){if(x.acceptData(e)){var r,i,o=e.nodeType,a=o?x.cache:e,s=o?e[x.expando]:x.expando;if(a[s]){if(t&&(r=n?a[s]:a[s].data)){x.isArray(t)?t=t.concat(x.map(t,x.camelCase)):t in r?t=[t]:(t=x.camelCase(t),t=t in r?[t]:t.split(" ")),i=t.length;while(i--)delete r[t[i]];if(n?!I(r):!x.isEmptyObject(r))return}(n||(delete a[s].data,I(a[s])))&&(o?x.cleanData([e],!0):x.support.deleteExpando||a!=a.window?delete a[s]:a[s]=null)}}}x.extend({cache:{},noData:{applet:!0,embed:!0,object:"clsid:D27CDB6E-AE6D-11cf-96B8-444553540000"},hasData:function(e){return e=e.nodeType?x.cache[e[x.expando]]:e[x.expando],!!e&&!I(e)},data:function(e,t,n){return R(e,t,n)},removeData:function(e,t){return W(e,t)},_data:function(e,t,n){return R(e,t,n,!0)},_removeData:function(e,t){return W(e,t,!0)},acceptData:function(e){if(e.nodeType&&1!==e.nodeType&&9!==e.nodeType)return!1;var t=e.nodeName&&x.noData[e.nodeName.toLowerCase()];return!t||t!==!0&&e.getAttribute("classid")===t}}),x.fn.extend({data:function(e,n){var r,i,o=null,a=0,s=this[0];if(e===t){if(this.length&&(o=x.data(s),1===s.nodeType&&!x._data(s,"parsedAttrs"))){for(r=s.attributes;r.length>a;a++)i=r[a].name,0===i.indexOf("data-")&&(i=x.camelCase(i.slice(5)),$(s,i,o[i]));x._data(s,"parsedAttrs",!0)}return o}return"object"==typeof e?this.each(function(){x.data(this,e)}):arguments.length>1?this.each(function(){x.data(this,e,n)}):s?$(s,e,x.data(s,e)):null},removeData:function(e){return this.each(function(){x.removeData(this,e)})}});function $(e,n,r){if(r===t&&1===e.nodeType){var i="data-"+n.replace(P,"-$1").toLowerCase();if(r=e.getAttribute(i),"string"==typeof r){try{r="true"===r?!0:"false"===r?!1:"null"===r?null:+r+""===r?+r:B.test(r)?x.parseJSON(r):r}catch(o){}x.data(e,n,r)}else r=t}return r}function I(e){var t;for(t in e)if(("data"!==t||!x.isEmptyObject(e[t]))&&"toJSON"!==t)return!1;return!0}x.extend({queue:function(e,n,r){var i;return e?(n=(n||"fx")+"queue",i=x._data(e,n),r&&(!i||x.isArray(r)?i=x._data(e,n,x.makeArray(r)):i.push(r)),i||[]):t},dequeue:function(e,t){t=t||"fx";var n=x.queue(e,t),r=n.length,i=n.shift(),o=x._queueHooks(e,t),a=function(){x.dequeue(e,t)};"inprogress"===i&&(i=n.shift(),r--),i&&("fx"===t&&n.unshift("inprogress"),delete o.stop,i.call(e,a,o)),!r&&o&&o.empty.fire()},_queueHooks:function(e,t){var n=t+"queueHooks";return x._data(e,n)||x._data(e,n,{empty:x.Callbacks("once memory").add(function(){x._removeData(e,t+"queue"),x._removeData(e,n)})})}}),x.fn.extend({queue:function(e,n){var r=2;return"string"!=typeof e&&(n=e,e="fx",r--),r>arguments.length?x.queue(this[0],e):n===t?this:this.each(function(){var t=x.queue(this,e,n);x._queueHooks(this,e),"fx"===e&&"inprogress"!==t[0]&&x.dequeue(this,e)})},dequeue:function(e){return this.each(function(){x.dequeue(this,e)})},delay:function(e,t){return e=x.fx?x.fx.speeds[e]||e:e,t=t||"fx",this.queue(t,function(t,n){var r=setTimeout(t,e);n.stop=function(){clearTimeout(r)}})},clearQueue:function(e){return this.queue(e||"fx",[])},promise:function(e,n){var r,i=1,o=x.Deferred(),a=this,s=this.length,l=function(){--i||o.resolveWith(a,[a])};"string"!=typeof e&&(n=e,e=t),e=e||"fx";while(s--)r=x._data(a[s],e+"queueHooks"),r&&r.empty&&(i++,r.empty.add(l));return l(),o.promise(n)}});var z,X,U=/[\t\r\n\f]/g,V=/\r/g,Y=/^(?:input|select|textarea|button|object)$/i,J=/^(?:a|area)$/i,G=/^(?:checked|selected)$/i,Q=x.support.getSetAttribute,K=x.support.input;x.fn.extend({attr:function(e,t){return x.access(this,x.attr,e,t,arguments.length>1)},removeAttr:function(e){return this.each(function(){x.removeAttr(this,e)})},prop:function(e,t){return x.access(this,x.prop,e,t,arguments.length>1)},removeProp:function(e){return e=x.propFix[e]||e,this.each(function(){try{this[e]=t,delete this[e]}catch(n){}})},addClass:function(e){var t,n,r,i,o,a=0,s=this.length,l="string"==typeof e&&e;if(x.isFunction(e))return this.each(function(t){x(this).addClass(e.call(this,t,this.className))});if(l)for(t=(e||"").match(T)||[];s>a;a++)if(n=this[a],r=1===n.nodeType&&(n.className?(" "+n.className+" ").replace(U," "):" ")){o=0;while(i=t[o++])0>r.indexOf(" "+i+" ")&&(r+=i+" ");n.className=x.trim(r)}return this},removeClass:function(e){var t,n,r,i,o,a=0,s=this.length,l=0===arguments.length||"string"==typeof e&&e;if(x.isFunction(e))return this.each(function(t){x(this).removeClass(e.call(this,t,this.className))});if(l)for(t=(e||"").match(T)||[];s>a;a++)if(n=this[a],r=1===n.nodeType&&(n.className?(" "+n.className+" ").replace(U," "):"")){o=0;while(i=t[o++])while(r.indexOf(" "+i+" ")>=0)r=r.replace(" "+i+" "," ");n.className=e?x.trim(r):""}return this},toggleClass:function(e,t){var n=typeof e;return"boolean"==typeof t&&"string"===n?t?this.addClass(e):this.removeClass(e):x.isFunction(e)?this.each(function(n){x(this).toggleClass(e.call(this,n,this.className,t),t)}):this.each(function(){if("string"===n){var t,r=0,o=x(this),a=e.match(T)||[];while(t=a[r++])o.hasClass(t)?o.removeClass(t):o.addClass(t)}else(n===i||"boolean"===n)&&(this.className&&x._data(this,"__className__",this.className),this.className=this.className||e===!1?"":x._data(this,"__className__")||"")})},hasClass:function(e){var t=" "+e+" ",n=0,r=this.length;for(;r>n;n++)if(1===this[n].nodeType&&(" "+this[n].className+" ").replace(U," ").indexOf(t)>=0)return!0;return!1},val:function(e){var n,r,i,o=this[0];{if(arguments.length)return i=x.isFunction(e),this.each(function(n){var o;1===this.nodeType&&(o=i?e.call(this,n,x(this).val()):e,null==o?o="":"number"==typeof o?o+="":x.isArray(o)&&(o=x.map(o,function(e){return null==e?"":e+""})),r=x.valHooks[this.type]||x.valHooks[this.nodeName.toLowerCase()],r&&"set"in r&&r.set(this,o,"value")!==t||(this.value=o))});if(o)return r=x.valHooks[o.type]||x.valHooks[o.nodeName.toLowerCase()],r&&"get"in r&&(n=r.get(o,"value"))!==t?n:(n=o.value,"string"==typeof n?n.replace(V,""):null==n?"":n)}}}),x.extend({valHooks:{option:{get:function(e){var t=x.find.attr(e,"value");return null!=t?t:e.text}},select:{get:function(e){var t,n,r=e.options,i=e.selectedIndex,o="select-one"===e.type||0>i,a=o?null:[],s=o?i+1:r.length,l=0>i?s:o?i:0;for(;s>l;l++)if(n=r[l],!(!n.selected&&l!==i||(x.support.optDisabled?n.disabled:null!==n.getAttribute("disabled"))||n.parentNode.disabled&&x.nodeName(n.parentNode,"optgroup"))){if(t=x(n).val(),o)return t;a.push(t)}return a},set:function(e,t){var n,r,i=e.options,o=x.makeArray(t),a=i.length;while(a--)r=i[a],(r.selected=x.inArray(x(r).val(),o)>=0)&&(n=!0);return n||(e.selectedIndex=-1),o}}},attr:function(e,n,r){var o,a,s=e.nodeType;if(e&&3!==s&&8!==s&&2!==s)return typeof e.getAttribute===i?x.prop(e,n,r):(1===s&&x.isXMLDoc(e)||(n=n.toLowerCase(),o=x.attrHooks[n]||(x.expr.match.bool.test(n)?X:z)),r===t?o&&"get"in o&&null!==(a=o.get(e,n))?a:(a=x.find.attr(e,n),null==a?t:a):null!==r?o&&"set"in o&&(a=o.set(e,r,n))!==t?a:(e.setAttribute(n,r+""),r):(x.removeAttr(e,n),t))},removeAttr:function(e,t){var n,r,i=0,o=t&&t.match(T);if(o&&1===e.nodeType)while(n=o[i++])r=x.propFix[n]||n,x.expr.match.bool.test(n)?K&&Q||!G.test(n)?e[r]=!1:e[x.camelCase("default-"+n)]=e[r]=!1:x.attr(e,n,""),e.removeAttribute(Q?n:r)},attrHooks:{type:{set:function(e,t){if(!x.support.radioValue&&"radio"===t&&x.nodeName(e,"input")){var n=e.value;return e.setAttribute("type",t),n&&(e.value=n),t}}}},propFix:{"for":"htmlFor","class":"className"},prop:function(e,n,r){var i,o,a,s=e.nodeType;if(e&&3!==s&&8!==s&&2!==s)return a=1!==s||!x.isXMLDoc(e),a&&(n=x.propFix[n]||n,o=x.propHooks[n]),r!==t?o&&"set"in o&&(i=o.set(e,r,n))!==t?i:e[n]=r:o&&"get"in o&&null!==(i=o.get(e,n))?i:e[n]},propHooks:{tabIndex:{get:function(e){var t=x.find.attr(e,"tabindex");return t?parseInt(t,10):Y.test(e.nodeName)||J.test(e.nodeName)&&e.href?0:-1}}}}),X={set:function(e,t,n){return t===!1?x.removeAttr(e,n):K&&Q||!G.test(n)?e.setAttribute(!Q&&x.propFix[n]||n,n):e[x.camelCase("default-"+n)]=e[n]=!0,n}},x.each(x.expr.match.bool.source.match(/\w+/g),function(e,n){var r=x.expr.attrHandle[n]||x.find.attr;x.expr.attrHandle[n]=K&&Q||!G.test(n)?function(e,n,i){var o=x.expr.attrHandle[n],a=i?t:(x.expr.attrHandle[n]=t)!=r(e,n,i)?n.toLowerCase():null;return x.expr.attrHandle[n]=o,a}:function(e,n,r){return r?t:e[x.camelCase("default-"+n)]?n.toLowerCase():null}}),K&&Q||(x.attrHooks.value={set:function(e,n,r){return x.nodeName(e,"input")?(e.defaultValue=n,t):z&&z.set(e,n,r)}}),Q||(z={set:function(e,n,r){var i=e.getAttributeNode(r);return i||e.setAttributeNode(i=e.ownerDocument.createAttribute(r)),i.value=n+="","value"===r||n===e.getAttribute(r)?n:t}},x.expr.attrHandle.id=x.expr.attrHandle.name=x.expr.attrHandle.coords=function(e,n,r){var i;return r?t:(i=e.getAttributeNode(n))&&""!==i.value?i.value:null},x.valHooks.button={get:function(e,n){var r=e.getAttributeNode(n);return r&&r.specified?r.value:t},set:z.set},x.attrHooks.contenteditable={set:function(e,t,n){z.set(e,""===t?!1:t,n)}},x.each(["width","height"],function(e,n){x.attrHooks[n]={set:function(e,r){return""===r?(e.setAttribute(n,"auto"),r):t}}})),x.support.hrefNormalized||x.each(["href","src"],function(e,t){x.propHooks[t]={get:function(e){return e.getAttribute(t,4)}}}),x.support.style||(x.attrHooks.style={get:function(e){return e.style.cssText||t},set:function(e,t){return e.style.cssText=t+""}}),x.support.optSelected||(x.propHooks.selected={get:function(e){var t=e.parentNode;return t&&(t.selectedIndex,t.parentNode&&t.parentNode.selectedIndex),null}}),x.each(["tabIndex","readOnly","maxLength","cellSpacing","cellPadding","rowSpan","colSpan","useMap","frameBorder","contentEditable"],function(){x.propFix[this.toLowerCase()]=this}),x.support.enctype||(x.propFix.enctype="encoding"),x.each(["radio","checkbox"],function(){x.valHooks[this]={set:function(e,n){return x.isArray(n)?e.checked=x.inArray(x(e).val(),n)>=0:t}},x.support.checkOn||(x.valHooks[this].get=function(e){return null===e.getAttribute("value")?"on":e.value})});var Z=/^(?:input|select|textarea)$/i,et=/^key/,tt=/^(?:mouse|contextmenu)|click/,nt=/^(?:focusinfocus|focusoutblur)$/,rt=/^([^.]*)(?:\.(.+)|)$/;function it(){return!0}function ot(){return!1}function at(){try{return a.activeElement}catch(e){}}x.event={global:{},add:function(e,n,r,o,a){var s,l,u,c,p,f,d,h,g,m,y,v=x._data(e);if(v){r.handler&&(c=r,r=c.handler,a=c.selector),r.guid||(r.guid=x.guid++),(l=v.events)||(l=v.events={}),(f=v.handle)||(f=v.handle=function(e){return typeof x===i||e&&x.event.triggered===e.type?t:x.event.dispatch.apply(f.elem,arguments)},f.elem=e),n=(n||"").match(T)||[""],u=n.length;while(u--)s=rt.exec(n[u])||[],g=y=s[1],m=(s[2]||"").split(".").sort(),g&&(p=x.event.special[g]||{},g=(a?p.delegateType:p.bindType)||g,p=x.event.special[g]||{},d=x.extend({type:g,origType:y,data:o,handler:r,guid:r.guid,selector:a,needsContext:a&&x.expr.match.needsContext.test(a),namespace:m.join(".")},c),(h=l[g])||(h=l[g]=[],h.delegateCount=0,p.setup&&p.setup.call(e,o,m,f)!==!1||(e.addEventListener?e.addEventListener(g,f,!1):e.attachEvent&&e.attachEvent("on"+g,f))),p.add&&(p.add.call(e,d),d.handler.guid||(d.handler.guid=r.guid)),a?h.splice(h.delegateCount++,0,d):h.push(d),x.event.global[g]=!0);e=null}},remove:function(e,t,n,r,i){var o,a,s,l,u,c,p,f,d,h,g,m=x.hasData(e)&&x._data(e);if(m&&(c=m.events)){t=(t||"").match(T)||[""],u=t.length;while(u--)if(s=rt.exec(t[u])||[],d=g=s[1],h=(s[2]||"").split(".").sort(),d){p=x.event.special[d]||{},d=(r?p.delegateType:p.bindType)||d,f=c[d]||[],s=s[2]&&RegExp("(^|\\.)"+h.join("\\.(?:.*\\.|)")+"(\\.|$)"),l=o=f.length;while(o--)a=f[o],!i&&g!==a.origType||n&&n.guid!==a.guid||s&&!s.test(a.namespace)||r&&r!==a.selector&&("**"!==r||!a.selector)||(f.splice(o,1),a.selector&&f.delegateCount--,p.remove&&p.remove.call(e,a));l&&!f.length&&(p.teardown&&p.teardown.call(e,h,m.handle)!==!1||x.removeEvent(e,d,m.handle),delete c[d])}else for(d in c)x.event.remove(e,d+t[u],n,r,!0);x.isEmptyObject(c)&&(delete m.handle,x._removeData(e,"events"))}},trigger:function(n,r,i,o){var s,l,u,c,p,f,d,h=[i||a],g=v.call(n,"type")?n.type:n,m=v.call(n,"namespace")?n.namespace.split("."):[];if(u=f=i=i||a,3!==i.nodeType&&8!==i.nodeType&&!nt.test(g+x.event.triggered)&&(g.indexOf(".")>=0&&(m=g.split("."),g=m.shift(),m.sort()),l=0>g.indexOf(":")&&"on"+g,n=n[x.expando]?n:new x.Event(g,"object"==typeof n&&n),n.isTrigger=o?2:3,n.namespace=m.join("."),n.namespace_re=n.namespace?RegExp("(^|\\.)"+m.join("\\.(?:.*\\.|)")+"(\\.|$)"):null,n.result=t,n.target||(n.target=i),r=null==r?[n]:x.makeArray(r,[n]),p=x.event.special[g]||{},o||!p.trigger||p.trigger.apply(i,r)!==!1)){if(!o&&!p.noBubble&&!x.isWindow(i)){for(c=p.delegateType||g,nt.test(c+g)||(u=u.parentNode);u;u=u.parentNode)h.push(u),f=u;f===(i.ownerDocument||a)&&h.push(f.defaultView||f.parentWindow||e)}d=0;while((u=h[d++])&&!n.isPropagationStopped())n.type=d>1?c:p.bindType||g,s=(x._data(u,"events")||{})[n.type]&&x._data(u,"handle"),s&&s.apply(u,r),s=l&&u[l],s&&x.acceptData(u)&&s.apply&&s.apply(u,r)===!1&&n.preventDefault();if(n.type=g,!o&&!n.isDefaultPrevented()&&(!p._default||p._default.apply(h.pop(),r)===!1)&&x.acceptData(i)&&l&&i[g]&&!x.isWindow(i)){f=i[l],f&&(i[l]=null),x.event.triggered=g;try{i[g]()}catch(y){}x.event.triggered=t,f&&(i[l]=f)}return n.result}},dispatch:function(e){e=x.event.fix(e);var n,r,i,o,a,s=[],l=g.call(arguments),u=(x._data(this,"events")||{})[e.type]||[],c=x.event.special[e.type]||{};if(l[0]=e,e.delegateTarget=this,!c.preDispatch||c.preDispatch.call(this,e)!==!1){s=x.event.handlers.call(this,e,u),n=0;while((o=s[n++])&&!e.isPropagationStopped()){e.currentTarget=o.elem,a=0;while((i=o.handlers[a++])&&!e.isImmediatePropagationStopped())(!e.namespace_re||e.namespace_re.test(i.namespace))&&(e.handleObj=i,e.data=i.data,r=((x.event.special[i.origType]||{}).handle||i.handler).apply(o.elem,l),r!==t&&(e.result=r)===!1&&(e.preventDefault(),e.stopPropagation()))}return c.postDispatch&&c.postDispatch.call(this,e),e.result}},handlers:function(e,n){var r,i,o,a,s=[],l=n.delegateCount,u=e.target;if(l&&u.nodeType&&(!e.button||"click"!==e.type))for(;u!=this;u=u.parentNode||this)if(1===u.nodeType&&(u.disabled!==!0||"click"!==e.type)){for(o=[],a=0;l>a;a++)i=n[a],r=i.selector+" ",o[r]===t&&(o[r]=i.needsContext?x(r,this).index(u)>=0:x.find(r,this,null,[u]).length),o[r]&&o.push(i);o.length&&s.push({elem:u,handlers:o})}return n.length>l&&s.push({elem:this,handlers:n.slice(l)}),s},fix:function(e){if(e[x.expando])return e;var t,n,r,i=e.type,o=e,s=this.fixHooks[i];s||(this.fixHooks[i]=s=tt.test(i)?this.mouseHooks:et.test(i)?this.keyHooks:{}),r=s.props?this.props.concat(s.props):this.props,e=new x.Event(o),t=r.length;while(t--)n=r[t],e[n]=o[n];return e.target||(e.target=o.srcElement||a),3===e.target.nodeType&&(e.target=e.target.parentNode),e.metaKey=!!e.metaKey,s.filter?s.filter(e,o):e},props:"altKey bubbles cancelable ctrlKey currentTarget eventPhase metaKey relatedTarget shiftKey target timeStamp view which".split(" "),fixHooks:{},keyHooks:{props:"char charCode key keyCode".split(" "),filter:function(e,t){return null==e.which&&(e.which=null!=t.charCode?t.charCode:t.keyCode),e}},mouseHooks:{props:"button buttons clientX clientY fromElement offsetX offsetY pageX pageY screenX screenY toElement".split(" "),filter:function(e,n){var r,i,o,s=n.button,l=n.fromElement;return null==e.pageX&&null!=n.clientX&&(i=e.target.ownerDocument||a,o=i.documentElement,r=i.body,e.pageX=n.clientX+(o&&o.scrollLeft||r&&r.scrollLeft||0)-(o&&o.clientLeft||r&&r.clientLeft||0),e.pageY=n.clientY+(o&&o.scrollTop||r&&r.scrollTop||0)-(o&&o.clientTop||r&&r.clientTop||0)),!e.relatedTarget&&l&&(e.relatedTarget=l===e.target?n.toElement:l),e.which||s===t||(e.which=1&s?1:2&s?3:4&s?2:0),e}},special:{load:{noBubble:!0},focus:{trigger:function(){if(this!==at()&&this.focus)try{return this.focus(),!1}catch(e){}},delegateType:"focusin"},blur:{trigger:function(){return this===at()&&this.blur?(this.blur(),!1):t},delegateType:"focusout"},click:{trigger:function(){return x.nodeName(this,"input")&&"checkbox"===this.type&&this.click?(this.click(),!1):t},_default:function(e){return x.nodeName(e.target,"a")}},beforeunload:{postDispatch:function(e){e.result!==t&&(e.originalEvent.returnValue=e.result)}}},simulate:function(e,t,n,r){var i=x.extend(new x.Event,n,{type:e,isSimulated:!0,originalEvent:{}});r?x.event.trigger(i,null,t):x.event.dispatch.call(t,i),i.isDefaultPrevented()&&n.preventDefault()}},x.removeEvent=a.removeEventListener?function(e,t,n){e.removeEventListener&&e.removeEventListener(t,n,!1)}:function(e,t,n){var r="on"+t;e.detachEvent&&(typeof e[r]===i&&(e[r]=null),e.detachEvent(r,n))},x.Event=function(e,n){return this instanceof x.Event?(e&&e.type?(this.originalEvent=e,this.type=e.type,this.isDefaultPrevented=e.defaultPrevented||e.returnValue===!1||e.getPreventDefault&&e.getPreventDefault()?it:ot):this.type=e,n&&x.extend(this,n),this.timeStamp=e&&e.timeStamp||x.now(),this[x.expando]=!0,t):new x.Event(e,n)},x.Event.prototype={isDefaultPrevented:ot,isPropagationStopped:ot,isImmediatePropagationStopped:ot,preventDefault:function(){var e=this.originalEvent;this.isDefaultPrevented=it,e&&(e.preventDefault?e.preventDefault():e.returnValue=!1)},stopPropagation:function(){var e=this.originalEvent;this.isPropagationStopped=it,e&&(e.stopPropagation&&e.stopPropagation(),e.cancelBubble=!0)},stopImmediatePropagation:function(){this.isImmediatePropagationStopped=it,this.stopPropagation()}},x.each({mouseenter:"mouseover",mouseleave:"mouseout"},function(e,t){x.event.special[e]={delegateType:t,bindType:t,handle:function(e){var n,r=this,i=e.relatedTarget,o=e.handleObj;return(!i||i!==r&&!x.contains(r,i))&&(e.type=o.origType,n=o.handler.apply(this,arguments),e.type=t),n}}}),x.support.submitBubbles||(x.event.special.submit={setup:function(){return x.nodeName(this,"form")?!1:(x.event.add(this,"click._submit keypress._submit",function(e){var n=e.target,r=x.nodeName(n,"input")||x.nodeName(n,"button")?n.form:t;r&&!x._data(r,"submitBubbles")&&(x.event.add(r,"submit._submit",function(e){e._submit_bubble=!0}),x._data(r,"submitBubbles",!0))}),t)},postDispatch:function(e){e._submit_bubble&&(delete e._submit_bubble,this.parentNode&&!e.isTrigger&&x.event.simulate("submit",this.parentNode,e,!0))},teardown:function(){return x.nodeName(this,"form")?!1:(x.event.remove(this,"._submit"),t)}}),x.support.changeBubbles||(x.event.special.change={setup:function(){return Z.test(this.nodeName)?(("checkbox"===this.type||"radio"===this.type)&&(x.event.add(this,"propertychange._change",function(e){"checked"===e.originalEvent.propertyName&&(this._just_changed=!0)}),x.event.add(this,"click._change",function(e){this._just_changed&&!e.isTrigger&&(this._just_changed=!1),x.event.simulate("change",this,e,!0)})),!1):(x.event.add(this,"beforeactivate._change",function(e){var t=e.target;Z.test(t.nodeName)&&!x._data(t,"changeBubbles")&&(x.event.add(t,"change._change",function(e){!this.parentNode||e.isSimulated||e.isTrigger||x.event.simulate("change",this.parentNode,e,!0)}),x._data(t,"changeBubbles",!0))}),t)},handle:function(e){var n=e.target;return this!==n||e.isSimulated||e.isTrigger||"radio"!==n.type&&"checkbox"!==n.type?e.handleObj.handler.apply(this,arguments):t},teardown:function(){return x.event.remove(this,"._change"),!Z.test(this.nodeName)}}),x.support.focusinBubbles||x.each({focus:"focusin",blur:"focusout"},function(e,t){var n=0,r=function(e){x.event.simulate(t,e.target,x.event.fix(e),!0)};x.event.special[t]={setup:function(){0===n++&&a.addEventListener(e,r,!0)},teardown:function(){0===--n&&a.removeEventListener(e,r,!0)}}}),x.fn.extend({on:function(e,n,r,i,o){var a,s;if("object"==typeof e){"string"!=typeof n&&(r=r||n,n=t);for(a in e)this.on(a,n,r,e[a],o);return this}if(null==r&&null==i?(i=n,r=n=t):null==i&&("string"==typeof n?(i=r,r=t):(i=r,r=n,n=t)),i===!1)i=ot;else if(!i)return this;return 1===o&&(s=i,i=function(e){return x().off(e),s.apply(this,arguments)},i.guid=s.guid||(s.guid=x.guid++)),this.each(function(){x.event.add(this,e,i,r,n)})},one:function(e,t,n,r){return this.on(e,t,n,r,1)},off:function(e,n,r){var i,o;if(e&&e.preventDefault&&e.handleObj)return i=e.handleObj,x(e.delegateTarget).off(i.namespace?i.origType+"."+i.namespace:i.origType,i.selector,i.handler),this;if("object"==typeof e){for(o in e)this.off(o,n,e[o]);return this}return(n===!1||"function"==typeof n)&&(r=n,n=t),r===!1&&(r=ot),this.each(function(){x.event.remove(this,e,r,n)})},trigger:function(e,t){return this.each(function(){x.event.trigger(e,t,this)})},triggerHandler:function(e,n){var r=this[0];return r?x.event.trigger(e,n,r,!0):t}});var st=/^.[^:#\[\.,]*$/,lt=/^(?:parents|prev(?:Until|All))/,ut=x.expr.match.needsContext,ct={children:!0,contents:!0,next:!0,prev:!0};x.fn.extend({find:function(e){var t,n=[],r=this,i=r.length;if("string"!=typeof e)return this.pushStack(x(e).filter(function(){for(t=0;i>t;t++)if(x.contains(r[t],this))return!0}));for(t=0;i>t;t++)x.find(e,r[t],n);return n=this.pushStack(i>1?x.unique(n):n),n.selector=this.selector?this.selector+" "+e:e,n},has:function(e){var t,n=x(e,this),r=n.length;return this.filter(function(){for(t=0;r>t;t++)if(x.contains(this,n[t]))return!0})},not:function(e){return this.pushStack(ft(this,e||[],!0))},filter:function(e){return this.pushStack(ft(this,e||[],!1))},is:function(e){return!!ft(this,"string"==typeof e&&ut.test(e)?x(e):e||[],!1).length},closest:function(e,t){var n,r=0,i=this.length,o=[],a=ut.test(e)||"string"!=typeof e?x(e,t||this.context):0;for(;i>r;r++)for(n=this[r];n&&n!==t;n=n.parentNode)if(11>n.nodeType&&(a?a.index(n)>-1:1===n.nodeType&&x.find.matchesSelector(n,e))){n=o.push(n);break}return this.pushStack(o.length>1?x.unique(o):o)},index:function(e){return e?"string"==typeof e?x.inArray(this[0],x(e)):x.inArray(e.jquery?e[0]:e,this):this[0]&&this[0].parentNode?this.first().prevAll().length:-1},add:function(e,t){var n="string"==typeof e?x(e,t):x.makeArray(e&&e.nodeType?[e]:e),r=x.merge(this.get(),n);return this.pushStack(x.unique(r))},addBack:function(e){return this.add(null==e?this.prevObject:this.prevObject.filter(e))}});function pt(e,t){do e=e[t];while(e&&1!==e.nodeType);return e}x.each({parent:function(e){var t=e.parentNode;return t&&11!==t.nodeType?t:null},parents:function(e){return x.dir(e,"parentNode")},parentsUntil:function(e,t,n){return x.dir(e,"parentNode",n)},next:function(e){return pt(e,"nextSibling")},prev:function(e){return pt(e,"previousSibling")},nextAll:function(e){return x.dir(e,"nextSibling")},prevAll:function(e){return x.dir(e,"previousSibling")},nextUntil:function(e,t,n){return x.dir(e,"nextSibling",n)},prevUntil:function(e,t,n){return x.dir(e,"previousSibling",n)},siblings:function(e){return x.sibling((e.parentNode||{}).firstChild,e)},children:function(e){return x.sibling(e.firstChild)},contents:function(e){return x.nodeName(e,"iframe")?e.contentDocument||e.contentWindow.document:x.merge([],e.childNodes)}},function(e,t){x.fn[e]=function(n,r){var i=x.map(this,t,n);return"Until"!==e.slice(-5)&&(r=n),r&&"string"==typeof r&&(i=x.filter(r,i)),this.length>1&&(ct[e]||(i=x.unique(i)),lt.test(e)&&(i=i.reverse())),this.pushStack(i)}}),x.extend({filter:function(e,t,n){var r=t[0];return n&&(e=":not("+e+")"),1===t.length&&1===r.nodeType?x.find.matchesSelector(r,e)?[r]:[]:x.find.matches(e,x.grep(t,function(e){return 1===e.nodeType}))},dir:function(e,n,r){var i=[],o=e[n];while(o&&9!==o.nodeType&&(r===t||1!==o.nodeType||!x(o).is(r)))1===o.nodeType&&i.push(o),o=o[n];return i},sibling:function(e,t){var n=[];for(;e;e=e.nextSibling)1===e.nodeType&&e!==t&&n.push(e);return n}});function ft(e,t,n){if(x.isFunction(t))return x.grep(e,function(e,r){return!!t.call(e,r,e)!==n});if(t.nodeType)return x.grep(e,function(e){return e===t!==n});if("string"==typeof t){if(st.test(t))return x.filter(t,e,n);t=x.filter(t,e)}return x.grep(e,function(e){return x.inArray(e,t)>=0!==n})}function dt(e){var t=ht.split("|"),n=e.createDocumentFragment();if(n.createElement)while(t.length)n.createElement(t.pop());return n}var ht="abbr|article|aside|audio|bdi|canvas|data|datalist|details|figcaption|figure|footer|header|hgroup|mark|meter|nav|output|progress|section|summary|time|video",gt=/ jQuery\d+="(?:null|\d+)"/g,mt=RegExp("<(?:"+ht+")[\\s/>]","i"),yt=/^\s+/,vt=/<(?!area|br|col|embed|hr|img|input|link|meta|param)(([\w:]+)[^>]*)\/>/gi,bt=/<([\w:]+)/,xt=/<tbody/i,wt=/<|&#?\w+;/,Tt=/<(?:script|style|link)/i,Ct=/^(?:checkbox|radio)$/i,Nt=/checked\s*(?:[^=]|=\s*.checked.)/i,kt=/^$|\/(?:java|ecma)script/i,Et=/^true\/(.*)/,St=/^\s*<!(?:\[CDATA\[|--)|(?:\]\]|--)>\s*$/g,At={option:[1,"<select multiple='multiple'>","</select>"],legend:[1,"<fieldset>","</fieldset>"],area:[1,"<map>","</map>"],param:[1,"<object>","</object>"],thead:[1,"<table>","</table>"],tr:[2,"<table><tbody>","</tbody></table>"],col:[2,"<table><tbody></tbody><colgroup>","</colgroup></table>"],td:[3,"<table><tbody><tr>","</tr></tbody></table>"],_default:x.support.htmlSerialize?[0,"",""]:[1,"X<div>","</div>"]},jt=dt(a),Dt=jt.appendChild(a.createElement("div"));At.optgroup=At.option,At.tbody=At.tfoot=At.colgroup=At.caption=At.thead,At.th=At.td,x.fn.extend({text:function(e){return x.access(this,function(e){return e===t?x.text(this):this.empty().append((this[0]&&this[0].ownerDocument||a).createTextNode(e))},null,e,arguments.length)},append:function(){return this.domManip(arguments,function(e){if(1===this.nodeType||11===this.nodeType||9===this.nodeType){var t=Lt(this,e);t.appendChild(e)}})},prepend:function(){return this.domManip(arguments,function(e){if(1===this.nodeType||11===this.nodeType||9===this.nodeType){var t=Lt(this,e);t.insertBefore(e,t.firstChild)}})},before:function(){return this.domManip(arguments,function(e){this.parentNode&&this.parentNode.insertBefore(e,this)})},after:function(){return this.domManip(arguments,function(e){this.parentNode&&this.parentNode.insertBefore(e,this.nextSibling)})},remove:function(e,t){var n,r=e?x.filter(e,this):this,i=0;for(;null!=(n=r[i]);i++)t||1!==n.nodeType||x.cleanData(Ft(n)),n.parentNode&&(t&&x.contains(n.ownerDocument,n)&&_t(Ft(n,"script")),n.parentNode.removeChild(n));return this},empty:function(){var e,t=0;for(;null!=(e=this[t]);t++){1===e.nodeType&&x.cleanData(Ft(e,!1));while(e.firstChild)e.removeChild(e.firstChild);e.options&&x.nodeName(e,"select")&&(e.options.length=0)}return this},clone:function(e,t){return e=null==e?!1:e,t=null==t?e:t,this.map(function(){return x.clone(this,e,t)})},html:function(e){return x.access(this,function(e){var n=this[0]||{},r=0,i=this.length;if(e===t)return 1===n.nodeType?n.innerHTML.replace(gt,""):t;if(!("string"!=typeof e||Tt.test(e)||!x.support.htmlSerialize&&mt.test(e)||!x.support.leadingWhitespace&&yt.test(e)||At[(bt.exec(e)||["",""])[1].toLowerCase()])){e=e.replace(vt,"<$1></$2>");try{for(;i>r;r++)n=this[r]||{},1===n.nodeType&&(x.cleanData(Ft(n,!1)),n.innerHTML=e);n=0}catch(o){}}n&&this.empty().append(e)},null,e,arguments.length)},replaceWith:function(){var e=x.map(this,function(e){return[e.nextSibling,e.parentNode]}),t=0;return this.domManip(arguments,function(n){var r=e[t++],i=e[t++];i&&(r&&r.parentNode!==i&&(r=this.nextSibling),x(this).remove(),i.insertBefore(n,r))},!0),t?this:this.remove()},detach:function(e){return this.remove(e,!0)},domManip:function(e,t,n){e=d.apply([],e);var r,i,o,a,s,l,u=0,c=this.length,p=this,f=c-1,h=e[0],g=x.isFunction(h);if(g||!(1>=c||"string"!=typeof h||x.support.checkClone)&&Nt.test(h))return this.each(function(r){var i=p.eq(r);g&&(e[0]=h.call(this,r,i.html())),i.domManip(e,t,n)});if(c&&(l=x.buildFragment(e,this[0].ownerDocument,!1,!n&&this),r=l.firstChild,1===l.childNodes.length&&(l=r),r)){for(a=x.map(Ft(l,"script"),Ht),o=a.length;c>u;u++)i=l,u!==f&&(i=x.clone(i,!0,!0),o&&x.merge(a,Ft(i,"script"))),t.call(this[u],i,u);if(o)for(s=a[a.length-1].ownerDocument,x.map(a,qt),u=0;o>u;u++)i=a[u],kt.test(i.type||"")&&!x._data(i,"globalEval")&&x.contains(s,i)&&(i.src?x._evalUrl(i.src):x.globalEval((i.text||i.textContent||i.innerHTML||"").replace(St,"")));l=r=null}return this}});function Lt(e,t){return x.nodeName(e,"table")&&x.nodeName(1===t.nodeType?t:t.firstChild,"tr")?e.getElementsByTagName("tbody")[0]||e.appendChild(e.ownerDocument.createElement("tbody")):e}function Ht(e){return e.type=(null!==x.find.attr(e,"type"))+"/"+e.type,e}function qt(e){var t=Et.exec(e.type);return t?e.type=t[1]:e.removeAttribute("type"),e}function _t(e,t){var n,r=0;for(;null!=(n=e[r]);r++)x._data(n,"globalEval",!t||x._data(t[r],"globalEval"))}function Mt(e,t){if(1===t.nodeType&&x.hasData(e)){var n,r,i,o=x._data(e),a=x._data(t,o),s=o.events;if(s){delete a.handle,a.events={};for(n in s)for(r=0,i=s[n].length;i>r;r++)x.event.add(t,n,s[n][r])}a.data&&(a.data=x.extend({},a.data))}}function Ot(e,t){var n,r,i;if(1===t.nodeType){if(n=t.nodeName.toLowerCase(),!x.support.noCloneEvent&&t[x.expando]){i=x._data(t);for(r in i.events)x.removeEvent(t,r,i.handle);t.removeAttribute(x.expando)}"script"===n&&t.text!==e.text?(Ht(t).text=e.text,qt(t)):"object"===n?(t.parentNode&&(t.outerHTML=e.outerHTML),x.support.html5Clone&&e.innerHTML&&!x.trim(t.innerHTML)&&(t.innerHTML=e.innerHTML)):"input"===n&&Ct.test(e.type)?(t.defaultChecked=t.checked=e.checked,t.value!==e.value&&(t.value=e.value)):"option"===n?t.defaultSelected=t.selected=e.defaultSelected:("input"===n||"textarea"===n)&&(t.defaultValue=e.defaultValue)}}x.each({appendTo:"append",prependTo:"prepend",insertBefore:"before",insertAfter:"after",replaceAll:"replaceWith"},function(e,t){x.fn[e]=function(e){var n,r=0,i=[],o=x(e),a=o.length-1;for(;a>=r;r++)n=r===a?this:this.clone(!0),x(o[r])[t](n),h.apply(i,n.get());return this.pushStack(i)}});function Ft(e,n){var r,o,a=0,s=typeof e.getElementsByTagName!==i?e.getElementsByTagName(n||"*"):typeof e.querySelectorAll!==i?e.querySelectorAll(n||"*"):t;if(!s)for(s=[],r=e.childNodes||e;null!=(o=r[a]);a++)!n||x.nodeName(o,n)?s.push(o):x.merge(s,Ft(o,n));return n===t||n&&x.nodeName(e,n)?x.merge([e],s):s}function Bt(e){Ct.test(e.type)&&(e.defaultChecked=e.checked)}x.extend({clone:function(e,t,n){var r,i,o,a,s,l=x.contains(e.ownerDocument,e);if(x.support.html5Clone||x.isXMLDoc(e)||!mt.test("<"+e.nodeName+">")?o=e.cloneNode(!0):(Dt.innerHTML=e.outerHTML,Dt.removeChild(o=Dt.firstChild)),!(x.support.noCloneEvent&&x.support.noCloneChecked||1!==e.nodeType&&11!==e.nodeType||x.isXMLDoc(e)))for(r=Ft(o),s=Ft(e),a=0;null!=(i=s[a]);++a)r[a]&&Ot(i,r[a]);if(t)if(n)for(s=s||Ft(e),r=r||Ft(o),a=0;null!=(i=s[a]);a++)Mt(i,r[a]);else Mt(e,o);return r=Ft(o,"script"),r.length>0&&_t(r,!l&&Ft(e,"script")),r=s=i=null,o},buildFragment:function(e,t,n,r){var i,o,a,s,l,u,c,p=e.length,f=dt(t),d=[],h=0;for(;p>h;h++)if(o=e[h],o||0===o)if("object"===x.type(o))x.merge(d,o.nodeType?[o]:o);else if(wt.test(o)){s=s||f.appendChild(t.createElement("div")),l=(bt.exec(o)||["",""])[1].toLowerCase(),c=At[l]||At._default,s.innerHTML=c[1]+o.replace(vt,"<$1></$2>")+c[2],i=c[0];while(i--)s=s.lastChild;if(!x.support.leadingWhitespace&&yt.test(o)&&d.push(t.createTextNode(yt.exec(o)[0])),!x.support.tbody){o="table"!==l||xt.test(o)?"<table>"!==c[1]||xt.test(o)?0:s:s.firstChild,i=o&&o.childNodes.length;while(i--)x.nodeName(u=o.childNodes[i],"tbody")&&!u.childNodes.length&&o.removeChild(u)}x.merge(d,s.childNodes),s.textContent="";while(s.firstChild)s.removeChild(s.firstChild);s=f.lastChild}else d.push(t.createTextNode(o));s&&f.removeChild(s),x.support.appendChecked||x.grep(Ft(d,"input"),Bt),h=0;while(o=d[h++])if((!r||-1===x.inArray(o,r))&&(a=x.contains(o.ownerDocument,o),s=Ft(f.appendChild(o),"script"),a&&_t(s),n)){i=0;while(o=s[i++])kt.test(o.type||"")&&n.push(o)}return s=null,f},cleanData:function(e,t){var n,r,o,a,s=0,l=x.expando,u=x.cache,c=x.support.deleteExpando,f=x.event.special;for(;null!=(n=e[s]);s++)if((t||x.acceptData(n))&&(o=n[l],a=o&&u[o])){if(a.events)for(r in a.events)f[r]?x.event.remove(n,r):x.removeEvent(n,r,a.handle); u[o]&&(delete u[o],c?delete n[l]:typeof n.removeAttribute!==i?n.removeAttribute(l):n[l]=null,p.push(o))}},_evalUrl:function(e){return x.ajax({url:e,type:"GET",dataType:"script",async:!1,global:!1,"throws":!0})}}),x.fn.extend({wrapAll:function(e){if(x.isFunction(e))return this.each(function(t){x(this).wrapAll(e.call(this,t))});if(this[0]){var t=x(e,this[0].ownerDocument).eq(0).clone(!0);this[0].parentNode&&t.insertBefore(this[0]),t.map(function(){var e=this;while(e.firstChild&&1===e.firstChild.nodeType)e=e.firstChild;return e}).append(this)}return this},wrapInner:function(e){return x.isFunction(e)?this.each(function(t){x(this).wrapInner(e.call(this,t))}):this.each(function(){var t=x(this),n=t.contents();n.length?n.wrapAll(e):t.append(e)})},wrap:function(e){var t=x.isFunction(e);return this.each(function(n){x(this).wrapAll(t?e.call(this,n):e)})},unwrap:function(){return this.parent().each(function(){x.nodeName(this,"body")||x(this).replaceWith(this.childNodes)}).end()}});var Pt,Rt,Wt,$t=/alpha\([^)]*\)/i,It=/opacity\s*=\s*([^)]*)/,zt=/^(top|right|bottom|left)$/,Xt=/^(none|table(?!-c[ea]).+)/,Ut=/^margin/,Vt=RegExp("^("+w+")(.*)$","i"),Yt=RegExp("^("+w+")(?!px)[a-z%]+$","i"),Jt=RegExp("^([+-])=("+w+")","i"),Gt={BODY:"block"},Qt={position:"absolute",visibility:"hidden",display:"block"},Kt={letterSpacing:0,fontWeight:400},Zt=["Top","Right","Bottom","Left"],en=["Webkit","O","Moz","ms"];function tn(e,t){if(t in e)return t;var n=t.charAt(0).toUpperCase()+t.slice(1),r=t,i=en.length;while(i--)if(t=en[i]+n,t in e)return t;return r}function nn(e,t){return e=t||e,"none"===x.css(e,"display")||!x.contains(e.ownerDocument,e)}function rn(e,t){var n,r,i,o=[],a=0,s=e.length;for(;s>a;a++)r=e[a],r.style&&(o[a]=x._data(r,"olddisplay"),n=r.style.display,t?(o[a]||"none"!==n||(r.style.display=""),""===r.style.display&&nn(r)&&(o[a]=x._data(r,"olddisplay",ln(r.nodeName)))):o[a]||(i=nn(r),(n&&"none"!==n||!i)&&x._data(r,"olddisplay",i?n:x.css(r,"display"))));for(a=0;s>a;a++)r=e[a],r.style&&(t&&"none"!==r.style.display&&""!==r.style.display||(r.style.display=t?o[a]||"":"none"));return e}x.fn.extend({css:function(e,n){return x.access(this,function(e,n,r){var i,o,a={},s=0;if(x.isArray(n)){for(o=Rt(e),i=n.length;i>s;s++)a[n[s]]=x.css(e,n[s],!1,o);return a}return r!==t?x.style(e,n,r):x.css(e,n)},e,n,arguments.length>1)},show:function(){return rn(this,!0)},hide:function(){return rn(this)},toggle:function(e){return"boolean"==typeof e?e?this.show():this.hide():this.each(function(){nn(this)?x(this).show():x(this).hide()})}}),x.extend({cssHooks:{opacity:{get:function(e,t){if(t){var n=Wt(e,"opacity");return""===n?"1":n}}}},cssNumber:{columnCount:!0,fillOpacity:!0,fontWeight:!0,lineHeight:!0,opacity:!0,order:!0,orphans:!0,widows:!0,zIndex:!0,zoom:!0},cssProps:{"float":x.support.cssFloat?"cssFloat":"styleFloat"},style:function(e,n,r,i){if(e&&3!==e.nodeType&&8!==e.nodeType&&e.style){var o,a,s,l=x.camelCase(n),u=e.style;if(n=x.cssProps[l]||(x.cssProps[l]=tn(u,l)),s=x.cssHooks[n]||x.cssHooks[l],r===t)return s&&"get"in s&&(o=s.get(e,!1,i))!==t?o:u[n];if(a=typeof r,"string"===a&&(o=Jt.exec(r))&&(r=(o[1]+1)*o[2]+parseFloat(x.css(e,n)),a="number"),!(null==r||"number"===a&&isNaN(r)||("number"!==a||x.cssNumber[l]||(r+="px"),x.support.clearCloneStyle||""!==r||0!==n.indexOf("background")||(u[n]="inherit"),s&&"set"in s&&(r=s.set(e,r,i))===t)))try{u[n]=r}catch(c){}}},css:function(e,n,r,i){var o,a,s,l=x.camelCase(n);return n=x.cssProps[l]||(x.cssProps[l]=tn(e.style,l)),s=x.cssHooks[n]||x.cssHooks[l],s&&"get"in s&&(a=s.get(e,!0,r)),a===t&&(a=Wt(e,n,i)),"normal"===a&&n in Kt&&(a=Kt[n]),""===r||r?(o=parseFloat(a),r===!0||x.isNumeric(o)?o||0:a):a}}),e.getComputedStyle?(Rt=function(t){return e.getComputedStyle(t,null)},Wt=function(e,n,r){var i,o,a,s=r||Rt(e),l=s?s.getPropertyValue(n)||s[n]:t,u=e.style;return s&&(""!==l||x.contains(e.ownerDocument,e)||(l=x.style(e,n)),Yt.test(l)&&Ut.test(n)&&(i=u.width,o=u.minWidth,a=u.maxWidth,u.minWidth=u.maxWidth=u.width=l,l=s.width,u.width=i,u.minWidth=o,u.maxWidth=a)),l}):a.documentElement.currentStyle&&(Rt=function(e){return e.currentStyle},Wt=function(e,n,r){var i,o,a,s=r||Rt(e),l=s?s[n]:t,u=e.style;return null==l&&u&&u[n]&&(l=u[n]),Yt.test(l)&&!zt.test(n)&&(i=u.left,o=e.runtimeStyle,a=o&&o.left,a&&(o.left=e.currentStyle.left),u.left="fontSize"===n?"1em":l,l=u.pixelLeft+"px",u.left=i,a&&(o.left=a)),""===l?"auto":l});function on(e,t,n){var r=Vt.exec(t);return r?Math.max(0,r[1]-(n||0))+(r[2]||"px"):t}function an(e,t,n,r,i){var o=n===(r?"border":"content")?4:"width"===t?1:0,a=0;for(;4>o;o+=2)"margin"===n&&(a+=x.css(e,n+Zt[o],!0,i)),r?("content"===n&&(a-=x.css(e,"padding"+Zt[o],!0,i)),"margin"!==n&&(a-=x.css(e,"border"+Zt[o]+"Width",!0,i))):(a+=x.css(e,"padding"+Zt[o],!0,i),"padding"!==n&&(a+=x.css(e,"border"+Zt[o]+"Width",!0,i)));return a}function sn(e,t,n){var r=!0,i="width"===t?e.offsetWidth:e.offsetHeight,o=Rt(e),a=x.support.boxSizing&&"border-box"===x.css(e,"boxSizing",!1,o);if(0>=i||null==i){if(i=Wt(e,t,o),(0>i||null==i)&&(i=e.style[t]),Yt.test(i))return i;r=a&&(x.support.boxSizingReliable||i===e.style[t]),i=parseFloat(i)||0}return i+an(e,t,n||(a?"border":"content"),r,o)+"px"}function ln(e){var t=a,n=Gt[e];return n||(n=un(e,t),"none"!==n&&n||(Pt=(Pt||x("<iframe frameborder='0' width='0' height='0'/>").css("cssText","display:block !important")).appendTo(t.documentElement),t=(Pt[0].contentWindow||Pt[0].contentDocument).document,t.write("<!doctype html><html><body>"),t.close(),n=un(e,t),Pt.detach()),Gt[e]=n),n}function un(e,t){var n=x(t.createElement(e)).appendTo(t.body),r=x.css(n[0],"display");return n.remove(),r}x.each(["height","width"],function(e,n){x.cssHooks[n]={get:function(e,r,i){return r?0===e.offsetWidth&&Xt.test(x.css(e,"display"))?x.swap(e,Qt,function(){return sn(e,n,i)}):sn(e,n,i):t},set:function(e,t,r){var i=r&&Rt(e);return on(e,t,r?an(e,n,r,x.support.boxSizing&&"border-box"===x.css(e,"boxSizing",!1,i),i):0)}}}),x.support.opacity||(x.cssHooks.opacity={get:function(e,t){return It.test((t&&e.currentStyle?e.currentStyle.filter:e.style.filter)||"")?.01*parseFloat(RegExp.$1)+"":t?"1":""},set:function(e,t){var n=e.style,r=e.currentStyle,i=x.isNumeric(t)?"alpha(opacity="+100*t+")":"",o=r&&r.filter||n.filter||"";n.zoom=1,(t>=1||""===t)&&""===x.trim(o.replace($t,""))&&n.removeAttribute&&(n.removeAttribute("filter"),""===t||r&&!r.filter)||(n.filter=$t.test(o)?o.replace($t,i):o+" "+i)}}),x(function(){x.support.reliableMarginRight||(x.cssHooks.marginRight={get:function(e,n){return n?x.swap(e,{display:"inline-block"},Wt,[e,"marginRight"]):t}}),!x.support.pixelPosition&&x.fn.position&&x.each(["top","left"],function(e,n){x.cssHooks[n]={get:function(e,r){return r?(r=Wt(e,n),Yt.test(r)?x(e).position()[n]+"px":r):t}}})}),x.expr&&x.expr.filters&&(x.expr.filters.hidden=function(e){return 0>=e.offsetWidth&&0>=e.offsetHeight||!x.support.reliableHiddenOffsets&&"none"===(e.style&&e.style.display||x.css(e,"display"))},x.expr.filters.visible=function(e){return!x.expr.filters.hidden(e)}),x.each({margin:"",padding:"",border:"Width"},function(e,t){x.cssHooks[e+t]={expand:function(n){var r=0,i={},o="string"==typeof n?n.split(" "):[n];for(;4>r;r++)i[e+Zt[r]+t]=o[r]||o[r-2]||o[0];return i}},Ut.test(e)||(x.cssHooks[e+t].set=on)});var cn=/%20/g,pn=/\[\]$/,fn=/\r?\n/g,dn=/^(?:submit|button|image|reset|file)$/i,hn=/^(?:input|select|textarea|keygen)/i;x.fn.extend({serialize:function(){return x.param(this.serializeArray())},serializeArray:function(){return this.map(function(){var e=x.prop(this,"elements");return e?x.makeArray(e):this}).filter(function(){var e=this.type;return this.name&&!x(this).is(":disabled")&&hn.test(this.nodeName)&&!dn.test(e)&&(this.checked||!Ct.test(e))}).map(function(e,t){var n=x(this).val();return null==n?null:x.isArray(n)?x.map(n,function(e){return{name:t.name,value:e.replace(fn,"\r\n")}}):{name:t.name,value:n.replace(fn,"\r\n")}}).get()}}),x.param=function(e,n){var r,i=[],o=function(e,t){t=x.isFunction(t)?t():null==t?"":t,i[i.length]=encodeURIComponent(e)+"="+encodeURIComponent(t)};if(n===t&&(n=x.ajaxSettings&&x.ajaxSettings.traditional),x.isArray(e)||e.jquery&&!x.isPlainObject(e))x.each(e,function(){o(this.name,this.value)});else for(r in e)gn(r,e[r],n,o);return i.join("&").replace(cn,"+")};function gn(e,t,n,r){var i;if(x.isArray(t))x.each(t,function(t,i){n||pn.test(e)?r(e,i):gn(e+"["+("object"==typeof i?t:"")+"]",i,n,r)});else if(n||"object"!==x.type(t))r(e,t);else for(i in t)gn(e+"["+i+"]",t[i],n,r)}x.each("blur focus focusin focusout load resize scroll unload click dblclick mousedown mouseup mousemove mouseover mouseout mouseenter mouseleave change select submit keydown keypress keyup error contextmenu".split(" "),function(e,t){x.fn[t]=function(e,n){return arguments.length>0?this.on(t,null,e,n):this.trigger(t)}}),x.fn.extend({hover:function(e,t){return this.mouseenter(e).mouseleave(t||e)},bind:function(e,t,n){return this.on(e,null,t,n)},unbind:function(e,t){return this.off(e,null,t)},delegate:function(e,t,n,r){return this.on(t,e,n,r)},undelegate:function(e,t,n){return 1===arguments.length?this.off(e,"**"):this.off(t,e||"**",n)}});var mn,yn,vn=x.now(),bn=/\?/,xn=/#.*$/,wn=/([?&])_=[^&]*/,Tn=/^(.*?):[ \t]*([^\r\n]*)\r?$/gm,Cn=/^(?:about|app|app-storage|.+-extension|file|res|widget):$/,Nn=/^(?:GET|HEAD)$/,kn=/^\/\//,En=/^([\w.+-]+:)(?:\/\/([^\/?#:]*)(?::(\d+)|)|)/,Sn=x.fn.load,An={},jn={},Dn="*/".concat("*");try{yn=o.href}catch(Ln){yn=a.createElement("a"),yn.href="",yn=yn.href}mn=En.exec(yn.toLowerCase())||[];function Hn(e){return function(t,n){"string"!=typeof t&&(n=t,t="*");var r,i=0,o=t.toLowerCase().match(T)||[];if(x.isFunction(n))while(r=o[i++])"+"===r[0]?(r=r.slice(1)||"*",(e[r]=e[r]||[]).unshift(n)):(e[r]=e[r]||[]).push(n)}}function qn(e,n,r,i){var o={},a=e===jn;function s(l){var u;return o[l]=!0,x.each(e[l]||[],function(e,l){var c=l(n,r,i);return"string"!=typeof c||a||o[c]?a?!(u=c):t:(n.dataTypes.unshift(c),s(c),!1)}),u}return s(n.dataTypes[0])||!o["*"]&&s("*")}function _n(e,n){var r,i,o=x.ajaxSettings.flatOptions||{};for(i in n)n[i]!==t&&((o[i]?e:r||(r={}))[i]=n[i]);return r&&x.extend(!0,e,r),e}x.fn.load=function(e,n,r){if("string"!=typeof e&&Sn)return Sn.apply(this,arguments);var i,o,a,s=this,l=e.indexOf(" ");return l>=0&&(i=e.slice(l,e.length),e=e.slice(0,l)),x.isFunction(n)?(r=n,n=t):n&&"object"==typeof n&&(a="POST"),s.length>0&&x.ajax({url:e,type:a,dataType:"html",data:n}).done(function(e){o=arguments,s.html(i?x("<div>").append(x.parseHTML(e)).find(i):e)}).complete(r&&function(e,t){s.each(r,o||[e.responseText,t,e])}),this},x.each(["ajaxStart","ajaxStop","ajaxComplete","ajaxError","ajaxSuccess","ajaxSend"],function(e,t){x.fn[t]=function(e){return this.on(t,e)}}),x.extend({active:0,lastModified:{},etag:{},ajaxSettings:{url:yn,type:"GET",isLocal:Cn.test(mn[1]),global:!0,processData:!0,async:!0,contentType:"application/x-www-form-urlencoded; charset=UTF-8",accepts:{"*":Dn,text:"text/plain",html:"text/html",xml:"application/xml, text/xml",json:"application/json, text/javascript"},contents:{xml:/xml/,html:/html/,json:/json/},responseFields:{xml:"responseXML",text:"responseText",json:"responseJSON"},converters:{"* text":String,"text html":!0,"text json":x.parseJSON,"text xml":x.parseXML},flatOptions:{url:!0,context:!0}},ajaxSetup:function(e,t){return t?_n(_n(e,x.ajaxSettings),t):_n(x.ajaxSettings,e)},ajaxPrefilter:Hn(An),ajaxTransport:Hn(jn),ajax:function(e,n){"object"==typeof e&&(n=e,e=t),n=n||{};var r,i,o,a,s,l,u,c,p=x.ajaxSetup({},n),f=p.context||p,d=p.context&&(f.nodeType||f.jquery)?x(f):x.event,h=x.Deferred(),g=x.Callbacks("once memory"),m=p.statusCode||{},y={},v={},b=0,w="canceled",C={readyState:0,getResponseHeader:function(e){var t;if(2===b){if(!c){c={};while(t=Tn.exec(a))c[t[1].toLowerCase()]=t[2]}t=c[e.toLowerCase()]}return null==t?null:t},getAllResponseHeaders:function(){return 2===b?a:null},setRequestHeader:function(e,t){var n=e.toLowerCase();return b||(e=v[n]=v[n]||e,y[e]=t),this},overrideMimeType:function(e){return b||(p.mimeType=e),this},statusCode:function(e){var t;if(e)if(2>b)for(t in e)m[t]=[m[t],e[t]];else C.always(e[C.status]);return this},abort:function(e){var t=e||w;return u&&u.abort(t),k(0,t),this}};if(h.promise(C).complete=g.add,C.success=C.done,C.error=C.fail,p.url=((e||p.url||yn)+"").replace(xn,"").replace(kn,mn[1]+"//"),p.type=n.method||n.type||p.method||p.type,p.dataTypes=x.trim(p.dataType||"*").toLowerCase().match(T)||[""],null==p.crossDomain&&(r=En.exec(p.url.toLowerCase()),p.crossDomain=!(!r||r[1]===mn[1]&&r[2]===mn[2]&&(r[3]||("http:"===r[1]?"80":"443"))===(mn[3]||("http:"===mn[1]?"80":"443")))),p.data&&p.processData&&"string"!=typeof p.data&&(p.data=x.param(p.data,p.traditional)),qn(An,p,n,C),2===b)return C;l=p.global,l&&0===x.active++&&x.event.trigger("ajaxStart"),p.type=p.type.toUpperCase(),p.hasContent=!Nn.test(p.type),o=p.url,p.hasContent||(p.data&&(o=p.url+=(bn.test(o)?"&":"?")+p.data,delete p.data),p.cache===!1&&(p.url=wn.test(o)?o.replace(wn,"$1_="+vn++):o+(bn.test(o)?"&":"?")+"_="+vn++)),p.ifModified&&(x.lastModified[o]&&C.setRequestHeader("If-Modified-Since",x.lastModified[o]),x.etag[o]&&C.setRequestHeader("If-None-Match",x.etag[o])),(p.data&&p.hasContent&&p.contentType!==!1||n.contentType)&&C.setRequestHeader("Content-Type",p.contentType),C.setRequestHeader("Accept",p.dataTypes[0]&&p.accepts[p.dataTypes[0]]?p.accepts[p.dataTypes[0]]+("*"!==p.dataTypes[0]?", "+Dn+"; q=0.01":""):p.accepts["*"]);for(i in p.headers)C.setRequestHeader(i,p.headers[i]);if(p.beforeSend&&(p.beforeSend.call(f,C,p)===!1||2===b))return C.abort();w="abort";for(i in{success:1,error:1,complete:1})C[i](p[i]);if(u=qn(jn,p,n,C)){C.readyState=1,l&&d.trigger("ajaxSend",[C,p]),p.async&&p.timeout>0&&(s=setTimeout(function(){C.abort("timeout")},p.timeout));try{b=1,u.send(y,k)}catch(N){if(!(2>b))throw N;k(-1,N)}}else k(-1,"No Transport");function k(e,n,r,i){var c,y,v,w,T,N=n;2!==b&&(b=2,s&&clearTimeout(s),u=t,a=i||"",C.readyState=e>0?4:0,c=e>=200&&300>e||304===e,r&&(w=Mn(p,C,r)),w=On(p,w,C,c),c?(p.ifModified&&(T=C.getResponseHeader("Last-Modified"),T&&(x.lastModified[o]=T),T=C.getResponseHeader("etag"),T&&(x.etag[o]=T)),204===e||"HEAD"===p.type?N="nocontent":304===e?N="notmodified":(N=w.state,y=w.data,v=w.error,c=!v)):(v=N,(e||!N)&&(N="error",0>e&&(e=0))),C.status=e,C.statusText=(n||N)+"",c?h.resolveWith(f,[y,N,C]):h.rejectWith(f,[C,N,v]),C.statusCode(m),m=t,l&&d.trigger(c?"ajaxSuccess":"ajaxError",[C,p,c?y:v]),g.fireWith(f,[C,N]),l&&(d.trigger("ajaxComplete",[C,p]),--x.active||x.event.trigger("ajaxStop")))}return C},getJSON:function(e,t,n){return x.get(e,t,n,"json")},getScript:function(e,n){return x.get(e,t,n,"script")}}),x.each(["get","post"],function(e,n){x[n]=function(e,r,i,o){return x.isFunction(r)&&(o=o||i,i=r,r=t),x.ajax({url:e,type:n,dataType:o,data:r,success:i})}});function Mn(e,n,r){var i,o,a,s,l=e.contents,u=e.dataTypes;while("*"===u[0])u.shift(),o===t&&(o=e.mimeType||n.getResponseHeader("Content-Type"));if(o)for(s in l)if(l[s]&&l[s].test(o)){u.unshift(s);break}if(u[0]in r)a=u[0];else{for(s in r){if(!u[0]||e.converters[s+" "+u[0]]){a=s;break}i||(i=s)}a=a||i}return a?(a!==u[0]&&u.unshift(a),r[a]):t}function On(e,t,n,r){var i,o,a,s,l,u={},c=e.dataTypes.slice();if(c[1])for(a in e.converters)u[a.toLowerCase()]=e.converters[a];o=c.shift();while(o)if(e.responseFields[o]&&(n[e.responseFields[o]]=t),!l&&r&&e.dataFilter&&(t=e.dataFilter(t,e.dataType)),l=o,o=c.shift())if("*"===o)o=l;else if("*"!==l&&l!==o){if(a=u[l+" "+o]||u["* "+o],!a)for(i in u)if(s=i.split(" "),s[1]===o&&(a=u[l+" "+s[0]]||u["* "+s[0]])){a===!0?a=u[i]:u[i]!==!0&&(o=s[0],c.unshift(s[1]));break}if(a!==!0)if(a&&e["throws"])t=a(t);else try{t=a(t)}catch(p){return{state:"parsererror",error:a?p:"No conversion from "+l+" to "+o}}}return{state:"success",data:t}}x.ajaxSetup({accepts:{script:"text/javascript, application/javascript, application/ecmascript, application/x-ecmascript"},contents:{script:/(?:java|ecma)script/},converters:{"text script":function(e){return x.globalEval(e),e}}}),x.ajaxPrefilter("script",function(e){e.cache===t&&(e.cache=!1),e.crossDomain&&(e.type="GET",e.global=!1)}),x.ajaxTransport("script",function(e){if(e.crossDomain){var n,r=a.head||x("head")[0]||a.documentElement;return{send:function(t,i){n=a.createElement("script"),n.async=!0,e.scriptCharset&&(n.charset=e.scriptCharset),n.src=e.url,n.onload=n.onreadystatechange=function(e,t){(t||!n.readyState||/loaded|complete/.test(n.readyState))&&(n.onload=n.onreadystatechange=null,n.parentNode&&n.parentNode.removeChild(n),n=null,t||i(200,"success"))},r.insertBefore(n,r.firstChild)},abort:function(){n&&n.onload(t,!0)}}}});var Fn=[],Bn=/(=)\?(?=&|$)|\?\?/;x.ajaxSetup({jsonp:"callback",jsonpCallback:function(){var e=Fn.pop()||x.expando+"_"+vn++;return this[e]=!0,e}}),x.ajaxPrefilter("json jsonp",function(n,r,i){var o,a,s,l=n.jsonp!==!1&&(Bn.test(n.url)?"url":"string"==typeof n.data&&!(n.contentType||"").indexOf("application/x-www-form-urlencoded")&&Bn.test(n.data)&&"data");return l||"jsonp"===n.dataTypes[0]?(o=n.jsonpCallback=x.isFunction(n.jsonpCallback)?n.jsonpCallback():n.jsonpCallback,l?n[l]=n[l].replace(Bn,"$1"+o):n.jsonp!==!1&&(n.url+=(bn.test(n.url)?"&":"?")+n.jsonp+"="+o),n.converters["script json"]=function(){return s||x.error(o+" was not called"),s[0]},n.dataTypes[0]="json",a=e[o],e[o]=function(){s=arguments},i.always(function(){e[o]=a,n[o]&&(n.jsonpCallback=r.jsonpCallback,Fn.push(o)),s&&x.isFunction(a)&&a(s[0]),s=a=t}),"script"):t});var Pn,Rn,Wn=0,$n=e.ActiveXObject&&function(){var e;for(e in Pn)Pn[e](t,!0)};function In(){try{return new e.XMLHttpRequest}catch(t){}}function zn(){try{return new e.ActiveXObject("Microsoft.XMLHTTP")}catch(t){}}x.ajaxSettings.xhr=e.ActiveXObject?function(){return!this.isLocal&&In()||zn()}:In,Rn=x.ajaxSettings.xhr(),x.support.cors=!!Rn&&"withCredentials"in Rn,Rn=x.support.ajax=!!Rn,Rn&&x.ajaxTransport(function(n){if(!n.crossDomain||x.support.cors){var r;return{send:function(i,o){var a,s,l=n.xhr();if(n.username?l.open(n.type,n.url,n.async,n.username,n.password):l.open(n.type,n.url,n.async),n.xhrFields)for(s in n.xhrFields)l[s]=n.xhrFields[s];n.mimeType&&l.overrideMimeType&&l.overrideMimeType(n.mimeType),n.crossDomain||i["X-Requested-With"]||(i["X-Requested-With"]="XMLHttpRequest");try{for(s in i)l.setRequestHeader(s,i[s])}catch(u){}l.send(n.hasContent&&n.data||null),r=function(e,i){var s,u,c,p;try{if(r&&(i||4===l.readyState))if(r=t,a&&(l.onreadystatechange=x.noop,$n&&delete Pn[a]),i)4!==l.readyState&&l.abort();else{p={},s=l.status,u=l.getAllResponseHeaders(),"string"==typeof l.responseText&&(p.text=l.responseText);try{c=l.statusText}catch(f){c=""}s||!n.isLocal||n.crossDomain?1223===s&&(s=204):s=p.text?200:404}}catch(d){i||o(-1,d)}p&&o(s,c,p,u)},n.async?4===l.readyState?setTimeout(r):(a=++Wn,$n&&(Pn||(Pn={},x(e).unload($n)),Pn[a]=r),l.onreadystatechange=r):r()},abort:function(){r&&r(t,!0)}}}});var Xn,Un,Vn=/^(?:toggle|show|hide)$/,Yn=RegExp("^(?:([+-])=|)("+w+")([a-z%]*)$","i"),Jn=/queueHooks$/,Gn=[nr],Qn={"*":[function(e,t){var n=this.createTween(e,t),r=n.cur(),i=Yn.exec(t),o=i&&i[3]||(x.cssNumber[e]?"":"px"),a=(x.cssNumber[e]||"px"!==o&&+r)&&Yn.exec(x.css(n.elem,e)),s=1,l=20;if(a&&a[3]!==o){o=o||a[3],i=i||[],a=+r||1;do s=s||".5",a/=s,x.style(n.elem,e,a+o);while(s!==(s=n.cur()/r)&&1!==s&&--l)}return i&&(a=n.start=+a||+r||0,n.unit=o,n.end=i[1]?a+(i[1]+1)*i[2]:+i[2]),n}]};function Kn(){return setTimeout(function(){Xn=t}),Xn=x.now()}function Zn(e,t,n){var r,i=(Qn[t]||[]).concat(Qn["*"]),o=0,a=i.length;for(;a>o;o++)if(r=i[o].call(n,t,e))return r}function er(e,t,n){var r,i,o=0,a=Gn.length,s=x.Deferred().always(function(){delete l.elem}),l=function(){if(i)return!1;var t=Xn||Kn(),n=Math.max(0,u.startTime+u.duration-t),r=n/u.duration||0,o=1-r,a=0,l=u.tweens.length;for(;l>a;a++)u.tweens[a].run(o);return s.notifyWith(e,[u,o,n]),1>o&&l?n:(s.resolveWith(e,[u]),!1)},u=s.promise({elem:e,props:x.extend({},t),opts:x.extend(!0,{specialEasing:{}},n),originalProperties:t,originalOptions:n,startTime:Xn||Kn(),duration:n.duration,tweens:[],createTween:function(t,n){var r=x.Tween(e,u.opts,t,n,u.opts.specialEasing[t]||u.opts.easing);return u.tweens.push(r),r},stop:function(t){var n=0,r=t?u.tweens.length:0;if(i)return this;for(i=!0;r>n;n++)u.tweens[n].run(1);return t?s.resolveWith(e,[u,t]):s.rejectWith(e,[u,t]),this}}),c=u.props;for(tr(c,u.opts.specialEasing);a>o;o++)if(r=Gn[o].call(u,e,c,u.opts))return r;return x.map(c,Zn,u),x.isFunction(u.opts.start)&&u.opts.start.call(e,u),x.fx.timer(x.extend(l,{elem:e,anim:u,queue:u.opts.queue})),u.progress(u.opts.progress).done(u.opts.done,u.opts.complete).fail(u.opts.fail).always(u.opts.always)}function tr(e,t){var n,r,i,o,a;for(n in e)if(r=x.camelCase(n),i=t[r],o=e[n],x.isArray(o)&&(i=o[1],o=e[n]=o[0]),n!==r&&(e[r]=o,delete e[n]),a=x.cssHooks[r],a&&"expand"in a){o=a.expand(o),delete e[r];for(n in o)n in e||(e[n]=o[n],t[n]=i)}else t[r]=i}x.Animation=x.extend(er,{tweener:function(e,t){x.isFunction(e)?(t=e,e=["*"]):e=e.split(" ");var n,r=0,i=e.length;for(;i>r;r++)n=e[r],Qn[n]=Qn[n]||[],Qn[n].unshift(t)},prefilter:function(e,t){t?Gn.unshift(e):Gn.push(e)}});function nr(e,t,n){var r,i,o,a,s,l,u=this,c={},p=e.style,f=e.nodeType&&nn(e),d=x._data(e,"fxshow");n.queue||(s=x._queueHooks(e,"fx"),null==s.unqueued&&(s.unqueued=0,l=s.empty.fire,s.empty.fire=function(){s.unqueued||l()}),s.unqueued++,u.always(function(){u.always(function(){s.unqueued--,x.queue(e,"fx").length||s.empty.fire()})})),1===e.nodeType&&("height"in t||"width"in t)&&(n.overflow=[p.overflow,p.overflowX,p.overflowY],"inline"===x.css(e,"display")&&"none"===x.css(e,"float")&&(x.support.inlineBlockNeedsLayout&&"inline"!==ln(e.nodeName)?p.zoom=1:p.display="inline-block")),n.overflow&&(p.overflow="hidden",x.support.shrinkWrapBlocks||u.always(function(){p.overflow=n.overflow[0],p.overflowX=n.overflow[1],p.overflowY=n.overflow[2]}));for(r in t)if(i=t[r],Vn.exec(i)){if(delete t[r],o=o||"toggle"===i,i===(f?"hide":"show"))continue;c[r]=d&&d[r]||x.style(e,r)}if(!x.isEmptyObject(c)){d?"hidden"in d&&(f=d.hidden):d=x._data(e,"fxshow",{}),o&&(d.hidden=!f),f?x(e).show():u.done(function(){x(e).hide()}),u.done(function(){var t;x._removeData(e,"fxshow");for(t in c)x.style(e,t,c[t])});for(r in c)a=Zn(f?d[r]:0,r,u),r in d||(d[r]=a.start,f&&(a.end=a.start,a.start="width"===r||"height"===r?1:0))}}function rr(e,t,n,r,i){return new rr.prototype.init(e,t,n,r,i)}x.Tween=rr,rr.prototype={constructor:rr,init:function(e,t,n,r,i,o){this.elem=e,this.prop=n,this.easing=i||"swing",this.options=t,this.start=this.now=this.cur(),this.end=r,this.unit=o||(x.cssNumber[n]?"":"px")},cur:function(){var e=rr.propHooks[this.prop];return e&&e.get?e.get(this):rr.propHooks._default.get(this)},run:function(e){var t,n=rr.propHooks[this.prop];return this.pos=t=this.options.duration?x.easing[this.easing](e,this.options.duration*e,0,1,this.options.duration):e,this.now=(this.end-this.start)*t+this.start,this.options.step&&this.options.step.call(this.elem,this.now,this),n&&n.set?n.set(this):rr.propHooks._default.set(this),this}},rr.prototype.init.prototype=rr.prototype,rr.propHooks={_default:{get:function(e){var t;return null==e.elem[e.prop]||e.elem.style&&null!=e.elem.style[e.prop]?(t=x.css(e.elem,e.prop,""),t&&"auto"!==t?t:0):e.elem[e.prop]},set:function(e){x.fx.step[e.prop]?x.fx.step[e.prop](e):e.elem.style&&(null!=e.elem.style[x.cssProps[e.prop]]||x.cssHooks[e.prop])?x.style(e.elem,e.prop,e.now+e.unit):e.elem[e.prop]=e.now}}},rr.propHooks.scrollTop=rr.propHooks.scrollLeft={set:function(e){e.elem.nodeType&&e.elem.parentNode&&(e.elem[e.prop]=e.now)}},x.each(["toggle","show","hide"],function(e,t){var n=x.fn[t];x.fn[t]=function(e,r,i){return null==e||"boolean"==typeof e?n.apply(this,arguments):this.animate(ir(t,!0),e,r,i)}}),x.fn.extend({fadeTo:function(e,t,n,r){return this.filter(nn).css("opacity",0).show().end().animate({opacity:t},e,n,r)},animate:function(e,t,n,r){var i=x.isEmptyObject(e),o=x.speed(t,n,r),a=function(){var t=er(this,x.extend({},e),o);(i||x._data(this,"finish"))&&t.stop(!0)};return a.finish=a,i||o.queue===!1?this.each(a):this.queue(o.queue,a)},stop:function(e,n,r){var i=function(e){var t=e.stop;delete e.stop,t(r)};return"string"!=typeof e&&(r=n,n=e,e=t),n&&e!==!1&&this.queue(e||"fx",[]),this.each(function(){var t=!0,n=null!=e&&e+"queueHooks",o=x.timers,a=x._data(this);if(n)a[n]&&a[n].stop&&i(a[n]);else for(n in a)a[n]&&a[n].stop&&Jn.test(n)&&i(a[n]);for(n=o.length;n--;)o[n].elem!==this||null!=e&&o[n].queue!==e||(o[n].anim.stop(r),t=!1,o.splice(n,1));(t||!r)&&x.dequeue(this,e)})},finish:function(e){return e!==!1&&(e=e||"fx"),this.each(function(){var t,n=x._data(this),r=n[e+"queue"],i=n[e+"queueHooks"],o=x.timers,a=r?r.length:0;for(n.finish=!0,x.queue(this,e,[]),i&&i.stop&&i.stop.call(this,!0),t=o.length;t--;)o[t].elem===this&&o[t].queue===e&&(o[t].anim.stop(!0),o.splice(t,1));for(t=0;a>t;t++)r[t]&&r[t].finish&&r[t].finish.call(this);delete n.finish})}});function ir(e,t){var n,r={height:e},i=0;for(t=t?1:0;4>i;i+=2-t)n=Zt[i],r["margin"+n]=r["padding"+n]=e;return t&&(r.opacity=r.width=e),r}x.each({slideDown:ir("show"),slideUp:ir("hide"),slideToggle:ir("toggle"),fadeIn:{opacity:"show"},fadeOut:{opacity:"hide"},fadeToggle:{opacity:"toggle"}},function(e,t){x.fn[e]=function(e,n,r){return this.animate(t,e,n,r)}}),x.speed=function(e,t,n){var r=e&&"object"==typeof e?x.extend({},e):{complete:n||!n&&t||x.isFunction(e)&&e,duration:e,easing:n&&t||t&&!x.isFunction(t)&&t};return r.duration=x.fx.off?0:"number"==typeof r.duration?r.duration:r.duration in x.fx.speeds?x.fx.speeds[r.duration]:x.fx.speeds._default,(null==r.queue||r.queue===!0)&&(r.queue="fx"),r.old=r.complete,r.complete=function(){x.isFunction(r.old)&&r.old.call(this),r.queue&&x.dequeue(this,r.queue)},r},x.easing={linear:function(e){return e},swing:function(e){return.5-Math.cos(e*Math.PI)/2}},x.timers=[],x.fx=rr.prototype.init,x.fx.tick=function(){var e,n=x.timers,r=0;for(Xn=x.now();n.length>r;r++)e=n[r],e()||n[r]!==e||n.splice(r--,1);n.length||x.fx.stop(),Xn=t},x.fx.timer=function(e){e()&&x.timers.push(e)&&x.fx.start()},x.fx.interval=13,x.fx.start=function(){Un||(Un=setInterval(x.fx.tick,x.fx.interval))},x.fx.stop=function(){clearInterval(Un),Un=null},x.fx.speeds={slow:600,fast:200,_default:400},x.fx.step={},x.expr&&x.expr.filters&&(x.expr.filters.animated=function(e){return x.grep(x.timers,function(t){return e===t.elem}).length}),x.fn.offset=function(e){if(arguments.length)return e===t?this:this.each(function(t){x.offset.setOffset(this,e,t)});var n,r,o={top:0,left:0},a=this[0],s=a&&a.ownerDocument;if(s)return n=s.documentElement,x.contains(n,a)?(typeof a.getBoundingClientRect!==i&&(o=a.getBoundingClientRect()),r=or(s),{top:o.top+(r.pageYOffset||n.scrollTop)-(n.clientTop||0),left:o.left+(r.pageXOffset||n.scrollLeft)-(n.clientLeft||0)}):o},x.offset={setOffset:function(e,t,n){var r=x.css(e,"position");"static"===r&&(e.style.position="relative");var i=x(e),o=i.offset(),a=x.css(e,"top"),s=x.css(e,"left"),l=("absolute"===r||"fixed"===r)&&x.inArray("auto",[a,s])>-1,u={},c={},p,f;l?(c=i.position(),p=c.top,f=c.left):(p=parseFloat(a)||0,f=parseFloat(s)||0),x.isFunction(t)&&(t=t.call(e,n,o)),null!=t.top&&(u.top=t.top-o.top+p),null!=t.left&&(u.left=t.left-o.left+f),"using"in t?t.using.call(e,u):i.css(u)}},x.fn.extend({position:function(){if(this[0]){var e,t,n={top:0,left:0},r=this[0];return"fixed"===x.css(r,"position")?t=r.getBoundingClientRect():(e=this.offsetParent(),t=this.offset(),x.nodeName(e[0],"html")||(n=e.offset()),n.top+=x.css(e[0],"borderTopWidth",!0),n.left+=x.css(e[0],"borderLeftWidth",!0)),{top:t.top-n.top-x.css(r,"marginTop",!0),left:t.left-n.left-x.css(r,"marginLeft",!0)}}},offsetParent:function(){return this.map(function(){var e=this.offsetParent||s;while(e&&!x.nodeName(e,"html")&&"static"===x.css(e,"position"))e=e.offsetParent;return e||s})}}),x.each({scrollLeft:"pageXOffset",scrollTop:"pageYOffset"},function(e,n){var r=/Y/.test(n);x.fn[e]=function(i){return x.access(this,function(e,i,o){var a=or(e);return o===t?a?n in a?a[n]:a.document.documentElement[i]:e[i]:(a?a.scrollTo(r?x(a).scrollLeft():o,r?o:x(a).scrollTop()):e[i]=o,t)},e,i,arguments.length,null)}});function or(e){return x.isWindow(e)?e:9===e.nodeType?e.defaultView||e.parentWindow:!1}x.each({Height:"height",Width:"width"},function(e,n){x.each({padding:"inner"+e,content:n,"":"outer"+e},function(r,i){x.fn[i]=function(i,o){var a=arguments.length&&(r||"boolean"!=typeof i),s=r||(i===!0||o===!0?"margin":"border");return x.access(this,function(n,r,i){var o;return x.isWindow(n)?n.document.documentElement["client"+e]:9===n.nodeType?(o=n.documentElement,Math.max(n.body["scroll"+e],o["scroll"+e],n.body["offset"+e],o["offset"+e],o["client"+e])):i===t?x.css(n,r,s):x.style(n,r,i,s)},n,a?i:t,a,null)}})}),x.fn.size=function(){return this.length},x.fn.andSelf=x.fn.addBack,"object"==typeof module&&module&&"object"==typeof module.exports?module.exports=x:(e.jQuery=e.$=x,"function"==typeof define&&define.amd&&define("jquery",[],function(){return x}))})(window);
ajax/libs/forerunnerdb/1.3.840/fdb-legacy.min.js
tholu/cdnjs
!function a(b,c,d){function e(g,h){if(!c[g]){if(!b[g]){var i="function"==typeof require&&require;if(!h&&i)return i(g,!0);if(f)return f(g,!0);var j=new Error("Cannot find module '"+g+"'");throw j.code="MODULE_NOT_FOUND",j}var k=c[g]={exports:{}};b[g][0].call(k.exports,function(a){var c=b[g][1][a];return e(c?c:a)},k,k.exports,a,b,c,d)}return c[g].exports}for(var f="function"==typeof require&&require,g=0;g<d.length;g++)e(d[g]);return e}({1:[function(a,b,c){var d=a("../lib/Core");a("../lib/CollectionGroup"),a("../lib/View"),a("../lib/Highchart"),a("../lib/Persist"),a("../lib/Document"),a("../lib/Overview"),a("../lib/OldView"),a("../lib/OldView.Bind"),a("../lib/Grid");"undefined"!=typeof window&&(window.ForerunnerDB=d),b.exports=d},{"../lib/CollectionGroup":6,"../lib/Core":8,"../lib/Document":10,"../lib/Grid":12,"../lib/Highchart":13,"../lib/OldView":30,"../lib/OldView.Bind":29,"../lib/Overview":33,"../lib/Persist":35,"../lib/View":41}],2:[function(a,b,c){"use strict";var d,e=a("./Shared"),f=a("./Path"),g=function(a){this._primaryKey="_id",this._keyArr=[],this._data=[],this._objLookup={},this._count=0,this._keyArr=d.parse(a,!0)};e.addModule("ActiveBucket",g),e.mixin(g.prototype,"Mixin.Sorting"),d=new f,e.synthesize(g.prototype,"primaryKey"),g.prototype.qs=function(a,b,c,d){if(!b.length)return 0;for(var e,f,g,h=-1,i=0,j=b.length-1;j>=i&&(e=Math.floor((i+j)/2),h!==e);)f=b[e],void 0!==f&&(g=d(this,a,c,f),g>0&&(i=e+1),0>g&&(j=e-1)),h=e;return g>0?e+1:e},g.prototype._sortFunc=function(a,b,c,e){var f,g,h,i=c.split(".:."),j=e.split(".:."),k=a._keyArr,l=k.length;for(f=0;l>f;f++)if(g=k[f],h=typeof d.get(b,g.path),"number"===h&&(i[f]=Number(i[f]),j[f]=Number(j[f])),i[f]!==j[f]){if(1===g.value)return a.sortAsc(i[f],j[f]);if(-1===g.value)return a.sortDesc(i[f],j[f])}},g.prototype.insert=function(a){var b,c;return b=this.documentKey(a),c=this._data.indexOf(b),-1===c?(c=this.qs(a,this._data,b,this._sortFunc),this._data.splice(c,0,b)):this._data.splice(c,0,b),this._objLookup[a[this._primaryKey]]=b,this._count++,c},g.prototype.remove=function(a){var b,c;return b=this._objLookup[a[this._primaryKey]],b?(c=this._data.indexOf(b),c>-1?(this._data.splice(c,1),delete this._objLookup[a[this._primaryKey]],this._count--,!0):!1):!1},g.prototype.index=function(a){var b,c;return b=this.documentKey(a),c=this._data.indexOf(b),-1===c&&(c=this.qs(a,this._data,b,this._sortFunc)),c},g.prototype.documentKey=function(a){var b,c,e="",f=this._keyArr,g=f.length;for(b=0;g>b;b++)c=f[b],e&&(e+=".:."),e+=d.get(a,c.path);return e+=".:."+a[this._primaryKey]},g.prototype.count=function(){return this._count},e.finishModule("ActiveBucket"),b.exports=g},{"./Path":34,"./Shared":40}],3:[function(a,b,c){"use strict";var d=a("./Shared"),e=a("./Path"),f=new e,g=function(a,b,c){this.init.apply(this,arguments)};g.prototype.init=function(a,b,c,d,e){this._store=[],this._keys=[],void 0!==c&&this.primaryKey(c),void 0!==b&&this.index(b),void 0!==d&&this.compareFunc(d),void 0!==e&&this.hashFunc(e),void 0!==a&&this.data(a)},d.addModule("BinaryTree",g),d.mixin(g.prototype,"Mixin.ChainReactor"),d.mixin(g.prototype,"Mixin.Sorting"),d.mixin(g.prototype,"Mixin.Common"),d.synthesize(g.prototype,"compareFunc"),d.synthesize(g.prototype,"hashFunc"),d.synthesize(g.prototype,"indexDir"),d.synthesize(g.prototype,"primaryKey"),d.synthesize(g.prototype,"keys"),d.synthesize(g.prototype,"index",function(a){return void 0!==a&&(this.debug()&&console.log("Setting index",a,f.parse(a,!0)),this.keys(f.parse(a,!0))),this.$super.call(this,a)}),g.prototype.clear=function(){delete this._data,delete this._left,delete this._right,this._store=[]},g.prototype.data=function(a){return void 0!==a?(this._data=a,this._hashFunc&&(this._hash=this._hashFunc(a)),this):this._data},g.prototype.push=function(a){return void 0!==a?(this._store.push(a),this):!1},g.prototype.pull=function(a){if(void 0!==a){var b=this._store.indexOf(a);if(b>-1)return this._store.splice(b,1),this}return!1},g.prototype._compareFunc=function(a,b){var c,d,e=0;for(c=0;c<this._keys.length;c++)if(d=this._keys[c],1===d.value?e=this.sortAsc(f.get(a,d.path),f.get(b,d.path)):-1===d.value&&(e=this.sortDesc(f.get(a,d.path),f.get(b,d.path))),this.debug()&&console.log("Compared %s with %s order %d in path %s and result was %d",f.get(a,d.path),f.get(b,d.path),d.value,d.path,e),0!==e)return this.debug()&&console.log("Retuning result %d",e),e;return this.debug()&&console.log("Retuning result %d",e),e},g.prototype._hashFunc=function(a){return a[this._keys[0].path]},g.prototype.removeChildNode=function(a){this._left===a?delete this._left:this._right===a&&delete this._right},g.prototype.nodeBranch=function(a){return this._left===a?"left":this._right===a?"right":void 0},g.prototype.insert=function(a){var b,c,d,e;if(a instanceof Array){for(c=[],d=[],e=0;e<a.length;e++)this.insert(a[e])?c.push(a[e]):d.push(a[e]);return{inserted:c,failed:d}}return this.debug()&&console.log("Inserting",a),this._data?(b=this._compareFunc(this._data,a),0===b?(this.debug()&&console.log("Data is equal (currrent, new)",this._data,a),this._left?this._left.insert(a):(this._left=new g(a,this._index,this._binaryTree,this._compareFunc,this._hashFunc),this._left._parent=this),!0):-1===b?(this.debug()&&console.log("Data is greater (currrent, new)",this._data,a),this._right?this._right.insert(a):(this._right=new g(a,this._index,this._binaryTree,this._compareFunc,this._hashFunc),this._right._parent=this),!0):1===b?(this.debug()&&console.log("Data is less (currrent, new)",this._data,a),this._left?this._left.insert(a):(this._left=new g(a,this._index,this._binaryTree,this._compareFunc,this._hashFunc),this._left._parent=this),!0):!1):(this.debug()&&console.log("Node has no data, setting data",a),this.data(a),!0)},g.prototype.remove=function(a){var b,c,d,e=this.primaryKey();if(a instanceof Array){for(c=[],d=0;d<a.length;d++)this.remove(a[d])&&c.push(a[d]);return c}return this.debug()&&console.log("Removing",a),this._data[e]===a[e]?this._remove(this):(b=this._compareFunc(this._data,a),-1===b&&this._right?this._right.remove(a):1===b&&this._left?this._left.remove(a):!1)},g.prototype._remove=function(a){var b,c;return this._left?(b=this._left,c=this._right,this._left=b._left,this._right=b._right,this._data=b._data,this._store=b._store,c&&(b.rightMost()._right=c)):this._right?(c=this._right,this._left=c._left,this._right=c._right,this._data=c._data,this._store=c._store):this.clear(),!0},g.prototype.leftMost=function(){return this._left?this._left.leftMost():this},g.prototype.rightMost=function(){return this._right?this._right.rightMost():this},g.prototype.lookup=function(a,b,c,d){var e=this._compareFunc(this._data,a);return d=d||[],0===e&&(this._left&&this._left.lookup(a,b,c,d),d.push(this._data),this._right&&this._right.lookup(a,b,c,d)),-1===e&&this._right&&this._right.lookup(a,b,c,d),1===e&&this._left&&this._left.lookup(a,b,c,d),d},g.prototype.inOrder=function(a,b){switch(b=b||[],this._left&&this._left.inOrder(a,b),a){case"hash":b.push(this._hash);break;case"data":b.push(this._data);break;default:b.push({key:this._data,arr:this._store})}return this._right&&this._right.inOrder(a,b),b},g.prototype.startsWith=function(a,b,c,d){var e,g,h=f.get(this._data,a),i=h.substr(0,b.length);return d=d||[],void 0===d._visitedCount&&(d._visitedCount=0),d._visitedCount++,d._visitedNodes=d._visitedNodes||[],d._visitedNodes.push(h),g=this.sortAsc(i,b),e=i===b,0===g&&(this._left&&this._left.startsWith(a,b,c,d),e&&d.push(this._data),this._right&&this._right.startsWith(a,b,c,d)),-1===g&&(e&&d.push(this._data),this._right&&this._right.startsWith(a,b,c,d)),1===g&&(this._left&&this._left.startsWith(a,b,c,d),e&&d.push(this._data)),d},g.prototype.findRange=function(a,b,c,d,f,g){f=f||[],g=g||new e(b),this._left&&this._left.findRange(a,b,c,d,f,g);var h=g.value(this._data),i=this.sortAsc(h,c),j=this.sortAsc(h,d);if(!(0!==i&&1!==i||0!==j&&-1!==j))switch(a){case"hash":f.push(this._hash);break;case"data":f.push(this._data);break;default:f.push({key:this._data,arr:this._store})}return this._right&&this._right.findRange(a,b,c,d,f,g),f},g.prototype.match=function(a,b,c){var d,e,g,h=[],i=0;for(d=f.parseArr(this._index,{verbose:!0}),e=f.parseArr(a,c&&c.pathOptions?c.pathOptions:{ignore:/\$/,verbose:!0}),g=0;g<d.length;g++)e[g]===d[g]&&(i++,h.push(e[g]));return{matchedKeys:h,totalKeyCount:e.length,score:i}},d.finishModule("BinaryTree"),b.exports=g},{"./Path":34,"./Shared":40}],4:[function(a,b,c){"use strict";var d,e;d=function(){var a,b,c,d=[];for(b=0;256>b;b++){for(a=b,c=0;8>c;c++)a=1&a?3988292384^a>>>1:a>>>1;d[b]=a}return d}(),e=function(a){var b,c=-1;for(b=0;b<a.length;b++)c=c>>>8^d[255&(c^a.charCodeAt(b))];return(-1^c)>>>0},b.exports=e},{}],5:[function(a,b,c){"use strict";var d,e,f,g,h,i,j,k,l,m,n,o;d=a("./Shared");var p=function(a,b){this.init.apply(this,arguments)};p.prototype.init=function(a,b){this.sharedPathSolver=o,this._primaryKey="_id",this._primaryIndex=new g("primary"),this._primaryCrc=new g("primaryCrc"),this._crcLookup=new g("crcLookup"),this._name=a,this._data=[],this._metrics=new f,this._options=b||{changeTimestamp:!1},this._options.db&&this.db(this._options.db),this._metaData={},this._deferQueue={insert:[],update:[],remove:[],upsert:[],async:[]},this._deferThreshold={insert:100,update:100,remove:100,upsert:100},this._deferTime={insert:1,update:1,remove:1,upsert:1},this._deferredCalls=!0,this.subsetOf(this)},d.addModule("Collection",p),d.mixin(p.prototype,"Mixin.Common"),d.mixin(p.prototype,"Mixin.Events"),d.mixin(p.prototype,"Mixin.ChainReactor"),d.mixin(p.prototype,"Mixin.CRUD"),d.mixin(p.prototype,"Mixin.Constants"),d.mixin(p.prototype,"Mixin.Triggers"),d.mixin(p.prototype,"Mixin.Sorting"),d.mixin(p.prototype,"Mixin.Matching"),d.mixin(p.prototype,"Mixin.Updating"),d.mixin(p.prototype,"Mixin.Tags"),f=a("./Metrics"),g=a("./KeyValueStore"),h=a("./Path"),i=a("./IndexHashMap"),j=a("./IndexBinaryTree"),k=a("./Index2d"),e=d.modules.Db,l=a("./Overload"),m=a("./ReactorIO"),n=a("./Condition"),o=new h,d.synthesize(p.prototype,"deferredCalls"),d.synthesize(p.prototype,"state"),d.synthesize(p.prototype,"name"),d.synthesize(p.prototype,"metaData"),d.synthesize(p.prototype,"capped"),d.synthesize(p.prototype,"cappedSize"),p.prototype._asyncPending=function(a){this._deferQueue.async.push(a)},p.prototype._asyncComplete=function(a){for(var b=this._deferQueue.async.indexOf(a);b>-1;)this._deferQueue.async.splice(b,1),b=this._deferQueue.async.indexOf(a);0===this._deferQueue.async.length&&this.deferEmit("ready")},p.prototype.data=function(){return this._data},p.prototype.drop=function(a){var b;if(this.isDropped())return a&&a.call(this,!1,!0),!0;if(this._db&&this._db._collection&&this._name){if(this.debug()&&console.log(this.logIdentifier()+" Dropping"),this._state="dropped",this.emit("drop",this),delete this._db._collection[this._name],this._collate)for(b in this._collate)this._collate.hasOwnProperty(b)&&this.collateRemove(b);return delete this._primaryKey,delete this._primaryIndex,delete this._primaryCrc,delete this._crcLookup,delete this._data,delete this._metrics,delete this._listeners,a&&a.call(this,!1,!0),!0}return a&&a.call(this,!1,!0),!1},p.prototype.primaryKey=function(a){if(void 0!==a){if(this._primaryKey!==a){var b=this._primaryKey;this._primaryKey=a,this._primaryIndex.primaryKey(a),this.rebuildPrimaryKeyIndex(),this.chainSend("primaryKey",{keyName:a,oldData:b})}return this}return this._primaryKey},p.prototype._onInsert=function(a,b){this.emit("insert",a,b)},p.prototype._onUpdate=function(a){this.emit("update",a)},p.prototype._onRemove=function(a){this.emit("remove",a)},p.prototype._onChange=function(){this._options.changeTimestamp&&(this._metaData.lastChange=this.serialiser.convert(new Date))},d.synthesize(p.prototype,"db",function(a){return a&&"_id"===this.primaryKey()&&(this.primaryKey(a.primaryKey()),this.debug(a.debug())),this.$super.apply(this,arguments)}),d.synthesize(p.prototype,"mongoEmulation"),p.prototype.setData=new l("Collection.prototype.setData",{"*":function(a){return this.$main.call(this,a,{})},"*, object":function(a,b){return this.$main.call(this,a,b)},"*, function":function(a,b){return this.$main.call(this,a,{},b)},"*, *, function":function(a,b,c){return this.$main.call(this,a,b,c)},"*, *, *":function(a,b,c){return this.$main.call(this,a,b,c)},$main:function(a,b,c){if(this.isDropped())throw this.logIdentifier()+" Cannot operate in a dropped state!";if(a){var d=this.deferredCalls(),e=[].concat(this._data);this.deferredCalls(!1),b=this.options(b),b.$decouple&&(a=this.decouple(a)),a instanceof Array||(a=[a]),this.remove({}),this.insert(a),this.deferredCalls(d),this._onChange(),this.emit("setData",this._data,e)}return c&&c.call(this),this}}),p.prototype.rebuildPrimaryKeyIndex=function(a){a=a||{$ensureKeys:void 0,$violationCheck:void 0};var b,c,d,e,f=a&&void 0!==a.$ensureKeys?a.$ensureKeys:!0,g=a&&void 0!==a.$violationCheck?a.$violationCheck:!0,h=this._primaryIndex,i=this._primaryCrc,j=this._crcLookup,k=this._primaryKey;for(h.truncate(),i.truncate(),j.truncate(),b=this._data,c=b.length;c--;){if(d=b[c],f&&this.ensurePrimaryKey(d),g){if(!h.uniqueSet(d[k],d))throw this.logIdentifier()+" Call to setData on collection failed because your data violates the primary key unique constraint. One or more documents are using the same primary key: "+d[this._primaryKey]}else h.set(d[k],d);e=this.hash(d),i.set(d[k],e),j.set(e,d)}},p.prototype.ensurePrimaryKey=function(a){void 0===a[this._primaryKey]&&(a[this._primaryKey]=this.objectId())},p.prototype.truncate=function(){if(this.isDropped())throw this.logIdentifier()+" Cannot operate in a dropped state!";return this.emit("truncate",this._data),this._data.length=0,this._primaryIndex=new g("primary"),this._primaryCrc=new g("primaryCrc"),this._crcLookup=new g("crcLookup"),this._onChange(),this.emit("immediateChange",{type:"truncate"}),this.deferEmit("change",{type:"truncate"}),this},p.prototype.upsert=function(a,b){if(this.isDropped())throw this.logIdentifier()+" Cannot operate in a dropped state!";if(a){var c,d,e=this._deferQueue.upsert,f=this._deferThreshold.upsert,g={};if(a instanceof Array){if(this._deferredCalls&&a.length>f)return this._deferQueue.upsert=e.concat(a),this._asyncPending("upsert"),this.processQueue("upsert",b),{};for(g=[],d=0;d<a.length;d++)g.push(this.upsert(a[d]));return b&&b.call(this),g}switch(a[this._primaryKey]?(c={},c[this._primaryKey]=a[this._primaryKey],this._primaryIndex.lookup(c)[0]?g.op="update":g.op="insert"):g.op="insert",g.op){case"insert":g.result=this.insert(a,b);break;case"update":g.result=this.update(c,a,{},b)}return g}return b&&b.call(this),{}},p.prototype.filter=function(a,b,c){return this.find(a,c).filter(b)},p.prototype.filterUpdate=function(a,b,c){var d,e,f,g,h=this.find(a,c),i=[],j=this.primaryKey();for(g=0;g<h.length;g++)d=h[g],f=b(d),f&&(e={},e[j]=d[j],i.push(this.update(e,f)));return i},p.prototype.update=function(a,b,c,d){if(this.isDropped())throw this.logIdentifier()+" Cannot operate in a dropped state!";return this.mongoEmulation()?(this.convertToFdb(a),this.convertToFdb(b)):b=this.decouple(b),b=this.transformIn(b),this._handleUpdate(a,b,c,d)},p.prototype._handleUpdate=function(a,b,c,d){var e,f,g=this,h=this._metrics.create("update"),i=function(d){var e,f,i,j=g.decouple(d);return g.willTrigger(g.TYPE_UPDATE,g.PHASE_BEFORE)||g.willTrigger(g.TYPE_UPDATE,g.PHASE_AFTER)?(e=g.decouple(d),f={type:"update",query:g.decouple(a),update:g.decouple(b),options:g.decouple(c),op:h},i=g.updateObject(e,f.update,f.query,f.options,""),g.processTrigger(f,g.TYPE_UPDATE,g.PHASE_BEFORE,d,e)!==!1?(i=g.updateObject(d,e,f.query,f.options,""),g.processTrigger(f,g.TYPE_UPDATE,g.PHASE_AFTER,j,e)):i=!1):i=g.updateObject(d,b,a,c,""),g._updateIndexes(j,d),i};return h.start(),h.time("Retrieve documents to update"),e=this.find(a,{$decouple:!1}),h.time("Retrieve documents to update"),e.length?(h.time("Update documents"),f=e.filter(i),h.time("Update documents"),f.length?(this.debug()&&console.log(this.logIdentifier()+" Updated some data"),h.time("Resolve chains"),this.chainWillSend()&&this.chainSend("update",{query:a,update:b,dataSet:this.decouple(f)},c),h.time("Resolve chains"),this._onUpdate(f),this._onChange(),d&&d.call(this,f||[]),this.emit("immediateChange",{type:"update",data:f}),this.deferEmit("change",{type:"update",data:f})):d&&d.call(this,f||[])):d&&d.call(this,f||[]),h.stop(),f||[]},p.prototype._replaceObj=function(a,b){var c;this._removeFromIndexes(a);for(c in a)a.hasOwnProperty(c)&&delete a[c];for(c in b)b.hasOwnProperty(c)&&(a[c]=b[c]);if(!this._insertIntoIndexes(a))throw this.logIdentifier()+" Primary key violation in update! Key violated: "+a[this._primaryKey];return this},p.prototype.updateById=function(a,b){var c={};return c[this._primaryKey]=a,this.update(c,b)[0]},p.prototype.updateObject=function(a,b,c,d,e,f){b=this.decouple(b),e=e||"","."===e.substr(0,1)&&(e=e.substr(1,e.length-1));var g,i,j,k,l,m,n,o,p,q,r,s,t=!1,u=!1;for(s in b)if(b.hasOwnProperty(s)){if(g=!1,"$"===s.substr(0,1))switch(s){case"$key":case"$index":case"$data":case"$min":case"$max":g=!0;break;case"$each":for(g=!0,k=b.$each.length,j=0;k>j;j++)u=this.updateObject(a,b.$each[j],c,d,e),u&&(t=!0);t=t||u;break;case"$replace":g=!0,n=b.$replace,o=this.primaryKey();for(m in a)a.hasOwnProperty(m)&&m!==o&&void 0===n[m]&&(this._updateUnset(a,m),t=!0);for(m in n)n.hasOwnProperty(m)&&m!==o&&(this._updateOverwrite(a,m,n[m]),t=!0);break;default:g=!0,u=this.updateObject(a,b[s],c,d,e,s),t=t||u}if(this._isPositionalKey(s)&&(g=!0,s=s.substr(0,s.length-2),p=new h(e+"."+s),a[s]&&a[s]instanceof Array&&a[s].length)){for(i=[],j=0;j<a[s].length;j++)this._match(a[s][j],p.value(c)[0],d,"",{})&&i.push(j);for(j=0;j<i.length;j++)u=this.updateObject(a[s][i[j]],b[s+".$"],c,d,e+"."+s,f),t=t||u}if(!g)if(f||"object"!=typeof b[s])switch(f){case"$inc":var v=!0;b[s]>0?b.$max&&a[s]>=b.$max&&(v=!1):b[s]<0&&b.$min&&a[s]<=b.$min&&(v=!1),v&&(this._updateIncrement(a,s,b[s]),t=!0);break;case"$cast":switch(b[s]){case"array":a[s]instanceof Array||(this._updateProperty(a,s,b.$data||[]),t=!0);break;case"object":a[s]instanceof Object&&!(a[s]instanceof Array)||(this._updateProperty(a,s,b.$data||{}),t=!0);break;case"number":"number"!=typeof a[s]&&(this._updateProperty(a,s,Number(a[s])),t=!0);break;case"string":"string"!=typeof a[s]&&(this._updateProperty(a,s,String(a[s])),t=!0);break;default:throw this.logIdentifier()+" Cannot update cast to unknown type: "+b[s]}break;case"$push":if(void 0===a[s]&&this._updateProperty(a,s,[]),!(a[s]instanceof Array))throw this.logIdentifier()+" Cannot push to a key that is not an array! ("+s+")";if(void 0!==b[s].$position&&b[s].$each instanceof Array)for(l=b[s].$position,k=b[s].$each.length,j=0;k>j;j++)this._updateSplicePush(a[s],l+j,b[s].$each[j]);else if(b[s].$each instanceof Array)for(k=b[s].$each.length,j=0;k>j;j++)this._updatePush(a[s],b[s].$each[j]);else this._updatePush(a[s],b[s]);t=!0;break;case"$pull":if(a[s]instanceof Array){for(i=[],j=0;j<a[s].length;j++)this._match(a[s][j],b[s],d,"",{})&&i.push(j);for(k=i.length;k--;)this._updatePull(a[s],i[k]),t=!0}break;case"$pullAll":if(a[s]instanceof Array){if(!(b[s]instanceof Array))throw this.logIdentifier()+" Cannot pullAll without being given an array of values to pull! ("+s+")";if(i=a[s],k=i.length,k>0)for(;k--;){for(l=0;l<b[s].length;l++)i[k]===b[s][l]&&(this._updatePull(a[s],k),k--,t=!0);if(0>k)break}}break;case"$addToSet":if(void 0===a[s]&&this._updateProperty(a,s,[]),!(a[s]instanceof Array))throw this.logIdentifier()+" Cannot addToSet on a key that is not an array! ("+s+")";var w,x,y,z,A=a[s],B=A.length,C=!0,D=d&&d.$addToSet;for(b[s].$key?(y=!1,z=new h(b[s].$key),x=z.value(b[s])[0],delete b[s].$key):D&&D.key?(y=!1,z=new h(D.key),x=z.value(b[s])[0]):(x=this.jStringify(b[s]),y=!0),w=0;B>w;w++)if(y){if(this.jStringify(A[w])===x){C=!1;break}}else if(x===z.value(A[w])[0]){C=!1;break}C&&(this._updatePush(a[s],b[s]),t=!0);break;case"$splicePush":if(void 0===a[s]&&this._updateProperty(a,s,[]),!(a[s]instanceof Array))throw this.logIdentifier()+" Cannot splicePush with a key that is not an array! ("+s+")";if(l=b.$index,void 0===l)throw this.logIdentifier()+" Cannot splicePush without a $index integer value!";delete b.$index,l>a[s].length&&(l=a[s].length),this._updateSplicePush(a[s],l,b[s]),t=!0;break;case"$splicePull":if(void 0!==a[s]){if(!(a[s]instanceof Array))throw this.logIdentifier()+" Cannot splicePull from a key that is not an array! ("+s+")";if(l=b[s].$index,void 0===l)throw this.logIdentifier()+" Cannot splicePull without a $index integer value!";l<a[s].length&&(this._updateSplicePull(a[s],l),t=!0)}break;case"$move":if(!(a[s]instanceof Array))throw this.logIdentifier()+" Cannot move on a key that is not an array! ("+s+")";for(j=0;j<a[s].length;j++)if(this._match(a[s][j],b[s],d,"",{})){var E=b.$index;if(void 0===E)throw this.logIdentifier()+" Cannot move without a $index integer value!";delete b.$index,this._updateSpliceMove(a[s],j,E),t=!0;break}break;case"$mul":this._updateMultiply(a,s,b[s]),t=!0;break;case"$rename":this._updateRename(a,s,b[s]),t=!0;break;case"$overwrite":this._updateOverwrite(a,s,b[s]),t=!0;break;case"$unset":this._updateUnset(a,s),t=!0;break;case"$clear":this._updateClear(a,s),t=!0;break;case"$pop":if(!(a[s]instanceof Array))throw this.logIdentifier()+" Cannot pop from a key that is not an array! ("+s+")";this._updatePop(a[s],b[s])&&(t=!0);break;case"$toggle":this._updateProperty(a,s,!a[s]),t=!0;break;default:a[s]!==b[s]&&(this._updateProperty(a,s,b[s]),t=!0)}else if(null!==a[s]&&"object"==typeof a[s])if(q=a[s]instanceof Array,r=b[s]instanceof Array,q||r)if(!r&&q)for(j=0;j<a[s].length;j++)u=this.updateObject(a[s][j],b[s],c,d,e+"."+s,f),t=t||u;else a[s]!==b[s]&&(this._updateProperty(a,s,b[s]),t=!0);else u=this.updateObject(a[s],b[s],c,d,e+"."+s,f),t=t||u;else a[s]!==b[s]&&(this._updateProperty(a,s,b[s]),t=!0)}return t},p.prototype._isPositionalKey=function(a){return".$"===a.substr(a.length-2,2)},p.prototype.remove=function(a,b,c){if(this.isDropped())throw this.logIdentifier()+" Cannot operate in a dropped state!";var d,e,f,g,h,i,j,k,l=this;if("function"==typeof b&&(c=b,b={}),this.mongoEmulation()&&this.convertToFdb(a),a instanceof Array){for(g=[],f=0;f<a.length;f++)g.push(this.remove(a[f],{noEmit:!0}));return(!b||b&&!b.noEmit)&&this._onRemove(g),c&&c.call(this,!1,g),g}if(g=[],d=this.find(a,{$decouple:!1}),d.length){h=function(a){l._removeFromIndexes(a),e=l._data.indexOf(a),l._dataRemoveAtIndex(e),g.push(a)};for(var m=0;m<d.length;m++)j=d[m],l.willTrigger(l.TYPE_REMOVE,l.PHASE_BEFORE)||l.willTrigger(l.TYPE_REMOVE,l.PHASE_AFTER)?(i={type:"remove"},k=l.decouple(j),l.processTrigger(i,l.TYPE_REMOVE,l.PHASE_BEFORE,k,k)!==!1&&(h(j),l.processTrigger(i,l.TYPE_REMOVE,l.PHASE_AFTER,k,k))):h(j);g.length&&(l.chainSend("remove",{query:a,dataSet:g},b),(!b||b&&!b.noEmit)&&this._onRemove(g),this._onChange(),this.emit("immediateChange",{type:"remove",data:g}),this.deferEmit("change",{type:"remove",data:g}))}return c&&c.call(this,!1,g),g},p.prototype.removeById=function(a){var b={};return b[this._primaryKey]=a,this.remove(b)[0]},p.prototype.processQueue=function(a,b,c){var d,e,f=this,g=this._deferQueue[a],h=this._deferThreshold[a],i=this._deferTime[a];if(c=c||{deferred:!0},g.length){switch(d=g.length>h?g.splice(0,h):g.splice(0,g.length),e=f[a](d),a){case"insert":c.inserted=c.inserted||[],c.failed=c.failed||[],c.inserted=c.inserted.concat(e.inserted),c.failed=c.failed.concat(e.failed)}setTimeout(function(){f.processQueue.call(f,a,b,c)},i)}else b&&b.call(this,c),this._asyncComplete(a);this.isProcessingQueue()||this.deferEmit("queuesComplete")},p.prototype.isProcessingQueue=function(){var a;for(a in this._deferQueue)if(this._deferQueue.hasOwnProperty(a)&&this._deferQueue[a].length)return!0;return!1},p.prototype.insert=function(a,b,c){if(this.isDropped())throw this.logIdentifier()+" Cannot operate in a dropped state!";return"function"==typeof b?(c=b,b=this._data.length):void 0===b&&(b=this._data.length),a=this.transformIn(a),this._insertHandle(a,b,c)},p.prototype._insertHandle=function(a,b,c){var d,e,f,g=this._deferQueue.insert,h=this._deferThreshold.insert,i=[],j=[];if(a instanceof Array){if(this._deferredCalls&&a.length>h)return this._deferQueue.insert=g.concat(a),this._asyncPending("insert"),void this.processQueue("insert",c);for(f=0;f<a.length;f++)d=this._insert(a[f],b+f),d===!0?i.push(a[f]):j.push({doc:a[f],reason:d})}else d=this._insert(a,b),d===!0?i.push(a):j.push({doc:a,reason:d});return e={deferred:!1,inserted:i,failed:j},this._onInsert(i,j),c&&c.call(this,e),this._onChange(),this.emit("immediateChange",{type:"insert",data:i,failed:j}),this.deferEmit("change",{type:"insert",data:i,failed:j}),e},p.prototype._insert=function(a,b){if(a){var c,d,e,f,g=this,h=this.capped(),i=this.cappedSize();if(this.ensurePrimaryKey(a),c=this.insertIndexViolation(a),e=function(a){g._insertIntoIndexes(a),b>g._data.length&&(b=g._data.length),g._dataInsertAtIndex(b,a),h&&g._data.length>i&&g.removeById(g._data[0][g._primaryKey]),g.chainWillSend()&&g.chainSend("insert",{dataSet:g.decouple([a])},{index:b})},c)return"Index violation in index: "+c;if(g.willTrigger(g.TYPE_INSERT,g.PHASE_BEFORE)||g.willTrigger(g.TYPE_INSERT,g.PHASE_AFTER)){if(d={type:"insert"},g.processTrigger(d,g.TYPE_INSERT,g.PHASE_BEFORE,{},a)===!1)return"Trigger cancelled operation";e(a),g.willTrigger(g.TYPE_INSERT,g.PHASE_AFTER)&&(f=g.decouple(a),g.processTrigger(d,g.TYPE_INSERT,g.PHASE_AFTER,{},f))}else e(a);return!0}return"No document passed to insert"},p.prototype._dataInsertAtIndex=function(a,b){this._data.splice(a,0,b)},p.prototype._dataRemoveAtIndex=function(a){this._data.splice(a,1)},p.prototype._dataReplace=function(a){for(;this._data.length;)this._data.pop();this._data=this._data.concat(a)},p.prototype._insertIntoIndexes=function(a){var b,c,d=this._indexByName,e=this.hash(a),f=this._primaryKey;c=this._primaryIndex.uniqueSet(a[f],a),this._primaryCrc.uniqueSet(a[f],e),this._crcLookup.uniqueSet(e,a);for(b in d)d.hasOwnProperty(b)&&d[b].insert(a);return c},p.prototype._removeFromIndexes=function(a){var b,c=this._indexByName,d=this.hash(a),e=this._primaryKey;this._primaryIndex.unSet(a[e]),this._primaryCrc.unSet(a[e]),this._crcLookup.unSet(d);for(b in c)c.hasOwnProperty(b)&&c[b].remove(a)},p.prototype._updateIndexes=function(a,b){this._removeFromIndexes(a),this._insertIntoIndexes(b)},p.prototype._rebuildIndexes=function(){var a,b=this._indexByName;for(a in b)b.hasOwnProperty(a)&&b[a].rebuild()},p.prototype.subset=function(a,b){var c,d=this.find(a,b);return c=new p,c.db(this._db),c.subsetOf(this).primaryKey(this._primaryKey).setData(d),c},d.synthesize(p.prototype,"subsetOf"),p.prototype.isSubsetOf=function(a){return this._subsetOf===a},p.prototype.distinct=function(a,b,c){if(this.isDropped())throw this.logIdentifier()+" Cannot operate in a dropped state!";var d,e,f=this.find(b,c),g=new h(a),i={},j=[];for(e=0;e<f.length;e++)d=g.value(f[e])[0],d&&!i[d]&&(i[d]=!0,j.push(d));return j},p.prototype.findById=function(a,b){var c={};return c[this._primaryKey]=a,this.find(c,b)[0]},p.prototype.peek=function(a,b){var c,d,e=this._data,f=e.length,g=new p,h=typeof a;if("string"===h){for(c=0;f>c;c++)d=this.jStringify(e[c]),d.indexOf(a)>-1&&g.insert(e[c]);return g.find({},b)}return this.find(a,b)},p.prototype.explain=function(a,b){var c=this.find(a,b);return c.__fdbOp._data},p.prototype.options=function(a){return a=a||{},a.$decouple=void 0!==a.$decouple?a.$decouple:!0,a.$explain=void 0!==a.$explain?a.$explain:!1,a},p.prototype.find=function(a,b,c){return this.mongoEmulation()&&this.convertToFdb(a),c?(c.call(this,"Callbacks for the find() operation are not yet implemented!",[]),[]):this._find.call(this,a,b,c)},p.prototype._find=function(a,b){if(this.isDropped())throw this.logIdentifier()+" Cannot operate in a dropped state!";a=a||{};var c,d,e,f,g,i,j,k,l,m,n,o,p,q,r,s,t,u,v,w,x=this._metrics.create("find"),y=this.primaryKey(),z=this,A=!0,B={},C=[],D=[],E=[],F={},G={};if(b instanceof Array||(b=this.options(b)),w=function(c){return z._match(c,a,b,"and",F)},x.start(),a){if(a instanceof Array){for(v=this,n=0;n<a.length;n++)v=v.subset(a[n],b&&b[n]?b[n]:{});return v.find()}if(a.$findSub){if(!a.$findSub.$path)throw"$findSub missing $path property!";return this.findSub(a.$findSub.$query,a.$findSub.$path,a.$findSub.$subQuery,a.$findSub.$subOptions)}if(a.$findSubOne){if(!a.$findSubOne.$path)throw"$findSubOne missing $path property!";return this.findSubOne(a.$findSubOne.$query,a.$findSubOne.$path,a.$findSubOne.$subQuery,a.$findSubOne.$subOptions)}if(x.time("analyseQuery"),c=this._analyseQuery(z.decouple(a),b,x),x.time("analyseQuery"),x.data("analysis",c),c.hasJoin&&c.queriesJoin){for(x.time("joinReferences"),f=0;f<c.joinsOn.length;f++)m=c.joinsOn[f],j=m.key,k=m.type,l=m.id,i=new h(c.joinQueries[j]),g=i.value(a)[0],B[l]=this._db[k](j).subset(g),delete a[c.joinQueries[j]];x.time("joinReferences")}if(c.indexMatch.length&&(!b||b&&!b.$skipIndex)?(x.data("index.potential",c.indexMatch),x.data("index.used",c.indexMatch[0].index),x.time("indexLookup"),e=c.indexMatch[0].lookup||[],x.time("indexLookup"),c.indexMatch[0].keyData.totalKeyCount===c.indexMatch[0].keyData.score&&(A=!1)):x.flag("usedIndex",!1),A&&(e&&e.length?(d=e.length,x.time("tableScan: "+d),e=e.filter(w)):(d=this._data.length,x.time("tableScan: "+d),e=this._data.filter(w)),x.time("tableScan: "+d)),b.$orderBy&&(x.time("sort"),e=this.sort(b.$orderBy,e),x.time("sort")),void 0!==b.$page&&void 0!==b.$limit&&(G.page=b.$page,G.pages=Math.ceil(e.length/b.$limit),G.records=e.length,b.$page&&b.$limit>0&&(x.data("cursor",G),e.splice(0,b.$page*b.$limit))),b.$skip&&(G.skip=b.$skip,e.splice(0,b.$skip),x.data("skip",b.$skip)),b.$limit&&e&&e.length>b.$limit&&(G.limit=b.$limit,e.length=b.$limit,x.data("limit",b.$limit)),b.$decouple&&(x.time("decouple"),e=this.decouple(e),x.time("decouple"),x.data("flag.decouple",!0)),b.$join&&(C=C.concat(this.applyJoin(e,b.$join,B)),x.data("flag.join",!0)),C.length&&(x.time("removalQueue"),this.spliceArrayByIndexList(e,C),x.time("removalQueue")),b.$transform){for(x.time("transform"),n=0;n<e.length;n++)e.splice(n,1,b.$transform(e[n]));x.time("transform"),x.data("flag.transform",!0)}this._transformEnabled&&this._transformOut&&(x.time("transformOut"),e=this.transformOut(e),x.time("transformOut")),x.data("results",e.length)}else e=[];if(!b.$aggregate){x.time("scanFields");for(n in b)b.hasOwnProperty(n)&&0!==n.indexOf("$")&&(1===b[n]?D.push(n):0===b[n]&&E.push(n));if(x.time("scanFields"),D.length||E.length){for(x.data("flag.limitFields",!0),x.data("limitFields.on",D),x.data("limitFields.off",E),x.time("limitFields"),n=0;n<e.length;n++){t=e[n];for(o in t)t.hasOwnProperty(o)&&(D.length&&o!==y&&-1===D.indexOf(o)&&delete t[o],E.length&&E.indexOf(o)>-1&&delete t[o])}x.time("limitFields")}if(b.$elemMatch){x.data("flag.elemMatch",!0),x.time("projection-elemMatch");for(n in b.$elemMatch)if(b.$elemMatch.hasOwnProperty(n))for(q=new h(n),o=0;o<e.length;o++)if(r=q.value(e[o])[0],r&&r.length)for(p=0;p<r.length;p++)if(z._match(r[p],b.$elemMatch[n],b,"",{})){q.set(e[o],n,[r[p]]);break}x.time("projection-elemMatch")}if(b.$elemsMatch){x.data("flag.elemsMatch",!0),x.time("projection-elemsMatch");for(n in b.$elemsMatch)if(b.$elemsMatch.hasOwnProperty(n))for(q=new h(n),o=0;o<e.length;o++)if(r=q.value(e[o])[0],r&&r.length){for(s=[],p=0;p<r.length;p++)z._match(r[p],b.$elemsMatch[n],b,"",{})&&s.push(r[p]);q.set(e[o],n,s)}x.time("projection-elemsMatch")}}return b.$aggregate&&(x.data("flag.aggregate",!0),x.time("aggregate"),u=new h(b.$aggregate),e=u.value(e),x.time("aggregate")),b.$groupBy&&(x.data("flag.group",!0),x.time("group"),e=this.group(b.$groupBy,e),x.time("group")),x.stop(),e.__fdbOp=x,e.$cursor=G,e},p.prototype.findOne=function(){return this.find.apply(this,arguments)[0]},p.prototype.indexOf=function(a,b){var c,d=this.find(a,{$decouple:!1})[0];return d?!b||b&&!b.$orderBy?this._data.indexOf(d):(b.$decouple=!1,c=this.find(a,b),c.indexOf(d)):-1},p.prototype.indexOfDocById=function(a,b){var c,d;return c="object"!=typeof a?this._primaryIndex.get(a):this._primaryIndex.get(a[this._primaryKey]), c?!b||b&&!b.$orderBy?this._data.indexOf(c):(b.$decouple=!1,d=this.find({},b),d.indexOf(c)):-1},p.prototype.removeByIndex=function(a){var b,c;return b=this._data[a],void 0!==b?(b=this.decouple(b),c=b[this.primaryKey()],this.removeById(c)):!1},p.prototype.transform=function(a){return void 0!==a?("object"==typeof a?(void 0!==a.enabled&&(this._transformEnabled=a.enabled),void 0!==a.dataIn&&(this._transformIn=a.dataIn),void 0!==a.dataOut&&(this._transformOut=a.dataOut)):this._transformEnabled=a!==!1,this):{enabled:this._transformEnabled,dataIn:this._transformIn,dataOut:this._transformOut}},p.prototype.transformIn=function(a){if(this._transformEnabled&&this._transformIn){if(a instanceof Array){var b,c,d=[];for(c=0;c<a.length;c++)b=this._transformIn(a[c]),b instanceof Array?d=d.concat(b):d.push(b);return d}return this._transformIn(a)}return a},p.prototype.transformOut=function(a){if(this._transformEnabled&&this._transformOut){if(a instanceof Array){var b,c,d=[];for(c=0;c<a.length;c++)b=this._transformOut(a[c]),b instanceof Array?d=d.concat(b):d.push(b);return d}return this._transformOut(a)}return a},p.prototype.sort=function(a,b){var c=this,d=o.parse(a,!0);return d.length&&b.sort(function(a,b){var e,f,g=0;for(e=0;e<d.length;e++)if(f=d[e],1===f.value?g=c.sortAsc(o.get(a,f.path),o.get(b,f.path)):-1===f.value&&(g=c.sortDesc(o.get(a,f.path),o.get(b,f.path))),0!==g)return g;return g}),b},p.prototype.group=function(a,b){var c,d,e,f=o.parse(a,!0),g=new h,i={};if(f.length)for(d=0;d<f.length;d++)for(g.path(f[d].path),e=0;e<b.length;e++)c=g.get(b[e]),i[c]=i[c]||[],i[c].push(b[e]);return i},p.prototype._sort=function(a,b){var c,d=this,e=new h,f=e.parse(a,!0)[0];if(e.path(f.path),1===f.value)c=function(a,b){var c=e.value(a)[0],f=e.value(b)[0];return d.sortAsc(c,f)};else{if(-1!==f.value)throw this.logIdentifier()+" $orderBy clause has invalid direction: "+f.value+", accepted values are 1 or -1 for ascending or descending!";c=function(a,b){var c=e.value(a)[0],f=e.value(b)[0];return d.sortDesc(c,f)}}return b.sort(c)},p.prototype._analyseQuery=function(a,b,c){var d,e,f,g,i,j,k,l,m,n,o,p,q,r,s,t,u={queriesOn:[{id:"$collection."+this._name,type:"colletion",key:this._name}],indexMatch:[],hasJoin:!1,queriesJoin:!1,joinQueries:{},query:a,options:b},v=[],w=[];if(c.time("checkIndexes"),p=new h,q=p.parseArr(a,{ignore:/\$/,verbose:!0}).length){void 0!==a[this._primaryKey]&&(r=typeof a[this._primaryKey],("string"===r||"number"===r||a[this._primaryKey]instanceof Array)&&(c.time("checkIndexMatch: Primary Key"),s=this._primaryIndex.lookup(a,b,c),u.indexMatch.push({lookup:s,keyData:{matchedKeys:[this._primaryKey],totalKeyCount:q,score:1},index:this._primaryIndex}),c.time("checkIndexMatch: Primary Key")));for(t in this._indexById)if(this._indexById.hasOwnProperty(t)&&(m=this._indexById[t],n=m.name(),c.time("checkIndexMatch: "+n),l=m.match(a,b),l.score>0&&(o=m.lookup(a,b,c),u.indexMatch.push({lookup:o,keyData:l,index:m})),c.time("checkIndexMatch: "+n),l.score===q))break;c.time("checkIndexes"),u.indexMatch.length>1&&(c.time("findOptimalIndex"),u.indexMatch.sort(function(a,b){return a.keyData.score>b.keyData.score?-1:a.keyData.score<b.keyData.score?1:a.keyData.score===b.keyData.score?a.lookup.length-b.lookup.length:void 0}),c.time("findOptimalIndex"))}if(b.$join){for(u.hasJoin=!0,d=0;d<b.$join.length;d++)for(e in b.$join[d])b.$join[d].hasOwnProperty(e)&&(i=b.$join[d][e],f=i.$sourceType||"collection",g="$"+f+"."+e,v.push({id:g,type:f,key:e}),void 0!==b.$join[d][e].$as?w.push(b.$join[d][e].$as):w.push(e));for(k=0;k<w.length;k++)j=this._queryReferencesSource(a,w[k],""),j&&(u.joinQueries[v[k].key]=j,u.queriesJoin=!0);u.joinsOn=v,u.queriesOn=u.queriesOn.concat(v)}return u},p.prototype._queryReferencesSource=function(a,b,c){var d;for(d in a)if(a.hasOwnProperty(d)){if(d===b)return c&&(c+="."),c+d;if("object"==typeof a[d])return c&&(c+="."),c+=d,this._queryReferencesSource(a[d],b,c)}return!1},p.prototype.count=function(a,b){return a?this.find(a,b).length:this._data.length},p.prototype.findSub=function(a,b,c,d){return this._findSub(this.find(a),b,c,d)},p.prototype._findSub=function(a,b,c,d){var e,f,g,i=new h(b),j=a.length,k=new p("__FDB_temp_"+this.objectId()).db(this._db),l={parents:j,subDocTotal:0,subDocs:[],pathFound:!1,err:""};for(d=d||{},e=0;j>e;e++)if(f=i.value(a[e])[0]){if(k.setData(f),g=k.find(c,d),d.returnFirst&&g.length)return g[0];d.$split?l.subDocs.push(g):l.subDocs=l.subDocs.concat(g),l.subDocTotal+=g.length,l.pathFound=!0}return k.drop(),l.pathFound||(l.err="No objects found in the parent documents with a matching path of: "+b),d.$stats?l:l.subDocs},p.prototype.findSubOne=function(a,b,c,d){return this.findSub(a,b,c,d)[0]},p.prototype.insertIndexViolation=function(a){var b,c,d,e=this._indexByName;if(this._primaryIndex.get(a[this._primaryKey]))b=this._primaryIndex;else for(c in e)if(e.hasOwnProperty(c)&&(d=e[c],d.unique()&&d.violation(a))){b=d;break}return b?b.name():!1},p.prototype.ensureIndex=function(a,b){if(this.isDropped())throw this.logIdentifier()+" Cannot operate in a dropped state!";this._indexByName=this._indexByName||{},this._indexById=this._indexById||{};var c,e={start:(new Date).getTime()};if(b)if(b.type){if(!d.index[b.type])throw this.logIdentifier()+' Cannot create index of type "'+b.type+'", type not found in the index type register (Shared.index)';c=new d.index[b.type](a,b,this)}else c=new i(a,b,this);else c=new i(a,b,this);return this._indexByName[c.name()]?{err:"Index with that name already exists"}:(c.rebuild(),this._indexByName[c.name()]=c,this._indexById[c.id()]=c,e.end=(new Date).getTime(),e.total=e.end-e.start,this._lastOp={type:"ensureIndex",stats:{time:e}},{index:c,id:c.id(),name:c.name(),state:c.state()})},p.prototype.index=function(a){return this._indexByName?this._indexByName[a]:void 0},p.prototype.lastOp=function(){return this._metrics.list()},p.prototype.diff=function(a){var b,c,d,e,f={insert:[],update:[],remove:[]},g=this.primaryKey();if(g!==a.primaryKey())throw this.logIdentifier()+" Diffing requires that both collections have the same primary key!";for(b=a._data;b&&!(b instanceof Array);)a=b,b=a._data;for(e=b.length,c=0;e>c;c++)d=b[c],this._primaryIndex.get(d[g])?this._primaryCrc.get(d[g])!==a._primaryCrc.get(d[g])&&f.update.push(d):f.insert.push(d);for(b=this._data,e=b.length,c=0;e>c;c++)d=b[c],a._primaryIndex.get(d[g])||f.remove.push(d);return f},p.prototype.collateAdd=new l("Collection.prototype.collateAdd",{"object, string":function(a,b){var c=this;c.collateAdd(a,function(d){var e,f;switch(d.type){case"insert":b?(e={$push:{}},e.$push[b]=c.decouple(d.data.dataSet),c.update({},e)):c.insert(d.data.dataSet);break;case"update":b?(e={},f={},e[b]=d.data.query,f[b+".$"]=d.data.update,c.update(e,f)):c.update(d.data.query,d.data.update);break;case"remove":b?(e={$pull:{}},e.$pull[b]={},e.$pull[b][c.primaryKey()]=d.data.dataSet[0][a.primaryKey()],c.update({},e)):c.remove(d.data.dataSet)}})},"object, function":function(a,b){if("string"==typeof a&&(a=this._db.collection(a,{autoCreate:!1,throwError:!1})),a)return this._collate=this._collate||{},this._collate[a.name()]=new m(a,this,b),this;throw"Cannot collate from a non-existent collection!"}}),p.prototype.collateRemove=function(a){if("object"==typeof a&&(a=a.name()),a)return this._collate[a].drop(),delete this._collate[a],this;throw"No collection name passed to collateRemove() or collection not found!"},p.prototype.when=function(a){var b=this.objectId();return this._when=this._when||{},this._when[b]=this._when[b]||new n(this,b,a),this._when[b]},e.prototype.collection=new l("Db.prototype.collection",{"":function(){return this.$main.call(this,{name:this.objectId()})},object:function(a){return a instanceof p?"droppped"!==a.state()?a:this.$main.call(this,{name:a.name()}):this.$main.call(this,a)},string:function(a){return this.$main.call(this,{name:a})},"string, string":function(a,b){return this.$main.call(this,{name:a,primaryKey:b})},"string, object":function(a,b){return b.name=a,this.$main.call(this,b)},"string, string, object":function(a,b,c){return c.name=a,c.primaryKey=b,this.$main.call(this,c)},$main:function(a){var b=this,c=a.name;if(c){if(this._collection[c])return this._collection[c];if(a&&a.autoCreate===!1){if(a&&a.throwError!==!1)throw this.logIdentifier()+" Cannot get collection "+c+" because it does not exist and auto-create has been disabled!";return}if(this.debug()&&console.log(this.logIdentifier()+" Creating collection "+c),this._collection[c]=this._collection[c]||new p(c,a).db(this),this._collection[c].mongoEmulation(this.mongoEmulation()),void 0!==a.primaryKey&&this._collection[c].primaryKey(a.primaryKey),void 0!==a.capped){if(void 0===a.size)throw this.logIdentifier()+" Cannot create a capped collection without specifying a size!";this._collection[c].capped(a.capped),this._collection[c].cappedSize(a.size)}return b._collection[c].on("change",function(){b.emit("change",b._collection[c],"collection",c)}),b.emit("create",b._collection[c],"collection",c),this._collection[c]}if(!a||a&&a.throwError!==!1)throw this.logIdentifier()+" Cannot get collection with undefined name!"}}),e.prototype.collectionExists=function(a){return Boolean(this._collection[a])},e.prototype.collections=function(a){var b,c,d=[],e=this._collection;a&&(a instanceof RegExp||(a=new RegExp(a)));for(c in e)e.hasOwnProperty(c)&&(b=e[c],a?a.exec(c)&&d.push({name:c,count:b.count(),linked:void 0!==b.isLinked?b.isLinked():!1}):d.push({name:c,count:b.count(),linked:void 0!==b.isLinked?b.isLinked():!1}));return d.sort(function(a,b){return a.name.localeCompare(b.name)}),d},d.finishModule("Collection"),b.exports=p},{"./Condition":7,"./Index2d":14,"./IndexBinaryTree":15,"./IndexHashMap":16,"./KeyValueStore":17,"./Metrics":18,"./Overload":32,"./Path":34,"./ReactorIO":38,"./Shared":40}],6:[function(a,b,c){"use strict";var d,e,f,g;d=a("./Shared");var h=function(){this.init.apply(this,arguments)};h.prototype.init=function(a){var b=this;b._name=a,b._data=new g("__FDB__cg_data_"+b._name),b._collections=[],b._view=[]},d.addModule("CollectionGroup",h),d.mixin(h.prototype,"Mixin.Common"),d.mixin(h.prototype,"Mixin.ChainReactor"),d.mixin(h.prototype,"Mixin.Constants"),d.mixin(h.prototype,"Mixin.Triggers"),d.mixin(h.prototype,"Mixin.Tags"),d.mixin(h.prototype,"Mixin.Events"),g=a("./Collection"),e=d.modules.Db,f=d.modules.Db.prototype.init,h.prototype.on=function(){this._data.on.apply(this._data,arguments)},h.prototype.off=function(){this._data.off.apply(this._data,arguments)},h.prototype.emit=function(){this._data.emit.apply(this._data,arguments)},h.prototype.primaryKey=function(a){return void 0!==a?(this._primaryKey=a,this):this._primaryKey},d.synthesize(h.prototype,"state"),d.synthesize(h.prototype,"db"),d.synthesize(h.prototype,"name"),h.prototype.addCollection=function(a){if(a&&-1===this._collections.indexOf(a)){if(this._collections.length){if(this._primaryKey!==a.primaryKey())throw this.logIdentifier()+" All collections in a collection group must have the same primary key!"}else this.primaryKey(a.primaryKey());this._collections.push(a),a._groups=a._groups||[],a._groups.push(this),a.chain(this),a.on("drop",function(){if(a._groups&&a._groups.length){var b,c=[];for(b=0;b<a._groups.length;b++)c.push(a._groups[b]);for(b=0;b<c.length;b++)a._groups[b].removeCollection(a)}delete a._groups}),this._data.insert(a.find())}return this},h.prototype.removeCollection=function(a){if(a){var b,c=this._collections.indexOf(a);-1!==c&&(a.unChain(this),this._collections.splice(c,1),a._groups=a._groups||[],b=a._groups.indexOf(this),-1!==b&&a._groups.splice(b,1),a.off("drop")),0===this._collections.length&&delete this._primaryKey}return this},h.prototype._chainHandler=function(a){switch(a.type){case"setData":a.data.dataSet=this.decouple(a.data.dataSet),this._data.remove(a.data.oldData),this._data.insert(a.data.dataSet);break;case"insert":a.data.dataSet=this.decouple(a.data.dataSet),this._data.insert(a.data.dataSet);break;case"update":this._data.update(a.data.query,a.data.update,a.options);break;case"remove":this._data.remove(a.data.query,a.options)}},h.prototype.insert=function(){this._collectionsRun("insert",arguments)},h.prototype.update=function(){this._collectionsRun("update",arguments)},h.prototype.updateById=function(){this._collectionsRun("updateById",arguments)},h.prototype.remove=function(){this._collectionsRun("remove",arguments)},h.prototype._collectionsRun=function(a,b){for(var c=0;c<this._collections.length;c++)this._collections[c][a].apply(this._collections[c],b)},h.prototype.find=function(a,b){return this._data.find(a,b)},h.prototype.removeById=function(a){for(var b=0;b<this._collections.length;b++)this._collections[b].removeById(a)},h.prototype.subset=function(a,b){var c=this.find(a,b);return(new g).subsetOf(this).primaryKey(this._primaryKey).setData(c)},h.prototype.drop=function(a){if(!this.isDropped()){var b,c,d;if(this._debug&&console.log(this.logIdentifier()+" Dropping"),this._state="dropped",this._collections&&this._collections.length)for(c=[].concat(this._collections),b=0;b<c.length;b++)this.removeCollection(c[b]);if(this._view&&this._view.length)for(d=[].concat(this._view),b=0;b<d.length;b++)this._removeView(d[b]);this.emit("drop",this),delete this._listeners,a&&a(!1,!0)}return!0},e.prototype.init=function(){this._collectionGroup={},f.apply(this,arguments)},e.prototype.collectionGroup=function(a){var b=this;return a?a instanceof h?a:this._collectionGroup&&this._collectionGroup[a]?this._collectionGroup[a]:(this._collectionGroup[a]=new h(a).db(this),b.emit("create",b._collectionGroup[a],"collectionGroup",a),this._collectionGroup[a]):this._collectionGroup},e.prototype.collectionGroups=function(){var a,b=[];for(a in this._collectionGroup)this._collectionGroup.hasOwnProperty(a)&&b.push({name:a});return b},b.exports=h},{"./Collection":5,"./Shared":40}],7:[function(a,b,c){"use strict";var d,e;d=a("./Shared"),e=function(){this.init.apply(this,arguments)},e.prototype.init=function(a,b,c){this._dataSource=a,this._id=b,this._query=[c],this._started=!1,this._state=[!1],this._satisfied=!1,this.earlyExit(!0)},d.addModule("Condition",e),d.mixin(e.prototype,"Mixin.Common"),d.mixin(e.prototype,"Mixin.ChainReactor"),d.synthesize(e.prototype,"id"),d.synthesize(e.prototype,"then"),d.synthesize(e.prototype,"else"),d.synthesize(e.prototype,"earlyExit"),d.synthesize(e.prototype,"debug"),e.prototype.and=function(a){return this._query.push(a),this._state.push(!1),this},e.prototype.start=function(a){if(!this._started){var b=this;0!==arguments.length&&(this._satisfied=a),this._updateStates(),b._onChange=function(){b._updateStates()},this._dataSource.on("change",b._onChange),this._started=!0}return this},e.prototype._updateStates=function(){var a,b=!0;for(a=0;a<this._query.length&&(this._state[a]=this._dataSource.count(this._query[a])>0,this._debug&&console.log(this.logIdentifier()+" Evaluating",this._query[a],"=",this._query[a]),this._state[a]||(b=!1,!this._earlyExit));a++);this._satisfied!==b&&(b?this._then&&this._then():this._else&&this._else(),this._satisfied=b)},e.prototype.stop=function(){return this._started&&(this._dataSource.off("change",this._onChange),delete this._onChange,this._started=!1),this},e.prototype.drop=function(){return this.stop(),delete this._dataSource.when[this._id],this},d.finishModule("Condition"),b.exports=e},{"./Shared":40}],8:[function(a,b,c){"use strict";var d,e,f,g,h=[];d=a("./Shared"),g=a("./Overload");var i=function(a){this.init.apply(this,arguments)};i.prototype.init=function(a){this._db={},this._debug={},this._name=a||"ForerunnerDB",h.push(this)},i.prototype.instantiatedCount=function(){return h.length},i.prototype.instances=function(a){return void 0!==a?h[a]:h},i.prototype.namedInstances=function(a){var b,c;{if(void 0===a){for(c=[],b=0;b<h.length;b++)c.push(h[b].name);return c}for(b=0;b<h.length;b++)if(h[b].name===a)return h[b]}},i.prototype.moduleLoaded=new g({string:function(a){if(void 0!==a){a=a.replace(/ /g,"");var b,c=a.split(",");for(b=0;b<c.length;b++)if(!d.modules[c[b]])return!1;return!0}return!1},"string, function":function(a,b){if(void 0!==a){a=a.replace(/ /g,"");var c,e=a.split(",");for(c=0;c<e.length;c++)if(!d.modules[e[c]])return!1;b&&b()}},"array, function":function(a,b){var c,e;for(e=0;e<a.length;e++)if(c=a[e],void 0!==c){c=c.replace(/ /g,"");var f,g=c.split(",");for(f=0;f<g.length;f++)if(!d.modules[g[f]])return!1}b&&b()},"string, function, function":function(a,b,c){if(void 0!==a){a=a.replace(/ /g,"");var e,f=a.split(",");for(e=0;e<f.length;e++)if(!d.modules[f[e]])return c(),!1;b()}}}),i.prototype.version=function(a,b){return void 0!==a?0===d.version.indexOf(a)?(b&&b(),!0):!1:d.version},i.moduleLoaded=i.prototype.moduleLoaded,i.version=i.prototype.version,i.instances=i.prototype.instances,i.instantiatedCount=i.prototype.instantiatedCount,i.shared=d,i.prototype.shared=d,d.addModule("Core",i),d.mixin(i.prototype,"Mixin.Common"),d.mixin(i.prototype,"Mixin.Constants"),e=a("./Db.js"),f=a("./Metrics.js"),d.synthesize(i.prototype,"name"),d.synthesize(i.prototype,"mongoEmulation"),i.prototype._isServer=!1,i.prototype.isClient=function(){return!this._isServer},i.prototype.isServer=function(){return this._isServer},i.prototype.collection=function(){throw"ForerunnerDB's instantiation has changed since version 1.3.36 to support multiple database instances. Please see the readme.md file for the minor change you have to make to get your project back up and running, or see the issue related to this change at https://github.com/Irrelon/ForerunnerDB/issues/44"},b.exports=i},{"./Db.js":9,"./Metrics.js":18,"./Overload":32,"./Shared":40}],9:[function(a,b,c){"use strict";var d,e,f,g,h,i;d=a("./Shared"),i=a("./Overload");var j=function(a,b){this.init.apply(this,arguments)};j.prototype.init=function(a,b){this.core(b),this._primaryKey="_id",this._name=a,this._collection={},this._debug={}},d.addModule("Db",j),j.prototype.moduleLoaded=new i({string:function(a){if(void 0!==a){a=a.replace(/ /g,"");var b,c=a.split(",");for(b=0;b<c.length;b++)if(!d.modules[c[b]])return!1;return!0}return!1},"string, function":function(a,b){if(void 0!==a){a=a.replace(/ /g,"");var c,e=a.split(",");for(c=0;c<e.length;c++)if(!d.modules[e[c]])return!1;b&&b()}},"string, function, function":function(a,b,c){if(void 0!==a){a=a.replace(/ /g,"");var e,f=a.split(",");for(e=0;e<f.length;e++)if(!d.modules[f[e]])return c(),!1;b()}}}),j.prototype.version=function(a,b){return void 0!==a?0===d.version.indexOf(a)?(b&&b(),!0):!1:d.version},j.moduleLoaded=j.prototype.moduleLoaded,j.version=j.prototype.version,j.shared=d,j.prototype.shared=d,d.addModule("Db",j),d.mixin(j.prototype,"Mixin.Common"),d.mixin(j.prototype,"Mixin.ChainReactor"),d.mixin(j.prototype,"Mixin.Constants"),d.mixin(j.prototype,"Mixin.Tags"),e=d.modules.Core,f=a("./Collection.js"),g=a("./Metrics.js"),h=a("./Checksum.js"),j.prototype._isServer=!1,d.synthesize(j.prototype,"core"),d.synthesize(j.prototype,"primaryKey"),d.synthesize(j.prototype,"state"),d.synthesize(j.prototype,"name"),d.synthesize(j.prototype,"mongoEmulation"),j.prototype.isClient=function(){return!this._isServer},j.prototype.isServer=function(){return this._isServer},j.prototype.Checksum=h,j.prototype.isClient=function(){return!this._isServer},j.prototype.isServer=function(){return this._isServer},j.prototype.arrayToCollection=function(a){return(new f).setData(a)},j.prototype.on=function(a,b){return this._listeners=this._listeners||{},this._listeners[a]=this._listeners[a]||[],this._listeners[a].push(b),this},j.prototype.off=function(a,b){if(a in this._listeners){var c=this._listeners[a],d=c.indexOf(b);d>-1&&c.splice(d,1)}return this},j.prototype.emit=function(a,b){if(this._listeners=this._listeners||{},a in this._listeners){var c,d=this._listeners[a],e=d.length;for(c=0;e>c;c++)d[c].apply(this,Array.prototype.slice.call(arguments,1))}return this},j.prototype.peek=function(a){var b,c,d=[],e=typeof a;for(b in this._collection)this._collection.hasOwnProperty(b)&&(c=this._collection[b],d="string"===e?d.concat(c.peek(a)):d.concat(c.find(a)));return d},j.prototype.peek=function(a){var b,c,d=[],e=typeof a;for(b in this._collection)this._collection.hasOwnProperty(b)&&(c=this._collection[b],d="string"===e?d.concat(c.peek(a)):d.concat(c.find(a)));return d},j.prototype.peekCat=function(a){var b,c,d,e={},f=typeof a;for(b in this._collection)this._collection.hasOwnProperty(b)&&(c=this._collection[b],"string"===f?(d=c.peek(a),d&&d.length&&(e[c.name()]=d)):(d=c.find(a),d&&d.length&&(e[c.name()]=d)));return e},j.prototype.drop=new i({"":function(){if(!this.isDropped()){var a,b=this.collections(),c=b.length;for(this._state="dropped",a=0;c>a;a++)this.collection(b[a].name).drop(),delete this._collection[b[a].name];this.emit("drop",this),delete this._listeners,delete this._core._db[this._name]}return!0},"function":function(a){if(!this.isDropped()){var b,c=this.collections(),d=c.length,e=0,f=function(){e++,e===d&&a&&a()};for(this._state="dropped",b=0;d>b;b++)this.collection(c[b].name).drop(f),delete this._collection[c[b].name];this.emit("drop",this),delete this._listeners,delete this._core._db[this._name]}return!0},"boolean":function(a){if(!this.isDropped()){var b,c=this.collections(),d=c.length;for(this._state="dropped",b=0;d>b;b++)this.collection(c[b].name).drop(a),delete this._collection[c[b].name];this.emit("drop",this),delete this._listeners,delete this._core._db[this._name]}return!0},"boolean, function":function(a,b){if(!this.isDropped()){var c,d=this.collections(),e=d.length,f=0,g=function(){f++,f===e&&b&&b()};for(this._state="dropped",c=0;e>c;c++)this.collection(d[c].name).drop(a,g),delete this._collection[d[c].name];this.emit("drop",this),delete this._listeners,delete this._core._db[this._name]}return!0}}),e.prototype.db=function(a){return a instanceof j?a:(a||(a=this.objectId()),this._db[a]=this._db[a]||new j(a,this),this._db[a].mongoEmulation(this.mongoEmulation()),this._db[a])},e.prototype.databases=function(a){var b,c,d,e=[];a&&(a instanceof RegExp||(a=new RegExp(a)));for(d in this._db)this._db.hasOwnProperty(d)&&(c=!0,a&&(a.exec(d)||(c=!1)),c&&(b={name:d,children:[]},this.shared.moduleExists("Collection")&&b.children.push({module:"collection",moduleName:"Collections",count:this._db[d].collections().length}),this.shared.moduleExists("CollectionGroup")&&b.children.push({module:"collectionGroup",moduleName:"Collection Groups",count:this._db[d].collectionGroups().length}),this.shared.moduleExists("Document")&&b.children.push({module:"document",moduleName:"Documents",count:this._db[d].documents().length}),this.shared.moduleExists("Grid")&&b.children.push({module:"grid",moduleName:"Grids",count:this._db[d].grids().length}),this.shared.moduleExists("Overview")&&b.children.push({module:"overview",moduleName:"Overviews",count:this._db[d].overviews().length}),this.shared.moduleExists("View")&&b.children.push({module:"view",moduleName:"Views",count:this._db[d].views().length}),e.push(b)));return e.sort(function(a,b){return a.name.localeCompare(b.name)}),e},d.finishModule("Db"),b.exports=j},{"./Checksum.js":4,"./Collection.js":5,"./Metrics.js":18,"./Overload":32,"./Shared":40}],10:[function(a,b,c){"use strict";var d,e,f;d=a("./Shared");var g=function(){this.init.apply(this,arguments)};g.prototype.init=function(a){this._name=a,this._data={}},d.addModule("Document",g),d.mixin(g.prototype,"Mixin.Common"),d.mixin(g.prototype,"Mixin.Events"),d.mixin(g.prototype,"Mixin.ChainReactor"),d.mixin(g.prototype,"Mixin.Constants"),d.mixin(g.prototype,"Mixin.Triggers"),d.mixin(g.prototype,"Mixin.Matching"),d.mixin(g.prototype,"Mixin.Updating"),d.mixin(g.prototype,"Mixin.Tags"),e=a("./Collection"),f=d.modules.Db,d.synthesize(g.prototype,"state"),d.synthesize(g.prototype,"db"),d.synthesize(g.prototype,"name"),g.prototype.setData=function(a,b){var c,d;if(a){if(b=b||{$decouple:!0},b&&b.$decouple===!0&&(a=this.decouple(a)),this._linked){d={};for(c in this._data)"jQuery"!==c.substr(0,6)&&this._data.hasOwnProperty(c)&&void 0===a[c]&&(d[c]=1);a.$unset=d,this.updateObject(this._data,a,{})}else this._data=a;this.deferEmit("change",{type:"setData",data:this.decouple(this._data)})}return this},g.prototype.find=function(a,b){var c;return c=b&&b.$decouple===!1?this._data:this.decouple(this._data)},g.prototype.update=function(a,b,c){var d=this.updateObject(this._data,b,a,c);d&&this.deferEmit("change",{type:"update",data:this.decouple(this._data)})},g.prototype.updateObject=e.prototype.updateObject,g.prototype._isPositionalKey=function(a){return".$"===a.substr(a.length-2,2)},g.prototype._updateProperty=function(a,b,c){this._linked?(window.jQuery.observable(a).setProperty(b,c),this.debug()&&console.log(this.logIdentifier()+' Setting data-bound document property "'+b+'"')):(a[b]=c,this.debug()&&console.log(this.logIdentifier()+' Setting non-data-bound document property "'+b+'" to val "'+c+'"'))},g.prototype._updateIncrement=function(a,b,c){this._linked?window.jQuery.observable(a).setProperty(b,a[b]+c):a[b]+=c},g.prototype._updateSpliceMove=function(a,b,c){this._linked?(window.jQuery.observable(a).move(b,c),this.debug()&&console.log(this.logIdentifier()+' Moving data-bound document array index from "'+b+'" to "'+c+'"')):(a.splice(c,0,a.splice(b,1)[0]),this.debug()&&console.log(this.logIdentifier()+' Moving non-data-bound document array index from "'+b+'" to "'+c+'"'))},g.prototype._updateSplicePush=function(a,b,c){a.length>b?this._linked?window.jQuery.observable(a).insert(b,c):a.splice(b,0,c):this._linked?window.jQuery.observable(a).insert(c):a.push(c)},g.prototype._updatePush=function(a,b){this._linked?window.jQuery.observable(a).insert(b):a.push(b)},g.prototype._updatePull=function(a,b){this._linked?window.jQuery.observable(a).remove(b):a.splice(b,1)},g.prototype._updateMultiply=function(a,b,c){this._linked?window.jQuery.observable(a).setProperty(b,a[b]*c):a[b]*=c},g.prototype._updateRename=function(a,b,c){var d=a[b];this._linked?(window.jQuery.observable(a).setProperty(c,d),window.jQuery.observable(a).removeProperty(b)):(a[c]=d,delete a[b])},g.prototype._updateUnset=function(a,b){this._linked?window.jQuery.observable(a).removeProperty(b):delete a[b]},g.prototype.drop=function(a){return this.isDropped()?!0:this._db&&this._name&&this._db&&this._db._document&&this._db._document[this._name]?(this._state="dropped",delete this._db._document[this._name],delete this._data,this.emit("drop",this),a&&a(!1,!0),delete this._listeners,!0):!1},f.prototype.document=function(a){var b=this;if(a){if(a instanceof g){if("droppped"!==a.state())return a;a=a.name()}return this._document&&this._document[a]?this._document[a]:(this._document=this._document||{},this._document[a]=new g(a).db(this),b.emit("create",b._document[a],"document",a),this._document[a])}return this._document},f.prototype.documents=function(){var a,b,c=[];for(b in this._document)this._document.hasOwnProperty(b)&&(a=this._document[b],c.push({name:b,linked:void 0!==a.isLinked?a.isLinked():!1}));return c},d.finishModule("Document"),b.exports=g},{"./Collection":5,"./Shared":40}],11:[function(a,b,c){"use strict";var d,e,f,g,h=Math.PI/180,i=180/Math.PI,j=6371;d=[16,8,4,2,1],e="0123456789bcdefghjkmnpqrstuvwxyz",f={right:{even:"bc01fg45238967deuvhjyznpkmstqrwx"},left:{even:"238967debc01fg45kmstqrwxuvhjyznp"},top:{even:"p0r21436x8zb9dcf5h7kjnmqesgutwvy"},bottom:{even:"14365h7k9dcfesgujnmqp0r2twvyx8zb"}},g={right:{even:"bcfguvyz"},left:{even:"0145hjnp"},top:{even:"prxz"},bottom:{even:"028b"}},f.bottom.odd=f.left.even,f.top.odd=f.right.even,f.left.odd=f.bottom.even,f.right.odd=f.top.even,g.bottom.odd=g.left.even,g.top.odd=g.right.even,g.left.odd=g.bottom.even,g.right.odd=g.top.even;var k=function(){};k.prototype.radians=function(a){return a*h},k.prototype.degrees=function(a){return a*i},k.prototype.refineInterval=function(a,b,c){b&c?a[0]=(a[0]+a[1])/2:a[1]=(a[0]+a[1])/2},k.prototype.calculateNeighbours=function(a,b){var c;return b&&"object"!==b.type?(c=[],c[4]=a,c[3]=this.calculateAdjacent(a,"left"),c[5]=this.calculateAdjacent(a,"right"),c[1]=this.calculateAdjacent(a,"top"),c[7]=this.calculateAdjacent(a,"bottom"),c[0]=this.calculateAdjacent(c[3],"top"),c[2]=this.calculateAdjacent(c[5],"top"),c[6]=this.calculateAdjacent(c[3],"bottom"),c[8]=this.calculateAdjacent(c[5],"bottom")):(c={center:a,left:this.calculateAdjacent(a,"left"),right:this.calculateAdjacent(a,"right"),top:this.calculateAdjacent(a,"top"),bottom:this.calculateAdjacent(a,"bottom")},c.topLeft=this.calculateAdjacent(c.left,"top"),c.topRight=this.calculateAdjacent(c.right,"top"),c.bottomLeft=this.calculateAdjacent(c.left,"bottom"),c.bottomRight=this.calculateAdjacent(c.right,"bottom")),c},k.prototype.calculateLatLngByDistanceBearing=function(a,b,c){var d=a[1],e=a[0],f=Math.asin(Math.sin(this.radians(e))*Math.cos(b/j)+Math.cos(this.radians(e))*Math.sin(b/j)*Math.cos(this.radians(c))),g=this.radians(d)+Math.atan2(Math.sin(this.radians(c))*Math.sin(b/j)*Math.cos(this.radians(e)),Math.cos(b/j)-Math.sin(this.radians(e))*Math.sin(f)),h=(g+3*Math.PI)%(2*Math.PI)-Math.PI;return{lat:this.degrees(f),lng:this.degrees(h)}},k.prototype.calculateExtentByRadius=function(a,b){var c,d,e,f,g=[],h=[];return e=this.calculateLatLngByDistanceBearing(a,b,0),d=this.calculateLatLngByDistanceBearing(a,b,90),f=this.calculateLatLngByDistanceBearing(a,b,180),c=this.calculateLatLngByDistanceBearing(a,b,270),g[0]=e.lat,g[1]=f.lat,h[0]=c.lng,h[1]=d.lng,{lat:g,lng:h}},k.prototype.calculateHashArrayByRadius=function(a,b,c){var d,e,f,g=this.calculateExtentByRadius(a,b),h=[g.lat[0],g.lng[0]],i=[g.lat[0],g.lng[1]],j=[g.lat[1],g.lng[0]],k=this.encode(h[0],h[1],c),l=this.encode(i[0],i[1],c),m=this.encode(j[0],j[1],c),n=0,o=0,p=[];for(d=k,p.push(d);d!==l;)d=this.calculateAdjacent(d,"right"),n++,p.push(d);for(d=k;d!==m;)d=this.calculateAdjacent(d,"bottom"),o++;for(e=0;n>=e;e++)for(d=p[e],f=0;o>f;f++)d=this.calculateAdjacent(d,"bottom"),p.push(d);return p},k.prototype.calculateAdjacent=function(a,b){a=a.toLowerCase();var c=a.charAt(a.length-1),d=a.length%2?"odd":"even",h=a.substring(0,a.length-1);return-1!==g[b][d].indexOf(c)&&(h=this.calculateAdjacent(h,b)),h+e[f[b][d].indexOf(c)]},k.prototype.decode=function(a){var b,c,f,g,h,i,j,k=1,l=[],m=[];for(l[0]=-90,l[1]=90,m[0]=-180,m[1]=180,i=90,j=180,b=0;b<a.length;b++)for(c=a[b],f=e.indexOf(c),g=0;5>g;g++)h=d[g],k?(j/=2,this.refineInterval(m,f,h)):(i/=2,this.refineInterval(l,f,h)),k=!k;return l[2]=(l[0]+l[1])/2,m[2]=(m[0]+m[1])/2,{lat:l,lng:m}},k.prototype.encode=function(a,b,c){var f,g=1,h=[],i=[],j=0,k=0,l="";for(c||(c=12),h[0]=-90,h[1]=90,i[0]=-180,i[1]=180;l.length<c;)g?(f=(i[0]+i[1])/2,b>f?(k|=d[j],i[0]=f):i[1]=f):(f=(h[0]+h[1])/2,a>f?(k|=d[j],h[0]=f):h[1]=f),g=!g,4>j?j++:(l+=e[k],j=0,k=0);return l},"undefined"!=typeof b&&(b.exports=k)},{}],12:[function(a,b,c){"use strict";var d,e,f,g,h,i,j,k;d=a("./Shared");var l=function(a,b,c){this.init.apply(this,arguments)};l.prototype.init=function(a,b,c){var d=this;this._baseQuery={},this._selector=a,this._template=b,this._options=c||{},this._debug={},this._id=this.objectId(),this._collectionDroppedWrap=function(){d._collectionDropped.apply(d,arguments)}},d.addModule("Grid",l),d.mixin(l.prototype,"Mixin.Common"),d.mixin(l.prototype,"Mixin.ChainReactor"),d.mixin(l.prototype,"Mixin.Constants"),d.mixin(l.prototype,"Mixin.Triggers"),d.mixin(l.prototype,"Mixin.Events"),d.mixin(l.prototype,"Mixin.Tags"),f=a("./Collection"),g=a("./CollectionGroup"),h=a("./View"),k=a("./ReactorIO"),i=f.prototype.init,e=d.modules.Db,j=e.prototype.init,d.synthesize(l.prototype,"state"),d.synthesize(l.prototype,"name"),l.prototype.insert=function(){this._from.insert.apply(this._from,arguments)},l.prototype.update=function(){this._from.update.apply(this._from,arguments)},l.prototype.updateById=function(){this._from.updateById.apply(this._from,arguments)},l.prototype.remove=function(){this._from.remove.apply(this._from,arguments)},l.prototype.from=function(a){return void 0!==a&&(this._from&&(this._from.off("drop",this._collectionDroppedWrap),this._from._removeGrid(this)),"string"==typeof a&&(a=this._db.collection(a)),this._from=a,this._from.on("drop",this._collectionDroppedWrap), "function"==typeof this._from.query&&(this._baseQuery=this._from.query()),this.refresh()),this},d.synthesize(l.prototype,"db",function(a){return a&&this.debug(a.debug()),this.$super.apply(this,arguments)}),l.prototype._collectionDropped=function(a){a&&delete this._from},l.prototype.drop=function(a){return this.isDropped()?!0:this._from?(this._from.unlink(this._selector,this.template()),this._from.off("drop",this._collectionDroppedWrap),this._from._removeGrid(this),(this.debug()||this._db&&this._db.debug())&&console.log(this.logIdentifier()+" Dropping grid "+this._selector),this._state="dropped",this._db&&this._selector&&delete this._db._grid[this._selector],this.emit("drop",this),a&&a(!1,!0),delete this._selector,delete this._template,delete this._from,delete this._db,delete this._listeners,!0):!1},l.prototype.template=function(a){return void 0!==a?(this._template=a,this):this._template},l.prototype._sortGridClick=function(a){var b,c=window.jQuery(a.currentTarget),e=c.attr("data-grid-sort")||"",f=-1===parseInt(c.attr("data-grid-dir")||"-1",10)?1:-1,g=e.split(","),h={};for(window.jQuery(this._selector).find("[data-grid-dir]").removeAttr("data-grid-dir"),c.attr("data-grid-dir",f),b=0;b<g.length;b++)h[g]=f;d.mixin(h,this._options.$orderBy),this.emit("beforeChange","sort"),this.emit("beforeSort",h),this._from.orderBy(h),this.emit("sort",h)},l.prototype.query=function(a,b){return this._baseQuery=a,this._baseQueryOptions=b,this},l.prototype.refresh=function(){if(this._from){if(!this._from.link)throw"Grid requires the AutoBind module in order to operate!";var a=this,b=window.jQuery(this._selector),c=function(){a._sortGridClick.apply(a,arguments)};if(b.html(""),a._from.orderBy&&b.off("click","[data-grid-sort]",c),a._options.$wrap=a._options.$wrap||"gridRow",a._from.link(a._selector,a.template(),a._options),a._from.orderBy&&b.on("click","[data-grid-sort]",c),a._from.query){var d=a.decouple(a._baseQuery);b.find("[data-grid-filter]").each(function(c,e){e=window.jQuery(e);var f,g,h,i,j,k=e.attr("data-grid-filter"),l=e.attr("data-grid-vartype"),m={},n=e.html(),o=a._db.view("tmpGridFilter_"+a._id+"_"+k);m[k]=1,j={$distinct:m},o.query(j).orderBy(m).from(a._from._from),i=function(){o.refresh()},a._from._from.on("change",i),a.on("drop",function(){a._from&&a._from._from&&a._from._from.off("change",i),o.drop()}),h=['<div class="dropdown" id="'+a._id+"_"+k+'">','<button class="btn btn-default dropdown-toggle" type="button" id="'+a._id+"_"+k+'_dropdownButton" data-toggle="dropdown" aria-expanded="true">',n+' <span class="caret"></span>',"</button>","</div>"],f=window.jQuery(h.join("")),g=window.jQuery('<ul class="dropdown-menu" role="menu" id="'+a._id+"_"+k+'_dropdownMenu"></ul>'),f.append(g),e.html(f),o.link(g,{template:['<li role="presentation" class="input-group" style="width: 240px; padding-left: 10px; padding-right: 10px; padding-top: 5px;">','<input type="search" class="form-control gridFilterSearch" placeholder="Search...">','<span class="input-group-btn">','<button class="btn btn-default gridFilterClearSearch" type="button"><span class="glyphicon glyphicon-remove-circle glyphicons glyphicons-remove"></span></button>',"</span>","</li>",'<li role="presentation" class="divider"></li>','<li role="presentation" data-val="$all">','<a role="menuitem" tabindex="-1">','<input type="checkbox" checked>&nbsp;All',"</a>","</li>",'<li role="presentation" class="divider"></li>',"{^{for options}}",'<li role="presentation" data-link="data-val{:'+k+'}">','<a role="menuitem" tabindex="-1">','<input type="checkbox">&nbsp;{^{:'+k+"}}","</a>","</li>","{{/for}}"].join("")},{$wrap:"options"}),b.on("keyup","#"+a._id+"_"+k+"_dropdownMenu .gridFilterSearch",function(a){var b=window.jQuery(this),c=o.query(),d=b.val();d?c[k]=new RegExp(d,"gi"):delete c[k],o.query(c)}),b.on("click","#"+a._id+"_"+k+"_dropdownMenu .gridFilterClearSearch",function(a){window.jQuery(this).parents("li").find(".gridFilterSearch").val("");var b=o.query();delete b[k],o.query(b)}),b.on("click","#"+a._id+"_"+k+"_dropdownMenu li",function(b){b.stopPropagation();var c,e,f,g,h,i=$(this),j=i.find('input[type="checkbox"]'),m=!0;if(window.jQuery(b.target).is("input")?(j.prop("checked",j.prop("checked")),e=j.is(":checked")):(j.prop("checked",!j.prop("checked")),e=j.is(":checked")),g=window.jQuery(this),c=g.attr("data-val"),"$all"===c)delete d[k],g.parent().find('li[data-val!="$all"]').find('input[type="checkbox"]').prop("checked",!1);else{switch(g.parent().find('[data-val="$all"]').find('input[type="checkbox"]').prop("checked",!1),l){case"integer":c=parseInt(c,10);break;case"float":c=parseFloat(c)}for(d[k]=d[k]||{$in:[]},f=d[k].$in,f||(f=d[k].$in=[]),h=0;h<f.length;h++)if(f[h]===c){e===!1&&f.splice(h,1),m=!1;break}m&&e&&f.push(c),f.length||delete d[k]}a.emit("beforeChange","filter"),a.emit("beforeFilter",d),a._from.queryData(d),a._from.pageFirst&&a._from.pageFirst()})})}a.emit("refresh")}return this},l.prototype.count=function(){return this._from.count()},f.prototype.grid=h.prototype.grid=function(a,b,c){if(this._db&&this._db._grid){if(void 0!==a){if(void 0!==b){if(this._db._grid[a])throw this.logIdentifier()+" Cannot create a grid because a grid with this name already exists: "+a;var d=new l(a,b,c).db(this._db).from(this);return this._grid=this._grid||[],this._grid.push(d),this._db._grid[a]=d,d}return this._db._grid[a]}return this._db._grid}},f.prototype.unGrid=h.prototype.unGrid=function(a,b,c){var d,e;if(this._db&&this._db._grid){if(a&&b){if(this._db._grid[a])return e=this._db._grid[a],delete this._db._grid[a],e.drop();throw this.logIdentifier()+" Cannot remove grid because a grid with this name does not exist: "+name}for(d in this._db._grid)this._db._grid.hasOwnProperty(d)&&(e=this._db._grid[d],delete this._db._grid[d],e.drop(),this.debug()&&console.log(this.logIdentifier()+' Removed grid binding "'+d+'"'));this._db._grid={}}},f.prototype._addGrid=g.prototype._addGrid=h.prototype._addGrid=function(a){return void 0!==a&&(this._grid=this._grid||[],this._grid.push(a)),this},f.prototype._removeGrid=g.prototype._removeGrid=h.prototype._removeGrid=function(a){if(void 0!==a&&this._grid){var b=this._grid.indexOf(a);b>-1&&this._grid.splice(b,1)}return this},e.prototype.init=function(){this._grid={},j.apply(this,arguments)},e.prototype.gridExists=function(a){return Boolean(this._grid[a])},e.prototype.grid=function(a,b,c){return this._grid[a]||(this.debug()||this._db&&this._db.debug())&&console.log(this.logIdentifier()+" Creating grid "+a),this._grid[a]=this._grid[a]||new l(a,b,c).db(this),this._grid[a]},e.prototype.unGrid=function(a,b,c){return this._grid[a]||(this.debug()||this._db&&this._db.debug())&&console.log(this.logIdentifier()+" Creating grid "+a),this._grid[a]=this._grid[a]||new l(a,b,c).db(this),this._grid[a]},e.prototype.grids=function(){var a,b,c=[];for(b in this._grid)this._grid.hasOwnProperty(b)&&(a=this._grid[b],c.push({name:b,count:a.count(),linked:void 0!==a.isLinked?a.isLinked():!1}));return c},d.finishModule("Grid"),b.exports=l},{"./Collection":5,"./CollectionGroup":6,"./ReactorIO":38,"./Shared":40,"./View":41}],13:[function(a,b,c){"use strict";var d,e,f,g;d=a("./Shared"),g=a("./Overload");var h=function(a,b){this.init.apply(this,arguments)};h.prototype.init=function(a,b){if(this._options=b,this._selector=window.jQuery(this._options.selector),!this._selector[0])throw this.classIdentifier()+' "'+a.name()+'": Chart target element does not exist via selector: '+this._options.selector;this._listeners={},this._collection=a,this._options.series=[],b.chartOptions=b.chartOptions||{},b.chartOptions.credits=!1;var c,d,e;switch(this._options.type){case"pie":this._selector.highcharts(this._options.chartOptions),this._chart=this._selector.highcharts(),c=this._collection.find(),d={allowPointSelect:!0,cursor:"pointer",dataLabels:{enabled:!0,format:"<b>{point.name}</b>: {y} ({point.percentage:.0f}%)",style:{color:window.Highcharts.theme&&window.Highcharts.theme.contrastTextColor||"black"}}},e=this.pieDataFromCollectionData(c,this._options.keyField,this._options.valField),window.jQuery.extend(d,this._options.seriesOptions),window.jQuery.extend(d,{name:this._options.seriesName,data:e}),this._chart.addSeries(d,!0,!0);break;case"line":case"area":case"column":case"bar":e=this.seriesDataFromCollectionData(this._options.seriesField,this._options.keyField,this._options.valField,this._options.orderBy,this._options),this._options.chartOptions.xAxis=e.xAxis,this._options.chartOptions.series=e.series,this._selector.highcharts(this._options.chartOptions),this._chart=this._selector.highcharts();break;default:throw this.classIdentifier()+' "'+a.name()+'": Chart type specified is not currently supported by ForerunnerDB: '+this._options.type}this._hookEvents()},d.addModule("Highchart",h),e=d.modules.Collection,f=e.prototype.init,d.mixin(h.prototype,"Mixin.Common"),d.mixin(h.prototype,"Mixin.Events"),d.synthesize(h.prototype,"state"),h.prototype.pieDataFromCollectionData=function(a,b,c){var d,e=[];for(d=0;d<a.length;d++)e.push([a[d][b],a[d][c]]);return e},h.prototype.seriesDataFromCollectionData=function(a,b,c,d,e){var f,g,h,i,j,k,l,m=this._collection.distinct(a),n=[],o=e&&e.chartOptions&&e.chartOptions.xAxis?e.chartOptions.xAxis:{categories:[]};for(k=0;k<m.length;k++){for(f=m[k],g={},g[a]=f,i=[],h=this._collection.find(g,{orderBy:d}),l=0;l<h.length;l++)o.categories?(o.categories.push(h[l][b]),i.push(h[l][c])):i.push([h[l][b],h[l][c]]);if(j={name:f,data:i},e.seriesOptions)for(l in e.seriesOptions)e.seriesOptions.hasOwnProperty(l)&&(j[l]=e.seriesOptions[l]);n.push(j)}return{xAxis:o,series:n}},h.prototype._hookEvents=function(){var a=this;a._collection.on("change",function(){a._changeListener.apply(a,arguments)}),a._collection.on("drop",function(){a.drop.apply(a)})},h.prototype._changeListener=function(){var a=this;if("undefined"!=typeof a._collection&&a._chart){var b,c=a._collection.find();switch(a._options.type){case"pie":a._chart.series[0].setData(a.pieDataFromCollectionData(c,a._options.keyField,a._options.valField),!0,!0);break;case"bar":case"line":case"area":case"column":var d=a.seriesDataFromCollectionData(a._options.seriesField,a._options.keyField,a._options.valField,a._options.orderBy,a._options);for(d.xAxis.categories&&a._chart.xAxis[0].setCategories(d.xAxis.categories),b=0;b<d.series.length;b++)a._chart.series[b]?a._chart.series[b].setData(d.series[b].data,!0,!0):a._chart.addSeries(d.series[b],!0,!0)}}},h.prototype.drop=function(a){return this.isDropped()?!0:(this._state="dropped",this._chart&&this._chart.destroy(),this._collection&&(this._collection.off("change",this._changeListener),this._collection.off("drop",this.drop),this._collection._highcharts&&delete this._collection._highcharts[this._options.selector]),delete this._chart,delete this._options,delete this._collection,this.emit("drop",this),a&&a(!1,!0),delete this._listeners,!0)},e.prototype.init=function(){this._highcharts={},f.apply(this,arguments)},e.prototype.pieChart=new g({object:function(a){return a.type="pie",a.chartOptions=a.chartOptions||{},a.chartOptions.chart=a.chartOptions.chart||{},a.chartOptions.chart.type="pie",this._highcharts[a.selector]||(this._highcharts[a.selector]=new h(this,a)),this._highcharts[a.selector]},"*, string, string, string, ...":function(a,b,c,d,e){e=e||{},e.selector=a,e.keyField=b,e.valField=c,e.seriesName=d,this.pieChart(e)}}),e.prototype.lineChart=new g({string:function(a){return this._highcharts[a]},object:function(a){return a.type="line",a.chartOptions=a.chartOptions||{},a.chartOptions.chart=a.chartOptions.chart||{},a.chartOptions.chart.type="line",this._highcharts[a.selector]||(this._highcharts[a.selector]=new h(this,a)),this._highcharts[a.selector]},"*, string, string, string, ...":function(a,b,c,d,e){e=e||{},e.seriesField=b,e.selector=a,e.keyField=c,e.valField=d,this.lineChart(e)}}),e.prototype.areaChart=new g({object:function(a){return a.type="area",a.chartOptions=a.chartOptions||{},a.chartOptions.chart=a.chartOptions.chart||{},a.chartOptions.chart.type="area",this._highcharts[a.selector]||(this._highcharts[a.selector]=new h(this,a)),this._highcharts[a.selector]},"*, string, string, string, ...":function(a,b,c,d,e){e=e||{},e.seriesField=b,e.selector=a,e.keyField=c,e.valField=d,this.areaChart(e)}}),e.prototype.columnChart=new g({object:function(a){return a.type="column",a.chartOptions=a.chartOptions||{},a.chartOptions.chart=a.chartOptions.chart||{},a.chartOptions.chart.type="column",this._highcharts[a.selector]||(this._highcharts[a.selector]=new h(this,a)),this._highcharts[a.selector]},"*, string, string, string, ...":function(a,b,c,d,e){e=e||{},e.seriesField=b,e.selector=a,e.keyField=c,e.valField=d,this.columnChart(e)}}),e.prototype.barChart=new g({object:function(a){return a.type="bar",a.chartOptions=a.chartOptions||{},a.chartOptions.chart=a.chartOptions.chart||{},a.chartOptions.chart.type="bar",this._highcharts[a.selector]||(this._highcharts[a.selector]=new h(this,a)),this._highcharts[a.selector]},"*, string, string, string, ...":function(a,b,c,d,e){e=e||{},e.seriesField=b,e.selector=a,e.keyField=c,e.valField=d,this.barChart(e)}}),e.prototype.stackedBarChart=new g({object:function(a){return a.type="bar",a.chartOptions=a.chartOptions||{},a.chartOptions.chart=a.chartOptions.chart||{},a.chartOptions.chart.type="bar",a.plotOptions=a.plotOptions||{},a.plotOptions.series=a.plotOptions.series||{},a.plotOptions.series.stacking=a.plotOptions.series.stacking||"normal",this._highcharts[a.selector]||(this._highcharts[a.selector]=new h(this,a)),this._highcharts[a.selector]},"*, string, string, string, ...":function(a,b,c,d,e){e=e||{},e.seriesField=b,e.selector=a,e.keyField=c,e.valField=d,this.stackedBarChart(e)}}),e.prototype.dropChart=function(a){this._highcharts&&this._highcharts[a]&&this._highcharts[a].drop()},d.finishModule("Highchart"),b.exports=h},{"./Overload":32,"./Shared":40}],14:[function(a,b,c){"use strict";var d=a("./Shared"),e=a("./Path"),f=a("./BinaryTree"),g=a("./GeoHash"),h=new e,i=new g,j=[5e3,1250,156,39.1,4.89,1.22,.153,.0382,.00477,.00119,149e-6,372e-7],k=function(){this.init.apply(this,arguments)};k.prototype.init=function(a,b,c){this._btree=new f,this._btree.index(a),this._size=0,this._id=this._itemKeyHash(a,a),this._debug=b&&b.debug?b.debug:!1,this.unique(b&&b.unique?b.unique:!1),void 0!==a&&this.keys(a),void 0!==c&&(this.collection(c),this._btree.primaryKey(c.primaryKey())),this.name(b&&b.name?b.name:this._id),this._btree.debug(this._debug)},d.addModule("Index2d",k),d.mixin(k.prototype,"Mixin.Common"),d.mixin(k.prototype,"Mixin.ChainReactor"),d.mixin(k.prototype,"Mixin.Sorting"),k.prototype.id=function(){return this._id},k.prototype.state=function(){return this._state},k.prototype.size=function(){return this._size},d.synthesize(k.prototype,"data"),d.synthesize(k.prototype,"name"),d.synthesize(k.prototype,"collection"),d.synthesize(k.prototype,"type"),d.synthesize(k.prototype,"unique"),k.prototype.keys=function(a){return void 0!==a?(this._keys=a,this._keyCount=h.parse(this._keys).length,this):this._keys},k.prototype.rebuild=function(){if(this._collection){var a,b=this._collection.subset({},{$decouple:!1,$orderBy:this._keys}),c=b.find(),d=c.length;for(this._btree.clear(),this._size=0,this._unique&&(this._uniqueLookup={}),a=0;d>a;a++)this.insert(c[a])}this._state={name:this._name,keys:this._keys,indexSize:this._size,built:new Date,updated:new Date,ok:!0}},k.prototype.insert=function(a,b){var c,d=this._unique;a=this.decouple(a),d&&(c=this._itemHash(a,this._keys),this._uniqueLookup[c]=a);var e,f,g,j,k,l=this._btree.keys();for(k=0;k<l.length;k++)e=h.get(a,l[k].path),e instanceof Array&&(g=e[0],j=e[1],f=i.encode(g,j),h.set(a,l[k].path,f));return this._btree.insert(a)?(this._size++,!0):!1},k.prototype.remove=function(a,b){var c,d=this._unique;return d&&(c=this._itemHash(a,this._keys),delete this._uniqueLookup[c]),this._btree.remove(a)?(this._size--,!0):!1},k.prototype.violation=function(a){var b=this._itemHash(a,this._keys);return Boolean(this._uniqueLookup[b])},k.prototype.hashViolation=function(a){return Boolean(this._uniqueLookup[a])},k.prototype.lookup=function(a,b,c){var d,e,f,g,i=this._btree.keys();for(g=0;g<i.length;g++)if(d=i[g].path,e=h.get(a,d),"object"==typeof e)return e.$near&&(f=[],f=f.concat(this.near(d,e.$near,b,c))),e.$geoWithin&&(f=[],f=f.concat(this.geoWithin(d,e.$geoWithin,b,c))),f;return this._btree.lookup(a,b)},k.prototype.near=function(a,b,c,d){var e,f,g,k,l,m,n,o,p,q,r,s,t=this,u=[],v=this._collection.primaryKey();if("km"===b.$distanceUnits){for(o=b.$maxDistance,s=0;s<j.length;s++)if(o>j[s]){n=s+1;break}}else if("miles"===b.$distanceUnits)for(o=1.60934*b.$maxDistance,s=0;s<j.length;s++)if(o>j[s]){n=s+1;break}for(0===n&&(n=1),d&&d.time("index2d.calculateHashArea"),e=i.calculateHashArrayByRadius(b.$point,o,n),d&&d.time("index2d.calculateHashArea"),d&&(d.data("index2d.near.precision",n),d.data("index2d.near.hashArea",e),d.data("index2d.near.maxDistanceKm",o),d.data("index2d.near.centerPointCoords",[b.$point[0],b.$point[1]])),m=[],f=0,k={},g=[],d&&d.time("index2d.near.getDocsInsideHashArea"),s=0;s<e.length;s++)l=this._btree.startsWith(a,e[s]),k[e[s]]=l,f+=l._visitedCount,g=g.concat(l._visitedNodes),m=m.concat(l);if(d&&(d.time("index2d.near.getDocsInsideHashArea"),d.data("index2d.near.startsWith",k),d.data("index2d.near.visitedTreeNodes",g)),d&&d.time("index2d.near.lookupDocsById"),m=this._collection._primaryIndex.lookup(m),d&&d.time("index2d.near.lookupDocsById"),b.$distanceField&&(m=this.decouple(m)),m.length){for(p={},d&&d.time("index2d.near.calculateDistanceFromCenter"),s=0;s<m.length;s++)r=h.get(m[s],a),q=p[m[s][v]]=this.distanceBetweenPoints(b.$point[0],b.$point[1],r[0],r[1]),o>=q&&(b.$distanceField&&h.set(m[s],b.$distanceField,"km"===b.$distanceUnits?q:Math.round(.621371*q)),b.$geoHashField&&h.set(m[s],b.$geoHashField,i.encode(r[0],r[1],n)),u.push(m[s]));d&&d.time("index2d.near.calculateDistanceFromCenter"),d&&d.time("index2d.near.sortResultsByDistance"),u.sort(function(a,b){return t.sortAsc(p[a[v]],p[b[v]])}),d&&d.time("index2d.near.sortResultsByDistance")}return u},k.prototype.geoWithin=function(a,b,c){return console.log("geoWithin() is currently a prototype method with no actual implementation... it just returns a blank array."),[]},k.prototype.distanceBetweenPoints=function(a,b,c,d){var e=6371,f=this.toRadians(a),g=this.toRadians(c),h=this.toRadians(c-a),i=this.toRadians(d-b),j=Math.sin(h/2)*Math.sin(h/2)+Math.cos(f)*Math.cos(g)*Math.sin(i/2)*Math.sin(i/2),k=2*Math.atan2(Math.sqrt(j),Math.sqrt(1-j));return e*k},k.prototype.toRadians=function(a){return.01747722222222*a},k.prototype.match=function(a,b){return this._btree.match(a,b)},k.prototype._itemHash=function(a,b){var c,d,f=new e,g="";for(c=f.parse(b),d=0;d<c.length;d++)g&&(g+="_"),g+=f.value(a,c[d].path).join(":");return g},k.prototype._itemKeyHash=function(a,b){var c,d,f=new e,g="";for(c=f.parse(b),d=0;d<c.length;d++)g&&(g+="_"),g+=f.keyValue(a,c[d].path);return g},k.prototype._itemHashArr=function(a,b){var c,d,f,g,h,i=new e,j=[];for(c=i.parse(b),g=0;g<c.length;g++)for(d=i.value(a,c[g].path),f=0;f<d.length;f++)if(0===g)j.push(d[f]);else for(h=0;h<j.length;h++)j[h]=j[h]+"_"+d[f];return j},d.index["2d"]=k,d.finishModule("Index2d"),b.exports=k},{"./BinaryTree":3,"./GeoHash":11,"./Path":34,"./Shared":40}],15:[function(a,b,c){"use strict";var d=a("./Shared"),e=a("./Path"),f=a("./BinaryTree"),g=function(){this.init.apply(this,arguments)};g.prototype.init=function(a,b,c){this._btree=new f,this._btree.index(a),this._size=0,this._id=this._itemKeyHash(a,a),this._debug=b&&b.debug?b.debug:!1,this.unique(b&&b.unique?b.unique:!1),void 0!==a&&this.keys(a),void 0!==c&&(this.collection(c),this._btree.primaryKey(c.primaryKey())),this.name(b&&b.name?b.name:this._id),this._btree.debug(this._debug)},d.addModule("IndexBinaryTree",g),d.mixin(g.prototype,"Mixin.ChainReactor"),d.mixin(g.prototype,"Mixin.Sorting"),g.prototype.id=function(){return this._id},g.prototype.state=function(){return this._state},g.prototype.size=function(){return this._size},d.synthesize(g.prototype,"data"),d.synthesize(g.prototype,"name"),d.synthesize(g.prototype,"collection"),d.synthesize(g.prototype,"type"),d.synthesize(g.prototype,"unique"),g.prototype.keys=function(a){return void 0!==a?(this._keys=a,this._keyCount=(new e).parse(this._keys).length,this):this._keys},g.prototype.rebuild=function(){if(this._collection){var a,b=this._collection.subset({},{$decouple:!1,$orderBy:this._keys}),c=b.find(),d=c.length;for(this._btree.clear(),this._size=0,this._unique&&(this._uniqueLookup={}),a=0;d>a;a++)this.insert(c[a])}this._state={name:this._name,keys:this._keys,indexSize:this._size,built:new Date,updated:new Date,ok:!0}},g.prototype.insert=function(a,b){var c,d=this._unique;return d&&(c=this._itemHash(a,this._keys),this._uniqueLookup[c]=a),this._btree.insert(a)?(this._size++,!0):!1},g.prototype.remove=function(a,b){var c,d=this._unique;return d&&(c=this._itemHash(a,this._keys),delete this._uniqueLookup[c]),this._btree.remove(a)?(this._size--,!0):!1},g.prototype.violation=function(a){var b=this._itemHash(a,this._keys);return Boolean(this._uniqueLookup[b])},g.prototype.hashViolation=function(a){return Boolean(this._uniqueLookup[a])},g.prototype.lookup=function(a,b,c){return this._btree.lookup(a,b,c)},g.prototype.match=function(a,b){return this._btree.match(a,b)},g.prototype._itemHash=function(a,b){var c,d,f=new e,g="";for(c=f.parse(b),d=0;d<c.length;d++)g&&(g+="_"),g+=f.value(a,c[d].path).join(":");return g},g.prototype._itemKeyHash=function(a,b){var c,d,f=new e,g="";for(c=f.parse(b),d=0;d<c.length;d++)g&&(g+="_"),g+=f.keyValue(a,c[d].path);return g},g.prototype._itemHashArr=function(a,b){var c,d,f,g,h,i=new e,j=[];for(c=i.parse(b),g=0;g<c.length;g++)for(d=i.value(a,c[g].path),f=0;f<d.length;f++)if(0===g)j.push(d[f]);else for(h=0;h<j.length;h++)j[h]=j[h]+"_"+d[f];return j},d.index.btree=g,d.finishModule("IndexBinaryTree"),b.exports=g},{"./BinaryTree":3,"./Path":34,"./Shared":40}],16:[function(a,b,c){"use strict";var d=a("./Shared"),e=a("./Path"),f=function(){this.init.apply(this,arguments)};f.prototype.init=function(a,b,c){this._crossRef={},this._size=0,this._id=this._itemKeyHash(a,a),this.data({}),this.unique(b&&b.unique?b.unique:!1),void 0!==a&&this.keys(a),void 0!==c&&this.collection(c),this.name(b&&b.name?b.name:this._id)},d.addModule("IndexHashMap",f),d.mixin(f.prototype,"Mixin.ChainReactor"),f.prototype.id=function(){return this._id},f.prototype.state=function(){return this._state},f.prototype.size=function(){return this._size},d.synthesize(f.prototype,"data"),d.synthesize(f.prototype,"name"),d.synthesize(f.prototype,"collection"),d.synthesize(f.prototype,"type"),d.synthesize(f.prototype,"unique"),f.prototype.keys=function(a){return void 0!==a?(this._keys=a,this._keyCount=(new e).parse(this._keys).length,this):this._keys},f.prototype.rebuild=function(){if(this._collection){var a,b=this._collection.subset({},{$decouple:!1,$orderBy:this._keys}),c=b.find(),d=c.length;for(this._data={},this._size=0,this._unique&&(this._uniqueLookup={}),a=0;d>a;a++)this.insert(c[a])}this._state={name:this._name,keys:this._keys,indexSize:this._size,built:new Date,updated:new Date,ok:!0}},f.prototype.insert=function(a,b){var c,d,e,f=this._unique;for(f&&(c=this._itemHash(a,this._keys),this._uniqueLookup[c]=a),d=this._itemHashArr(a,this._keys),e=0;e<d.length;e++)this.pushToPathValue(d[e],a)},f.prototype.update=function(a,b){},f.prototype.remove=function(a,b){var c,d,e,f=this._unique;for(f&&(c=this._itemHash(a,this._keys),delete this._uniqueLookup[c]),d=this._itemHashArr(a,this._keys),e=0;e<d.length;e++)this.pullFromPathValue(d[e],a)},f.prototype.violation=function(a){var b=this._itemHash(a,this._keys);return Boolean(this._uniqueLookup[b])},f.prototype.hashViolation=function(a){return Boolean(this._uniqueLookup[a])},f.prototype.pushToPathValue=function(a,b){var c=this._data[a]=this._data[a]||[];-1===c.indexOf(b)&&(c.push(b),this._size++,this.pushToCrossRef(b,c))},f.prototype.pullFromPathValue=function(a,b){var c,d=this._data[a];c=d.indexOf(b),c>-1&&(d.splice(c,1),this._size--,this.pullFromCrossRef(b,d)),d.length||delete this._data[a]},f.prototype.pull=function(a){var b,c,d=a[this._collection.primaryKey()],e=this._crossRef[d],f=e.length;for(b=0;f>b;b++)c=e[b],this._pullFromArray(c,a);this._size--,delete this._crossRef[d]},f.prototype._pullFromArray=function(a,b){for(var c=a.length;c--;)a[c]===b&&a.splice(c,1)},f.prototype.pushToCrossRef=function(a,b){var c,d=a[this._collection.primaryKey()];this._crossRef[d]=this._crossRef[d]||[],c=this._crossRef[d],-1===c.indexOf(b)&&c.push(b)},f.prototype.pullFromCrossRef=function(a,b){var c=a[this._collection.primaryKey()];delete this._crossRef[c]},f.prototype.lookup=function(a){return this._data[this._itemHash(a,this._keys)]||[]},f.prototype.match=function(a,b){var c,d=new e,f=d.parseArr(this._keys),g=d.parseArr(a),h=[],i=0;for(c=0;c<f.length;c++){if(g[c]!==f[c])return{matchedKeys:[],totalKeyCount:g.length,score:0};i++,h.push(g[c])}return{matchedKeys:h,totalKeyCount:g.length,score:i}},f.prototype._itemHash=function(a,b){var c,d,f=new e,g="";for(c=f.parse(b),d=0;d<c.length;d++)g&&(g+="_"),g+=f.value(a,c[d].path).join(":");return g},f.prototype._itemKeyHash=function(a,b){var c,d,f=new e,g="";for(c=f.parse(b),d=0;d<c.length;d++)g&&(g+="_"),g+=f.keyValue(a,c[d].path);return g},f.prototype._itemHashArr=function(a,b){var c,d,f,g,h,i=new e,j=[];for(c=i.parse(b),g=0;g<c.length;g++)for(d=i.value(a,c[g].path),f=0;f<d.length;f++)if(0===g)j.push(d[f]);else for(h=0;h<j.length;h++)j[h]=j[h]+"_"+d[f];return j},d.index.hashed=f,d.finishModule("IndexHashMap"),b.exports=f},{"./Path":34,"./Shared":40}],17:[function(a,b,c){"use strict";var d=a("./Shared"),e=function(a){this.init.apply(this,arguments)};e.prototype.init=function(a){this._name=a,this._data={},this._primaryKey="_id"},d.addModule("KeyValueStore",e),d.mixin(e.prototype,"Mixin.ChainReactor"),d.synthesize(e.prototype,"name"),e.prototype.primaryKey=function(a){return void 0!==a?(this._primaryKey=a,this):this._primaryKey},e.prototype.truncate=function(){return this._data={},this},e.prototype.set=function(a,b){return this._data[a]=b?b:!0,this},e.prototype.get=function(a){return this._data[a]},e.prototype.lookup=function(a){var b,c,d,e=this._primaryKey,f=typeof a,g=[];if("string"===f||"number"===f)return d=this.get(a),void 0!==d?[d]:[];if("object"===f){if(a instanceof Array){for(c=a.length,g=[],b=0;c>b;b++)d=this.lookup(a[b]),d&&(d instanceof Array?g=g.concat(d):g.push(d));return g}if(void 0!==a[e]&&null!==a[e])return this.lookup(a[e])}},e.prototype.unSet=function(a){return delete this._data[a],this},e.prototype.uniqueSet=function(a,b){return void 0===this._data[a]?(this._data[a]=b,!0):!1},d.finishModule("KeyValueStore"),b.exports=e},{"./Shared":40}],18:[function(a,b,c){"use strict";var d=a("./Shared"),e=a("./Operation"),f=function(){this.init.apply(this,arguments)};f.prototype.init=function(){this._data=[]},d.addModule("Metrics",f),d.mixin(f.prototype,"Mixin.ChainReactor"),f.prototype.create=function(a){var b=new e(a);return this._enabled&&this._data.push(b),b},f.prototype.start=function(){return this._enabled=!0,this},f.prototype.stop=function(){return this._enabled=!1,this},f.prototype.clear=function(){return this._data=[],this},f.prototype.list=function(){return this._data},d.finishModule("Metrics"),b.exports=f},{"./Operation":31,"./Shared":40}],19:[function(a,b,c){"use strict";var d={preSetData:function(){},postSetData:function(){}};b.exports=d},{}],20:[function(a,b,c){"use strict";var d={chain:function(a){this.debug&&this.debug()&&(a._reactorIn&&a._reactorOut?console.log(a._reactorIn.logIdentifier()+' Adding target "'+a._reactorOut.instanceIdentifier()+'" to the chain reactor target list'):console.log(this.logIdentifier()+' Adding target "'+a.instanceIdentifier()+'" to the chain reactor target list')),this._chain=this._chain||[];var b=this._chain.indexOf(a);-1===b&&this._chain.push(a)},unChain:function(a){if(this.debug&&this.debug()&&(a._reactorIn&&a._reactorOut?console.log(a._reactorIn.logIdentifier()+' Removing target "'+a._reactorOut.instanceIdentifier()+'" from the chain reactor target list'):console.log(this.logIdentifier()+' Removing target "'+a.instanceIdentifier()+'" from the chain reactor target list')),this._chain){var b=this._chain.indexOf(a);b>-1&&this._chain.splice(b,1)}},chainEnabled:function(a){return void 0!==a?(this._chainDisabled=!a,this):!this._chainDisabled},chainWillSend:function(){return Boolean(this._chain&&!this._chainDisabled)},chainSend:function(a,b,c){if(this._chain&&!this._chainDisabled){var d,e,f=this._chain,g=f.length,h=this.decouple(b,g);for(e=0;g>e;e++){if(d=f[e],d._state&&(!d._state||d.isDropped()))throw console.log("Reactor Data:",a,b,c),console.log("Reactor Node:",d),"Chain reactor attempting to send data to target reactor node that is in a dropped state!";this.debug&&this.debug()&&(d._reactorIn&&d._reactorOut?console.log(d._reactorIn.logIdentifier()+' Sending data down the chain reactor pipe to "'+d._reactorOut.instanceIdentifier()+'"'):console.log(this.logIdentifier()+' Sending data down the chain reactor pipe to "'+d.instanceIdentifier()+'"')),d.chainReceive&&d.chainReceive(this,a,h[e],c)}}},chainReceive:function(a,b,c,d){var e={sender:a,type:b,data:c,options:d},f=!1;this.debug&&this.debug()&&console.log(this.logIdentifier()+" Received data from parent reactor node"),this._chainHandler&&(f=this._chainHandler(e)),f||this.chainSend(e.type,e.data,e.options)}};b.exports=d},{}],21:[function(a,b,c){"use strict";var d,e=0,f=a("./Overload"),g=a("./Serialiser"),h=new g;d={serialiser:h,make:function(a){return h.convert(a)},store:function(a,b){if(void 0!==a){if(void 0!==b)return this._store=this._store||{},this._store[a]=b,this;if(this._store)return this._store[a]}},unStore:function(a){return void 0!==a&&delete this._store[a],this},decouple:function(a,b){if(void 0!==a&&""!==a){if(b){var c,d=this.jStringify(a),e=[];for(c=0;b>c;c++)e.push(this.jParse(d));return e}return this.jParse(this.jStringify(a))}},jParse:function(a){return JSON.parse(a,h.reviver())},jStringify:function(a){return JSON.stringify(a)},objectId:function(a){var b,c=Math.pow(10,17);if(a){var d,f=0,g=a.length;for(d=0;g>d;d++)f+=a.charCodeAt(d)*c;b=f.toString(16)}else e++,b=(e+(Math.random()*c+Math.random()*c+Math.random()*c+Math.random()*c)).toString(16);return b},hash:function(a){return JSON.stringify(a)},debug:new f([function(){return this._debug&&this._debug.all},function(a){return void 0!==a?"boolean"==typeof a?(this._debug=this._debug||{},this._debug.all=a,this.chainSend("debug",this._debug),this):this._debug&&this._debug[a]||this._db&&this._db._debug&&this._db._debug[a]||this._debug&&this._debug.all:this._debug&&this._debug.all},function(a,b){return void 0!==a?void 0!==b?(this._debug=this._debug||{},this._debug[a]=b,this.chainSend("debug",this._debug),this):this._debug&&this._debug[b]||this._db&&this._db._debug&&this._db._debug[a]:this._debug&&this._debug.all}]),classIdentifier:function(){return"ForerunnerDB."+this.className},instanceIdentifier:function(){return"["+this.className+"]"+this.name()},logIdentifier:function(){return"ForerunnerDB "+this.instanceIdentifier()},convertToFdb:function(a){var b,c,d,e;for(e in a)if(a.hasOwnProperty(e)&&(d=a,e.indexOf(".")>-1)){for(e=e.replace(".$","[|$|]"),c=e.split(".");b=c.shift();)b=b.replace("[|$|]",".$"),c.length?d[b]={}:d[b]=a[e],d=d[b];delete a[e]}},isDropped:function(){return"dropped"===this._state},debounce:function(a,b,c){var d,e=this;e._debounce=e._debounce||{},e._debounce[a]&&clearTimeout(e._debounce[a].timeout),d={callback:b,timeout:setTimeout(function(){delete e._debounce[a],b()},c)},e._debounce[a]=d}},b.exports=d},{"./Overload":32,"./Serialiser":39}],22:[function(a,b,c){"use strict";var d={TYPE_INSERT:0,TYPE_UPDATE:1,TYPE_REMOVE:2,PHASE_BEFORE:0,PHASE_AFTER:1};b.exports=d},{}],23:[function(a,b,c){"use strict";var d=a("./Overload"),e={on:new d({"string, function":function(a,b){return this._listeners=this._listeners||{},this._listeners[a]=this._listeners[a]||{}, this._listeners[a]["*"]=this._listeners[a]["*"]||[],this._listeners[a]["*"].push(b),this},"string, *, function":function(a,b,c){return this._listeners=this._listeners||{},this._listeners[a]=this._listeners[a]||{},this._listeners[a][b]=this._listeners[a][b]||[],this._listeners[a][b].push(c),this}}),once:new d({"string, function":function(a,b){var c=this,d=!1,e=function(){d||(c.off(a,e),b.apply(c,arguments),d=!0)};return this.on(a,e)},"string, *, function":function(a,b,c){var d=this,e=!1,f=function(){e||(d.off(a,b,f),c.apply(d,arguments),e=!0)};return this.on(a,b,f)}}),off:new d({string:function(a){var b=this;return this._emitting?(this._eventRemovalQueue=this._eventRemovalQueue||[],this._eventRemovalQueue.push(function(){b.off(a)})):this._listeners&&this._listeners[a]&&a in this._listeners&&delete this._listeners[a],this},"string, function":function(a,b){var c,d,e=this;return this._emitting?(this._eventRemovalQueue=this._eventRemovalQueue||[],this._eventRemovalQueue.push(function(){e.off(a,b)})):"string"==typeof b?this._listeners&&this._listeners[a]&&this._listeners[a][b]&&delete this._listeners[a][b]:this._listeners&&a in this._listeners&&(c=this._listeners[a]["*"],d=c.indexOf(b),d>-1&&c.splice(d,1)),this},"string, *, function":function(a,b,c){var d=this;if(this._emitting)this._eventRemovalQueue=this._eventRemovalQueue||[],this._eventRemovalQueue.push(function(){d.off(a,b,c)});else if(this._listeners&&a in this._listeners&&b in this.listeners[a]){var e=this._listeners[a][b],f=e.indexOf(c);f>-1&&e.splice(f,1)}},"string, *":function(a,b){var c=this;this._emitting?(this._eventRemovalQueue=this._eventRemovalQueue||[],this._eventRemovalQueue.push(function(){c.off(a,b)})):this._listeners&&a in this._listeners&&b in this._listeners[a]&&delete this._listeners[a][b]}}),emit:function(a,b){if(this._listeners=this._listeners||{},this._emitting=!0,a in this._listeners){var c,d,e,f,g,h,i;if(this._listeners[a]["*"])for(f=this._listeners[a]["*"],d=f.length,c=0;d>c;c++)e=f[c],"function"==typeof e&&e.apply(this,Array.prototype.slice.call(arguments,1));if(b instanceof Array&&b[0]&&b[0][this._primaryKey])for(g=this._listeners[a],d=b.length,c=0;d>c;c++)if(g[b[c][this._primaryKey]])for(h=g[b[c][this._primaryKey]].length,i=0;h>i;i++)e=g[b[c][this._primaryKey]][i],"function"==typeof e&&g[b[c][this._primaryKey]][i].apply(this,Array.prototype.slice.call(arguments,1))}return this._emitting=!1,this._processRemovalQueue(),this},_processRemovalQueue:function(){var a;if(this._eventRemovalQueue&&this._eventRemovalQueue.length){for(a=0;a<this._eventRemovalQueue.length;a++)this._eventRemovalQueue[a]();this._eventRemovalQueue=[]}},deferEmit:function(a,b){var c,d=this;return this._noEmitDefer||this._db&&(!this._db||this._db._noEmitDefer)?this.emit.apply(this,arguments):(c=arguments,this._deferTimeout=this._deferTimeout||{},this._deferTimeout[a]&&clearTimeout(this._deferTimeout[a]),this._deferTimeout[a]=setTimeout(function(){d.debug()&&console.log(d.logIdentifier()+" Emitting "+c[0]),d.emit.apply(d,c)},1)),this}};b.exports=e},{"./Overload":32}],24:[function(a,b,c){"use strict";var d={_match:function(a,b,c,d,e){var f,g,h,i,j,k,l=d,m=typeof a,n=typeof b,o=!0;if("object"===m&&null===a&&(m="null"),"object"===n&&null===b&&(n="null"),e=e||{},c=c||{},e.$rootQuery||(e.$rootQuery=b),e.$rootSource||(e.$rootSource=a),e.$currentQuery=b,e.$rootData=e.$rootData||{},"string"!==m&&"number"!==m&&"null"!==m||"string"!==n&&"number"!==n&&"null"!==n){if(("string"===m||"number"===m)&&"object"===n&&b instanceof RegExp)b.test(a)||(o=!1);else for(k in b)if(b.hasOwnProperty(k)){if(e.$previousQuery=e.$parent,e.$parent={query:b[k],key:k,parent:e.$previousQuery},f=!1,j=k.substr(0,2),"//"===j)continue;if(0===j.indexOf("$")&&(i=this._matchOp(k,a,b[k],c,e),i>-1)){if(i){if("or"===d)return!0}else o=i;f=!0}if(!f&&b[k]instanceof RegExp)if(f=!0,"object"===m&&void 0!==a[k]&&b[k].test(a[k])){if("or"===d)return!0}else o=!1;if(!f)if("object"==typeof b[k])if(void 0!==a[k])if(a[k]instanceof Array&&!(b[k]instanceof Array)){for(g=!1,h=0;h<a[k].length&&!(g=this._match(a[k][h],b[k],c,l,e));h++);if(g){if("or"===d)return!0}else o=!1}else if(!(a[k]instanceof Array)&&b[k]instanceof Array){for(g=!1,h=0;h<b[k].length&&!(g=this._match(a[k],b[k][h],c,l,e));h++);if(g){if("or"===d)return!0}else o=!1}else if("object"==typeof a)if(g=this._match(a[k],b[k],c,l,e)){if("or"===d)return!0}else o=!1;else if(g=this._match(void 0,b[k],c,l,e)){if("or"===d)return!0}else o=!1;else if(b[k]&&void 0!==b[k].$exists)if(g=this._match(void 0,b[k],c,l,e)){if("or"===d)return!0}else o=!1;else o=!1;else if(a&&a[k]===b[k]){if("or"===d)return!0}else if(a&&a[k]&&a[k]instanceof Array&&b[k]&&"object"!=typeof b[k]){for(g=!1,h=0;h<a[k].length&&!(g=this._match(a[k][h],b[k],c,l,e));h++);if(g){if("or"===d)return!0}else o=!1}else o=!1;if("and"===d&&!o)return!1}}else"number"===m||"null"===m||"null"===n?a!==b&&(o=!1):a.localeCompare(b)&&(o=!1);return o},_matchOp:function(a,b,c,d,e){switch(a){case"$gt":return b>c;case"$gte":return b>=c;case"$lt":return c>b;case"$lte":return c>=b;case"$exists":return void 0===b!==c;case"$eq":return b==c;case"$eeq":return b===c;case"$ne":return b!=c;case"$nee":return b!==c;case"$or":for(var f=0;f<c.length;f++)if(this._match(b,c[f],d,"and",e))return!0;return!1;case"$and":for(var g=0;g<c.length;g++)if(!this._match(b,c[g],d,"and",e))return!1;return!0;case"$in":if(c instanceof Array){var h,i=c,j=i.length;for(h=0;j>h;h++)if(this._match(b,i[h],d,"and",e))return!0;return!1}return"object"==typeof c?this._match(b,c,d,"and",e):(console.log(this.logIdentifier()+" Cannot use an $in operator on a non-array key: "+a,e.$rootQuery),!1);case"$nin":if(c instanceof Array){var k,l=c,m=l.length;for(k=0;m>k;k++)if(this._match(b,l[k],d,"and",e))return!1;return!0}return"object"==typeof c?this._match(b,c,d,"and",e):(console.log(this.logIdentifier()+" Cannot use a $nin operator on a non-array key: "+a,e.$rootQuery),!1);case"$fastIn":return c instanceof Array?-1!==c.indexOf(b):(console.log(this.logIdentifier()+" Cannot use an $fastIn operator on a non-array key: "+a,e.$rootQuery),!1);case"$distinct":e.$rootData["//distinctLookup"]=e.$rootData["//distinctLookup"]||{};for(var n in c)if(c.hasOwnProperty(n))return e.$rootData["//distinctLookup"][n]=e.$rootData["//distinctLookup"][n]||{},e.$rootData["//distinctLookup"][n][b[n]]?!1:(e.$rootData["//distinctLookup"][n][b[n]]=!0,!0);break;case"$count":var o,p,q;for(o in c)if(c.hasOwnProperty(o)&&(p=b[o],q="object"==typeof p&&p instanceof Array?p.length:0,!this._match(q,c[o],d,"and",e)))return!1;return!0;case"$find":case"$findOne":case"$findSub":var r,s,t,u,v,w,x="collection",y={};if(!c.$from)throw a+" missing $from property!";if(c.$fromType&&(x=c.$fromType,!this.db()[x]||"function"!=typeof this.db()[x]))throw a+' cannot operate against $fromType "'+x+'" because the database does not recognise this type of object!';if(r=c.$query||{},s=c.$options||{},"$findSub"===a){if(!c.$path)throw a+" missing $path property!";if(v=c.$path,t=c.$subQuery||{},u=c.$subOptions||{},!(e.$parent&&e.$parent.parent&&e.$parent.parent.key))return this._match(b,r,{},"and",e)&&(w=this._findSub([b],v,t,u)),w&&w.length>0;w=this.db()[x](c.$from).findSub(r,v,t,u)}else w=this.db()[x](c.$from)[a.substr(1)](r,s);return y[e.$parent.parent.key]=w,this._match(b,y,d,"and",e)}return-1},applyJoin:function(a,b,c,d){var e,f,g,h,i,j,k,l,m,n,o,p,q,r,s,t,u,v,w,x=this,y=[];for(a instanceof Array||(a=[a]),e=0;e<b.length;e++)for(f in b[e])if(b[e].hasOwnProperty(f))for(g=b[e][f],h=g.$sourceType||"collection",i="$"+h+"."+f,j=f,c[i]?k=c[i]:this._db[h]&&"function"==typeof this._db[h]&&(k=this._db[h](f)),l=0;l<a.length;l++){m={},n=!1,o=!1,p="";for(q in g)if(g.hasOwnProperty(q))if(r=g[q],"$"===q.substr(0,1))switch(q){case"$where":if(!r.$query&&!r.$options)throw'$join $where clause requires "$query" and / or "$options" keys to work!';r.$query&&(m=x.resolveDynamicQuery(r.$query,a[l])),r.$options&&(s=r.$options);break;case"$as":j=r;break;case"$multi":n=r;break;case"$require":o=r;break;case"$prefix":p=r}else m[q]=x.resolveDynamicQuery(r,a[l]);if(t=k.find(m,s),!o||o&&t[0])if("$root"===j){if(n!==!1)throw this.logIdentifier()+' Cannot combine [$as: "$root"] with [$multi: true] in $join clause!';u=t[0],v=a[l];for(w in u)u.hasOwnProperty(w)&&void 0===v[p+w]&&(v[p+w]=u[w])}else a[l][j]=n===!1?t[0]:t;else y.push(l)}return y},resolveDynamicQuery:function(a,b){var c,d,e,f,g,h=this;if("string"==typeof a)return f="$$."===a.substr(0,3)?this.sharedPathSolver.value(b,a.substr(3,a.length-3)):this.sharedPathSolver.value(b,a),f.length>1?{$in:f}:f[0];c={};for(g in a)if(a.hasOwnProperty(g))switch(d=typeof a[g],e=a[g],d){case"string":"$$."===e.substr(0,3)?c[g]=this.sharedPathSolver.value(b,e.substr(3,e.length-3))[0]:c[g]=e;break;case"object":c[g]=h.resolveDynamicQuery(e,b);break;default:c[g]=e}return c},spliceArrayByIndexList:function(a,b){var c;for(c=b.length-1;c>=0;c--)a.splice(b[c],1)}};b.exports=d},{}],25:[function(a,b,c){"use strict";var d={sortAsc:function(a,b){return"string"==typeof a&&"string"==typeof b?a.localeCompare(b):a>b?1:b>a?-1:0},sortDesc:function(a,b){return"string"==typeof a&&"string"==typeof b?b.localeCompare(a):a>b?-1:b>a?1:0}};b.exports=d},{}],26:[function(a,b,c){"use strict";var d,e={};d={tagAdd:function(a){var b,c=this,d=e[a]=e[a]||[];for(b=0;b<d.length;b++)if(d[b]===c)return!0;return d.push(c),c.on&&c.on("drop",function(){c.tagRemove(a)}),!0},tagRemove:function(a){var b,c=e[a];if(c)for(b=0;b<c.length;b++)if(c[b]===this)return c.splice(b,1),!0;return!1},tagLookup:function(a){return e[a]||[]},tagDrop:function(a,b){var c,d,e,f=this.tagLookup(a);if(c=function(){d--,b&&0===d&&b(!1)},f.length)for(d=f.length,e=f.length-1;e>=0;e--)f[e].drop(c);return!0}},b.exports=d},{}],27:[function(a,b,c){"use strict";var d=a("./Overload"),e={addTrigger:function(a,b,c,d){var e,f=this;return e=f._triggerIndexOf(a,b,c),-1===e?(f.triggerStack={},f._trigger=f._trigger||{},f._trigger[b]=f._trigger[b]||{},f._trigger[b][c]=f._trigger[b][c]||[],f._trigger[b][c].push({id:a,method:d,enabled:!0}),!0):!1},removeTrigger:function(a,b,c){var d,e=this;return d=e._triggerIndexOf(a,b,c),d>-1&&e._trigger[b][c].splice(d,1),!1},ignoreTriggers:function(a){return void 0!==a?(this._ignoreTriggers=a,this):this._ignoreTriggers},addLinkIO:function(a,b){var c,d,e,f,g,h,i,j,k,l=this;if(l._linkIO=l._linkIO||{},l._linkIO[a]=b,d=b["export"],e=b["import"],d&&(h=l.db().collection(d.to)),e&&(i=l.db().collection(e.from)),j=[l.TYPE_INSERT,l.TYPE_UPDATE,l.TYPE_REMOVE],c=function(a,b){b(!1,!0)},d&&(d.match||(d.match=c),d.types||(d.types=j),f=function(a,b,c){d.match(c,function(b,e){!b&&e&&d.data(c,a.type,function(b,c,d){!b&&c&&(h.ignoreTriggers(!0),"remove"!==a.type?h.upsert(c,d):h.remove(c,d),h.ignoreTriggers(!1))})})}),e&&(e.match||(e.match=c),e.types||(e.types=j),g=function(a,b,c){e.match(c,function(b,d){!b&&d&&e.data(c,a.type,function(b,c,d){!b&&c&&(h.ignoreTriggers(!0),"remove"!==a.type?l.upsert(c,d):l.remove(c,d),h.ignoreTriggers(!1))})})}),d)for(k=0;k<d.types.length;k++)l.addTrigger(a+"export"+d.types[k],d.types[k],l.PHASE_AFTER,f);if(e)for(k=0;k<e.types.length;k++)i.addTrigger(a+"import"+e.types[k],e.types[k],l.PHASE_AFTER,g)},removeLinkIO:function(a){var b,c,d,e,f=this,g=f._linkIO[a];if(g){if(b=g["export"],c=g["import"],b)for(e=0;e<b.types.length;e++)f.removeTrigger(a+"export"+b.types[e],b.types[e],f.db.PHASE_AFTER);if(c)for(d=f.db().collection(c.from),e=0;e<c.types.length;e++)d.removeTrigger(a+"import"+c.types[e],c.types[e],f.db.PHASE_AFTER);return delete f._linkIO[a],!0}return!1},enableTrigger:new d({string:function(a){var b,c,d,e,f,g=this,h=g._trigger,i=!1;if(h)for(f in h)if(h.hasOwnProperty(f)&&(b=h[f]))for(d in b)if(b.hasOwnProperty(d))for(c=b[d],e=0;e<c.length;e++)c[e].id===a&&(c[e].enabled=!0,i=!0);return i},number:function(a){var b,c,d,e=this,f=e._trigger[a],g=!1;if(f)for(c in f)if(f.hasOwnProperty(c))for(b=f[c],d=0;d<b.length;d++)b[d].enabled=!0,g=!0;return g},"number, number":function(a,b){var c,d,e=this,f=e._trigger[a],g=!1;if(f&&(c=f[b]))for(d=0;d<c.length;d++)c[d].enabled=!0,g=!0;return g},"string, number, number":function(a,b,c){var d=this,e=d._triggerIndexOf(a,b,c);return e>-1?(d._trigger[b][c][e].enabled=!0,!0):!1}}),disableTrigger:new d({string:function(a){var b,c,d,e,f,g=this,h=g._trigger,i=!1;if(h)for(f in h)if(h.hasOwnProperty(f)&&(b=h[f]))for(d in b)if(b.hasOwnProperty(d))for(c=b[d],e=0;e<c.length;e++)c[e].id===a&&(c[e].enabled=!1,i=!0);return i},number:function(a){var b,c,d,e=this,f=e._trigger[a],g=!1;if(f)for(c in f)if(f.hasOwnProperty(c))for(b=f[c],d=0;d<b.length;d++)b[d].enabled=!1,g=!0;return g},"number, number":function(a,b){var c,d,e=this,f=e._trigger[a],g=!1;if(f&&(c=f[b]))for(d=0;d<c.length;d++)c[d].enabled=!1,g=!0;return g},"string, number, number":function(a,b,c){var d=this,e=d._triggerIndexOf(a,b,c);return e>-1?(d._trigger[b][c][e].enabled=!1,!0):!1}}),willTrigger:function(a,b){if(!this._ignoreTriggers&&this._trigger&&this._trigger[a]&&this._trigger[a][b]&&this._trigger[a][b].length){var c,d=this._trigger[a][b];for(c=0;c<d.length;c++)if(d[c].enabled)return!0}return!1},processTrigger:function(a,b,c,d,e){var f,g,h,i,j,k,l,m=this;if(!m._ignoreTriggers&&m._trigger&&m._trigger[b]&&m._trigger[b][c]){for(f=m._trigger[b][c],h=f.length,g=0;h>g;g++)if(i=f[g],i.enabled){if(m.debug()){switch(b){case this.TYPE_INSERT:k="insert";break;case this.TYPE_UPDATE:k="update";break;case this.TYPE_REMOVE:k="remove";break;default:k=""}switch(c){case this.PHASE_BEFORE:l="before";break;case this.PHASE_AFTER:l="after";break;default:l=""}console.log('Triggers: Processing trigger "'+i.id+'" for '+k+' in phase "'+l+'"')}if(m.triggerStack&&m.triggerStack[b]&&m.triggerStack[b][c]&&m.triggerStack[b][c][i.id]){m.debug()&&console.log('Triggers: Will not run trigger "'+i.id+'" for '+k+' in phase "'+l+'" as it is already in the stack!');continue}if(m.triggerStack=m.triggerStack||{},m.triggerStack[b]={},m.triggerStack[b][c]={},m.triggerStack[b][c][i.id]=!0,j=i.method.call(m,a,d,e),m.triggerStack=m.triggerStack||{},m.triggerStack[b]={},m.triggerStack[b][c]={},m.triggerStack[b][c][i.id]=!1,j===!1)return!1;if(void 0!==j&&j!==!0&&j!==!1)throw"ForerunnerDB.Mixin.Triggers: Trigger error: "+j}return!0}},_triggerIndexOf:function(a,b,c){var d,e,f,g=this;if(g._trigger&&g._trigger[b]&&g._trigger[b][c])for(d=g._trigger[b][c],e=d.length,f=0;e>f;f++)if(d[f].id===a)return f;return-1}};b.exports=e},{"./Overload":32}],28:[function(a,b,c){"use strict";var d={_updateProperty:function(a,b,c){a[b]=c,this.debug()&&console.log(this.logIdentifier()+' Setting non-data-bound document property "'+b+'" to val "'+c+'"')},_updateIncrement:function(a,b,c){a[b]+=c},_updateSpliceMove:function(a,b,c){a.splice(c,0,a.splice(b,1)[0]),this.debug()&&console.log(this.logIdentifier()+' Moving non-data-bound document array index from "'+b+'" to "'+c+'"')},_updateSplicePush:function(a,b,c){a.length>b?a.splice(b,0,c):a.push(c)},_updateSplicePull:function(a,b,c){c||(c=1),a.splice(b,c)},_updatePush:function(a,b){a.push(b)},_updatePull:function(a,b){a.splice(b,1)},_updateMultiply:function(a,b,c){a[b]*=c},_updateRename:function(a,b,c){a[c]=a[b],delete a[b]},_updateOverwrite:function(a,b,c){a[b]=c},_updateUnset:function(a,b){delete a[b]},_updateClear:function(a,b){var c,d=a[b];if(d&&"object"==typeof d)for(c in d)d.hasOwnProperty(c)&&this._updateUnset(d,c)},_updatePop:function(a,b){var c,d=!1;if(a.length>0)if(b>0){for(c=0;b>c;c++)a.pop();d=!0}else if(0>b){for(c=0;c>b;c--)a.shift();d=!0}return d}};b.exports=d},{}],29:[function(a,b,c){"use strict";var d,e,f,g;d=a("./Shared"),e=d.modules.Core,f=d.modules.OldView,g=f.prototype.init,f.prototype.init=function(){var a=this;this._binds=[],this._renderStart=0,this._renderEnd=0,this._deferQueue={insert:[],update:[],remove:[],upsert:[],_bindInsert:[],_bindUpdate:[],_bindRemove:[],_bindUpsert:[]},this._deferThreshold={insert:100,update:100,remove:100,upsert:100,_bindInsert:100,_bindUpdate:100,_bindRemove:100,_bindUpsert:100},this._deferTime={insert:100,update:1,remove:1,upsert:1,_bindInsert:100,_bindUpdate:1,_bindRemove:1,_bindUpsert:1},g.apply(this,arguments),this.on("insert",function(b,c){a._bindEvent("insert",b,c)}),this.on("update",function(b,c){a._bindEvent("update",b,c)}),this.on("remove",function(b,c){a._bindEvent("remove",b,c)}),this.on("change",a._bindChange)},f.prototype.bind=function(a,b){if(!b||!b.template)throw'ForerunnerDB.OldView "'+this.name()+'": Cannot bind data to element, missing options information!';return this._binds[a]=b,this},f.prototype.unBind=function(a){return delete this._binds[a],this},f.prototype.isBound=function(a){return Boolean(this._binds[a])},f.prototype.bindSortDom=function(a,b){var c,d,e,f=window.jQuery(a);for(this.debug()&&console.log("ForerunnerDB.OldView.Bind: Sorting data in DOM...",b),c=0;c<b.length;c++)d=b[c],e=f.find("#"+d[this._primaryKey]),e.length?0===c?(this.debug()&&console.log("ForerunnerDB.OldView.Bind: Sort, moving to index 0...",e),f.prepend(e)):(this.debug()&&console.log("ForerunnerDB.OldView.Bind: Sort, moving to index "+c+"...",e),e.insertAfter(f.children(":eq("+(c-1)+")"))):this.debug()&&console.log("ForerunnerDB.OldView.Bind: Warning, element for array item not found!",d)},f.prototype.bindRefresh=function(a){var b,c,d=this._binds;a||(a={data:this.find()});for(b in d)d.hasOwnProperty(b)&&(c=d[b],this.debug()&&console.log("ForerunnerDB.OldView.Bind: Sorting DOM..."),this.bindSortDom(b,a.data),c.afterOperation&&c.afterOperation(),c.refresh&&c.refresh())},f.prototype.bindRender=function(a,b){var c,d,e,f,g,h=this._binds[a],i=window.jQuery(a),j=window.jQuery("<ul></ul>");if(h){for(c=this._data.find(),f=function(a){j.append(a)},g=0;g<c.length;g++)d=c[g],e=h.template(d,f);b?b(a,j.html()):i.append(j.html())}},f.prototype.processQueue=function(a,b){var c=this._deferQueue[a],d=this._deferThreshold[a],e=this._deferTime[a];if(c.length){var f,g=this;c.length&&(f=c.length>d?c.splice(0,d):c.splice(0,c.length),this._bindEvent(a,f,[])),setTimeout(function(){g.processQueue(a,b)},e)}else b&&b(),this.emit("bindQueueComplete")},f.prototype._bindEvent=function(a,b,c){var d,e,f=this._binds,g=this.find({});for(e in f)if(f.hasOwnProperty(e))switch(d=f[e].reduce?this.find(f[e].reduce.query,f[e].reduce.options):g,a){case"insert":this._bindInsert(e,f[e],b,c,d);break;case"update":this._bindUpdate(e,f[e],b,c,d);break;case"remove":this._bindRemove(e,f[e],b,c,d)}},f.prototype._bindChange=function(a){this.debug()&&console.log("ForerunnerDB.OldView.Bind: Bind data change, refreshing bind...",a),this.bindRefresh(a)},f.prototype._bindInsert=function(a,b,c,d,e){var f,g,h,i,j=window.jQuery(a);for(h=function(a,c,d,e){return function(a){b.insert?b.insert(a,c,d,e):b.prependInsert?j.prepend(a):j.append(a),b.afterInsert&&b.afterInsert(a,c,d,e)}},i=0;i<c.length;i++)f=j.find("#"+c[i][this._primaryKey]),f.length||(g=b.template(c[i],h(f,c[i],d,e)))},f.prototype._bindUpdate=function(a,b,c,d,e){var f,g,h,i=window.jQuery(a);for(g=function(a,c){return function(d){b.update?b.update(d,c,e,a.length?"update":"append"):a.length?a.replaceWith(d):b.prependUpdate?i.prepend(d):i.append(d),b.afterUpdate&&b.afterUpdate(d,c,e)}},h=0;h<c.length;h++)f=i.find("#"+c[h][this._primaryKey]),b.template(c[h],g(f,c[h]))},f.prototype._bindRemove=function(a,b,c,d,e){var f,g,h,i=window.jQuery(a);for(g=function(a,c,d){return function(){b.remove?b.remove(a,c,d):(a.remove(),b.afterRemove&&b.afterRemove(a,c,d))}},h=0;h<c.length;h++)f=i.find("#"+c[h][this._primaryKey]),f.length&&(b.beforeRemove?b.beforeRemove(f,c[h],e,g(f,c[h],e)):b.remove?b.remove(f,c[h],e):(f.remove(),b.afterRemove&&b.afterRemove(f,c[h],e)))}},{"./Shared":40}],30:[function(a,b,c){"use strict";var d,e,f,g,h,i,j;d=a("./Shared");var k=function(a){this.init.apply(this,arguments)};k.prototype.init=function(a){var b=this;this._name=a,this._listeners={},this._query={query:{},options:{}},this._onFromSetData=function(){b._onSetData.apply(b,arguments)},this._onFromInsert=function(){b._onInsert.apply(b,arguments)},this._onFromUpdate=function(){b._onUpdate.apply(b,arguments)},this._onFromRemove=function(){b._onRemove.apply(b,arguments)},this._onFromChange=function(){b.debug()&&console.log("ForerunnerDB.OldView: Received change"),b._onChange.apply(b,arguments)}},d.addModule("OldView",k),f=a("./CollectionGroup"),g=a("./Collection"),h=g.prototype.init,i=f.prototype.init,e=d.modules.Db,j=e.prototype.init,d.mixin(k.prototype,"Mixin.Events"),k.prototype.drop=function(){return(this._db||this._from)&&this._name?(this.debug()&&console.log("ForerunnerDB.OldView: Dropping view "+this._name),this._state="dropped",this.emit("drop",this),this._db&&this._db._oldViews&&delete this._db._oldViews[this._name],this._from&&this._from._oldViews&&delete this._from._oldViews[this._name],delete this._listeners,!0):!1},k.prototype.debug=function(){return!1},k.prototype.db=function(a){return void 0!==a?(this._db=a,this):this._db},k.prototype.from=function(a){if(void 0!==a){if("string"==typeof a){if(!this._db.collectionExists(a))throw'ForerunnerDB.OldView "'+this.name()+'": Invalid collection in view.from() call.';a=this._db.collection(a)}return this._from!==a&&(this._from&&this.removeFrom(),this.addFrom(a)),this}return this._from},k.prototype.addFrom=function(a){if(this._from=a,this._from)return this._from.on("setData",this._onFromSetData),this._from.on("change",this._onFromChange),this._from._addOldView(this),this._primaryKey=this._from._primaryKey,this.refresh(),this;throw'ForerunnerDB.OldView "'+this.name()+'": Cannot determine collection type in view.from()'},k.prototype.removeFrom=function(){this._from.off("setData",this._onFromSetData),this._from.off("change",this._onFromChange),this._from._removeOldView(this)},k.prototype.primaryKey=function(){return this._from?this._from.primaryKey():void 0},k.prototype.queryData=function(a,b,c){return void 0!==a&&(this._query.query=a),void 0!==b&&(this._query.options=b),void 0!==a||void 0!==b?(void 0!==c&&c!==!0||this.refresh(),this):this._query},k.prototype.queryAdd=function(a,b,c){var d,e=this._query.query;if(void 0!==a)for(d in a)a.hasOwnProperty(d)&&(void 0===e[d]||void 0!==e[d]&&b)&&(e[d]=a[d]);void 0!==c&&c!==!0||this.refresh()},k.prototype.queryRemove=function(a,b){var c,d=this._query.query;if(void 0!==a)for(c in a)a.hasOwnProperty(c)&&delete d[c];void 0!==b&&b!==!0||this.refresh()},k.prototype.query=function(a,b){return void 0!==a?(this._query.query=a,void 0!==b&&b!==!0||this.refresh(),this):this._query.query},k.prototype.queryOptions=function(a,b){return void 0!==a?(this._query.options=a,void 0!==b&&b!==!0||this.refresh(),this):this._query.options},k.prototype.refresh=function(a){if(this._from){var b,c,d,e,f,g,h,i,j=this._data,k=[],l=[],m=[],n=!1;if(this.debug()&&(console.log("ForerunnerDB.OldView: Refreshing view "+this._name),console.log("ForerunnerDB.OldView: Existing data: "+("undefined"!=typeof this._data)),"undefined"!=typeof this._data&&console.log("ForerunnerDB.OldView: Current data rows: "+this._data.find().length)),this._query?(this.debug()&&console.log("ForerunnerDB.OldView: View has query and options, getting subset..."),this._data=this._from.subset(this._query.query,this._query.options)):this._query.options?(this.debug()&&console.log("ForerunnerDB.OldView: View has options, getting subset..."),this._data=this._from.subset({},this._query.options)):(this.debug()&&console.log("ForerunnerDB.OldView: View has no query or options, getting subset..."),this._data=this._from.subset({})),!a&&j)if(this.debug()&&console.log("ForerunnerDB.OldView: Refresh not forced, old data detected..."),d=this._data,j.subsetOf()===d.subsetOf()){for(this.debug()&&console.log("ForerunnerDB.OldView: Old and new data are from same collection..."),e=d.find(),b=j.find(),g=d._primaryKey,i=0;i<e.length;i++)h=e[i],f={},f[g]=h[g],c=j.find(f)[0],c?JSON.stringify(c)!==JSON.stringify(h)&&l.push(h):k.push(h);for(i=0;i<b.length;i++)h=b[i],f={},f[g]=h[g],d.find(f)[0]||m.push(h);this.debug()&&(console.log("ForerunnerDB.OldView: Removed "+m.length+" rows"),console.log("ForerunnerDB.OldView: Inserted "+k.length+" rows"),console.log("ForerunnerDB.OldView: Updated "+l.length+" rows")),k.length&&(this._onInsert(k,[]),n=!0),l.length&&(this._onUpdate(l,[]),n=!0),m.length&&(this._onRemove(m,[]),n=!0)}else this.debug()&&console.log("ForerunnerDB.OldView: Old and new data are from different collections..."),m=j.find(),m.length&&(this._onRemove(m),n=!0),k=d.find(),k.length&&(this._onInsert(k),n=!0);else this.debug()&&console.log("ForerunnerDB.OldView: Forcing data update",e),this._data=this._from.subset(this._query.query,this._query.options),e=this._data.find(),this.debug()&&console.log("ForerunnerDB.OldView: Emitting change event with data",e),this._onInsert(e,[]);this.debug()&&console.log("ForerunnerDB.OldView: Emitting change"),this.emit("change")}return this},k.prototype.count=function(){return this._data&&this._data._data?this._data._data.length:0},k.prototype.find=function(){return this._data?(this.debug()&&console.log("ForerunnerDB.OldView: Finding data in view collection...",this._data),this._data.find.apply(this._data,arguments)):[]},k.prototype.insert=function(){return this._from?this._from.insert.apply(this._from,arguments):[]},k.prototype.update=function(){return this._from?this._from.update.apply(this._from,arguments):[]},k.prototype.remove=function(){return this._from?this._from.remove.apply(this._from,arguments):[]},k.prototype._onSetData=function(a,b){this.emit("remove",b,[]),this.emit("insert",a,[])},k.prototype._onInsert=function(a,b){this.emit("insert",a,b)},k.prototype._onUpdate=function(a,b){this.emit("update",a,b)},k.prototype._onRemove=function(a,b){this.emit("remove",a,b)},k.prototype._onChange=function(){this.debug()&&console.log("ForerunnerDB.OldView: Refreshing data"),this.refresh()},g.prototype.init=function(){this._oldViews=[],h.apply(this,arguments)},g.prototype._addOldView=function(a){return void 0!==a&&(this._oldViews[a._name]=a),this},g.prototype._removeOldView=function(a){return void 0!==a&&delete this._oldViews[a._name],this},f.prototype.init=function(){this._oldViews=[],i.apply(this,arguments)},f.prototype._addOldView=function(a){return void 0!==a&&(this._oldViews[a._name]=a),this},f.prototype._removeOldView=function(a){return void 0!==a&&delete this._oldViews[a._name],this},e.prototype.init=function(){this._oldViews={},j.apply(this,arguments)},e.prototype.oldView=function(a){return this._oldViews[a]||this.debug()&&console.log("ForerunnerDB.OldView: Creating view "+a),this._oldViews[a]=this._oldViews[a]||new k(a).db(this),this._oldViews[a]},e.prototype.oldViewExists=function(a){return Boolean(this._oldViews[a])},e.prototype.oldViews=function(){var a,b=[];for(a in this._oldViews)this._oldViews.hasOwnProperty(a)&&b.push({name:a,count:this._oldViews[a].count()});return b},d.finishModule("OldView"),b.exports=k},{"./Collection":5,"./CollectionGroup":6,"./Shared":40}],31:[function(a,b,c){"use strict";var d=a("./Shared"),e=a("./Path"),f=function(a){this.pathSolver=new e,this.counter=0,this.init.apply(this,arguments)};f.prototype.init=function(a){this._data={operation:a,index:{potential:[],used:!1},steps:[],time:{startMs:0,stopMs:0,totalMs:0,process:{}},flag:{},log:[]}},d.addModule("Operation",f),d.mixin(f.prototype,"Mixin.ChainReactor"),f.prototype.start=function(){this._data.time.startMs=(new Date).getTime()},f.prototype.log=function(a){if(a){var b=this._log.length>0?this._data.log[this._data.log.length-1].time:0,c={event:a,time:(new Date).getTime(),delta:0};return this._data.log.push(c),b&&(c.delta=c.time-b),this}return this._data.log},f.prototype.time=function(a){if(void 0!==a){var b=this._data.time.process,c=b[a]=b[a]||{};return c.startMs?(c.stopMs=(new Date).getTime(),c.totalMs=c.stopMs-c.startMs,c.stepObj.totalMs=c.totalMs,delete c.stepObj):(c.startMs=(new Date).getTime(),c.stepObj={name:a},this._data.steps.push(c.stepObj)),this}return this._data.time},f.prototype.flag=function(a,b){return void 0===a||void 0===b?void 0!==a?this._data.flag[a]:this._data.flag:void(this._data.flag[a]=b)},f.prototype.data=function(a,b,c){return void 0!==b?(this.pathSolver.set(this._data,a,b),this):this.pathSolver.get(this._data,a)},f.prototype.pushData=function(a,b,c){this.pathSolver.push(this._data,a,b)},f.prototype.stop=function(){this._data.time.stopMs=(new Date).getTime(),this._data.time.totalMs=this._data.time.stopMs-this._data.time.startMs},d.finishModule("Operation"),b.exports=f},{"./Path":34,"./Shared":40}],32:[function(a,b,c){"use strict";var d=function(a,b){if(b||(b=a,a=void 0),b){var c,d,e,f,g,h,i=this;if(!(b instanceof Array)){e={};for(c in b)if(b.hasOwnProperty(c))if(f=c.replace(/ /g,""),-1===f.indexOf("*"))e[f]=b[c];else for(h=this.generateSignaturePermutations(f),g=0;g<h.length;g++)e[h[g]]||(e[h[g]]=b[c]);b=e}return function(){var e,f,g,h=[];if(b instanceof Array){for(d=b.length,c=0;d>c;c++)if(b[c].length===arguments.length)return i.callExtend(this,"$main",b,b[c],arguments)}else{for(c=0;c<arguments.length&&(f=typeof arguments[c],"object"===f&&arguments[c]instanceof Array&&(f="array"),1!==arguments.length||"undefined"!==f);c++)h.push(f);if(e=h.join(","),b[e])return i.callExtend(this,"$main",b,b[e],arguments);for(c=h.length;c>=0;c--)if(e=h.slice(0,c).join(","),b[e+",..."])return i.callExtend(this,"$main",b,b[e+",..."],arguments)}throw g=void 0!==a?a:"function"==typeof this.name?this.name():"Unknown",console.log("Overload Definition:",b),'ForerunnerDB.Overload "'+g+'": Overloaded method does not have a matching signature "'+e+'" for the passed arguments: '+this.jStringify(h)}}return function(){}};d.prototype.generateSignaturePermutations=function(a){var b,c,d=[],e=["array","string","object","number","function","undefined"];if(a.indexOf("*")>-1)for(c=0;c<e.length;c++)b=a.replace("*",e[c]),d=d.concat(this.generateSignaturePermutations(b));else d.push(a);return d},d.prototype.callExtend=function(a,b,c,d,e){var f,g;return a&&c[b]?(f=a[b],a[b]=c[b],g=d.apply(a,e),a[b]=f,g):d.apply(a,e)},b.exports=d},{}],33:[function(a,b,c){"use strict";var d,e,f,g;d=a("./Shared");var h=function(){this.init.apply(this,arguments)};h.prototype.init=function(a){var b=this;this._name=a,this._data=new g("__FDB__dc_data_"+this._name),this._collData=new f,this._sources=[],this._sourceDroppedWrap=function(){b._sourceDropped.apply(b,arguments)}},d.addModule("Overview",h),d.mixin(h.prototype,"Mixin.Common"),d.mixin(h.prototype,"Mixin.ChainReactor"),d.mixin(h.prototype,"Mixin.Constants"),d.mixin(h.prototype,"Mixin.Triggers"),d.mixin(h.prototype,"Mixin.Events"),d.mixin(h.prototype,"Mixin.Tags"),f=a("./Collection"),g=a("./Document"),e=d.modules.Db,d.synthesize(h.prototype,"state"),d.synthesize(h.prototype,"db"),d.synthesize(h.prototype,"name"),d.synthesize(h.prototype,"query",function(a){var b=this.$super(a);return void 0!==a&&this._refresh(),b}),d.synthesize(h.prototype,"queryOptions",function(a){var b=this.$super(a);return void 0!==a&&this._refresh(),b}),d.synthesize(h.prototype,"reduce",function(a){var b=this.$super(a);return void 0!==a&&this._refresh(),b}),h.prototype.from=function(a){return void 0!==a?("string"==typeof a&&(a=this._db.collection(a)),this._setFrom(a),this):this._sources},h.prototype.find=function(){return this._collData.find.apply(this._collData,arguments)},h.prototype.exec=function(){var a=this.reduce();return a?a.apply(this):void 0},h.prototype.count=function(){return this._collData.count.apply(this._collData,arguments)},h.prototype._setFrom=function(a){for(;this._sources.length;)this._removeSource(this._sources[0]);return this._addSource(a),this},h.prototype._addSource=function(a){return a&&"View"===a.className&&(a=a.data(),this.debug()&&console.log(this.logIdentifier()+' Using internal private data "'+a.instanceIdentifier()+'" for IO graph linking')),-1===this._sources.indexOf(a)&&(this._sources.push(a),a.chain(this),a.on("drop",this._sourceDroppedWrap),this._refresh()),this},h.prototype._removeSource=function(a){a&&"View"===a.className&&(a=a.data(),this.debug()&&console.log(this.logIdentifier()+' Using internal private data "'+a.instanceIdentifier()+'" for IO graph linking')); var b=this._sources.indexOf(a);return b>-1&&(this._sources.splice(a,1),a.unChain(this),a.off("drop",this._sourceDroppedWrap),this._refresh()),this},h.prototype._sourceDropped=function(a){a&&this._removeSource(a)},h.prototype._refresh=function(){if(!this.isDropped()){if(this._sources&&this._sources[0]){this._collData.primaryKey(this._sources[0].primaryKey());var a,b=[];for(a=0;a<this._sources.length;a++)b=b.concat(this._sources[a].find(this._query,this._queryOptions));this._collData.setData(b)}if(this._reduce){var c=this._reduce.apply(this);this._data.setData(c)}}},h.prototype._chainHandler=function(a){switch(a.type){case"setData":case"insert":case"update":case"remove":this._refresh()}},h.prototype.data=function(){return this._data},h.prototype.drop=function(a){if(!this.isDropped()){for(this._state="dropped",delete this._data,delete this._collData;this._sources.length;)this._removeSource(this._sources[0]);delete this._sources,this._db&&this._name&&delete this._db._overview[this._name],this.emit("drop",this),a&&a(!1,!0),delete this._listeners}return!0},e.prototype.overview=function(a){var b=this;return a?a instanceof h?a:this._overview&&this._overview[a]?this._overview[a]:(this._overview=this._overview||{},this._overview[a]=new h(a).db(this),b.emit("create",b._overview[a],"overview",a),this._overview[a]):this._overview||{}},e.prototype.overviews=function(){var a,b,c=[];for(b in this._overview)this._overview.hasOwnProperty(b)&&(a=this._overview[b],c.push({name:b,count:a.count(),linked:void 0!==a.isLinked?a.isLinked():!1}));return c},d.finishModule("Overview"),b.exports=h},{"./Collection":5,"./Document":10,"./Shared":40}],34:[function(a,b,c){"use strict";var d=a("./Shared"),e=function(a){this.init.apply(this,arguments)};e.prototype.init=function(a){a&&this.path(a)},d.addModule("Path",e),d.mixin(e.prototype,"Mixin.Common"),d.mixin(e.prototype,"Mixin.ChainReactor"),e.prototype.path=function(a){return void 0!==a?(this._path=this.clean(a),this._pathParts=this._path.split("."),this):this._path},e.prototype.hasObjectPaths=function(a,b){var c,d=!0;for(c in a)if(a.hasOwnProperty(c)){if(void 0===b[c])return!1;if("object"==typeof a[c]&&(d=this.hasObjectPaths(a[c],b[c]),!d))return!1}return d},e.prototype.countKeys=function(a){var b,c=0;for(b in a)a.hasOwnProperty(b)&&void 0!==a[b]&&("object"!=typeof a[b]?c++:c+=this.countKeys(a[b]));return c},e.prototype.countObjectPaths=function(a,b){var c,d,e={},f=0,g=0;for(d in b)b.hasOwnProperty(d)&&("object"==typeof b[d]?(c=this.countObjectPaths(a[d],b[d]),e[d]=c.matchedKeys,g+=c.totalKeyCount,f+=c.matchedKeyCount):(g++,a&&a[d]&&"object"!=typeof a[d]?(e[d]=!0,f++):e[d]=!1));return{matchedKeys:e,matchedKeyCount:f,totalKeyCount:g}},e.prototype.parse=function(a,b){var c,d,e,f=[],g="";for(d in a)if(a.hasOwnProperty(d))if(g=d,"object"==typeof a[d])if(b)for(c=this.parse(a[d],b),e=0;e<c.length;e++)f.push({path:g+"."+c[e].path,value:c[e].value});else for(c=this.parse(a[d]),e=0;e<c.length;e++)f.push({path:g+"."+c[e].path});else b?f.push({path:g,value:a[d]}):f.push({path:g});return f},e.prototype.parseArr=function(a,b){return b=b||{},this._parseArr(a,"",[],b)},e.prototype._parseArr=function(a,b,c,d){var e,f="";b=b||"",c=c||[];for(e in a)a.hasOwnProperty(e)&&(!d.ignore||d.ignore&&!d.ignore.test(e))&&(f=b?b+"."+e:e,"object"==typeof a[e]?(d.verbose&&c.push(f),this._parseArr(a[e],f,c,d)):c.push(f));return c},e.prototype.set=function(a,b,c){if(void 0!==a&&void 0!==b){var d,e;b=this.clean(b),d=b.split("."),e=d.shift(),d.length?(a[e]=a[e]||{},this.set(a[e],d.join("."),c)):a[e]=c}return a},e.prototype.get=function(a,b){return this.value(a,b)[0]},e.prototype.value=function(a,b,c){var d,e,f,g,h,i,j,k,l;if(b&&-1===b.indexOf("."))return[a[b]];if(void 0!==a&&"object"==typeof a){if((!c||c&&!c.skipArrCheck)&&a instanceof Array){for(j=[],k=0;k<a.length;k++)j.push(this.get(a[k],b));return j}for(i=[],void 0!==b&&(b=this.clean(b),d=b.split(".")),e=d||this._pathParts,f=e.length,g=a,k=0;f>k;k++){if(g=g[e[k]],h instanceof Array){for(l=0;l<h.length;l++)i=i.concat(this.value(h,l+"."+e[k],{skipArrCheck:!0}));return i}if(!g||"object"!=typeof g)break;h=g}return[g]}return[]},e.prototype.push=function(a,b,c){if(void 0!==a&&void 0!==b){var d,e;if(b=this.clean(b),d=b.split("."),e=d.shift(),d.length)a[e]=a[e]||{},this.set(a[e],d.join("."),c);else{if(a[e]=a[e]||[],!(a[e]instanceof Array))throw"ForerunnerDB.Path: Cannot push to a path whose endpoint is not an array!";a[e].push(c)}}return a},e.prototype.keyValue=function(a,b){var c,d,e,f,g,h,i;for(void 0!==b&&(b=this.clean(b),c=b.split(".")),d=c||this._pathParts,e=d.length,f=a,i=0;e>i;i++){if(f=f[d[i]],!f||"object"!=typeof f){h=d[i]+":"+f;break}g=f}return h},e.prototype.set=function(a,b,c){if(void 0!==a&&void 0!==b){var d,e;b=this.clean(b),d=b.split("."),e=d.shift(),d.length?(a[e]=a[e]||{},this.set(a[e],d.join("."),c)):a[e]=c}return a},e.prototype.clean=function(a){return"."===a.substr(0,1)&&(a=a.substr(1,a.length-1)),a},d.finishModule("Path"),b.exports=e},{"./Shared":40}],35:[function(a,b,c){"use strict";var d,e,f,g,h,i,j,k,l,m=a("./Shared"),n=a("async"),o=a("localforage");a("./PersistCompress"),a("./PersistCrypto");k=function(){this.init.apply(this,arguments)},k.prototype.localforage=o,k.prototype.init=function(a){var b=this;this._encodeSteps=[function(){return b._encode.apply(b,arguments)}],this._decodeSteps=[function(){return b._decode.apply(b,arguments)}],a.isClient()&&void 0!==window.Storage&&(this.mode("localforage"),o.config({driver:[o.INDEXEDDB,o.WEBSQL,o.LOCALSTORAGE],name:String(a.core().name()),storeName:"FDB"}))},m.addModule("Persist",k),m.mixin(k.prototype,"Mixin.ChainReactor"),m.mixin(k.prototype,"Mixin.Common"),d=m.modules.Db,e=a("./Collection"),f=e.prototype.drop,g=a("./CollectionGroup"),h=e.prototype.init,i=d.prototype.init,j=d.prototype.drop,l=m.overload,m.synthesize(k.prototype,"auto",function(a){var b=this;return void 0!==a&&(a?(this._db.on("create",function(){b._autoLoad.apply(b,arguments)}),this._db.on("change",function(){b._autoSave.apply(b,arguments)}),this._db.debug()&&console.log(this._db.logIdentifier()+" Automatic load/save enabled")):(this._db.off("create",this._autoLoad),this._db.off("change",this._autoSave),this._db.debug()&&console.log(this._db.logIdentifier()+" Automatic load/save disbled"))),this.$super.call(this,a)}),k.prototype._autoLoad=function(a,b,c){var d=this;"function"==typeof a.load?(d._db.debug()&&console.log(d._db.logIdentifier()+" Auto-loading data for "+b+":",c),a.load(function(a,b){a&&d._db.debug()&&console.log(d._db.logIdentifier()+" Automatic load failed:",a),d.emit("load",a,b)})):d._db.debug()&&console.log(d._db.logIdentifier()+" Auto-load for "+b+":",c,"no load method, skipping")},k.prototype._autoSave=function(a,b,c){var d=this;"function"==typeof a.save&&(d._db.debug()&&console.log(d._db.logIdentifier()+" Auto-saving data for "+b+":",c),a.save(function(a,b){a&&d._db.debug()&&console.log(d._db.logIdentifier()+" Automatic save failed:",a),d.emit("save",a,b)}))},k.prototype.mode=function(a){return void 0!==a?(this._mode=a,this):this._mode},k.prototype.driver=function(a){if(void 0!==a){switch(a.toUpperCase()){case"LOCALSTORAGE":o.setDriver(o.LOCALSTORAGE);break;case"WEBSQL":o.setDriver(o.WEBSQL);break;case"INDEXEDDB":o.setDriver(o.INDEXEDDB);break;default:throw"ForerunnerDB.Persist: The persistence driver you have specified is not found. Please use either IndexedDB, WebSQL or LocalStorage!"}return this}return o.driver()},k.prototype.decode=function(a,b){n.waterfall([function(b){b&&b(!1,a,{})}].concat(this._decodeSteps),b)},k.prototype.encode=function(a,b){n.waterfall([function(b){b&&b(!1,a,{})}].concat(this._encodeSteps),b)},m.synthesize(k.prototype,"encodeSteps"),m.synthesize(k.prototype,"decodeSteps"),k.prototype.addStep=new l({object:function(a){this.$main.call(this,function(){a.encode.apply(a,arguments)},function(){a.decode.apply(a,arguments)},0)},"function, function":function(a,b){this.$main.call(this,a,b,0)},"function, function, number":function(a,b,c){this.$main.call(this,a,b,c)},$main:function(a,b,c){0===c||void 0===c?(this._encodeSteps.push(a),this._decodeSteps.unshift(b)):(this._encodeSteps.splice(c,0,a),this._decodeSteps.splice(this._decodeSteps.length-c,0,b))}}),k.prototype.unwrap=function(a){var b,c=a.split("::fdb::");switch(c[0]){case"json":b=this.jParse(c[1]);break;case"raw":b=c[1]}},k.prototype._decode=function(a,b,c){var d,e;if(a){switch(d=a.split("::fdb::"),d[0]){case"json":e=this.jParse(d[1]);break;case"raw":e=d[1]}e?(b.foundData=!0,b.rowCount=e.length||0):(b.foundData=!1,b.rowCount=0),c&&c(!1,e,b)}else b.foundData=!1,b.rowCount=0,c&&c(!1,a,b)},k.prototype._encode=function(a,b,c){var d=a;a="object"==typeof a?"json::fdb::"+this.jStringify(a):"raw::fdb::"+a,d?(b.foundData=!0,b.rowCount=d.length||0):(b.foundData=!1,b.rowCount=0),c&&c(!1,a,b)},k.prototype.save=function(a,b,c){switch(this.mode()){case"localforage":this.encode(b,function(b,d,e){b?c(b):o.setItem(a,d).then(function(a){c&&c(!1,a,e)},function(a){c&&c(a)})});break;default:c&&c("No data handler.")}},k.prototype.load=function(a,b){var c=this;switch(this.mode()){case"localforage":o.getItem(a).then(function(a){c.decode(a,b)},function(a){b&&b(a)});break;default:b&&b("No data handler or unrecognised data type.")}},k.prototype.drop=function(a,b){switch(this.mode()){case"localforage":o.removeItem(a).then(function(){b&&b(!1)},function(a){b&&b(a)});break;default:b&&b("No data handler or unrecognised data type.")}},e.prototype.drop=new l({"":function(){this.isDropped()||this.drop(!0)},"function":function(a){this.isDropped()||this.drop(!0,a)},"boolean":function(a){if(!this.isDropped()){if(a){if(!this._name)throw"ForerunnerDB.Persist: Cannot drop a collection's persistent storage when no name assigned to collection!";this._db&&(this._db.persist.drop(this._db._name+"-"+this._name),this._db.persist.drop(this._db._name+"-"+this._name+"-metaData"))}f.call(this)}},"boolean, function":function(a,b){var c=this;if(!this.isDropped()){if(!a)return f.call(this,b);if(this._name){if(this._db)return this._db.persist.drop(this._db._name+"-"+this._name,function(){c._db.persist.drop(c._db._name+"-"+c._name+"-metaData",b)}),f.call(this);b&&b("Cannot drop a collection's persistent storage when the collection is not attached to a database!")}else b&&b("Cannot drop a collection's persistent storage when no name assigned to collection!")}}}),e.prototype.save=function(a){var b,c=this;c._name?c._db?(b=function(){c._db.persist.save(c._db._name+"-"+c._name,c._data,function(b,d,e){b?a&&a(b):c._db.persist.save(c._db._name+"-"+c._name+"-metaData",c.metaData(),function(b,f,g){a&&a(b,e,g,{tableData:d,metaData:f,tableDataName:c._db._name+"-"+c._name,metaDataName:c._db._name+"-"+c._name+"-metaData"})})})},c.isProcessingQueue()?c.on("queuesComplete",function(){b()}):b()):a&&a("Cannot save a collection that is not attached to a database!"):a&&a("Cannot save a collection with no assigned name!")},e.prototype.load=function(a){var b=this;b._name?b._db?b._db.persist.load(b._db._name+"-"+b._name,function(c,d,e){c?a&&a(c):b.remove({},function(){d=d||[],b.insert(d,function(){b._db.persist.load(b._db._name+"-"+b._name+"-metaData",function(c,d,f){c||d&&b.metaData(d),a&&a(c,e,f)})})})}):a&&a("Cannot load a collection that is not attached to a database!"):a&&a("Cannot load a collection with no assigned name!")},e.prototype.saveCustom=function(a){var b,c=this,d={};c._name?c._db?(b=function(){c.encode(c._data,function(b,e,f){b?a(b):(d.data={name:c._db._name+"-"+c._name,store:e,tableStats:f},c.encode(c._data,function(b,e,f){b?a(b):(d.metaData={name:c._db._name+"-"+c._name+"-metaData",store:e,tableStats:f},a(!1,d))}))})},c.isProcessingQueue()?c.on("queuesComplete",function(){b()}):b()):a&&a("Cannot save a collection that is not attached to a database!"):a&&a("Cannot save a collection with no assigned name!")},e.prototype.loadCustom=function(a,b){var c=this;c._name?c._db?a.data&&a.data.store?a.metaData&&a.metaData.store?c.decode(a.data.store,function(d,e,f){d?b(d):e&&(c.remove({}),c.insert(e),c.decode(a.metaData.store,function(a,d,e){a?b(a):d&&(c.metaData(d),b&&b(a,f,e))}))}):b('No "metaData" key found in passed object!'):b('No "data" key found in passed object!'):b&&b("Cannot load a collection that is not attached to a database!"):b&&b("Cannot load a collection with no assigned name!")},d.prototype.init=function(){i.apply(this,arguments),this.persist=new k(this)},d.prototype.load=new l({"function":function(a){this.$main.call(this,{},a)},"object, function":function(a,b){this.$main.call(this,a,b)},$main:function(a,b){var c,d,e=this._collection,f=e.keys(),g=f.length;c=function(a){a?b&&b(a):(g--,0===g&&b&&b(!1))};for(d in e)e.hasOwnProperty(d)&&(a?e[d].loadCustom(a,c):e[d].load(c))}}),d.prototype.save=new l({"function":function(a){this.$main.call(this,{},a)},"object, function":function(a,b){this.$main.call(this,a,b)},$main:function(a,b){var c,d,e=this._collection,f=e.keys(),g=f.length;c=function(a){a?b&&b(a):(g--,0===g&&b&&b(!1))};for(d in e)e.hasOwnProperty(d)&&(a.custom?e[d].saveCustom(c):e[d].save(c))}}),m.finishModule("Persist"),b.exports=k},{"./Collection":5,"./CollectionGroup":6,"./PersistCompress":36,"./PersistCrypto":37,"./Shared":40,async:43,localforage:81}],36:[function(a,b,c){"use strict";var d=a("./Shared"),e=a("pako"),f=function(){this.init.apply(this,arguments)};f.prototype.init=function(a){},d.mixin(f.prototype,"Mixin.Common"),f.prototype.encode=function(a,b,c){var d,f,g,h={data:a,type:"fdbCompress",enabled:!1};d=a.length,g=e.deflate(a,{to:"string"}),f=g.length,d>f&&(h.data=g,h.enabled=!0),b.compression={enabled:h.enabled,compressedBytes:f,uncompressedBytes:d,effect:Math.round(100/d*f)+"%"},c(!1,this.jStringify(h),b)},f.prototype.decode=function(a,b,c){var d,f=!1;a?(a=this.jParse(a),a.enabled?(d=e.inflate(a.data,{to:"string"}),f=!0):(d=a.data,f=!1),b.compression={enabled:f},c&&c(!1,d,b)):c&&c(!1,d,b)},d.plugins.FdbCompress=f,b.exports=f},{"./Shared":40,pako:83}],37:[function(a,b,c){"use strict";var d=a("./Shared"),e=a("crypto-js"),f=function(){this.init.apply(this,arguments)};f.prototype.init=function(a){if(!a||!a.pass)throw'Cannot initialise persistent storage encryption without a passphrase provided in the passed options object as the "pass" field.';this._algo=a.algo||"AES",this._pass=a.pass},d.mixin(f.prototype,"Mixin.Common"),d.synthesize(f.prototype,"pass"),f.prototype.stringify=function(a){var b={ct:a.ciphertext.toString(e.enc.Base64)};return a.iv&&(b.iv=a.iv.toString()),a.salt&&(b.s=a.salt.toString()),this.jStringify(b)},f.prototype.parse=function(a){var b=this.jParse(a),c=e.lib.CipherParams.create({ciphertext:e.enc.Base64.parse(b.ct)});return b.iv&&(c.iv=e.enc.Hex.parse(b.iv)),b.s&&(c.salt=e.enc.Hex.parse(b.s)),c},f.prototype.encode=function(a,b,c){var d,f=this,g={type:"fdbCrypto"};d=e[this._algo].encrypt(a,this._pass,{format:{stringify:function(){return f.stringify.apply(f,arguments)},parse:function(){return f.parse.apply(f,arguments)}}}),g.data=d.toString(),g.enabled=!0,b.encryption={enabled:g.enabled},c&&c(!1,this.jStringify(g),b)},f.prototype.decode=function(a,b,c){var d,f=this;a?(a=this.jParse(a),d=e[this._algo].decrypt(a.data,this._pass,{format:{stringify:function(){return f.stringify.apply(f,arguments)},parse:function(){return f.parse.apply(f,arguments)}}}).toString(e.enc.Utf8),c&&c(!1,d,b)):c&&c(!1,a,b)},d.plugins.FdbCrypto=f,b.exports=f},{"./Shared":40,"crypto-js":52}],38:[function(a,b,c){"use strict";var d=a("./Shared"),e=function(a,b,c){if(!(a&&b&&c))throw"ForerunnerDB.ReactorIO: ReactorIO requires in, out and process arguments to instantiate!";if(this._reactorIn=a,this._reactorOut=b,this._chainHandler=c,!a.chain)throw"ForerunnerDB.ReactorIO: ReactorIO requires passed in and out objects to implement the ChainReactor mixin!";a.chain(this),this.chain(b)};d.addModule("ReactorIO",e),e.prototype.drop=function(){return this.isDropped()||(this._state="dropped",this._reactorIn&&this._reactorIn.unChain(this),this._reactorOut&&this.unChain(this._reactorOut),delete this._reactorIn,delete this._reactorOut,delete this._chainHandler,this.emit("drop",this),delete this._listeners),!0},d.synthesize(e.prototype,"state"),d.mixin(e.prototype,"Mixin.Common"),d.mixin(e.prototype,"Mixin.ChainReactor"),d.mixin(e.prototype,"Mixin.Events"),d.finishModule("ReactorIO"),b.exports=e},{"./Shared":40}],39:[function(a,b,c){"use strict";var d=function(){this.init.apply(this,arguments)};d.prototype.init=function(){var a=this;this._encoder=[],this._decoder=[],this.registerHandler("$date",function(a){return a instanceof Date?(a.toJSON=function(){return"$date:"+this.toISOString()},!0):!1},function(b){return"string"==typeof b&&0===b.indexOf("$date:")?a.convert(new Date(b.substr(6))):void 0}),this.registerHandler("$regexp",function(a){return a instanceof RegExp?(a.toJSON=function(){return"$regexp:"+this.source.length+":"+this.source+":"+(this.global?"g":"")+(this.ignoreCase?"i":"")},!0):!1},function(b){if("string"==typeof b&&0===b.indexOf("$regexp:")){var c=b.substr(8),d=c.indexOf(":"),e=Number(c.substr(0,d)),f=c.substr(d+1,e),g=c.substr(d+e+2);return a.convert(new RegExp(f,g))}})},d.prototype.registerHandler=function(a,b,c){void 0!==a&&(this._encoder.push(b),this._decoder.push(c))},d.prototype.convert=function(a){var b,c=this._encoder;for(b=0;b<c.length;b++)if(c[b](a))return a;return a},d.prototype.reviver=function(){var a=this._decoder;return function(b,c){var d,e;for(e=0;e<a.length;e++)if(d=a[e](c),void 0!==d)return d;return c}},b.exports=d},{}],40:[function(a,b,c){"use strict";var d=a("./Overload"),e={version:"1.3.840",modules:{},plugins:{},index:{},_synth:{},addModule:function(a,b){this.modules[a]=b,this.emit("moduleLoad",[a,b])},finishModule:function(a){if(!this.modules[a])throw"ForerunnerDB.Shared: finishModule called on a module that has not been registered with addModule(): "+a;this.modules[a]._fdbFinished=!0,this.modules[a].prototype?this.modules[a].prototype.className=a:this.modules[a].className=a,this.emit("moduleFinished",[a,this.modules[a]])},moduleFinished:function(a,b){this.modules[a]&&this.modules[a]._fdbFinished?b&&b(a,this.modules[a]):this.on("moduleFinished",b)},moduleExists:function(a){return Boolean(this.modules[a])},mixin:new d({"object, string":function(a,b){var c;if("string"==typeof b&&(c=this.mixins[b],!c))throw"ForerunnerDB.Shared: Cannot find mixin named: "+b;return this.$main.call(this,a,c)},"object, *":function(a,b){return this.$main.call(this,a,b)},$main:function(a,b){if(b&&"object"==typeof b)for(var c in b)b.hasOwnProperty(c)&&(a[c]=b[c]);return a}}),synthesize:function(a,b,c){if(this._synth[b]=this._synth[b]||function(a){return void 0!==a?(this["_"+b]=a,this):this["_"+b]},c){var d=this;a[b]=function(){var a,e=this.$super;return this.$super=d._synth[b],a=c.apply(this,arguments),this.$super=e,a}}else a[b]=this._synth[b]},overload:d,mixins:{"Mixin.Common":a("./Mixin.Common"),"Mixin.Events":a("./Mixin.Events"),"Mixin.ChainReactor":a("./Mixin.ChainReactor"),"Mixin.CRUD":a("./Mixin.CRUD"),"Mixin.Constants":a("./Mixin.Constants"),"Mixin.Triggers":a("./Mixin.Triggers"),"Mixin.Sorting":a("./Mixin.Sorting"),"Mixin.Matching":a("./Mixin.Matching"),"Mixin.Updating":a("./Mixin.Updating"),"Mixin.Tags":a("./Mixin.Tags")}};e.mixin(e,"Mixin.Events"),b.exports=e},{"./Mixin.CRUD":19,"./Mixin.ChainReactor":20,"./Mixin.Common":21,"./Mixin.Constants":22,"./Mixin.Events":23,"./Mixin.Matching":24,"./Mixin.Sorting":25,"./Mixin.Tags":26,"./Mixin.Triggers":27,"./Mixin.Updating":28,"./Overload":32}],41:[function(a,b,c){"use strict";var d,e,f,g,h,i,j,k,l,m,n=a("./Overload");d=a("./Shared");var o=function(a,b,c){this.init.apply(this,arguments)};d.addModule("View",o),d.mixin(o.prototype,"Mixin.Common"),d.mixin(o.prototype,"Mixin.Matching"),d.mixin(o.prototype,"Mixin.ChainReactor"),d.mixin(o.prototype,"Mixin.Constants"),d.mixin(o.prototype,"Mixin.Tags"),f=a("./Collection"),g=a("./CollectionGroup"),k=a("./ActiveBucket"),j=a("./ReactorIO"),h=f.prototype.init,e=d.modules.Db,i=e.prototype.init,l=d.modules.Path,m=new l,o.prototype.init=function(a,b,c){var d=this;this.sharedPathSolver=m,this._name=a,this._listeners={},this._querySettings={},this._debug={},this.query(b,c,!1),this._collectionDroppedWrap=function(){d._collectionDropped.apply(d,arguments)},this._data=new f(this.name()+"_internal")},o.prototype._handleChainIO=function(a,b){var c,d,e,f,g=a.type;return"setData"!==g&&"insert"!==g&&"update"!==g&&"remove"!==g?!1:(c=Boolean(b._querySettings.options&&b._querySettings.options.$join),d=Boolean(b._querySettings.query),e=void 0!==b._data._transformIn,c||d||e?(f={dataArr:[],removeArr:[]},"insert"===a.type?a.data.dataSet instanceof Array?f.dataArr=a.data.dataSet:f.dataArr=[a.data.dataSet]:"update"===a.type?f.dataArr=a.data.dataSet:"remove"===a.type&&(a.data.dataSet instanceof Array?f.removeArr=a.data.dataSet:f.removeArr=[a.data.dataSet]),f.dataArr instanceof Array||(console.warn("WARNING: dataArr being processed by chain reactor in View class is inconsistent!"),f.dataArr=[]),f.removeArr instanceof Array||(console.warn("WARNING: removeArr being processed by chain reactor in View class is inconsistent!"),f.removeArr=[]),c&&(this.debug()&&console.time(this.logIdentifier()+" :: _handleChainIO_ActiveJoin"),b._handleChainIO_ActiveJoin(a,f),this.debug()&&console.timeEnd(this.logIdentifier()+" :: _handleChainIO_ActiveJoin")),d&&(this.debug()&&console.time(this.logIdentifier()+" :: _handleChainIO_ActiveQuery"),b._handleChainIO_ActiveQuery(a,f),this.debug()&&console.timeEnd(this.logIdentifier()+" :: _handleChainIO_ActiveQuery")),e&&(this.debug()&&console.time(this.logIdentifier()+" :: _handleChainIO_TransformIn"),b._handleChainIO_TransformIn(a,f),this.debug()&&console.timeEnd(this.logIdentifier()+" :: _handleChainIO_TransformIn")),f.dataArr.length||f.removeArr.length?(f.pk=b._data.primaryKey(),f.removeArr.length&&(this.debug()&&console.time(this.logIdentifier()+" :: _handleChainIO_RemovePackets"),b._handleChainIO_RemovePackets(this,a,f),this.debug()&&console.timeEnd(this.logIdentifier()+" :: _handleChainIO_RemovePackets")),f.dataArr.length&&(this.debug()&&console.time(this.logIdentifier()+" :: _handleChainIO_UpsertPackets"),b._handleChainIO_UpsertPackets(this,a,f),this.debug()&&console.timeEnd(this.logIdentifier()+" :: _handleChainIO_UpsertPackets")),!0):!0):!1)},o.prototype._handleChainIO_ActiveJoin=function(a,b){var c,d=b.dataArr;c=this.applyJoin(d,this._querySettings.options.$join,{},{}),this.spliceArrayByIndexList(d,c),b.removeArr=b.removeArr.concat(c)},o.prototype._handleChainIO_ActiveQuery=function(a,b){var c,d=this,e=b.dataArr;for(c=e.length-1;c>=0;c--)d._match(e[c],d._querySettings.query,d._querySettings.options,"and",{})||(b.removeArr.push(e[c]),e.splice(c,1))},o.prototype._handleChainIO_TransformIn=function(a,b){var c,d=this,e=b.dataArr,f=b.removeArr,g=d._data._transformIn;for(c=0;c<e.length;c++)e[c]=g(e[c]);for(c=0;c<f.length;c++)f[c]=g(f[c])},o.prototype._handleChainIO_RemovePackets=function(a,b,c){var d,e,f=[],g=c.pk,h=c.removeArr,i={dataSet:h,query:{$or:f}};for(e=0;e<h.length;e++)d={},d[g]=h[e][g],f.push(d);a.chainSend("remove",i)},o.prototype._handleChainIO_UpsertPackets=function(a,b,c){var d,e,f,g=this._data,h=g._primaryIndex,i=g._primaryCrc,j=c.pk,k=c.dataArr,l=[],m=[];for(f=0;f<k.length;f++)d=k[f],h.get(d[j])?i.get(d[j])!==this.hash(d[j])&&m.push(d):l.push(d);if(l.length&&a.chainSend("insert",{dataSet:l}),m.length)for(f=0;f<m.length;f++)d=m[f],e={},e[j]=d[j],a.chainSend("update",{query:e,update:d,dataSet:[d]})},o.prototype.insert=function(){this._from.insert.apply(this._from,arguments)},o.prototype.update=function(a,b,c,d){var e={$and:[this.query(),a]};this._from.update.call(this._from,e,b,c,d)},o.prototype.updateById=function(){this._from.updateById.apply(this._from,arguments)},o.prototype.remove=function(){this._from.remove.apply(this._from,arguments)},o.prototype.find=function(a,b){return this._data.find(a,b)},o.prototype.findOne=function(a,b){return this._data.findOne(a,b)},o.prototype.findById=function(a,b){return this._data.findById(a,b)},o.prototype.findSub=function(a,b,c,d){return this._data.findSub(a,b,c,d)},o.prototype.findSubOne=function(a,b,c,d){return this._data.findSubOne(a,b,c,d)},o.prototype.data=function(){return this._data},o.prototype.from=function(a,b){var c=this;if(void 0!==a){this._from&&(this._from.off("drop",this._collectionDroppedWrap),delete this._from),this._io&&(this._io.drop(),delete this._io),"string"==typeof a&&(a=this._db.collection(a)),"View"===a.className&&(a=a._data,this.debug()&&console.log(this.logIdentifier()+' Using internal data "'+a.instanceIdentifier()+'" for IO graph linking')),this._from=a,this._from.on("drop",this._collectionDroppedWrap),this._io=new j(this._from,this,function(a){return c._handleChainIO.call(this,a,c)}),this._data.primaryKey(a.primaryKey());var d=a.find(this._querySettings.query,this._querySettings.options);return this._data.setData(d,{},b),this._querySettings.options&&this._querySettings.options.$orderBy?this.rebuildActiveBucket(this._querySettings.options.$orderBy):this.rebuildActiveBucket(),this}return this._from},o.prototype._chainHandler=function(a){var b,c,d,e,f,g,h,i;switch(this.debug()&&console.log(this.logIdentifier()+" Received chain reactor data: "+a.type),a.type){case"setData":this.debug()&&console.log(this.logIdentifier()+' Setting data in underlying (internal) view collection "'+this._data.name()+'"');var j=this._from.find(this._querySettings.query,this._querySettings.options);this._data.setData(j),this.rebuildActiveBucket(this._querySettings.options);break;case"insert":if(this.debug()&&console.log(this.logIdentifier()+' Inserting some data into underlying (internal) view collection "'+this._data.name()+'"'),a.data.dataSet=this.decouple(a.data.dataSet),a.data.dataSet instanceof Array||(a.data.dataSet=[a.data.dataSet]),this._querySettings.options&&this._querySettings.options.$orderBy)for(b=a.data.dataSet,c=b.length,d=0;c>d;d++)e=this._activeBucket.insert(b[d]),this._data._insertHandle(b[d],e);else e=this._data._data.length,this._data._insertHandle(a.data.dataSet,e);break;case"update":if(this.debug()&&console.log(this.logIdentifier()+' Updating some data in underlying (internal) view collection "'+this._data.name()+'"'),g=this._data.primaryKey(),f=this._data._handleUpdate(a.data.query,a.data.update,a.data.options),this._querySettings.options&&this._querySettings.options.$orderBy)for(c=f.length,d=0;c>d;d++)h=f[d],this._activeBucket.remove(h),i=this._data._data.indexOf(h),e=this._activeBucket.insert(h),i!==e&&this._data._updateSpliceMove(this._data._data,i,e);break;case"remove":if(this.debug()&&console.log(this.logIdentifier()+' Removing some data from underlying (internal) view collection "'+this._data.name()+'"'),this._data.remove(a.data.query,a.options),this._querySettings.options&&this._querySettings.options.$orderBy)for(b=a.data.dataSet,c=b.length,d=0;c>d;d++)this._activeBucket.remove(b[d])}},o.prototype._collectionDropped=function(a){a&&delete this._from},o.prototype.ensureIndex=function(){return this._data.ensureIndex.apply(this._data,arguments)},o.prototype.on=function(){return this._data.on.apply(this._data,arguments)},o.prototype.off=function(){return this._data.off.apply(this._data,arguments)},o.prototype.emit=function(){return this._data.emit.apply(this._data,arguments)},o.prototype.deferEmit=function(){return this._data.deferEmit.apply(this._data,arguments)},o.prototype.distinct=function(a,b,c){return this._data.distinct(a,b,c)},o.prototype.primaryKey=function(){return this._data.primaryKey()},o.prototype.addTrigger=function(){return this._data.addTrigger.apply(this._data,arguments)},o.prototype.removeTrigger=function(){return this._data.removeTrigger.apply(this._data,arguments)},o.prototype.ignoreTriggers=function(){return this._data.ignoreTriggers.apply(this._data,arguments)},o.prototype.addLinkIO=function(){return this._data.addLinkIO.apply(this._data,arguments)},o.prototype.removeLinkIO=function(){return this._data.removeLinkIO.apply(this._data,arguments)},o.prototype.willTrigger=function(){return this._data.willTrigger.apply(this._data,arguments)},o.prototype.processTrigger=function(){return this._data.processTrigger.apply(this._data,arguments)},o.prototype._triggerIndexOf=function(){return this._data._triggerIndexOf.apply(this._data,arguments)},o.prototype.drop=function(a){return this.isDropped()?!1:(this._from&&(this._from.off("drop",this._collectionDroppedWrap),this._from._removeView(this)),(this.debug()||this._db&&this._db.debug())&&console.log(this.logIdentifier()+" Dropping"),this._state="dropped",this._io&&this._io.drop(),this._data&&this._data.drop(),this._db&&this._name&&delete this._db._view[this._name],this.emit("drop",this),a&&a(!1,!0),delete this._chain,delete this._from,delete this._data,delete this._io,delete this._listeners,delete this._querySettings,delete this._db,!0)},o.prototype.queryData=function(a,b,c){return void 0!==a&&(this._querySettings.query=a,a.$findSub&&!a.$findSub.$from&&(a.$findSub.$from=this._data.name()),a.$findSubOne&&!a.$findSubOne.$from&&(a.$findSubOne.$from=this._data.name())),void 0!==b&&(this._querySettings.options=b),void 0===a&&void 0===b||void 0!==c&&c!==!0||this.refresh(),void 0!==a&&this.emit("queryChange",a),void 0!==b&&this.emit("queryOptionsChange",b),void 0!==a||void 0!==b?this:this._querySettings},o.prototype.queryAdd=function(a,b,c){this._querySettings.query=this._querySettings.query||{};var d,e=this._querySettings.query;if(void 0!==a)for(d in a)a.hasOwnProperty(d)&&(void 0===e[d]||void 0!==e[d]&&b!==!1)&&(e[d]=a[d]);void 0!==c&&c!==!0||this.refresh(),void 0!==e&&this.emit("queryChange",e)},o.prototype.queryRemove=function(a,b){var c,d=this._querySettings.query;if(d){if(void 0!==a)for(c in a)a.hasOwnProperty(c)&&delete d[c];void 0!==b&&b!==!0||this.refresh(),void 0!==d&&this.emit("queryChange",d)}},o.prototype.query=new n({"":function(){return this.decouple(this._querySettings.query)},object:function(a){return this.$main.call(this,a,void 0,!0)},"*, boolean":function(a,b){return this.$main.call(this,a,void 0,b)},"object, object":function(a,b){return this.$main.call(this,a,b,!0)},"*, *, boolean":function(a,b,c){return this.$main.call(this,a,b,c)},$main:function(a,b,c){return void 0!==a&&(this._querySettings.query=a,a.$findSub&&!a.$findSub.$from&&(a.$findSub.$from=this._data.name()),a.$findSubOne&&!a.$findSubOne.$from&&(a.$findSubOne.$from=this._data.name())),void 0!==b&&(this._querySettings.options=b),void 0===a&&void 0===b||void 0!==c&&c!==!0||this.refresh(),void 0!==a&&this.emit("queryChange",a),void 0!==b&&this.emit("queryOptionsChange",b),void 0!==a||void 0!==b?this:this.decouple(this._querySettings)}}),o.prototype.orderBy=function(a){if(void 0!==a){var b=this.queryOptions()||{};return b.$orderBy=a,this.queryOptions(b),this}return(this.queryOptions()||{}).$orderBy},o.prototype.page=function(a){if(void 0!==a){var b=this.queryOptions()||{};return a!==b.$page&&(b.$page=a,this.queryOptions(b)),this}return(this.queryOptions()||{}).$page},o.prototype.pageFirst=function(){return this.page(0)},o.prototype.pageLast=function(){var a=this.cursor().pages,b=void 0!==a?a:0;return this.page(b-1)},o.prototype.pageScan=function(a){if(void 0!==a){var b=this.cursor().pages,c=this.queryOptions()||{},d=void 0!==c.$page?c.$page:0;return d+=a,0>d&&(d=0),d>=b&&(d=b-1),this.page(d)}},o.prototype.queryOptions=function(a,b){return void 0!==a?(this._querySettings.options=a,void 0===a.$decouple&&(a.$decouple=!0),void 0===b||b===!0?this.refresh():this.rebuildActiveBucket(a.$orderBy),void 0!==a&&this.emit("queryOptionsChange",a),this):this._querySettings.options},o.prototype.rebuildActiveBucket=function(a){if(a){var b=this._data._data,c=b.length;this._activeBucket=new k(a),this._activeBucket.primaryKey(this._data.primaryKey());for(var d=0;c>d;d++)this._activeBucket.insert(b[d])}else delete this._activeBucket},o.prototype.refresh=function(){var a,b,c,d,e=this;if(this._from&&(this._data.remove(),a=this._from.find(this._querySettings.query,this._querySettings.options),this.cursor(a.$cursor), this._data.insert(a),this._data._data.$cursor=a.$cursor),this._querySettings&&this._querySettings.options&&this._querySettings.options.$join&&this._querySettings.options.$join.length){if(e.__joinChange=e.__joinChange||function(){e._joinChange()},this._joinCollections&&this._joinCollections.length)for(c=0;c<this._joinCollections.length;c++)this._db.collection(this._joinCollections[c]).off("immediateChange",e.__joinChange);for(b=this._querySettings.options.$join,this._joinCollections=[],c=0;c<b.length;c++)for(d in b[c])b[c].hasOwnProperty(d)&&this._joinCollections.push(d);if(this._joinCollections.length)for(c=0;c<this._joinCollections.length;c++)this._db.collection(this._joinCollections[c]).on("immediateChange",e.__joinChange)}return this._querySettings.options&&this._querySettings.options.$orderBy?this.rebuildActiveBucket(this._querySettings.options.$orderBy):this.rebuildActiveBucket(),this},o.prototype._joinChange=function(a,b){this.emit("joinChange"),this.refresh()},o.prototype.count=function(){return this._data.count.apply(this._data,arguments)},o.prototype.subset=function(){return this._data.subset.apply(this._data,arguments)},o.prototype.transform=function(a){var b,c;return b=this._data.transform(),this._data.transform(a),c=this._data.transform(),c.enabled&&c.dataIn&&(b.enabled!==c.enabled||b.dataIn!==c.dataIn)&&this.refresh(),c},o.prototype.filter=function(a,b,c){return this._data.filter(a,b,c)},o.prototype.data=function(){return this._data},o.prototype.indexOf=function(){return this._data.indexOf.apply(this._data,arguments)},d.synthesize(o.prototype,"db",function(a){return a&&(this._data.db(a),this.debug(a.debug()),this._data.debug(a.debug())),this.$super.apply(this,arguments)}),d.synthesize(o.prototype,"state"),d.synthesize(o.prototype,"name"),d.synthesize(o.prototype,"cursor",function(a){return void 0===a?this._cursor||{}:void this.$super.apply(this,arguments)}),f.prototype.init=function(){this._view=[],h.apply(this,arguments)},f.prototype.view=function(a,b,c){if(this._db&&this._db._view){if(this._db._view[a])throw this.logIdentifier()+" Cannot create a view using this collection because a view with this name already exists: "+a;var d=new o(a,b,c).db(this._db).from(this);return this._view=this._view||[],this._view.push(d),d}},f.prototype._addView=g.prototype._addView=function(a){return void 0!==a&&this._view.push(a),this},f.prototype._removeView=g.prototype._removeView=function(a){if(void 0!==a){var b=this._view.indexOf(a);b>-1&&this._view.splice(b,1)}return this},e.prototype.init=function(){this._view={},i.apply(this,arguments)},e.prototype.view=function(a){var b=this;return a instanceof o?a:this._view[a]?this._view[a]:((this.debug()||this._db&&this._db.debug())&&console.log(this.logIdentifier()+" Creating view "+a),this._view[a]=new o(a).db(this),b.emit("create",b._view[a],"view",a),this._view[a])},e.prototype.viewExists=function(a){return Boolean(this._view[a])},e.prototype.views=function(){var a,b,c=[];for(b in this._view)this._view.hasOwnProperty(b)&&(a=this._view[b],c.push({name:b,count:a.count(),linked:void 0!==a.isLinked?a.isLinked():!1}));return c},d.finishModule("View"),b.exports=o},{"./ActiveBucket":2,"./Collection":5,"./CollectionGroup":6,"./Overload":32,"./ReactorIO":38,"./Shared":40}],42:[function(a,b,c){(function(a){function c(){for(;e.next;){e=e.next;var a=e.task;e.task=void 0;var b=e.domain;b&&(e.domain=void 0,b.enter());try{a()}catch(d){if(i)throw b&&b.exit(),setTimeout(c,0),b&&b.enter(),d;setTimeout(function(){throw d},0)}b&&b.exit()}g=!1}function d(b){f=f.next={task:b,domain:i&&a.domain,next:null},g||(g=!0,h())}var e={task:void 0,next:null},f=e,g=!1,h=void 0,i=!1;if("undefined"!=typeof a&&a.nextTick)i=!0,h=function(){a.nextTick(c)};else if("function"==typeof setImmediate)h="undefined"!=typeof window?setImmediate.bind(window,c):function(){setImmediate(c)};else if("undefined"!=typeof MessageChannel){var j=new MessageChannel;j.port1.onmessage=c,h=function(){j.port2.postMessage(0)}}else h=function(){setTimeout(c,0)};b.exports=d}).call(this,a("_process"))},{_process:99}],43:[function(a,b,c){(function(a,c){!function(){function d(){}function e(a){return a}function f(a){return!!a}function g(a){return!a}function h(a){return function(){if(null===a)throw new Error("Callback was already called.");a.apply(this,arguments),a=null}}function i(a){return function(){null!==a&&(a.apply(this,arguments),a=null)}}function j(a){return N(a)||"number"==typeof a.length&&a.length>=0&&a.length%1===0}function k(a,b){for(var c=-1,d=a.length;++c<d;)b(a[c],c,a)}function l(a,b){for(var c=-1,d=a.length,e=Array(d);++c<d;)e[c]=b(a[c],c,a);return e}function m(a){return l(Array(a),function(a,b){return b})}function n(a,b,c){return k(a,function(a,d,e){c=b(c,a,d,e)}),c}function o(a,b){k(P(a),function(c){b(a[c],c)})}function p(a,b){for(var c=0;c<a.length;c++)if(a[c]===b)return c;return-1}function q(a){var b,c,d=-1;return j(a)?(b=a.length,function(){return d++,b>d?d:null}):(c=P(a),b=c.length,function(){return d++,b>d?c[d]:null})}function r(a,b){return b=null==b?a.length-1:+b,function(){for(var c=Math.max(arguments.length-b,0),d=Array(c),e=0;c>e;e++)d[e]=arguments[e+b];switch(b){case 0:return a.call(this,d);case 1:return a.call(this,arguments[0],d)}}}function s(a){return function(b,c,d){return a(b,d)}}function t(a){return function(b,c,e){e=i(e||d),b=b||[];var f=q(b);if(0>=a)return e(null);var g=!1,j=0,k=!1;!function l(){if(g&&0>=j)return e(null);for(;a>j&&!k;){var d=f();if(null===d)return g=!0,void(0>=j&&e(null));j+=1,c(b[d],d,h(function(a){j-=1,a?(e(a),k=!0):l()}))}}()}}function u(a){return function(b,c,d){return a(K.eachOf,b,c,d)}}function v(a){return function(b,c,d,e){return a(t(c),b,d,e)}}function w(a){return function(b,c,d){return a(K.eachOfSeries,b,c,d)}}function x(a,b,c,e){e=i(e||d),b=b||[];var f=j(b)?[]:{};a(b,function(a,b,d){c(a,function(a,c){f[b]=c,d(a)})},function(a){e(a,f)})}function y(a,b,c,d){var e=[];a(b,function(a,b,d){c(a,function(c){c&&e.push({index:b,value:a}),d()})},function(){d(l(e.sort(function(a,b){return a.index-b.index}),function(a){return a.value}))})}function z(a,b,c,d){y(a,b,function(a,b){c(a,function(a){b(!a)})},d)}function A(a,b,c){return function(d,e,f,g){function h(){g&&g(c(!1,void 0))}function i(a,d,e){return g?void f(a,function(d){g&&b(d)&&(g(c(!0,a)),g=f=!1),e()}):e()}arguments.length>3?a(d,e,i,h):(g=f,f=e,a(d,i,h))}}function B(a,b){return b}function C(a,b,c){c=c||d;var e=j(b)?[]:{};a(b,function(a,b,c){a(r(function(a,d){d.length<=1&&(d=d[0]),e[b]=d,c(a)}))},function(a){c(a,e)})}function D(a,b,c,d){var e=[];a(b,function(a,b,d){c(a,function(a,b){e=e.concat(b||[]),d(a)})},function(a){d(a,e)})}function E(a,b,c){function e(a,b,c,e){if(null!=e&&"function"!=typeof e)throw new Error("task callback must be a function");return a.started=!0,N(b)||(b=[b]),0===b.length&&a.idle()?K.setImmediate(function(){a.drain()}):(k(b,function(b){var f={data:b,callback:e||d};c?a.tasks.unshift(f):a.tasks.push(f),a.tasks.length===a.concurrency&&a.saturated()}),void K.setImmediate(a.process))}function f(a,b){return function(){g-=1;var c=!1,d=arguments;k(b,function(a){k(i,function(b,d){b!==a||c||(i.splice(d,1),c=!0)}),a.callback.apply(a,d)}),a.tasks.length+g===0&&a.drain(),a.process()}}if(null==b)b=1;else if(0===b)throw new Error("Concurrency must not be zero");var g=0,i=[],j={tasks:[],concurrency:b,payload:c,saturated:d,empty:d,drain:d,started:!1,paused:!1,push:function(a,b){e(j,a,!1,b)},kill:function(){j.drain=d,j.tasks=[]},unshift:function(a,b){e(j,a,!0,b)},process:function(){for(;!j.paused&&g<j.concurrency&&j.tasks.length;){var b=j.payload?j.tasks.splice(0,j.payload):j.tasks.splice(0,j.tasks.length),c=l(b,function(a){return a.data});0===j.tasks.length&&j.empty(),g+=1,i.push(b[0]);var d=h(f(j,b));a(c,d)}},length:function(){return j.tasks.length},running:function(){return g},workersList:function(){return i},idle:function(){return j.tasks.length+g===0},pause:function(){j.paused=!0},resume:function(){if(j.paused!==!1){j.paused=!1;for(var a=Math.min(j.concurrency,j.tasks.length),b=1;a>=b;b++)K.setImmediate(j.process)}}};return j}function F(a){return r(function(b,c){b.apply(null,c.concat([r(function(b,c){"object"==typeof console&&(b?console.error&&console.error(b):console[a]&&k(c,function(b){console[a](b)}))})]))})}function G(a){return function(b,c,d){a(m(b),c,d)}}function H(a){return r(function(b,c){var d=r(function(c){var d=this,e=c.pop();return a(b,function(a,b,e){a.apply(d,c.concat([e]))},e)});return c.length?d.apply(this,c):d})}function I(a){return r(function(b){var c=b.pop();b.push(function(){var a=arguments;d?K.setImmediate(function(){c.apply(null,a)}):c.apply(null,a)});var d=!0;a.apply(this,b),d=!1})}var J,K={},L="object"==typeof self&&self.self===self&&self||"object"==typeof c&&c.global===c&&c||this;null!=L&&(J=L.async),K.noConflict=function(){return L.async=J,K};var M=Object.prototype.toString,N=Array.isArray||function(a){return"[object Array]"===M.call(a)},O=function(a){var b=typeof a;return"function"===b||"object"===b&&!!a},P=Object.keys||function(a){var b=[];for(var c in a)a.hasOwnProperty(c)&&b.push(c);return b},Q="function"==typeof setImmediate&&setImmediate,R=Q?function(a){Q(a)}:function(a){setTimeout(a,0)};"object"==typeof a&&"function"==typeof a.nextTick?K.nextTick=a.nextTick:K.nextTick=R,K.setImmediate=Q?R:K.nextTick,K.forEach=K.each=function(a,b,c){return K.eachOf(a,s(b),c)},K.forEachSeries=K.eachSeries=function(a,b,c){return K.eachOfSeries(a,s(b),c)},K.forEachLimit=K.eachLimit=function(a,b,c,d){return t(b)(a,s(c),d)},K.forEachOf=K.eachOf=function(a,b,c){function e(a){j--,a?c(a):null===f&&0>=j&&c(null)}c=i(c||d),a=a||[];for(var f,g=q(a),j=0;null!=(f=g());)j+=1,b(a[f],f,h(e));0===j&&c(null)},K.forEachOfSeries=K.eachOfSeries=function(a,b,c){function e(){var d=!0;return null===g?c(null):(b(a[g],g,h(function(a){if(a)c(a);else{if(g=f(),null===g)return c(null);d?K.setImmediate(e):e()}})),void(d=!1))}c=i(c||d),a=a||[];var f=q(a),g=f();e()},K.forEachOfLimit=K.eachOfLimit=function(a,b,c,d){t(b)(a,c,d)},K.map=u(x),K.mapSeries=w(x),K.mapLimit=v(x),K.inject=K.foldl=K.reduce=function(a,b,c,d){K.eachOfSeries(a,function(a,d,e){c(b,a,function(a,c){b=c,e(a)})},function(a){d(a,b)})},K.foldr=K.reduceRight=function(a,b,c,d){var f=l(a,e).reverse();K.reduce(f,b,c,d)},K.transform=function(a,b,c,d){3===arguments.length&&(d=c,c=b,b=N(a)?[]:{}),K.eachOf(a,function(a,d,e){c(b,a,d,e)},function(a){d(a,b)})},K.select=K.filter=u(y),K.selectLimit=K.filterLimit=v(y),K.selectSeries=K.filterSeries=w(y),K.reject=u(z),K.rejectLimit=v(z),K.rejectSeries=w(z),K.any=K.some=A(K.eachOf,f,e),K.someLimit=A(K.eachOfLimit,f,e),K.all=K.every=A(K.eachOf,g,g),K.everyLimit=A(K.eachOfLimit,g,g),K.detect=A(K.eachOf,e,B),K.detectSeries=A(K.eachOfSeries,e,B),K.detectLimit=A(K.eachOfLimit,e,B),K.sortBy=function(a,b,c){function d(a,b){var c=a.criteria,d=b.criteria;return d>c?-1:c>d?1:0}K.map(a,function(a,c){b(a,function(b,d){b?c(b):c(null,{value:a,criteria:d})})},function(a,b){return a?c(a):void c(null,l(b.sort(d),function(a){return a.value}))})},K.auto=function(a,b,c){function e(a){s.unshift(a)}function f(a){var b=p(s,a);b>=0&&s.splice(b,1)}function g(){j--,k(s.slice(0),function(a){a()})}"function"==typeof arguments[1]&&(c=b,b=null),c=i(c||d);var h=P(a),j=h.length;if(!j)return c(null);b||(b=j);var l={},m=0,q=!1,s=[];e(function(){j||c(null,l)}),k(h,function(d){function h(){return b>m&&n(t,function(a,b){return a&&l.hasOwnProperty(b)},!0)&&!l.hasOwnProperty(d)}function i(){h()&&(m++,f(i),k[k.length-1](s,l))}if(!q){for(var j,k=N(a[d])?a[d]:[a[d]],s=r(function(a,b){if(m--,b.length<=1&&(b=b[0]),a){var e={};o(l,function(a,b){e[b]=a}),e[d]=b,q=!0,c(a,e)}else l[d]=b,K.setImmediate(g)}),t=k.slice(0,k.length-1),u=t.length;u--;){if(!(j=a[t[u]]))throw new Error("Has nonexistent dependency in "+t.join(", "));if(N(j)&&p(j,d)>=0)throw new Error("Has cyclic dependencies")}h()?(m++,k[k.length-1](s,l)):e(i)}})},K.retry=function(a,b,c){function d(a,b){if("number"==typeof b)a.times=parseInt(b,10)||f;else{if("object"!=typeof b)throw new Error("Unsupported argument type for 'times': "+typeof b);a.times=parseInt(b.times,10)||f,a.interval=parseInt(b.interval,10)||g}}function e(a,b){function c(a,c){return function(d){a(function(a,b){d(!a||c,{err:a,result:b})},b)}}function d(a){return function(b){setTimeout(function(){b(null)},a)}}for(;i.times;){var e=!(i.times-=1);h.push(c(i.task,e)),!e&&i.interval>0&&h.push(d(i.interval))}K.series(h,function(b,c){c=c[c.length-1],(a||i.callback)(c.err,c.result)})}var f=5,g=0,h=[],i={times:f,interval:g},j=arguments.length;if(1>j||j>3)throw new Error("Invalid arguments - must be either (task), (task, callback), (times, task) or (times, task, callback)");return 2>=j&&"function"==typeof a&&(c=b,b=a),"function"!=typeof a&&d(i,a),i.callback=c,i.task=b,i.callback?e():e},K.waterfall=function(a,b){function c(a){return r(function(d,e){if(d)b.apply(null,[d].concat(e));else{var f=a.next();f?e.push(c(f)):e.push(b),I(a).apply(null,e)}})}if(b=i(b||d),!N(a)){var e=new Error("First argument to waterfall must be an array of functions");return b(e)}return a.length?void c(K.iterator(a))():b()},K.parallel=function(a,b){C(K.eachOf,a,b)},K.parallelLimit=function(a,b,c){C(t(b),a,c)},K.series=function(a,b){C(K.eachOfSeries,a,b)},K.iterator=function(a){function b(c){function d(){return a.length&&a[c].apply(null,arguments),d.next()}return d.next=function(){return c<a.length-1?b(c+1):null},d}return b(0)},K.apply=r(function(a,b){return r(function(c){return a.apply(null,b.concat(c))})}),K.concat=u(D),K.concatSeries=w(D),K.whilst=function(a,b,c){if(c=c||d,a()){var e=r(function(d,f){d?c(d):a.apply(this,f)?b(e):c.apply(null,[null].concat(f))});b(e)}else c(null)},K.doWhilst=function(a,b,c){var d=0;return K.whilst(function(){return++d<=1||b.apply(this,arguments)},a,c)},K.until=function(a,b,c){return K.whilst(function(){return!a.apply(this,arguments)},b,c)},K.doUntil=function(a,b,c){return K.doWhilst(a,function(){return!b.apply(this,arguments)},c)},K.during=function(a,b,c){c=c||d;var e=r(function(b,d){b?c(b):(d.push(f),a.apply(this,d))}),f=function(a,d){a?c(a):d?b(e):c(null)};a(f)},K.doDuring=function(a,b,c){var d=0;K.during(function(a){d++<1?a(null,!0):b.apply(this,arguments)},a,c)},K.queue=function(a,b){var c=E(function(b,c){a(b[0],c)},b,1);return c},K.priorityQueue=function(a,b){function c(a,b){return a.priority-b.priority}function e(a,b,c){for(var d=-1,e=a.length-1;e>d;){var f=d+(e-d+1>>>1);c(b,a[f])>=0?d=f:e=f-1}return d}function f(a,b,f,g){if(null!=g&&"function"!=typeof g)throw new Error("task callback must be a function");return a.started=!0,N(b)||(b=[b]),0===b.length?K.setImmediate(function(){a.drain()}):void k(b,function(b){var h={data:b,priority:f,callback:"function"==typeof g?g:d};a.tasks.splice(e(a.tasks,h,c)+1,0,h),a.tasks.length===a.concurrency&&a.saturated(),K.setImmediate(a.process)})}var g=K.queue(a,b);return g.push=function(a,b,c){f(g,a,b,c)},delete g.unshift,g},K.cargo=function(a,b){return E(a,1,b)},K.log=F("log"),K.dir=F("dir"),K.memoize=function(a,b){var c={},d={},f=Object.prototype.hasOwnProperty;b=b||e;var g=r(function(e){var g=e.pop(),h=b.apply(null,e);f.call(c,h)?K.setImmediate(function(){g.apply(null,c[h])}):f.call(d,h)?d[h].push(g):(d[h]=[g],a.apply(null,e.concat([r(function(a){c[h]=a;var b=d[h];delete d[h];for(var e=0,f=b.length;f>e;e++)b[e].apply(null,a)})])))});return g.memo=c,g.unmemoized=a,g},K.unmemoize=function(a){return function(){return(a.unmemoized||a).apply(null,arguments)}},K.times=G(K.map),K.timesSeries=G(K.mapSeries),K.timesLimit=function(a,b,c,d){return K.mapLimit(m(a),b,c,d)},K.seq=function(){var a=arguments;return r(function(b){var c=this,e=b[b.length-1];"function"==typeof e?b.pop():e=d,K.reduce(a,b,function(a,b,d){b.apply(c,a.concat([r(function(a,b){d(a,b)})]))},function(a,b){e.apply(c,[a].concat(b))})})},K.compose=function(){return K.seq.apply(null,Array.prototype.reverse.call(arguments))},K.applyEach=H(K.eachOf),K.applyEachSeries=H(K.eachOfSeries),K.forever=function(a,b){function c(a){return a?e(a):void f(c)}var e=h(b||d),f=I(a);c()},K.ensureAsync=I,K.constant=r(function(a){var b=[null].concat(a);return function(a){return a.apply(this,b)}}),K.wrapSync=K.asyncify=function(a){return r(function(b){var c,d=b.pop();try{c=a.apply(this,b)}catch(e){return d(e)}O(c)&&"function"==typeof c.then?c.then(function(a){d(null,a)})["catch"](function(a){d(a.message?a:new Error(a))}):d(null,c)})},"object"==typeof b&&b.exports?b.exports=K:"function"==typeof define&&define.amd?define([],function(){return K}):L.async=K}()}).call(this,a("_process"),"undefined"!=typeof global?global:"undefined"!=typeof self?self:"undefined"!=typeof window?window:{})},{_process:99}],44:[function(a,b,c){!function(d,e,f){"object"==typeof c?b.exports=c=e(a("./core"),a("./enc-base64"),a("./md5"),a("./evpkdf"),a("./cipher-core")):"function"==typeof define&&define.amd?define(["./core","./enc-base64","./md5","./evpkdf","./cipher-core"],e):e(d.CryptoJS)}(this,function(a){return function(){var b=a,c=b.lib,d=c.BlockCipher,e=b.algo,f=[],g=[],h=[],i=[],j=[],k=[],l=[],m=[],n=[],o=[];!function(){for(var a=[],b=0;256>b;b++)128>b?a[b]=b<<1:a[b]=b<<1^283;for(var c=0,d=0,b=0;256>b;b++){var e=d^d<<1^d<<2^d<<3^d<<4;e=e>>>8^255&e^99,f[c]=e,g[e]=c;var p=a[c],q=a[p],r=a[q],s=257*a[e]^16843008*e;h[c]=s<<24|s>>>8,i[c]=s<<16|s>>>16,j[c]=s<<8|s>>>24,k[c]=s;var s=16843009*r^65537*q^257*p^16843008*c;l[e]=s<<24|s>>>8,m[e]=s<<16|s>>>16,n[e]=s<<8|s>>>24,o[e]=s,c?(c=p^a[a[a[r^p]]],d^=a[a[d]]):c=d=1}}();var p=[0,1,2,4,8,16,32,64,128,27,54],q=e.AES=d.extend({_doReset:function(){for(var a=this._key,b=a.words,c=a.sigBytes/4,d=this._nRounds=c+6,e=4*(d+1),g=this._keySchedule=[],h=0;e>h;h++)if(c>h)g[h]=b[h];else{var i=g[h-1];h%c?c>6&&h%c==4&&(i=f[i>>>24]<<24|f[i>>>16&255]<<16|f[i>>>8&255]<<8|f[255&i]):(i=i<<8|i>>>24,i=f[i>>>24]<<24|f[i>>>16&255]<<16|f[i>>>8&255]<<8|f[255&i],i^=p[h/c|0]<<24),g[h]=g[h-c]^i}for(var j=this._invKeySchedule=[],k=0;e>k;k++){var h=e-k;if(k%4)var i=g[h];else var i=g[h-4];4>k||4>=h?j[k]=i:j[k]=l[f[i>>>24]]^m[f[i>>>16&255]]^n[f[i>>>8&255]]^o[f[255&i]]}},encryptBlock:function(a,b){this._doCryptBlock(a,b,this._keySchedule,h,i,j,k,f)},decryptBlock:function(a,b){var c=a[b+1];a[b+1]=a[b+3],a[b+3]=c,this._doCryptBlock(a,b,this._invKeySchedule,l,m,n,o,g);var c=a[b+1];a[b+1]=a[b+3],a[b+3]=c},_doCryptBlock:function(a,b,c,d,e,f,g,h){for(var i=this._nRounds,j=a[b]^c[0],k=a[b+1]^c[1],l=a[b+2]^c[2],m=a[b+3]^c[3],n=4,o=1;i>o;o++){var p=d[j>>>24]^e[k>>>16&255]^f[l>>>8&255]^g[255&m]^c[n++],q=d[k>>>24]^e[l>>>16&255]^f[m>>>8&255]^g[255&j]^c[n++],r=d[l>>>24]^e[m>>>16&255]^f[j>>>8&255]^g[255&k]^c[n++],s=d[m>>>24]^e[j>>>16&255]^f[k>>>8&255]^g[255&l]^c[n++];j=p,k=q,l=r,m=s}var p=(h[j>>>24]<<24|h[k>>>16&255]<<16|h[l>>>8&255]<<8|h[255&m])^c[n++],q=(h[k>>>24]<<24|h[l>>>16&255]<<16|h[m>>>8&255]<<8|h[255&j])^c[n++],r=(h[l>>>24]<<24|h[m>>>16&255]<<16|h[j>>>8&255]<<8|h[255&k])^c[n++],s=(h[m>>>24]<<24|h[j>>>16&255]<<16|h[k>>>8&255]<<8|h[255&l])^c[n++];a[b]=p,a[b+1]=q,a[b+2]=r,a[b+3]=s},keySize:8});b.AES=d._createHelper(q)}(),a.AES})},{"./cipher-core":45,"./core":46,"./enc-base64":47,"./evpkdf":49,"./md5":54}],45:[function(a,b,c){!function(d,e){"object"==typeof c?b.exports=c=e(a("./core")):"function"==typeof define&&define.amd?define(["./core"],e):e(d.CryptoJS)}(this,function(a){a.lib.Cipher||function(b){var c=a,d=c.lib,e=d.Base,f=d.WordArray,g=d.BufferedBlockAlgorithm,h=c.enc,i=(h.Utf8,h.Base64),j=c.algo,k=j.EvpKDF,l=d.Cipher=g.extend({cfg:e.extend(),createEncryptor:function(a,b){return this.create(this._ENC_XFORM_MODE,a,b)},createDecryptor:function(a,b){return this.create(this._DEC_XFORM_MODE,a,b)},init:function(a,b,c){this.cfg=this.cfg.extend(c),this._xformMode=a,this._key=b,this.reset()},reset:function(){g.reset.call(this),this._doReset()},process:function(a){return this._append(a),this._process()},finalize:function(a){a&&this._append(a);var b=this._doFinalize();return b},keySize:4,ivSize:4,_ENC_XFORM_MODE:1,_DEC_XFORM_MODE:2,_createHelper:function(){function a(a){return"string"==typeof a?x:u}return function(b){return{encrypt:function(c,d,e){return a(d).encrypt(b,c,d,e)},decrypt:function(c,d,e){return a(d).decrypt(b,c,d,e)}}}}()}),m=(d.StreamCipher=l.extend({_doFinalize:function(){var a=this._process(!0);return a},blockSize:1}),c.mode={}),n=d.BlockCipherMode=e.extend({createEncryptor:function(a,b){return this.Encryptor.create(a,b)},createDecryptor:function(a,b){return this.Decryptor.create(a,b)},init:function(a,b){this._cipher=a,this._iv=b}}),o=m.CBC=function(){function a(a,c,d){var e=this._iv;if(e){var f=e;this._iv=b}else var f=this._prevBlock;for(var g=0;d>g;g++)a[c+g]^=f[g]}var c=n.extend();return c.Encryptor=c.extend({processBlock:function(b,c){var d=this._cipher,e=d.blockSize;a.call(this,b,c,e),d.encryptBlock(b,c),this._prevBlock=b.slice(c,c+e)}}),c.Decryptor=c.extend({processBlock:function(b,c){var d=this._cipher,e=d.blockSize,f=b.slice(c,c+e);d.decryptBlock(b,c),a.call(this,b,c,e),this._prevBlock=f}}),c}(),p=c.pad={},q=p.Pkcs7={pad:function(a,b){for(var c=4*b,d=c-a.sigBytes%c,e=d<<24|d<<16|d<<8|d,g=[],h=0;d>h;h+=4)g.push(e);var i=f.create(g,d);a.concat(i)},unpad:function(a){var b=255&a.words[a.sigBytes-1>>>2];a.sigBytes-=b}},r=(d.BlockCipher=l.extend({cfg:l.cfg.extend({mode:o,padding:q}),reset:function(){l.reset.call(this);var a=this.cfg,b=a.iv,c=a.mode;if(this._xformMode==this._ENC_XFORM_MODE)var d=c.createEncryptor;else{var d=c.createDecryptor;this._minBufferSize=1}this._mode=d.call(c,this,b&&b.words)},_doProcessBlock:function(a,b){this._mode.processBlock(a,b)},_doFinalize:function(){var a=this.cfg.padding;if(this._xformMode==this._ENC_XFORM_MODE){a.pad(this._data,this.blockSize);var b=this._process(!0)}else{var b=this._process(!0);a.unpad(b)}return b},blockSize:4}),d.CipherParams=e.extend({init:function(a){this.mixIn(a)},toString:function(a){return(a||this.formatter).stringify(this)}})),s=c.format={},t=s.OpenSSL={stringify:function(a){var b=a.ciphertext,c=a.salt;if(c)var d=f.create([1398893684,1701076831]).concat(c).concat(b);else var d=b;return d.toString(i)},parse:function(a){var b=i.parse(a),c=b.words;if(1398893684==c[0]&&1701076831==c[1]){var d=f.create(c.slice(2,4));c.splice(0,4),b.sigBytes-=16}return r.create({ciphertext:b,salt:d})}},u=d.SerializableCipher=e.extend({cfg:e.extend({format:t}),encrypt:function(a,b,c,d){d=this.cfg.extend(d);var e=a.createEncryptor(c,d),f=e.finalize(b),g=e.cfg;return r.create({ciphertext:f,key:c,iv:g.iv,algorithm:a,mode:g.mode,padding:g.padding,blockSize:a.blockSize,formatter:d.format})},decrypt:function(a,b,c,d){d=this.cfg.extend(d),b=this._parse(b,d.format);var e=a.createDecryptor(c,d).finalize(b.ciphertext);return e},_parse:function(a,b){return"string"==typeof a?b.parse(a,this):a}}),v=c.kdf={},w=v.OpenSSL={execute:function(a,b,c,d){d||(d=f.random(8));var e=k.create({keySize:b+c}).compute(a,d),g=f.create(e.words.slice(b),4*c);return e.sigBytes=4*b,r.create({key:e,iv:g,salt:d})}},x=d.PasswordBasedCipher=u.extend({cfg:u.cfg.extend({kdf:w}),encrypt:function(a,b,c,d){d=this.cfg.extend(d);var e=d.kdf.execute(c,a.keySize,a.ivSize);d.iv=e.iv;var f=u.encrypt.call(this,a,b,e.key,d);return f.mixIn(e),f},decrypt:function(a,b,c,d){d=this.cfg.extend(d),b=this._parse(b,d.format);var e=d.kdf.execute(c,a.keySize,a.ivSize,b.salt);d.iv=e.iv;var f=u.decrypt.call(this,a,b,e.key,d);return f}})}()})},{"./core":46}],46:[function(a,b,c){!function(a,d){"object"==typeof c?b.exports=c=d():"function"==typeof define&&define.amd?define([],d):a.CryptoJS=d()}(this,function(){var a=a||function(a,b){var c={},d=c.lib={},e=d.Base=function(){function a(){}return{extend:function(b){a.prototype=this;var c=new a;return b&&c.mixIn(b),c.hasOwnProperty("init")||(c.init=function(){c.$super.init.apply(this,arguments)}),c.init.prototype=c,c.$super=this,c},create:function(){var a=this.extend();return a.init.apply(a,arguments),a},init:function(){},mixIn:function(a){for(var b in a)a.hasOwnProperty(b)&&(this[b]=a[b]);a.hasOwnProperty("toString")&&(this.toString=a.toString)},clone:function(){return this.init.prototype.extend(this)}}}(),f=d.WordArray=e.extend({init:function(a,c){a=this.words=a||[],c!=b?this.sigBytes=c:this.sigBytes=4*a.length},toString:function(a){return(a||h).stringify(this)},concat:function(a){var b=this.words,c=a.words,d=this.sigBytes,e=a.sigBytes;if(this.clamp(),d%4)for(var f=0;e>f;f++){var g=c[f>>>2]>>>24-f%4*8&255;b[d+f>>>2]|=g<<24-(d+f)%4*8}else for(var f=0;e>f;f+=4)b[d+f>>>2]=c[f>>>2];return this.sigBytes+=e,this},clamp:function(){var b=this.words,c=this.sigBytes;b[c>>>2]&=4294967295<<32-c%4*8,b.length=a.ceil(c/4)},clone:function(){var a=e.clone.call(this);return a.words=this.words.slice(0),a},random:function(b){for(var c,d=[],e=function(b){var b=b,c=987654321,d=4294967295;return function(){c=36969*(65535&c)+(c>>16)&d,b=18e3*(65535&b)+(b>>16)&d;var e=(c<<16)+b&d;return e/=4294967296,e+=.5,e*(a.random()>.5?1:-1)}},g=0;b>g;g+=4){var h=e(4294967296*(c||a.random()));c=987654071*h(),d.push(4294967296*h()|0)}return new f.init(d,b)}}),g=c.enc={},h=g.Hex={stringify:function(a){for(var b=a.words,c=a.sigBytes,d=[],e=0;c>e;e++){var f=b[e>>>2]>>>24-e%4*8&255;d.push((f>>>4).toString(16)),d.push((15&f).toString(16))}return d.join("")},parse:function(a){for(var b=a.length,c=[],d=0;b>d;d+=2)c[d>>>3]|=parseInt(a.substr(d,2),16)<<24-d%8*4;return new f.init(c,b/2)}},i=g.Latin1={stringify:function(a){for(var b=a.words,c=a.sigBytes,d=[],e=0;c>e;e++){var f=b[e>>>2]>>>24-e%4*8&255;d.push(String.fromCharCode(f))}return d.join("")},parse:function(a){for(var b=a.length,c=[],d=0;b>d;d++)c[d>>>2]|=(255&a.charCodeAt(d))<<24-d%4*8;return new f.init(c,b)}},j=g.Utf8={stringify:function(a){try{return decodeURIComponent(escape(i.stringify(a)))}catch(b){throw new Error("Malformed UTF-8 data")}},parse:function(a){return i.parse(unescape(encodeURIComponent(a)))}},k=d.BufferedBlockAlgorithm=e.extend({reset:function(){this._data=new f.init,this._nDataBytes=0},_append:function(a){"string"==typeof a&&(a=j.parse(a)),this._data.concat(a),this._nDataBytes+=a.sigBytes},_process:function(b){var c=this._data,d=c.words,e=c.sigBytes,g=this.blockSize,h=4*g,i=e/h;i=b?a.ceil(i):a.max((0|i)-this._minBufferSize,0);var j=i*g,k=a.min(4*j,e);if(j){for(var l=0;j>l;l+=g)this._doProcessBlock(d,l);var m=d.splice(0,j);c.sigBytes-=k}return new f.init(m,k)},clone:function(){var a=e.clone.call(this);return a._data=this._data.clone(),a},_minBufferSize:0}),l=(d.Hasher=k.extend({cfg:e.extend(),init:function(a){this.cfg=this.cfg.extend(a),this.reset()},reset:function(){k.reset.call(this),this._doReset()},update:function(a){return this._append(a),this._process(),this},finalize:function(a){a&&this._append(a);var b=this._doFinalize();return b},blockSize:16,_createHelper:function(a){return function(b,c){return new a.init(c).finalize(b)}},_createHmacHelper:function(a){return function(b,c){return new l.HMAC.init(a,c).finalize(b)}}}),c.algo={});return c}(Math);return a})},{}],47:[function(a,b,c){!function(d,e){"object"==typeof c?b.exports=c=e(a("./core")):"function"==typeof define&&define.amd?define(["./core"],e):e(d.CryptoJS)}(this,function(a){return function(){var b=a,c=b.lib,d=c.WordArray,e=b.enc;e.Base64={stringify:function(a){var b=a.words,c=a.sigBytes,d=this._map;a.clamp();for(var e=[],f=0;c>f;f+=3)for(var g=b[f>>>2]>>>24-f%4*8&255,h=b[f+1>>>2]>>>24-(f+1)%4*8&255,i=b[f+2>>>2]>>>24-(f+2)%4*8&255,j=g<<16|h<<8|i,k=0;4>k&&c>f+.75*k;k++)e.push(d.charAt(j>>>6*(3-k)&63));var l=d.charAt(64);if(l)for(;e.length%4;)e.push(l);return e.join("")},parse:function(a){var b=a.length,c=this._map,e=c.charAt(64);if(e){var f=a.indexOf(e);-1!=f&&(b=f)}for(var g=[],h=0,i=0;b>i;i++)if(i%4){var j=c.indexOf(a.charAt(i-1))<<i%4*2,k=c.indexOf(a.charAt(i))>>>6-i%4*2,l=j|k;g[h>>>2]|=l<<24-h%4*8,h++}return d.create(g,h)},_map:"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/="}}(),a.enc.Base64})},{"./core":46}],48:[function(a,b,c){!function(d,e){"object"==typeof c?b.exports=c=e(a("./core")):"function"==typeof define&&define.amd?define(["./core"],e):e(d.CryptoJS)}(this,function(a){return function(){function b(a){return a<<8&4278255360|a>>>8&16711935}var c=a,d=c.lib,e=d.WordArray,f=c.enc;f.Utf16=f.Utf16BE={stringify:function(a){for(var b=a.words,c=a.sigBytes,d=[],e=0;c>e;e+=2){var f=b[e>>>2]>>>16-e%4*8&65535;d.push(String.fromCharCode(f))}return d.join("")},parse:function(a){for(var b=a.length,c=[],d=0;b>d;d++)c[d>>>1]|=a.charCodeAt(d)<<16-d%2*16;return e.create(c,2*b)}};f.Utf16LE={stringify:function(a){for(var c=a.words,d=a.sigBytes,e=[],f=0;d>f;f+=2){var g=b(c[f>>>2]>>>16-f%4*8&65535);e.push(String.fromCharCode(g))}return e.join("")},parse:function(a){for(var c=a.length,d=[],f=0;c>f;f++)d[f>>>1]|=b(a.charCodeAt(f)<<16-f%2*16);return e.create(d,2*c)}}}(),a.enc.Utf16})},{"./core":46}],49:[function(a,b,c){!function(d,e,f){"object"==typeof c?b.exports=c=e(a("./core"),a("./sha1"),a("./hmac")):"function"==typeof define&&define.amd?define(["./core","./sha1","./hmac"],e):e(d.CryptoJS)}(this,function(a){return function(){var b=a,c=b.lib,d=c.Base,e=c.WordArray,f=b.algo,g=f.MD5,h=f.EvpKDF=d.extend({cfg:d.extend({keySize:4,hasher:g,iterations:1}),init:function(a){this.cfg=this.cfg.extend(a)},compute:function(a,b){for(var c=this.cfg,d=c.hasher.create(),f=e.create(),g=f.words,h=c.keySize,i=c.iterations;g.length<h;){j&&d.update(j);var j=d.update(a).finalize(b);d.reset();for(var k=1;i>k;k++)j=d.finalize(j),d.reset();f.concat(j)}return f.sigBytes=4*h,f}});b.EvpKDF=function(a,b,c){return h.create(c).compute(a,b)}}(),a.EvpKDF})},{"./core":46,"./hmac":51,"./sha1":70}],50:[function(a,b,c){!function(d,e,f){"object"==typeof c?b.exports=c=e(a("./core"),a("./cipher-core")):"function"==typeof define&&define.amd?define(["./core","./cipher-core"],e):e(d.CryptoJS)}(this,function(a){return function(b){var c=a,d=c.lib,e=d.CipherParams,f=c.enc,g=f.Hex,h=c.format;h.Hex={stringify:function(a){return a.ciphertext.toString(g)},parse:function(a){var b=g.parse(a);return e.create({ciphertext:b})}}}(),a.format.Hex})},{"./cipher-core":45,"./core":46}],51:[function(a,b,c){!function(d,e){"object"==typeof c?b.exports=c=e(a("./core")):"function"==typeof define&&define.amd?define(["./core"],e):e(d.CryptoJS)}(this,function(a){!function(){var b=a,c=b.lib,d=c.Base,e=b.enc,f=e.Utf8,g=b.algo;g.HMAC=d.extend({init:function(a,b){a=this._hasher=new a.init,"string"==typeof b&&(b=f.parse(b));var c=a.blockSize,d=4*c;b.sigBytes>d&&(b=a.finalize(b)),b.clamp();for(var e=this._oKey=b.clone(),g=this._iKey=b.clone(),h=e.words,i=g.words,j=0;c>j;j++)h[j]^=1549556828,i[j]^=909522486;e.sigBytes=g.sigBytes=d,this.reset()},reset:function(){var a=this._hasher;a.reset(),a.update(this._iKey)},update:function(a){return this._hasher.update(a),this},finalize:function(a){var b=this._hasher,c=b.finalize(a);b.reset();var d=b.finalize(this._oKey.clone().concat(c));return d}})}()})},{"./core":46}],52:[function(a,b,c){!function(d,e,f){"object"==typeof c?b.exports=c=e(a("./core"),a("./x64-core"),a("./lib-typedarrays"),a("./enc-utf16"),a("./enc-base64"),a("./md5"),a("./sha1"),a("./sha256"),a("./sha224"),a("./sha512"),a("./sha384"),a("./sha3"),a("./ripemd160"),a("./hmac"),a("./pbkdf2"),a("./evpkdf"),a("./cipher-core"),a("./mode-cfb"),a("./mode-ctr"),a("./mode-ctr-gladman"),a("./mode-ofb"),a("./mode-ecb"),a("./pad-ansix923"),a("./pad-iso10126"),a("./pad-iso97971"),a("./pad-zeropadding"),a("./pad-nopadding"),a("./format-hex"),a("./aes"),a("./tripledes"),a("./rc4"),a("./rabbit"),a("./rabbit-legacy")):"function"==typeof define&&define.amd?define(["./core","./x64-core","./lib-typedarrays","./enc-utf16","./enc-base64","./md5","./sha1","./sha256","./sha224","./sha512","./sha384","./sha3","./ripemd160","./hmac","./pbkdf2","./evpkdf","./cipher-core","./mode-cfb","./mode-ctr","./mode-ctr-gladman","./mode-ofb","./mode-ecb","./pad-ansix923","./pad-iso10126","./pad-iso97971","./pad-zeropadding","./pad-nopadding","./format-hex","./aes","./tripledes","./rc4","./rabbit","./rabbit-legacy"],e):d.CryptoJS=e(d.CryptoJS)}(this,function(a){return a})},{"./aes":44,"./cipher-core":45,"./core":46,"./enc-base64":47,"./enc-utf16":48,"./evpkdf":49,"./format-hex":50,"./hmac":51, "./lib-typedarrays":53,"./md5":54,"./mode-cfb":55,"./mode-ctr":57,"./mode-ctr-gladman":56,"./mode-ecb":58,"./mode-ofb":59,"./pad-ansix923":60,"./pad-iso10126":61,"./pad-iso97971":62,"./pad-nopadding":63,"./pad-zeropadding":64,"./pbkdf2":65,"./rabbit":67,"./rabbit-legacy":66,"./rc4":68,"./ripemd160":69,"./sha1":70,"./sha224":71,"./sha256":72,"./sha3":73,"./sha384":74,"./sha512":75,"./tripledes":76,"./x64-core":77}],53:[function(a,b,c){!function(d,e){"object"==typeof c?b.exports=c=e(a("./core")):"function"==typeof define&&define.amd?define(["./core"],e):e(d.CryptoJS)}(this,function(a){return function(){if("function"==typeof ArrayBuffer){var b=a,c=b.lib,d=c.WordArray,e=d.init,f=d.init=function(a){if(a instanceof ArrayBuffer&&(a=new Uint8Array(a)),(a instanceof Int8Array||"undefined"!=typeof Uint8ClampedArray&&a instanceof Uint8ClampedArray||a instanceof Int16Array||a instanceof Uint16Array||a instanceof Int32Array||a instanceof Uint32Array||a instanceof Float32Array||a instanceof Float64Array)&&(a=new Uint8Array(a.buffer,a.byteOffset,a.byteLength)),a instanceof Uint8Array){for(var b=a.byteLength,c=[],d=0;b>d;d++)c[d>>>2]|=a[d]<<24-d%4*8;e.call(this,c,b)}else e.apply(this,arguments)};f.prototype=d}}(),a.lib.WordArray})},{"./core":46}],54:[function(a,b,c){!function(d,e){"object"==typeof c?b.exports=c=e(a("./core")):"function"==typeof define&&define.amd?define(["./core"],e):e(d.CryptoJS)}(this,function(a){return function(b){function c(a,b,c,d,e,f,g){var h=a+(b&c|~b&d)+e+g;return(h<<f|h>>>32-f)+b}function d(a,b,c,d,e,f,g){var h=a+(b&d|c&~d)+e+g;return(h<<f|h>>>32-f)+b}function e(a,b,c,d,e,f,g){var h=a+(b^c^d)+e+g;return(h<<f|h>>>32-f)+b}function f(a,b,c,d,e,f,g){var h=a+(c^(b|~d))+e+g;return(h<<f|h>>>32-f)+b}var g=a,h=g.lib,i=h.WordArray,j=h.Hasher,k=g.algo,l=[];!function(){for(var a=0;64>a;a++)l[a]=4294967296*b.abs(b.sin(a+1))|0}();var m=k.MD5=j.extend({_doReset:function(){this._hash=new i.init([1732584193,4023233417,2562383102,271733878])},_doProcessBlock:function(a,b){for(var g=0;16>g;g++){var h=b+g,i=a[h];a[h]=16711935&(i<<8|i>>>24)|4278255360&(i<<24|i>>>8)}var j=this._hash.words,k=a[b+0],m=a[b+1],n=a[b+2],o=a[b+3],p=a[b+4],q=a[b+5],r=a[b+6],s=a[b+7],t=a[b+8],u=a[b+9],v=a[b+10],w=a[b+11],x=a[b+12],y=a[b+13],z=a[b+14],A=a[b+15],B=j[0],C=j[1],D=j[2],E=j[3];B=c(B,C,D,E,k,7,l[0]),E=c(E,B,C,D,m,12,l[1]),D=c(D,E,B,C,n,17,l[2]),C=c(C,D,E,B,o,22,l[3]),B=c(B,C,D,E,p,7,l[4]),E=c(E,B,C,D,q,12,l[5]),D=c(D,E,B,C,r,17,l[6]),C=c(C,D,E,B,s,22,l[7]),B=c(B,C,D,E,t,7,l[8]),E=c(E,B,C,D,u,12,l[9]),D=c(D,E,B,C,v,17,l[10]),C=c(C,D,E,B,w,22,l[11]),B=c(B,C,D,E,x,7,l[12]),E=c(E,B,C,D,y,12,l[13]),D=c(D,E,B,C,z,17,l[14]),C=c(C,D,E,B,A,22,l[15]),B=d(B,C,D,E,m,5,l[16]),E=d(E,B,C,D,r,9,l[17]),D=d(D,E,B,C,w,14,l[18]),C=d(C,D,E,B,k,20,l[19]),B=d(B,C,D,E,q,5,l[20]),E=d(E,B,C,D,v,9,l[21]),D=d(D,E,B,C,A,14,l[22]),C=d(C,D,E,B,p,20,l[23]),B=d(B,C,D,E,u,5,l[24]),E=d(E,B,C,D,z,9,l[25]),D=d(D,E,B,C,o,14,l[26]),C=d(C,D,E,B,t,20,l[27]),B=d(B,C,D,E,y,5,l[28]),E=d(E,B,C,D,n,9,l[29]),D=d(D,E,B,C,s,14,l[30]),C=d(C,D,E,B,x,20,l[31]),B=e(B,C,D,E,q,4,l[32]),E=e(E,B,C,D,t,11,l[33]),D=e(D,E,B,C,w,16,l[34]),C=e(C,D,E,B,z,23,l[35]),B=e(B,C,D,E,m,4,l[36]),E=e(E,B,C,D,p,11,l[37]),D=e(D,E,B,C,s,16,l[38]),C=e(C,D,E,B,v,23,l[39]),B=e(B,C,D,E,y,4,l[40]),E=e(E,B,C,D,k,11,l[41]),D=e(D,E,B,C,o,16,l[42]),C=e(C,D,E,B,r,23,l[43]),B=e(B,C,D,E,u,4,l[44]),E=e(E,B,C,D,x,11,l[45]),D=e(D,E,B,C,A,16,l[46]),C=e(C,D,E,B,n,23,l[47]),B=f(B,C,D,E,k,6,l[48]),E=f(E,B,C,D,s,10,l[49]),D=f(D,E,B,C,z,15,l[50]),C=f(C,D,E,B,q,21,l[51]),B=f(B,C,D,E,x,6,l[52]),E=f(E,B,C,D,o,10,l[53]),D=f(D,E,B,C,v,15,l[54]),C=f(C,D,E,B,m,21,l[55]),B=f(B,C,D,E,t,6,l[56]),E=f(E,B,C,D,A,10,l[57]),D=f(D,E,B,C,r,15,l[58]),C=f(C,D,E,B,y,21,l[59]),B=f(B,C,D,E,p,6,l[60]),E=f(E,B,C,D,w,10,l[61]),D=f(D,E,B,C,n,15,l[62]),C=f(C,D,E,B,u,21,l[63]),j[0]=j[0]+B|0,j[1]=j[1]+C|0,j[2]=j[2]+D|0,j[3]=j[3]+E|0},_doFinalize:function(){var a=this._data,c=a.words,d=8*this._nDataBytes,e=8*a.sigBytes;c[e>>>5]|=128<<24-e%32;var f=b.floor(d/4294967296),g=d;c[(e+64>>>9<<4)+15]=16711935&(f<<8|f>>>24)|4278255360&(f<<24|f>>>8),c[(e+64>>>9<<4)+14]=16711935&(g<<8|g>>>24)|4278255360&(g<<24|g>>>8),a.sigBytes=4*(c.length+1),this._process();for(var h=this._hash,i=h.words,j=0;4>j;j++){var k=i[j];i[j]=16711935&(k<<8|k>>>24)|4278255360&(k<<24|k>>>8)}return h},clone:function(){var a=j.clone.call(this);return a._hash=this._hash.clone(),a}});g.MD5=j._createHelper(m),g.HmacMD5=j._createHmacHelper(m)}(Math),a.MD5})},{"./core":46}],55:[function(a,b,c){!function(d,e,f){"object"==typeof c?b.exports=c=e(a("./core"),a("./cipher-core")):"function"==typeof define&&define.amd?define(["./core","./cipher-core"],e):e(d.CryptoJS)}(this,function(a){return a.mode.CFB=function(){function b(a,b,c,d){var e=this._iv;if(e){var f=e.slice(0);this._iv=void 0}else var f=this._prevBlock;d.encryptBlock(f,0);for(var g=0;c>g;g++)a[b+g]^=f[g]}var c=a.lib.BlockCipherMode.extend();return c.Encryptor=c.extend({processBlock:function(a,c){var d=this._cipher,e=d.blockSize;b.call(this,a,c,e,d),this._prevBlock=a.slice(c,c+e)}}),c.Decryptor=c.extend({processBlock:function(a,c){var d=this._cipher,e=d.blockSize,f=a.slice(c,c+e);b.call(this,a,c,e,d),this._prevBlock=f}}),c}(),a.mode.CFB})},{"./cipher-core":45,"./core":46}],56:[function(a,b,c){!function(d,e,f){"object"==typeof c?b.exports=c=e(a("./core"),a("./cipher-core")):"function"==typeof define&&define.amd?define(["./core","./cipher-core"],e):e(d.CryptoJS)}(this,function(a){return a.mode.CTRGladman=function(){function b(a){if(255===(a>>24&255)){var b=a>>16&255,c=a>>8&255,d=255&a;255===b?(b=0,255===c?(c=0,255===d?d=0:++d):++c):++b,a=0,a+=b<<16,a+=c<<8,a+=d}else a+=1<<24;return a}function c(a){return 0===(a[0]=b(a[0]))&&(a[1]=b(a[1])),a}var d=a.lib.BlockCipherMode.extend(),e=d.Encryptor=d.extend({processBlock:function(a,b){var d=this._cipher,e=d.blockSize,f=this._iv,g=this._counter;f&&(g=this._counter=f.slice(0),this._iv=void 0),c(g);var h=g.slice(0);d.encryptBlock(h,0);for(var i=0;e>i;i++)a[b+i]^=h[i]}});return d.Decryptor=e,d}(),a.mode.CTRGladman})},{"./cipher-core":45,"./core":46}],57:[function(a,b,c){!function(d,e,f){"object"==typeof c?b.exports=c=e(a("./core"),a("./cipher-core")):"function"==typeof define&&define.amd?define(["./core","./cipher-core"],e):e(d.CryptoJS)}(this,function(a){return a.mode.CTR=function(){var b=a.lib.BlockCipherMode.extend(),c=b.Encryptor=b.extend({processBlock:function(a,b){var c=this._cipher,d=c.blockSize,e=this._iv,f=this._counter;e&&(f=this._counter=e.slice(0),this._iv=void 0);var g=f.slice(0);c.encryptBlock(g,0),f[d-1]=f[d-1]+1|0;for(var h=0;d>h;h++)a[b+h]^=g[h]}});return b.Decryptor=c,b}(),a.mode.CTR})},{"./cipher-core":45,"./core":46}],58:[function(a,b,c){!function(d,e,f){"object"==typeof c?b.exports=c=e(a("./core"),a("./cipher-core")):"function"==typeof define&&define.amd?define(["./core","./cipher-core"],e):e(d.CryptoJS)}(this,function(a){return a.mode.ECB=function(){var b=a.lib.BlockCipherMode.extend();return b.Encryptor=b.extend({processBlock:function(a,b){this._cipher.encryptBlock(a,b)}}),b.Decryptor=b.extend({processBlock:function(a,b){this._cipher.decryptBlock(a,b)}}),b}(),a.mode.ECB})},{"./cipher-core":45,"./core":46}],59:[function(a,b,c){!function(d,e,f){"object"==typeof c?b.exports=c=e(a("./core"),a("./cipher-core")):"function"==typeof define&&define.amd?define(["./core","./cipher-core"],e):e(d.CryptoJS)}(this,function(a){return a.mode.OFB=function(){var b=a.lib.BlockCipherMode.extend(),c=b.Encryptor=b.extend({processBlock:function(a,b){var c=this._cipher,d=c.blockSize,e=this._iv,f=this._keystream;e&&(f=this._keystream=e.slice(0),this._iv=void 0),c.encryptBlock(f,0);for(var g=0;d>g;g++)a[b+g]^=f[g]}});return b.Decryptor=c,b}(),a.mode.OFB})},{"./cipher-core":45,"./core":46}],60:[function(a,b,c){!function(d,e,f){"object"==typeof c?b.exports=c=e(a("./core"),a("./cipher-core")):"function"==typeof define&&define.amd?define(["./core","./cipher-core"],e):e(d.CryptoJS)}(this,function(a){return a.pad.AnsiX923={pad:function(a,b){var c=a.sigBytes,d=4*b,e=d-c%d,f=c+e-1;a.clamp(),a.words[f>>>2]|=e<<24-f%4*8,a.sigBytes+=e},unpad:function(a){var b=255&a.words[a.sigBytes-1>>>2];a.sigBytes-=b}},a.pad.Ansix923})},{"./cipher-core":45,"./core":46}],61:[function(a,b,c){!function(d,e,f){"object"==typeof c?b.exports=c=e(a("./core"),a("./cipher-core")):"function"==typeof define&&define.amd?define(["./core","./cipher-core"],e):e(d.CryptoJS)}(this,function(a){return a.pad.Iso10126={pad:function(b,c){var d=4*c,e=d-b.sigBytes%d;b.concat(a.lib.WordArray.random(e-1)).concat(a.lib.WordArray.create([e<<24],1))},unpad:function(a){var b=255&a.words[a.sigBytes-1>>>2];a.sigBytes-=b}},a.pad.Iso10126})},{"./cipher-core":45,"./core":46}],62:[function(a,b,c){!function(d,e,f){"object"==typeof c?b.exports=c=e(a("./core"),a("./cipher-core")):"function"==typeof define&&define.amd?define(["./core","./cipher-core"],e):e(d.CryptoJS)}(this,function(a){return a.pad.Iso97971={pad:function(b,c){b.concat(a.lib.WordArray.create([2147483648],1)),a.pad.ZeroPadding.pad(b,c)},unpad:function(b){a.pad.ZeroPadding.unpad(b),b.sigBytes--}},a.pad.Iso97971})},{"./cipher-core":45,"./core":46}],63:[function(a,b,c){!function(d,e,f){"object"==typeof c?b.exports=c=e(a("./core"),a("./cipher-core")):"function"==typeof define&&define.amd?define(["./core","./cipher-core"],e):e(d.CryptoJS)}(this,function(a){return a.pad.NoPadding={pad:function(){},unpad:function(){}},a.pad.NoPadding})},{"./cipher-core":45,"./core":46}],64:[function(a,b,c){!function(d,e,f){"object"==typeof c?b.exports=c=e(a("./core"),a("./cipher-core")):"function"==typeof define&&define.amd?define(["./core","./cipher-core"],e):e(d.CryptoJS)}(this,function(a){return a.pad.ZeroPadding={pad:function(a,b){var c=4*b;a.clamp(),a.sigBytes+=c-(a.sigBytes%c||c)},unpad:function(a){for(var b=a.words,c=a.sigBytes-1;!(b[c>>>2]>>>24-c%4*8&255);)c--;a.sigBytes=c+1}},a.pad.ZeroPadding})},{"./cipher-core":45,"./core":46}],65:[function(a,b,c){!function(d,e,f){"object"==typeof c?b.exports=c=e(a("./core"),a("./sha1"),a("./hmac")):"function"==typeof define&&define.amd?define(["./core","./sha1","./hmac"],e):e(d.CryptoJS)}(this,function(a){return function(){var b=a,c=b.lib,d=c.Base,e=c.WordArray,f=b.algo,g=f.SHA1,h=f.HMAC,i=f.PBKDF2=d.extend({cfg:d.extend({keySize:4,hasher:g,iterations:1}),init:function(a){this.cfg=this.cfg.extend(a)},compute:function(a,b){for(var c=this.cfg,d=h.create(c.hasher,a),f=e.create(),g=e.create([1]),i=f.words,j=g.words,k=c.keySize,l=c.iterations;i.length<k;){var m=d.update(b).finalize(g);d.reset();for(var n=m.words,o=n.length,p=m,q=1;l>q;q++){p=d.finalize(p),d.reset();for(var r=p.words,s=0;o>s;s++)n[s]^=r[s]}f.concat(m),j[0]++}return f.sigBytes=4*k,f}});b.PBKDF2=function(a,b,c){return i.create(c).compute(a,b)}}(),a.PBKDF2})},{"./core":46,"./hmac":51,"./sha1":70}],66:[function(a,b,c){!function(d,e,f){"object"==typeof c?b.exports=c=e(a("./core"),a("./enc-base64"),a("./md5"),a("./evpkdf"),a("./cipher-core")):"function"==typeof define&&define.amd?define(["./core","./enc-base64","./md5","./evpkdf","./cipher-core"],e):e(d.CryptoJS)}(this,function(a){return function(){function b(){for(var a=this._X,b=this._C,c=0;8>c;c++)h[c]=b[c];b[0]=b[0]+1295307597+this._b|0,b[1]=b[1]+3545052371+(b[0]>>>0<h[0]>>>0?1:0)|0,b[2]=b[2]+886263092+(b[1]>>>0<h[1]>>>0?1:0)|0,b[3]=b[3]+1295307597+(b[2]>>>0<h[2]>>>0?1:0)|0,b[4]=b[4]+3545052371+(b[3]>>>0<h[3]>>>0?1:0)|0,b[5]=b[5]+886263092+(b[4]>>>0<h[4]>>>0?1:0)|0,b[6]=b[6]+1295307597+(b[5]>>>0<h[5]>>>0?1:0)|0,b[7]=b[7]+3545052371+(b[6]>>>0<h[6]>>>0?1:0)|0,this._b=b[7]>>>0<h[7]>>>0?1:0;for(var c=0;8>c;c++){var d=a[c]+b[c],e=65535&d,f=d>>>16,g=((e*e>>>17)+e*f>>>15)+f*f,j=((4294901760&d)*d|0)+((65535&d)*d|0);i[c]=g^j}a[0]=i[0]+(i[7]<<16|i[7]>>>16)+(i[6]<<16|i[6]>>>16)|0,a[1]=i[1]+(i[0]<<8|i[0]>>>24)+i[7]|0,a[2]=i[2]+(i[1]<<16|i[1]>>>16)+(i[0]<<16|i[0]>>>16)|0,a[3]=i[3]+(i[2]<<8|i[2]>>>24)+i[1]|0,a[4]=i[4]+(i[3]<<16|i[3]>>>16)+(i[2]<<16|i[2]>>>16)|0,a[5]=i[5]+(i[4]<<8|i[4]>>>24)+i[3]|0,a[6]=i[6]+(i[5]<<16|i[5]>>>16)+(i[4]<<16|i[4]>>>16)|0,a[7]=i[7]+(i[6]<<8|i[6]>>>24)+i[5]|0}var c=a,d=c.lib,e=d.StreamCipher,f=c.algo,g=[],h=[],i=[],j=f.RabbitLegacy=e.extend({_doReset:function(){var a=this._key.words,c=this.cfg.iv,d=this._X=[a[0],a[3]<<16|a[2]>>>16,a[1],a[0]<<16|a[3]>>>16,a[2],a[1]<<16|a[0]>>>16,a[3],a[2]<<16|a[1]>>>16],e=this._C=[a[2]<<16|a[2]>>>16,4294901760&a[0]|65535&a[1],a[3]<<16|a[3]>>>16,4294901760&a[1]|65535&a[2],a[0]<<16|a[0]>>>16,4294901760&a[2]|65535&a[3],a[1]<<16|a[1]>>>16,4294901760&a[3]|65535&a[0]];this._b=0;for(var f=0;4>f;f++)b.call(this);for(var f=0;8>f;f++)e[f]^=d[f+4&7];if(c){var g=c.words,h=g[0],i=g[1],j=16711935&(h<<8|h>>>24)|4278255360&(h<<24|h>>>8),k=16711935&(i<<8|i>>>24)|4278255360&(i<<24|i>>>8),l=j>>>16|4294901760&k,m=k<<16|65535&j;e[0]^=j,e[1]^=l,e[2]^=k,e[3]^=m,e[4]^=j,e[5]^=l,e[6]^=k,e[7]^=m;for(var f=0;4>f;f++)b.call(this)}},_doProcessBlock:function(a,c){var d=this._X;b.call(this),g[0]=d[0]^d[5]>>>16^d[3]<<16,g[1]=d[2]^d[7]>>>16^d[5]<<16,g[2]=d[4]^d[1]>>>16^d[7]<<16,g[3]=d[6]^d[3]>>>16^d[1]<<16;for(var e=0;4>e;e++)g[e]=16711935&(g[e]<<8|g[e]>>>24)|4278255360&(g[e]<<24|g[e]>>>8),a[c+e]^=g[e]},blockSize:4,ivSize:2});c.RabbitLegacy=e._createHelper(j)}(),a.RabbitLegacy})},{"./cipher-core":45,"./core":46,"./enc-base64":47,"./evpkdf":49,"./md5":54}],67:[function(a,b,c){!function(d,e,f){"object"==typeof c?b.exports=c=e(a("./core"),a("./enc-base64"),a("./md5"),a("./evpkdf"),a("./cipher-core")):"function"==typeof define&&define.amd?define(["./core","./enc-base64","./md5","./evpkdf","./cipher-core"],e):e(d.CryptoJS)}(this,function(a){return function(){function b(){for(var a=this._X,b=this._C,c=0;8>c;c++)h[c]=b[c];b[0]=b[0]+1295307597+this._b|0,b[1]=b[1]+3545052371+(b[0]>>>0<h[0]>>>0?1:0)|0,b[2]=b[2]+886263092+(b[1]>>>0<h[1]>>>0?1:0)|0,b[3]=b[3]+1295307597+(b[2]>>>0<h[2]>>>0?1:0)|0,b[4]=b[4]+3545052371+(b[3]>>>0<h[3]>>>0?1:0)|0,b[5]=b[5]+886263092+(b[4]>>>0<h[4]>>>0?1:0)|0,b[6]=b[6]+1295307597+(b[5]>>>0<h[5]>>>0?1:0)|0,b[7]=b[7]+3545052371+(b[6]>>>0<h[6]>>>0?1:0)|0,this._b=b[7]>>>0<h[7]>>>0?1:0;for(var c=0;8>c;c++){var d=a[c]+b[c],e=65535&d,f=d>>>16,g=((e*e>>>17)+e*f>>>15)+f*f,j=((4294901760&d)*d|0)+((65535&d)*d|0);i[c]=g^j}a[0]=i[0]+(i[7]<<16|i[7]>>>16)+(i[6]<<16|i[6]>>>16)|0,a[1]=i[1]+(i[0]<<8|i[0]>>>24)+i[7]|0,a[2]=i[2]+(i[1]<<16|i[1]>>>16)+(i[0]<<16|i[0]>>>16)|0,a[3]=i[3]+(i[2]<<8|i[2]>>>24)+i[1]|0,a[4]=i[4]+(i[3]<<16|i[3]>>>16)+(i[2]<<16|i[2]>>>16)|0,a[5]=i[5]+(i[4]<<8|i[4]>>>24)+i[3]|0,a[6]=i[6]+(i[5]<<16|i[5]>>>16)+(i[4]<<16|i[4]>>>16)|0,a[7]=i[7]+(i[6]<<8|i[6]>>>24)+i[5]|0}var c=a,d=c.lib,e=d.StreamCipher,f=c.algo,g=[],h=[],i=[],j=f.Rabbit=e.extend({_doReset:function(){for(var a=this._key.words,c=this.cfg.iv,d=0;4>d;d++)a[d]=16711935&(a[d]<<8|a[d]>>>24)|4278255360&(a[d]<<24|a[d]>>>8);var e=this._X=[a[0],a[3]<<16|a[2]>>>16,a[1],a[0]<<16|a[3]>>>16,a[2],a[1]<<16|a[0]>>>16,a[3],a[2]<<16|a[1]>>>16],f=this._C=[a[2]<<16|a[2]>>>16,4294901760&a[0]|65535&a[1],a[3]<<16|a[3]>>>16,4294901760&a[1]|65535&a[2],a[0]<<16|a[0]>>>16,4294901760&a[2]|65535&a[3],a[1]<<16|a[1]>>>16,4294901760&a[3]|65535&a[0]];this._b=0;for(var d=0;4>d;d++)b.call(this);for(var d=0;8>d;d++)f[d]^=e[d+4&7];if(c){var g=c.words,h=g[0],i=g[1],j=16711935&(h<<8|h>>>24)|4278255360&(h<<24|h>>>8),k=16711935&(i<<8|i>>>24)|4278255360&(i<<24|i>>>8),l=j>>>16|4294901760&k,m=k<<16|65535&j;f[0]^=j,f[1]^=l,f[2]^=k,f[3]^=m,f[4]^=j,f[5]^=l,f[6]^=k,f[7]^=m;for(var d=0;4>d;d++)b.call(this)}},_doProcessBlock:function(a,c){var d=this._X;b.call(this),g[0]=d[0]^d[5]>>>16^d[3]<<16,g[1]=d[2]^d[7]>>>16^d[5]<<16,g[2]=d[4]^d[1]>>>16^d[7]<<16,g[3]=d[6]^d[3]>>>16^d[1]<<16;for(var e=0;4>e;e++)g[e]=16711935&(g[e]<<8|g[e]>>>24)|4278255360&(g[e]<<24|g[e]>>>8),a[c+e]^=g[e]},blockSize:4,ivSize:2});c.Rabbit=e._createHelper(j)}(),a.Rabbit})},{"./cipher-core":45,"./core":46,"./enc-base64":47,"./evpkdf":49,"./md5":54}],68:[function(a,b,c){!function(d,e,f){"object"==typeof c?b.exports=c=e(a("./core"),a("./enc-base64"),a("./md5"),a("./evpkdf"),a("./cipher-core")):"function"==typeof define&&define.amd?define(["./core","./enc-base64","./md5","./evpkdf","./cipher-core"],e):e(d.CryptoJS)}(this,function(a){return function(){function b(){for(var a=this._S,b=this._i,c=this._j,d=0,e=0;4>e;e++){b=(b+1)%256,c=(c+a[b])%256;var f=a[b];a[b]=a[c],a[c]=f,d|=a[(a[b]+a[c])%256]<<24-8*e}return this._i=b,this._j=c,d}var c=a,d=c.lib,e=d.StreamCipher,f=c.algo,g=f.RC4=e.extend({_doReset:function(){for(var a=this._key,b=a.words,c=a.sigBytes,d=this._S=[],e=0;256>e;e++)d[e]=e;for(var e=0,f=0;256>e;e++){var g=e%c,h=b[g>>>2]>>>24-g%4*8&255;f=(f+d[e]+h)%256;var i=d[e];d[e]=d[f],d[f]=i}this._i=this._j=0},_doProcessBlock:function(a,c){a[c]^=b.call(this)},keySize:8,ivSize:0});c.RC4=e._createHelper(g);var h=f.RC4Drop=g.extend({cfg:g.cfg.extend({drop:192}),_doReset:function(){g._doReset.call(this);for(var a=this.cfg.drop;a>0;a--)b.call(this)}});c.RC4Drop=e._createHelper(h)}(),a.RC4})},{"./cipher-core":45,"./core":46,"./enc-base64":47,"./evpkdf":49,"./md5":54}],69:[function(a,b,c){!function(d,e){"object"==typeof c?b.exports=c=e(a("./core")):"function"==typeof define&&define.amd?define(["./core"],e):e(d.CryptoJS)}(this,function(a){return function(b){function c(a,b,c){return a^b^c}function d(a,b,c){return a&b|~a&c}function e(a,b,c){return(a|~b)^c}function f(a,b,c){return a&c|b&~c}function g(a,b,c){return a^(b|~c)}function h(a,b){return a<<b|a>>>32-b}var i=a,j=i.lib,k=j.WordArray,l=j.Hasher,m=i.algo,n=k.create([0,1,2,3,4,5,6,7,8,9,10,11,12,13,14,15,7,4,13,1,10,6,15,3,12,0,9,5,2,14,11,8,3,10,14,4,9,15,8,1,2,7,0,6,13,11,5,12,1,9,11,10,0,8,12,4,13,3,7,15,14,5,6,2,4,0,5,9,7,12,2,10,14,1,3,8,11,6,15,13]),o=k.create([5,14,7,0,9,2,11,4,13,6,15,8,1,10,3,12,6,11,3,7,0,13,5,10,14,15,8,12,4,9,1,2,15,5,1,3,7,14,6,9,11,8,12,2,10,0,4,13,8,6,4,1,3,11,15,0,5,12,2,13,9,7,10,14,12,15,10,4,1,5,8,7,6,2,13,14,0,3,9,11]),p=k.create([11,14,15,12,5,8,7,9,11,13,14,15,6,7,9,8,7,6,8,13,11,9,7,15,7,12,15,9,11,7,13,12,11,13,6,7,14,9,13,15,14,8,13,6,5,12,7,5,11,12,14,15,14,15,9,8,9,14,5,6,8,6,5,12,9,15,5,11,6,8,13,12,5,12,13,14,11,8,5,6]),q=k.create([8,9,9,11,13,15,15,5,7,7,8,11,14,14,12,6,9,13,15,7,12,8,9,11,7,7,12,7,6,15,13,11,9,7,15,11,8,6,6,14,12,13,5,14,13,13,7,5,15,5,8,11,14,14,6,14,6,9,12,9,12,5,15,8,8,5,12,9,12,5,14,6,8,13,6,5,15,13,11,11]),r=k.create([0,1518500249,1859775393,2400959708,2840853838]),s=k.create([1352829926,1548603684,1836072691,2053994217,0]),t=m.RIPEMD160=l.extend({_doReset:function(){this._hash=k.create([1732584193,4023233417,2562383102,271733878,3285377520])},_doProcessBlock:function(a,b){for(var i=0;16>i;i++){var j=b+i,k=a[j];a[j]=16711935&(k<<8|k>>>24)|4278255360&(k<<24|k>>>8)}var l,m,t,u,v,w,x,y,z,A,B=this._hash.words,C=r.words,D=s.words,E=n.words,F=o.words,G=p.words,H=q.words;w=l=B[0],x=m=B[1],y=t=B[2],z=u=B[3],A=v=B[4];for(var I,i=0;80>i;i+=1)I=l+a[b+E[i]]|0,I+=16>i?c(m,t,u)+C[0]:32>i?d(m,t,u)+C[1]:48>i?e(m,t,u)+C[2]:64>i?f(m,t,u)+C[3]:g(m,t,u)+C[4],I=0|I,I=h(I,G[i]),I=I+v|0,l=v,v=u,u=h(t,10),t=m,m=I,I=w+a[b+F[i]]|0,I+=16>i?g(x,y,z)+D[0]:32>i?f(x,y,z)+D[1]:48>i?e(x,y,z)+D[2]:64>i?d(x,y,z)+D[3]:c(x,y,z)+D[4],I=0|I,I=h(I,H[i]),I=I+A|0,w=A,A=z,z=h(y,10),y=x,x=I;I=B[1]+t+z|0,B[1]=B[2]+u+A|0,B[2]=B[3]+v+w|0,B[3]=B[4]+l+x|0,B[4]=B[0]+m+y|0,B[0]=I},_doFinalize:function(){var a=this._data,b=a.words,c=8*this._nDataBytes,d=8*a.sigBytes;b[d>>>5]|=128<<24-d%32,b[(d+64>>>9<<4)+14]=16711935&(c<<8|c>>>24)|4278255360&(c<<24|c>>>8),a.sigBytes=4*(b.length+1),this._process();for(var e=this._hash,f=e.words,g=0;5>g;g++){var h=f[g];f[g]=16711935&(h<<8|h>>>24)|4278255360&(h<<24|h>>>8)}return e},clone:function(){var a=l.clone.call(this);return a._hash=this._hash.clone(),a}});i.RIPEMD160=l._createHelper(t),i.HmacRIPEMD160=l._createHmacHelper(t)}(Math),a.RIPEMD160})},{"./core":46}],70:[function(a,b,c){!function(d,e){"object"==typeof c?b.exports=c=e(a("./core")):"function"==typeof define&&define.amd?define(["./core"],e):e(d.CryptoJS)}(this,function(a){return function(){var b=a,c=b.lib,d=c.WordArray,e=c.Hasher,f=b.algo,g=[],h=f.SHA1=e.extend({_doReset:function(){this._hash=new d.init([1732584193,4023233417,2562383102,271733878,3285377520])},_doProcessBlock:function(a,b){for(var c=this._hash.words,d=c[0],e=c[1],f=c[2],h=c[3],i=c[4],j=0;80>j;j++){if(16>j)g[j]=0|a[b+j];else{var k=g[j-3]^g[j-8]^g[j-14]^g[j-16];g[j]=k<<1|k>>>31}var l=(d<<5|d>>>27)+i+g[j];l+=20>j?(e&f|~e&h)+1518500249:40>j?(e^f^h)+1859775393:60>j?(e&f|e&h|f&h)-1894007588:(e^f^h)-899497514,i=h,h=f,f=e<<30|e>>>2,e=d,d=l}c[0]=c[0]+d|0,c[1]=c[1]+e|0,c[2]=c[2]+f|0,c[3]=c[3]+h|0,c[4]=c[4]+i|0},_doFinalize:function(){var a=this._data,b=a.words,c=8*this._nDataBytes,d=8*a.sigBytes;return b[d>>>5]|=128<<24-d%32,b[(d+64>>>9<<4)+14]=Math.floor(c/4294967296),b[(d+64>>>9<<4)+15]=c,a.sigBytes=4*b.length,this._process(),this._hash},clone:function(){var a=e.clone.call(this);return a._hash=this._hash.clone(),a}});b.SHA1=e._createHelper(h),b.HmacSHA1=e._createHmacHelper(h)}(),a.SHA1})},{"./core":46}],71:[function(a,b,c){!function(d,e,f){"object"==typeof c?b.exports=c=e(a("./core"),a("./sha256")):"function"==typeof define&&define.amd?define(["./core","./sha256"],e):e(d.CryptoJS)}(this,function(a){return function(){var b=a,c=b.lib,d=c.WordArray,e=b.algo,f=e.SHA256,g=e.SHA224=f.extend({_doReset:function(){this._hash=new d.init([3238371032,914150663,812702999,4144912697,4290775857,1750603025,1694076839,3204075428])},_doFinalize:function(){var a=f._doFinalize.call(this);return a.sigBytes-=4,a}});b.SHA224=f._createHelper(g),b.HmacSHA224=f._createHmacHelper(g)}(),a.SHA224})},{"./core":46,"./sha256":72}],72:[function(a,b,c){!function(d,e){"object"==typeof c?b.exports=c=e(a("./core")):"function"==typeof define&&define.amd?define(["./core"],e):e(d.CryptoJS)}(this,function(a){return function(b){var c=a,d=c.lib,e=d.WordArray,f=d.Hasher,g=c.algo,h=[],i=[];!function(){function a(a){for(var c=b.sqrt(a),d=2;c>=d;d++)if(!(a%d))return!1;return!0}function c(a){return 4294967296*(a-(0|a))|0}for(var d=2,e=0;64>e;)a(d)&&(8>e&&(h[e]=c(b.pow(d,.5))),i[e]=c(b.pow(d,1/3)),e++),d++}();var j=[],k=g.SHA256=f.extend({_doReset:function(){this._hash=new e.init(h.slice(0))},_doProcessBlock:function(a,b){for(var c=this._hash.words,d=c[0],e=c[1],f=c[2],g=c[3],h=c[4],k=c[5],l=c[6],m=c[7],n=0;64>n;n++){if(16>n)j[n]=0|a[b+n];else{var o=j[n-15],p=(o<<25|o>>>7)^(o<<14|o>>>18)^o>>>3,q=j[n-2],r=(q<<15|q>>>17)^(q<<13|q>>>19)^q>>>10;j[n]=p+j[n-7]+r+j[n-16]}var s=h&k^~h&l,t=d&e^d&f^e&f,u=(d<<30|d>>>2)^(d<<19|d>>>13)^(d<<10|d>>>22),v=(h<<26|h>>>6)^(h<<21|h>>>11)^(h<<7|h>>>25),w=m+v+s+i[n]+j[n],x=u+t;m=l,l=k,k=h,h=g+w|0,g=f,f=e,e=d,d=w+x|0}c[0]=c[0]+d|0,c[1]=c[1]+e|0,c[2]=c[2]+f|0,c[3]=c[3]+g|0,c[4]=c[4]+h|0,c[5]=c[5]+k|0,c[6]=c[6]+l|0,c[7]=c[7]+m|0},_doFinalize:function(){var a=this._data,c=a.words,d=8*this._nDataBytes,e=8*a.sigBytes;return c[e>>>5]|=128<<24-e%32,c[(e+64>>>9<<4)+14]=b.floor(d/4294967296),c[(e+64>>>9<<4)+15]=d,a.sigBytes=4*c.length,this._process(),this._hash},clone:function(){var a=f.clone.call(this);return a._hash=this._hash.clone(),a}});c.SHA256=f._createHelper(k),c.HmacSHA256=f._createHmacHelper(k)}(Math),a.SHA256})},{"./core":46}],73:[function(a,b,c){!function(d,e,f){"object"==typeof c?b.exports=c=e(a("./core"),a("./x64-core")):"function"==typeof define&&define.amd?define(["./core","./x64-core"],e):e(d.CryptoJS)}(this,function(a){return function(b){var c=a,d=c.lib,e=d.WordArray,f=d.Hasher,g=c.x64,h=g.Word,i=c.algo,j=[],k=[],l=[];!function(){for(var a=1,b=0,c=0;24>c;c++){j[a+5*b]=(c+1)*(c+2)/2%64;var d=b%5,e=(2*a+3*b)%5;a=d,b=e}for(var a=0;5>a;a++)for(var b=0;5>b;b++)k[a+5*b]=b+(2*a+3*b)%5*5;for(var f=1,g=0;24>g;g++){for(var i=0,m=0,n=0;7>n;n++){if(1&f){var o=(1<<n)-1;32>o?m^=1<<o:i^=1<<o-32}128&f?f=f<<1^113:f<<=1}l[g]=h.create(i,m)}}();var m=[];!function(){for(var a=0;25>a;a++)m[a]=h.create()}();var n=i.SHA3=f.extend({cfg:f.cfg.extend({outputLength:512}),_doReset:function(){for(var a=this._state=[],b=0;25>b;b++)a[b]=new h.init;this.blockSize=(1600-2*this.cfg.outputLength)/32},_doProcessBlock:function(a,b){for(var c=this._state,d=this.blockSize/2,e=0;d>e;e++){var f=a[b+2*e],g=a[b+2*e+1];f=16711935&(f<<8|f>>>24)|4278255360&(f<<24|f>>>8),g=16711935&(g<<8|g>>>24)|4278255360&(g<<24|g>>>8);var h=c[e];h.high^=g,h.low^=f}for(var i=0;24>i;i++){for(var n=0;5>n;n++){for(var o=0,p=0,q=0;5>q;q++){var h=c[n+5*q];o^=h.high,p^=h.low}var r=m[n];r.high=o,r.low=p}for(var n=0;5>n;n++)for(var s=m[(n+4)%5],t=m[(n+1)%5],u=t.high,v=t.low,o=s.high^(u<<1|v>>>31),p=s.low^(v<<1|u>>>31),q=0;5>q;q++){var h=c[n+5*q];h.high^=o,h.low^=p}for(var w=1;25>w;w++){var h=c[w],x=h.high,y=h.low,z=j[w];if(32>z)var o=x<<z|y>>>32-z,p=y<<z|x>>>32-z;else var o=y<<z-32|x>>>64-z,p=x<<z-32|y>>>64-z;var A=m[k[w]];A.high=o,A.low=p}var B=m[0],C=c[0];B.high=C.high,B.low=C.low;for(var n=0;5>n;n++)for(var q=0;5>q;q++){var w=n+5*q,h=c[w],D=m[w],E=m[(n+1)%5+5*q],F=m[(n+2)%5+5*q];h.high=D.high^~E.high&F.high,h.low=D.low^~E.low&F.low}var h=c[0],G=l[i];h.high^=G.high,h.low^=G.low}},_doFinalize:function(){var a=this._data,c=a.words,d=(8*this._nDataBytes,8*a.sigBytes),f=32*this.blockSize;c[d>>>5]|=1<<24-d%32,c[(b.ceil((d+1)/f)*f>>>5)-1]|=128,a.sigBytes=4*c.length,this._process();for(var g=this._state,h=this.cfg.outputLength/8,i=h/8,j=[],k=0;i>k;k++){var l=g[k],m=l.high,n=l.low;m=16711935&(m<<8|m>>>24)|4278255360&(m<<24|m>>>8),n=16711935&(n<<8|n>>>24)|4278255360&(n<<24|n>>>8),j.push(n),j.push(m)}return new e.init(j,h)},clone:function(){for(var a=f.clone.call(this),b=a._state=this._state.slice(0),c=0;25>c;c++)b[c]=b[c].clone();return a}});c.SHA3=f._createHelper(n),c.HmacSHA3=f._createHmacHelper(n)}(Math),a.SHA3})},{"./core":46,"./x64-core":77}],74:[function(a,b,c){!function(d,e,f){"object"==typeof c?b.exports=c=e(a("./core"),a("./x64-core"),a("./sha512")):"function"==typeof define&&define.amd?define(["./core","./x64-core","./sha512"],e):e(d.CryptoJS)}(this,function(a){return function(){var b=a,c=b.x64,d=c.Word,e=c.WordArray,f=b.algo,g=f.SHA512,h=f.SHA384=g.extend({_doReset:function(){this._hash=new e.init([new d.init(3418070365,3238371032),new d.init(1654270250,914150663),new d.init(2438529370,812702999),new d.init(355462360,4144912697),new d.init(1731405415,4290775857),new d.init(2394180231,1750603025),new d.init(3675008525,1694076839),new d.init(1203062813,3204075428)])},_doFinalize:function(){var a=g._doFinalize.call(this);return a.sigBytes-=16,a}});b.SHA384=g._createHelper(h),b.HmacSHA384=g._createHmacHelper(h)}(),a.SHA384})},{"./core":46,"./sha512":75,"./x64-core":77}],75:[function(a,b,c){!function(d,e,f){"object"==typeof c?b.exports=c=e(a("./core"),a("./x64-core")):"function"==typeof define&&define.amd?define(["./core","./x64-core"],e):e(d.CryptoJS)}(this,function(a){return function(){function b(){return g.create.apply(g,arguments)}var c=a,d=c.lib,e=d.Hasher,f=c.x64,g=f.Word,h=f.WordArray,i=c.algo,j=[b(1116352408,3609767458),b(1899447441,602891725),b(3049323471,3964484399),b(3921009573,2173295548),b(961987163,4081628472),b(1508970993,3053834265),b(2453635748,2937671579),b(2870763221,3664609560),b(3624381080,2734883394),b(310598401,1164996542),b(607225278,1323610764),b(1426881987,3590304994),b(1925078388,4068182383),b(2162078206,991336113),b(2614888103,633803317),b(3248222580,3479774868),b(3835390401,2666613458),b(4022224774,944711139),b(264347078,2341262773),b(604807628,2007800933),b(770255983,1495990901),b(1249150122,1856431235),b(1555081692,3175218132),b(1996064986,2198950837),b(2554220882,3999719339),b(2821834349,766784016),b(2952996808,2566594879),b(3210313671,3203337956),b(3336571891,1034457026),b(3584528711,2466948901),b(113926993,3758326383),b(338241895,168717936),b(666307205,1188179964),b(773529912,1546045734),b(1294757372,1522805485),b(1396182291,2643833823),b(1695183700,2343527390),b(1986661051,1014477480),b(2177026350,1206759142),b(2456956037,344077627),b(2730485921,1290863460),b(2820302411,3158454273),b(3259730800,3505952657),b(3345764771,106217008),b(3516065817,3606008344),b(3600352804,1432725776),b(4094571909,1467031594),b(275423344,851169720),b(430227734,3100823752),b(506948616,1363258195),b(659060556,3750685593),b(883997877,3785050280),b(958139571,3318307427),b(1322822218,3812723403),b(1537002063,2003034995),b(1747873779,3602036899),b(1955562222,1575990012),b(2024104815,1125592928),b(2227730452,2716904306),b(2361852424,442776044),b(2428436474,593698344),b(2756734187,3733110249),b(3204031479,2999351573),b(3329325298,3815920427),b(3391569614,3928383900),b(3515267271,566280711),b(3940187606,3454069534),b(4118630271,4000239992),b(116418474,1914138554),b(174292421,2731055270),b(289380356,3203993006),b(460393269,320620315),b(685471733,587496836),b(852142971,1086792851),b(1017036298,365543100),b(1126000580,2618297676),b(1288033470,3409855158),b(1501505948,4234509866),b(1607167915,987167468),b(1816402316,1246189591)],k=[];!function(){for(var a=0;80>a;a++)k[a]=b()}();var l=i.SHA512=e.extend({_doReset:function(){this._hash=new h.init([new g.init(1779033703,4089235720),new g.init(3144134277,2227873595),new g.init(1013904242,4271175723),new g.init(2773480762,1595750129),new g.init(1359893119,2917565137),new g.init(2600822924,725511199),new g.init(528734635,4215389547),new g.init(1541459225,327033209)])},_doProcessBlock:function(a,b){for(var c=this._hash.words,d=c[0],e=c[1],f=c[2],g=c[3],h=c[4],i=c[5],l=c[6],m=c[7],n=d.high,o=d.low,p=e.high,q=e.low,r=f.high,s=f.low,t=g.high,u=g.low,v=h.high,w=h.low,x=i.high,y=i.low,z=l.high,A=l.low,B=m.high,C=m.low,D=n,E=o,F=p,G=q,H=r,I=s,J=t,K=u,L=v,M=w,N=x,O=y,P=z,Q=A,R=B,S=C,T=0;80>T;T++){var U=k[T];if(16>T)var V=U.high=0|a[b+2*T],W=U.low=0|a[b+2*T+1];else{var X=k[T-15],Y=X.high,Z=X.low,$=(Y>>>1|Z<<31)^(Y>>>8|Z<<24)^Y>>>7,_=(Z>>>1|Y<<31)^(Z>>>8|Y<<24)^(Z>>>7|Y<<25),aa=k[T-2],ba=aa.high,ca=aa.low,da=(ba>>>19|ca<<13)^(ba<<3|ca>>>29)^ba>>>6,ea=(ca>>>19|ba<<13)^(ca<<3|ba>>>29)^(ca>>>6|ba<<26),fa=k[T-7],ga=fa.high,ha=fa.low,ia=k[T-16],ja=ia.high,ka=ia.low,W=_+ha,V=$+ga+(_>>>0>W>>>0?1:0),W=W+ea,V=V+da+(ea>>>0>W>>>0?1:0),W=W+ka,V=V+ja+(ka>>>0>W>>>0?1:0);U.high=V,U.low=W}var la=L&N^~L&P,ma=M&O^~M&Q,na=D&F^D&H^F&H,oa=E&G^E&I^G&I,pa=(D>>>28|E<<4)^(D<<30|E>>>2)^(D<<25|E>>>7),qa=(E>>>28|D<<4)^(E<<30|D>>>2)^(E<<25|D>>>7),ra=(L>>>14|M<<18)^(L>>>18|M<<14)^(L<<23|M>>>9),sa=(M>>>14|L<<18)^(M>>>18|L<<14)^(M<<23|L>>>9),ta=j[T],ua=ta.high,va=ta.low,wa=S+sa,xa=R+ra+(S>>>0>wa>>>0?1:0),wa=wa+ma,xa=xa+la+(ma>>>0>wa>>>0?1:0),wa=wa+va,xa=xa+ua+(va>>>0>wa>>>0?1:0),wa=wa+W,xa=xa+V+(W>>>0>wa>>>0?1:0),ya=qa+oa,za=pa+na+(qa>>>0>ya>>>0?1:0);R=P,S=Q,P=N,Q=O,N=L,O=M,M=K+wa|0,L=J+xa+(K>>>0>M>>>0?1:0)|0,J=H,K=I,H=F,I=G,F=D,G=E,E=wa+ya|0,D=xa+za+(wa>>>0>E>>>0?1:0)|0}o=d.low=o+E,d.high=n+D+(E>>>0>o>>>0?1:0),q=e.low=q+G,e.high=p+F+(G>>>0>q>>>0?1:0),s=f.low=s+I,f.high=r+H+(I>>>0>s>>>0?1:0),u=g.low=u+K,g.high=t+J+(K>>>0>u>>>0?1:0),w=h.low=w+M,h.high=v+L+(M>>>0>w>>>0?1:0),y=i.low=y+O,i.high=x+N+(O>>>0>y>>>0?1:0),A=l.low=A+Q,l.high=z+P+(Q>>>0>A>>>0?1:0),C=m.low=C+S,m.high=B+R+(S>>>0>C>>>0?1:0)},_doFinalize:function(){var a=this._data,b=a.words,c=8*this._nDataBytes,d=8*a.sigBytes;b[d>>>5]|=128<<24-d%32,b[(d+128>>>10<<5)+30]=Math.floor(c/4294967296),b[(d+128>>>10<<5)+31]=c,a.sigBytes=4*b.length,this._process();var e=this._hash.toX32();return e},clone:function(){var a=e.clone.call(this);return a._hash=this._hash.clone(),a},blockSize:32});c.SHA512=e._createHelper(l),c.HmacSHA512=e._createHmacHelper(l)}(),a.SHA512})},{"./core":46,"./x64-core":77}],76:[function(a,b,c){!function(d,e,f){"object"==typeof c?b.exports=c=e(a("./core"),a("./enc-base64"),a("./md5"),a("./evpkdf"),a("./cipher-core")):"function"==typeof define&&define.amd?define(["./core","./enc-base64","./md5","./evpkdf","./cipher-core"],e):e(d.CryptoJS)}(this,function(a){return function(){function b(a,b){var c=(this._lBlock>>>a^this._rBlock)&b;this._rBlock^=c,this._lBlock^=c<<a}function c(a,b){var c=(this._rBlock>>>a^this._lBlock)&b;this._lBlock^=c,this._rBlock^=c<<a}var d=a,e=d.lib,f=e.WordArray,g=e.BlockCipher,h=d.algo,i=[57,49,41,33,25,17,9,1,58,50,42,34,26,18,10,2,59,51,43,35,27,19,11,3,60,52,44,36,63,55,47,39,31,23,15,7,62,54,46,38,30,22,14,6,61,53,45,37,29,21,13,5,28,20,12,4],j=[14,17,11,24,1,5,3,28,15,6,21,10,23,19,12,4,26,8,16,7,27,20,13,2,41,52,31,37,47,55,30,40,51,45,33,48,44,49,39,56,34,53,46,42,50,36,29,32],k=[1,2,4,6,8,10,12,14,15,17,19,21,23,25,27,28],l=[{ 0:8421888,268435456:32768,536870912:8421378,805306368:2,1073741824:512,1342177280:8421890,1610612736:8389122,1879048192:8388608,2147483648:514,2415919104:8389120,2684354560:33280,2952790016:8421376,3221225472:32770,3489660928:8388610,3758096384:0,4026531840:33282,134217728:0,402653184:8421890,671088640:33282,939524096:32768,1207959552:8421888,1476395008:512,1744830464:8421378,2013265920:2,2281701376:8389120,2550136832:33280,2818572288:8421376,3087007744:8389122,3355443200:8388610,3623878656:32770,3892314112:514,4160749568:8388608,1:32768,268435457:2,536870913:8421888,805306369:8388608,1073741825:8421378,1342177281:33280,1610612737:512,1879048193:8389122,2147483649:8421890,2415919105:8421376,2684354561:8388610,2952790017:33282,3221225473:514,3489660929:8389120,3758096385:32770,4026531841:0,134217729:8421890,402653185:8421376,671088641:8388608,939524097:512,1207959553:32768,1476395009:8388610,1744830465:2,2013265921:33282,2281701377:32770,2550136833:8389122,2818572289:514,3087007745:8421888,3355443201:8389120,3623878657:0,3892314113:33280,4160749569:8421378},{0:1074282512,16777216:16384,33554432:524288,50331648:1074266128,67108864:1073741840,83886080:1074282496,100663296:1073758208,117440512:16,134217728:540672,150994944:1073758224,167772160:1073741824,184549376:540688,201326592:524304,218103808:0,234881024:16400,251658240:1074266112,8388608:1073758208,25165824:540688,41943040:16,58720256:1073758224,75497472:1074282512,92274688:1073741824,109051904:524288,125829120:1074266128,142606336:524304,159383552:0,176160768:16384,192937984:1074266112,209715200:1073741840,226492416:540672,243269632:1074282496,260046848:16400,268435456:0,285212672:1074266128,301989888:1073758224,318767104:1074282496,335544320:1074266112,352321536:16,369098752:540688,385875968:16384,402653184:16400,419430400:524288,436207616:524304,452984832:1073741840,469762048:540672,486539264:1073758208,503316480:1073741824,520093696:1074282512,276824064:540688,293601280:524288,310378496:1074266112,327155712:16384,343932928:1073758208,360710144:1074282512,377487360:16,394264576:1073741824,411041792:1074282496,427819008:1073741840,444596224:1073758224,461373440:524304,478150656:0,494927872:16400,511705088:1074266128,528482304:540672},{0:260,1048576:0,2097152:67109120,3145728:65796,4194304:65540,5242880:67108868,6291456:67174660,7340032:67174400,8388608:67108864,9437184:67174656,10485760:65792,11534336:67174404,12582912:67109124,13631488:65536,14680064:4,15728640:256,524288:67174656,1572864:67174404,2621440:0,3670016:67109120,4718592:67108868,5767168:65536,6815744:65540,7864320:260,8912896:4,9961472:256,11010048:67174400,12058624:65796,13107200:65792,14155776:67109124,15204352:67174660,16252928:67108864,16777216:67174656,17825792:65540,18874368:65536,19922944:67109120,20971520:256,22020096:67174660,23068672:67108868,24117248:0,25165824:67109124,26214400:67108864,27262976:4,28311552:65792,29360128:67174400,30408704:260,31457280:65796,32505856:67174404,17301504:67108864,18350080:260,19398656:67174656,20447232:0,21495808:65540,22544384:67109120,23592960:256,24641536:67174404,25690112:65536,26738688:67174660,27787264:65796,28835840:67108868,29884416:67109124,30932992:67174400,31981568:4,33030144:65792},{0:2151682048,65536:2147487808,131072:4198464,196608:2151677952,262144:0,327680:4198400,393216:2147483712,458752:4194368,524288:2147483648,589824:4194304,655360:64,720896:2147487744,786432:2151678016,851968:4160,917504:4096,983040:2151682112,32768:2147487808,98304:64,163840:2151678016,229376:2147487744,294912:4198400,360448:2151682112,425984:0,491520:2151677952,557056:4096,622592:2151682048,688128:4194304,753664:4160,819200:2147483648,884736:4194368,950272:4198464,1015808:2147483712,1048576:4194368,1114112:4198400,1179648:2147483712,1245184:0,1310720:4160,1376256:2151678016,1441792:2151682048,1507328:2147487808,1572864:2151682112,1638400:2147483648,1703936:2151677952,1769472:4198464,1835008:2147487744,1900544:4194304,1966080:64,2031616:4096,1081344:2151677952,1146880:2151682112,1212416:0,1277952:4198400,1343488:4194368,1409024:2147483648,1474560:2147487808,1540096:64,1605632:2147483712,1671168:4096,1736704:2147487744,1802240:2151678016,1867776:4160,1933312:2151682048,1998848:4194304,2064384:4198464},{0:128,4096:17039360,8192:262144,12288:536870912,16384:537133184,20480:16777344,24576:553648256,28672:262272,32768:16777216,36864:537133056,40960:536871040,45056:553910400,49152:553910272,53248:0,57344:17039488,61440:553648128,2048:17039488,6144:553648256,10240:128,14336:17039360,18432:262144,22528:537133184,26624:553910272,30720:536870912,34816:537133056,38912:0,43008:553910400,47104:16777344,51200:536871040,55296:553648128,59392:16777216,63488:262272,65536:262144,69632:128,73728:536870912,77824:553648256,81920:16777344,86016:553910272,90112:537133184,94208:16777216,98304:553910400,102400:553648128,106496:17039360,110592:537133056,114688:262272,118784:536871040,122880:0,126976:17039488,67584:553648256,71680:16777216,75776:17039360,79872:537133184,83968:536870912,88064:17039488,92160:128,96256:553910272,100352:262272,104448:553910400,108544:0,112640:553648128,116736:16777344,120832:262144,124928:537133056,129024:536871040},{0:268435464,256:8192,512:270532608,768:270540808,1024:268443648,1280:2097152,1536:2097160,1792:268435456,2048:0,2304:268443656,2560:2105344,2816:8,3072:270532616,3328:2105352,3584:8200,3840:270540800,128:270532608,384:270540808,640:8,896:2097152,1152:2105352,1408:268435464,1664:268443648,1920:8200,2176:2097160,2432:8192,2688:268443656,2944:270532616,3200:0,3456:270540800,3712:2105344,3968:268435456,4096:268443648,4352:270532616,4608:270540808,4864:8200,5120:2097152,5376:268435456,5632:268435464,5888:2105344,6144:2105352,6400:0,6656:8,6912:270532608,7168:8192,7424:268443656,7680:270540800,7936:2097160,4224:8,4480:2105344,4736:2097152,4992:268435464,5248:268443648,5504:8200,5760:270540808,6016:270532608,6272:270540800,6528:270532616,6784:8192,7040:2105352,7296:2097160,7552:0,7808:268435456,8064:268443656},{0:1048576,16:33555457,32:1024,48:1049601,64:34604033,80:0,96:1,112:34603009,128:33555456,144:1048577,160:33554433,176:34604032,192:34603008,208:1025,224:1049600,240:33554432,8:34603009,24:0,40:33555457,56:34604032,72:1048576,88:33554433,104:33554432,120:1025,136:1049601,152:33555456,168:34603008,184:1048577,200:1024,216:34604033,232:1,248:1049600,256:33554432,272:1048576,288:33555457,304:34603009,320:1048577,336:33555456,352:34604032,368:1049601,384:1025,400:34604033,416:1049600,432:1,448:0,464:34603008,480:33554433,496:1024,264:1049600,280:33555457,296:34603009,312:1,328:33554432,344:1048576,360:1025,376:34604032,392:33554433,408:34603008,424:0,440:34604033,456:1049601,472:1024,488:33555456,504:1048577},{0:134219808,1:131072,2:134217728,3:32,4:131104,5:134350880,6:134350848,7:2048,8:134348800,9:134219776,10:133120,11:134348832,12:2080,13:0,14:134217760,15:133152,2147483648:2048,2147483649:134350880,2147483650:134219808,2147483651:134217728,2147483652:134348800,2147483653:133120,2147483654:133152,2147483655:32,2147483656:134217760,2147483657:2080,2147483658:131104,2147483659:134350848,2147483660:0,2147483661:134348832,2147483662:134219776,2147483663:131072,16:133152,17:134350848,18:32,19:2048,20:134219776,21:134217760,22:134348832,23:131072,24:0,25:131104,26:134348800,27:134219808,28:134350880,29:133120,30:2080,31:134217728,2147483664:131072,2147483665:2048,2147483666:134348832,2147483667:133152,2147483668:32,2147483669:134348800,2147483670:134217728,2147483671:134219808,2147483672:134350880,2147483673:134217760,2147483674:134219776,2147483675:0,2147483676:133120,2147483677:2080,2147483678:131104,2147483679:134350848}],m=[4160749569,528482304,33030144,2064384,129024,8064,504,2147483679],n=h.DES=g.extend({_doReset:function(){for(var a=this._key,b=a.words,c=[],d=0;56>d;d++){var e=i[d]-1;c[d]=b[e>>>5]>>>31-e%32&1}for(var f=this._subKeys=[],g=0;16>g;g++){for(var h=f[g]=[],l=k[g],d=0;24>d;d++)h[d/6|0]|=c[(j[d]-1+l)%28]<<31-d%6,h[4+(d/6|0)]|=c[28+(j[d+24]-1+l)%28]<<31-d%6;h[0]=h[0]<<1|h[0]>>>31;for(var d=1;7>d;d++)h[d]=h[d]>>>4*(d-1)+3;h[7]=h[7]<<5|h[7]>>>27}for(var m=this._invSubKeys=[],d=0;16>d;d++)m[d]=f[15-d]},encryptBlock:function(a,b){this._doCryptBlock(a,b,this._subKeys)},decryptBlock:function(a,b){this._doCryptBlock(a,b,this._invSubKeys)},_doCryptBlock:function(a,d,e){this._lBlock=a[d],this._rBlock=a[d+1],b.call(this,4,252645135),b.call(this,16,65535),c.call(this,2,858993459),c.call(this,8,16711935),b.call(this,1,1431655765);for(var f=0;16>f;f++){for(var g=e[f],h=this._lBlock,i=this._rBlock,j=0,k=0;8>k;k++)j|=l[k][((i^g[k])&m[k])>>>0];this._lBlock=i,this._rBlock=h^j}var n=this._lBlock;this._lBlock=this._rBlock,this._rBlock=n,b.call(this,1,1431655765),c.call(this,8,16711935),c.call(this,2,858993459),b.call(this,16,65535),b.call(this,4,252645135),a[d]=this._lBlock,a[d+1]=this._rBlock},keySize:2,ivSize:2,blockSize:2});d.DES=g._createHelper(n);var o=h.TripleDES=g.extend({_doReset:function(){var a=this._key,b=a.words;this._des1=n.createEncryptor(f.create(b.slice(0,2))),this._des2=n.createEncryptor(f.create(b.slice(2,4))),this._des3=n.createEncryptor(f.create(b.slice(4,6)))},encryptBlock:function(a,b){this._des1.encryptBlock(a,b),this._des2.decryptBlock(a,b),this._des3.encryptBlock(a,b)},decryptBlock:function(a,b){this._des3.decryptBlock(a,b),this._des2.encryptBlock(a,b),this._des1.decryptBlock(a,b)},keySize:6,ivSize:2,blockSize:2});d.TripleDES=g._createHelper(o)}(),a.TripleDES})},{"./cipher-core":45,"./core":46,"./enc-base64":47,"./evpkdf":49,"./md5":54}],77:[function(a,b,c){!function(d,e){"object"==typeof c?b.exports=c=e(a("./core")):"function"==typeof define&&define.amd?define(["./core"],e):e(d.CryptoJS)}(this,function(a){return function(b){var c=a,d=c.lib,e=d.Base,f=d.WordArray,g=c.x64={};g.Word=e.extend({init:function(a,b){this.high=a,this.low=b}}),g.WordArray=e.extend({init:function(a,c){a=this.words=a||[],c!=b?this.sigBytes=c:this.sigBytes=8*a.length},toX32:function(){for(var a=this.words,b=a.length,c=[],d=0;b>d;d++){var e=a[d];c.push(e.high),c.push(e.low)}return f.create(c,this.sigBytes)},clone:function(){for(var a=e.clone.call(this),b=a.words=this.words.slice(0),c=b.length,d=0;c>d;d++)b[d]=b[d].clone();return a}})}(),a})},{"./core":46}],78:[function(a,b,c){(function(){"use strict";function c(a,b){a=a||[],b=b||{};try{return new Blob(a,b)}catch(c){if("TypeError"!==c.name)throw c;for(var d=window.BlobBuilder||window.MSBlobBuilder||window.MozBlobBuilder||window.WebKitBlobBuilder,e=new d,f=0;f<a.length;f+=1)e.append(a[f]);return e.getBlob(b.type)}}function d(a){for(var b=a.length,c=new ArrayBuffer(b),d=new Uint8Array(c),e=0;b>e;e++)d[e]=a.charCodeAt(e);return c}function e(a){return new u(function(b,c){var d=new XMLHttpRequest;d.open("GET",a),d.withCredentials=!0,d.responseType="arraybuffer",d.onreadystatechange=function(){return 4===d.readyState?200===d.status?b({response:d.response,type:d.getResponseHeader("Content-Type")}):void c({status:d.status,response:d.response}):void 0},d.send()})}function f(a){return new u(function(b,d){var f=c([""],{type:"image/png"}),g=a.transaction([x],"readwrite");g.objectStore(x).put(f,"key"),g.oncomplete=function(){var c=a.transaction([x],"readwrite"),f=c.objectStore(x).get("key");f.onerror=d,f.onsuccess=function(a){var c=a.target.result,d=URL.createObjectURL(c);e(d).then(function(a){b(!(!a||"image/png"!==a.type))},function(){b(!1)}).then(function(){URL.revokeObjectURL(d)})}}})["catch"](function(){return!1})}function g(a){return"boolean"==typeof w?u.resolve(w):f(a).then(function(a){return w=a})}function h(a){return new u(function(b,c){var d=new FileReader;d.onerror=c,d.onloadend=function(c){var d=btoa(c.target.result||"");b({__local_forage_encoded_blob:!0,data:d,type:a.type})},d.readAsBinaryString(a)})}function i(a){var b=d(atob(a.data));return c([b],{type:a.type})}function j(a){return a&&a.__local_forage_encoded_blob}function k(a){var b=this,c={db:null};if(a)for(var d in a)c[d]=a[d];return new u(function(a,d){var e=v.open(c.name,c.version);e.onerror=function(){d(e.error)},e.onupgradeneeded=function(a){e.result.createObjectStore(c.storeName),a.oldVersion<=1&&e.result.createObjectStore(x)},e.onsuccess=function(){c.db=e.result,b._dbInfo=c,a()}})}function l(a,b){var c=this;"string"!=typeof a&&(window.console.warn(a+" used as a key, but it is not a string."),a=String(a));var d=new u(function(b,d){c.ready().then(function(){var e=c._dbInfo,f=e.db.transaction(e.storeName,"readonly").objectStore(e.storeName),g=f.get(a);g.onsuccess=function(){var a=g.result;void 0===a&&(a=null),j(a)&&(a=i(a)),b(a)},g.onerror=function(){d(g.error)}})["catch"](d)});return t(d,b),d}function m(a,b){var c=this,d=new u(function(b,d){c.ready().then(function(){var e=c._dbInfo,f=e.db.transaction(e.storeName,"readonly").objectStore(e.storeName),g=f.openCursor(),h=1;g.onsuccess=function(){var c=g.result;if(c){var d=c.value;j(d)&&(d=i(d));var e=a(d,c.key,h++);void 0!==e?b(e):c["continue"]()}else b()},g.onerror=function(){d(g.error)}})["catch"](d)});return t(d,b),d}function n(a,b,c){var d=this;"string"!=typeof a&&(window.console.warn(a+" used as a key, but it is not a string."),a=String(a));var e=new u(function(c,e){var f;d.ready().then(function(){return f=d._dbInfo,g(f.db)}).then(function(a){return!a&&b instanceof Blob?h(b):b}).then(function(b){var d=f.db.transaction(f.storeName,"readwrite"),g=d.objectStore(f.storeName);null===b&&(b=void 0);var h=g.put(b,a);d.oncomplete=function(){void 0===b&&(b=null),c(b)},d.onabort=d.onerror=function(){var a=h.error?h.error:h.transaction.error;e(a)}})["catch"](e)});return t(e,c),e}function o(a,b){var c=this;"string"!=typeof a&&(window.console.warn(a+" used as a key, but it is not a string."),a=String(a));var d=new u(function(b,d){c.ready().then(function(){var e=c._dbInfo,f=e.db.transaction(e.storeName,"readwrite"),g=f.objectStore(e.storeName),h=g["delete"](a);f.oncomplete=function(){b()},f.onerror=function(){d(h.error)},f.onabort=function(){var a=h.error?h.error:h.transaction.error;d(a)}})["catch"](d)});return t(d,b),d}function p(a){var b=this,c=new u(function(a,c){b.ready().then(function(){var d=b._dbInfo,e=d.db.transaction(d.storeName,"readwrite"),f=e.objectStore(d.storeName),g=f.clear();e.oncomplete=function(){a()},e.onabort=e.onerror=function(){var a=g.error?g.error:g.transaction.error;c(a)}})["catch"](c)});return t(c,a),c}function q(a){var b=this,c=new u(function(a,c){b.ready().then(function(){var d=b._dbInfo,e=d.db.transaction(d.storeName,"readonly").objectStore(d.storeName),f=e.count();f.onsuccess=function(){a(f.result)},f.onerror=function(){c(f.error)}})["catch"](c)});return t(c,a),c}function r(a,b){var c=this,d=new u(function(b,d){return 0>a?void b(null):void c.ready().then(function(){var e=c._dbInfo,f=e.db.transaction(e.storeName,"readonly").objectStore(e.storeName),g=!1,h=f.openCursor();h.onsuccess=function(){var c=h.result;return c?void(0===a?b(c.key):g?b(c.key):(g=!0,c.advance(a))):void b(null)},h.onerror=function(){d(h.error)}})["catch"](d)});return t(d,b),d}function s(a){var b=this,c=new u(function(a,c){b.ready().then(function(){var d=b._dbInfo,e=d.db.transaction(d.storeName,"readonly").objectStore(d.storeName),f=e.openCursor(),g=[];f.onsuccess=function(){var b=f.result;return b?(g.push(b.key),void b["continue"]()):void a(g)},f.onerror=function(){c(f.error)}})["catch"](c)});return t(c,a),c}function t(a,b){b&&a.then(function(a){b(null,a)},function(a){b(a)})}var u="undefined"!=typeof b&&b.exports&&"undefined"!=typeof a?a("promise"):this.Promise,v=v||this.indexedDB||this.webkitIndexedDB||this.mozIndexedDB||this.OIndexedDB||this.msIndexedDB;if(v){var w,x="local-forage-detect-blob-support",y={_driver:"asyncStorage",_initStorage:k,iterate:m,getItem:l,setItem:n,removeItem:o,clear:p,length:q,key:r,keys:s};"undefined"!=typeof b&&b.exports&&"undefined"!=typeof a?b.exports=y:"function"==typeof define&&define.amd?define("asyncStorage",function(){return y}):this.asyncStorage=y}}).call(window)},{promise:101}],79:[function(a,b,c){(function(){"use strict";function c(b){var c=this,d={};if(b)for(var e in b)d[e]=b[e];d.keyPrefix=d.name+"/",c._dbInfo=d;var f=new m(function(b){s===r.DEFINE?a(["localforageSerializer"],b):b(s===r.EXPORT?a("./../utils/serializer"):n.localforageSerializer)});return f.then(function(a){return o=a,m.resolve()})}function d(a){var b=this,c=b.ready().then(function(){for(var a=b._dbInfo.keyPrefix,c=p.length-1;c>=0;c--){var d=p.key(c);0===d.indexOf(a)&&p.removeItem(d)}});return l(c,a),c}function e(a,b){var c=this;"string"!=typeof a&&(window.console.warn(a+" used as a key, but it is not a string."),a=String(a));var d=c.ready().then(function(){var b=c._dbInfo,d=p.getItem(b.keyPrefix+a);return d&&(d=o.deserialize(d)),d});return l(d,b),d}function f(a,b){var c=this,d=c.ready().then(function(){for(var b=c._dbInfo.keyPrefix,d=b.length,e=p.length,f=1,g=0;e>g;g++){var h=p.key(g);if(0===h.indexOf(b)){var i=p.getItem(h);if(i&&(i=o.deserialize(i)),i=a(i,h.substring(d),f++),void 0!==i)return i}}});return l(d,b),d}function g(a,b){var c=this,d=c.ready().then(function(){var b,d=c._dbInfo;try{b=p.key(a)}catch(e){b=null}return b&&(b=b.substring(d.keyPrefix.length)),b});return l(d,b),d}function h(a){var b=this,c=b.ready().then(function(){for(var a=b._dbInfo,c=p.length,d=[],e=0;c>e;e++)0===p.key(e).indexOf(a.keyPrefix)&&d.push(p.key(e).substring(a.keyPrefix.length));return d});return l(c,a),c}function i(a){var b=this,c=b.keys().then(function(a){return a.length});return l(c,a),c}function j(a,b){var c=this;"string"!=typeof a&&(window.console.warn(a+" used as a key, but it is not a string."),a=String(a));var d=c.ready().then(function(){var b=c._dbInfo;p.removeItem(b.keyPrefix+a)});return l(d,b),d}function k(a,b,c){var d=this;"string"!=typeof a&&(window.console.warn(a+" used as a key, but it is not a string."),a=String(a));var e=d.ready().then(function(){void 0===b&&(b=null);var c=b;return new m(function(e,f){o.serialize(b,function(b,g){if(g)f(g);else try{var h=d._dbInfo;p.setItem(h.keyPrefix+a,b),e(c)}catch(i){"QuotaExceededError"!==i.name&&"NS_ERROR_DOM_QUOTA_REACHED"!==i.name||f(i),f(i)}})})});return l(e,c),e}function l(a,b){b&&a.then(function(a){b(null,a)},function(a){b(a)})}var m="undefined"!=typeof b&&b.exports&&"undefined"!=typeof a?a("promise"):this.Promise,n=this,o=null,p=null;try{if(!(this.localStorage&&"setItem"in this.localStorage))return;p=this.localStorage}catch(q){return}var r={DEFINE:1,EXPORT:2,WINDOW:3},s=r.WINDOW;"undefined"!=typeof b&&b.exports&&"undefined"!=typeof a?s=r.EXPORT:"function"==typeof define&&define.amd&&(s=r.DEFINE);var t={_driver:"localStorageWrapper",_initStorage:c,iterate:f,getItem:e,setItem:k,removeItem:j,clear:d,length:i,key:g,keys:h};s===r.EXPORT?b.exports=t:s===r.DEFINE?define("localStorageWrapper",function(){return t}):this.localStorageWrapper=t}).call(window)},{"./../utils/serializer":82,promise:101}],80:[function(a,b,c){(function(){"use strict";function c(b){var c=this,d={db:null};if(b)for(var e in b)d[e]="string"!=typeof b[e]?b[e].toString():b[e];var f=new m(function(b){r===q.DEFINE?a(["localforageSerializer"],b):b(r===q.EXPORT?a("./../utils/serializer"):n.localforageSerializer)}),g=new m(function(a,e){try{d.db=p(d.name,String(d.version),d.description,d.size)}catch(f){return c.setDriver(c.LOCALSTORAGE).then(function(){return c._initStorage(b)}).then(a)["catch"](e)}d.db.transaction(function(b){b.executeSql("CREATE TABLE IF NOT EXISTS "+d.storeName+" (id INTEGER PRIMARY KEY, key unique, value)",[],function(){c._dbInfo=d,a()},function(a,b){e(b)})})});return f.then(function(a){return o=a,g})}function d(a,b){var c=this;"string"!=typeof a&&(window.console.warn(a+" used as a key, but it is not a string."),a=String(a));var d=new m(function(b,d){c.ready().then(function(){var e=c._dbInfo;e.db.transaction(function(c){c.executeSql("SELECT * FROM "+e.storeName+" WHERE key = ? LIMIT 1",[a],function(a,c){var d=c.rows.length?c.rows.item(0).value:null;d&&(d=o.deserialize(d)),b(d)},function(a,b){d(b)})})})["catch"](d)});return l(d,b),d}function e(a,b){var c=this,d=new m(function(b,d){c.ready().then(function(){var e=c._dbInfo;e.db.transaction(function(c){c.executeSql("SELECT * FROM "+e.storeName,[],function(c,d){for(var e=d.rows,f=e.length,g=0;f>g;g++){var h=e.item(g),i=h.value;if(i&&(i=o.deserialize(i)),i=a(i,h.key,g+1),void 0!==i)return void b(i)}b()},function(a,b){d(b)})})})["catch"](d)});return l(d,b),d}function f(a,b,c){var d=this;"string"!=typeof a&&(window.console.warn(a+" used as a key, but it is not a string."),a=String(a));var e=new m(function(c,e){d.ready().then(function(){void 0===b&&(b=null);var f=b;o.serialize(b,function(b,g){if(g)e(g);else{var h=d._dbInfo;h.db.transaction(function(d){d.executeSql("INSERT OR REPLACE INTO "+h.storeName+" (key, value) VALUES (?, ?)",[a,b],function(){c(f)},function(a,b){e(b)})},function(a){a.code===a.QUOTA_ERR&&e(a)})}})})["catch"](e)});return l(e,c),e}function g(a,b){var c=this;"string"!=typeof a&&(window.console.warn(a+" used as a key, but it is not a string."),a=String(a));var d=new m(function(b,d){c.ready().then(function(){var e=c._dbInfo;e.db.transaction(function(c){c.executeSql("DELETE FROM "+e.storeName+" WHERE key = ?",[a],function(){b()},function(a,b){d(b)})})})["catch"](d)});return l(d,b),d}function h(a){var b=this,c=new m(function(a,c){b.ready().then(function(){var d=b._dbInfo;d.db.transaction(function(b){b.executeSql("DELETE FROM "+d.storeName,[],function(){a()},function(a,b){c(b)})})})["catch"](c)});return l(c,a),c}function i(a){var b=this,c=new m(function(a,c){b.ready().then(function(){var d=b._dbInfo;d.db.transaction(function(b){b.executeSql("SELECT COUNT(key) as c FROM "+d.storeName,[],function(b,c){var d=c.rows.item(0).c;a(d)},function(a,b){c(b)})})})["catch"](c)});return l(c,a),c}function j(a,b){var c=this,d=new m(function(b,d){c.ready().then(function(){var e=c._dbInfo;e.db.transaction(function(c){c.executeSql("SELECT key FROM "+e.storeName+" WHERE id = ? LIMIT 1",[a+1],function(a,c){var d=c.rows.length?c.rows.item(0).key:null;b(d)},function(a,b){d(b)})})})["catch"](d)});return l(d,b),d}function k(a){var b=this,c=new m(function(a,c){b.ready().then(function(){var d=b._dbInfo;d.db.transaction(function(b){b.executeSql("SELECT key FROM "+d.storeName,[],function(b,c){for(var d=[],e=0;e<c.rows.length;e++)d.push(c.rows.item(e).key);a(d)},function(a,b){c(b)})})})["catch"](c)});return l(c,a),c}function l(a,b){b&&a.then(function(a){b(null,a)},function(a){b(a)})}var m="undefined"!=typeof b&&b.exports&&"undefined"!=typeof a?a("promise"):this.Promise,n=this,o=null,p=this.openDatabase;if(p){var q={DEFINE:1,EXPORT:2,WINDOW:3},r=q.WINDOW;"undefined"!=typeof b&&b.exports&&"undefined"!=typeof a?r=q.EXPORT:"function"==typeof define&&define.amd&&(r=q.DEFINE);var s={_driver:"webSQLStorage",_initStorage:c,iterate:e,getItem:d,setItem:f,removeItem:g,clear:h,length:i,key:j,keys:k};r===q.DEFINE?define("webSQLStorage",function(){return s}):r===q.EXPORT?b.exports=s:this.webSQLStorage=s}}).call(window)},{"./../utils/serializer":82,promise:101}],81:[function(a,b,c){(function(){"use strict";function c(a,b){a[b]=function(){var c=arguments;return a.ready().then(function(){return a[b].apply(a,c)})}}function d(){for(var a=1;a<arguments.length;a++){var b=arguments[a];if(b)for(var c in b)b.hasOwnProperty(c)&&(p(b[c])?arguments[0][c]=b[c].slice():arguments[0][c]=b[c])}return arguments[0]}function e(a){for(var b in i)if(i.hasOwnProperty(b)&&i[b]===a)return!0;return!1}function f(a){this._config=d({},m,a),this._driverSet=null,this._ready=!1,this._dbInfo=null;for(var b=0;b<k.length;b++)c(this,k[b]);this.setDriver(this._config.driver)}var g="undefined"!=typeof b&&b.exports&&"undefined"!=typeof a?a("promise"):this.Promise,h={},i={INDEXEDDB:"asyncStorage",LOCALSTORAGE:"localStorageWrapper",WEBSQL:"webSQLStorage"},j=[i.INDEXEDDB,i.WEBSQL,i.LOCALSTORAGE],k=["clear","getItem","iterate","key","keys","length","removeItem","setItem"],l={DEFINE:1,EXPORT:2,WINDOW:3},m={description:"",driver:j.slice(),name:"localforage",size:4980736,storeName:"keyvaluepairs",version:1},n=l.WINDOW;"undefined"!=typeof b&&b.exports&&"undefined"!=typeof a?n=l.EXPORT:"function"==typeof define&&define.amd&&(n=l.DEFINE);var o=function(a){var b=b||a.indexedDB||a.webkitIndexedDB||a.mozIndexedDB||a.OIndexedDB||a.msIndexedDB,c={};return c[i.WEBSQL]=!!a.openDatabase,c[i.INDEXEDDB]=!!function(){if("undefined"!=typeof a.openDatabase&&a.navigator&&a.navigator.userAgent&&/Safari/.test(a.navigator.userAgent)&&!/Chrome/.test(a.navigator.userAgent))return!1;try{return b&&"function"==typeof b.open&&"undefined"!=typeof a.IDBKeyRange}catch(c){return!1}}(),c[i.LOCALSTORAGE]=!!function(){try{return a.localStorage&&"setItem"in a.localStorage&&a.localStorage.setItem}catch(b){return!1}}(),c}(this),p=Array.isArray||function(a){return"[object Array]"===Object.prototype.toString.call(a)},q=this;f.prototype.INDEXEDDB=i.INDEXEDDB,f.prototype.LOCALSTORAGE=i.LOCALSTORAGE,f.prototype.WEBSQL=i.WEBSQL,f.prototype.config=function(a){if("object"==typeof a){if(this._ready)return new Error("Can't call config() after localforage has been used.");for(var b in a)"storeName"===b&&(a[b]=a[b].replace(/\W/g,"_")),this._config[b]=a[b];return"driver"in a&&a.driver&&this.setDriver(this._config.driver),!0}return"string"==typeof a?this._config[a]:this._config},f.prototype.defineDriver=function(a,b,c){var d=new g(function(b,c){try{var d=a._driver,f=new Error("Custom driver not compliant; see https://mozilla.github.io/localForage/#definedriver"),i=new Error("Custom driver name already in use: "+a._driver);if(!a._driver)return void c(f);if(e(a._driver))return void c(i);for(var j=k.concat("_initStorage"),l=0;l<j.length;l++){var m=j[l];if(!m||!a[m]||"function"!=typeof a[m])return void c(f)}var n=g.resolve(!0);"_support"in a&&(n=a._support&&"function"==typeof a._support?a._support():g.resolve(!!a._support)),n.then(function(c){o[d]=c,h[d]=a,b()},c)}catch(p){c(p)}});return d.then(b,c),d},f.prototype.driver=function(){return this._driver||null},f.prototype.ready=function(a){var b=this,c=new g(function(a,c){b._driverSet.then(function(){null===b._ready&&(b._ready=b._initStorage(b._config)),b._ready.then(a,c)})["catch"](c)});return c.then(a,a),c},f.prototype.setDriver=function(b,c,d){function f(){i._config.driver=i.driver()}var i=this;return"string"==typeof b&&(b=[b]),this._driverSet=new g(function(c,d){var f=i._getFirstSupportedDriver(b),j=new Error("No available storage method found.");if(!f)return i._driverSet=g.reject(j),void d(j);if(i._dbInfo=null,i._ready=null,e(f)){var k=new g(function(b){if(n===l.DEFINE)a([f],b);else if(n===l.EXPORT)switch(f){case i.INDEXEDDB:b(a("./drivers/indexeddb"));break;case i.LOCALSTORAGE:b(a("./drivers/localstorage"));break;case i.WEBSQL:b(a("./drivers/websql"))}else b(q[f])});k.then(function(a){i._extend(a),c()})}else h[f]?(i._extend(h[f]),c()):(i._driverSet=g.reject(j),d(j))}),this._driverSet.then(f,f),this._driverSet.then(c,d),this._driverSet},f.prototype.supports=function(a){return!!o[a]},f.prototype._extend=function(a){d(this,a)},f.prototype._getFirstSupportedDriver=function(a){if(a&&p(a))for(var b=0;b<a.length;b++){var c=a[b];if(this.supports(c))return c}return null},f.prototype.createInstance=function(a){return new f(a)};var r=new f;n===l.DEFINE?define("localforage",function(){return r}):n===l.EXPORT?b.exports=r:this.localforage=r}).call(window)},{"./drivers/indexeddb":78,"./drivers/localstorage":79,"./drivers/websql":80,promise:101}],82:[function(a,b,c){(function(){"use strict";function c(a,b){a=a||[],b=b||{};try{return new Blob(a,b)}catch(c){if("TypeError"!==c.name)throw c;for(var d=y.BlobBuilder||y.MSBlobBuilder||y.MozBlobBuilder||y.WebKitBlobBuilder,e=new d,f=0;f<a.length;f+=1)e.append(a[f]);return e.getBlob(b.type)}}function d(a,b){var c="";if(a&&(c=a.toString()),a&&("[object ArrayBuffer]"===a.toString()||a.buffer&&"[object ArrayBuffer]"===a.buffer.toString())){var d,e=k;a instanceof ArrayBuffer?(d=a,e+=m):(d=a.buffer,"[object Int8Array]"===c?e+=o:"[object Uint8Array]"===c?e+=p:"[object Uint8ClampedArray]"===c?e+=q:"[object Int16Array]"===c?e+=r:"[object Uint16Array]"===c?e+=t:"[object Int32Array]"===c?e+=s:"[object Uint32Array]"===c?e+=u:"[object Float32Array]"===c?e+=v:"[object Float64Array]"===c?e+=w:b(new Error("Failed to get type for BinaryArray"))),b(e+g(d))}else if("[object Blob]"===c){var f=new FileReader;f.onload=function(){var c=i+a.type+"~"+g(this.result);b(k+n+c)},f.readAsArrayBuffer(a)}else try{b(JSON.stringify(a))}catch(h){console.error("Couldn't convert value into a JSON string: ",a),b(null,h)}}function e(a){if(a.substring(0,l)!==k)return JSON.parse(a);var b,d=a.substring(x),e=a.substring(l,x);if(e===n&&j.test(d)){var g=d.match(j);b=g[1],d=d.substring(g[0].length)}var h=f(d);switch(e){case m:return h;case n:return c([h],{type:b});case o:return new Int8Array(h);case p:return new Uint8Array(h);case q:return new Uint8ClampedArray(h);case r:return new Int16Array(h);case t:return new Uint16Array(h);case s:return new Int32Array(h);case u:return new Uint32Array(h);case v:return new Float32Array(h);case w:return new Float64Array(h);default:throw new Error("Unkown type: "+e)}}function f(a){var b,c,d,e,f,g=.75*a.length,i=a.length,j=0;"="===a[a.length-1]&&(g--,"="===a[a.length-2]&&g--);var k=new ArrayBuffer(g),l=new Uint8Array(k);for(b=0;i>b;b+=4)c=h.indexOf(a[b]),d=h.indexOf(a[b+1]),e=h.indexOf(a[b+2]),f=h.indexOf(a[b+3]),l[j++]=c<<2|d>>4,l[j++]=(15&d)<<4|e>>2,l[j++]=(3&e)<<6|63&f;return k}function g(a){var b,c=new Uint8Array(a),d="";for(b=0;b<c.length;b+=3)d+=h[c[b]>>2],d+=h[(3&c[b])<<4|c[b+1]>>4],d+=h[(15&c[b+1])<<2|c[b+2]>>6],d+=h[63&c[b+2]];return c.length%3===2?d=d.substring(0,d.length-1)+"=":c.length%3===1&&(d=d.substring(0,d.length-2)+"=="),d}var h="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/",i="~~local_forage_type~",j=/^~~local_forage_type~([^~]+)~/,k="__lfsc__:",l=k.length,m="arbf",n="blob",o="si08",p="ui08",q="uic8",r="si16",s="si32",t="ur16",u="ui32",v="fl32",w="fl64",x=l+m.length,y=this,z={serialize:d,deserialize:e,stringToBuffer:f,bufferToString:g};"undefined"!=typeof b&&b.exports&&"undefined"!=typeof a?b.exports=z:"function"==typeof define&&define.amd?define("localforageSerializer",function(){return z}):this.localforageSerializer=z}).call(window)},{}],83:[function(a,b,c){"use strict";var d=a("./lib/utils/common").assign,e=a("./lib/deflate"),f=a("./lib/inflate"),g=a("./lib/zlib/constants"),h={};d(h,e,f,g),b.exports=h},{"./lib/deflate":84,"./lib/inflate":85,"./lib/utils/common":86,"./lib/zlib/constants":89}],84:[function(a,b,c){"use strict";function d(a){if(!(this instanceof d))return new d(a);this.options=i.assign({level:s,method:u,chunkSize:16384,windowBits:15,memLevel:8,strategy:t,to:""},a||{});var b=this.options;b.raw&&b.windowBits>0?b.windowBits=-b.windowBits:b.gzip&&b.windowBits>0&&b.windowBits<16&&(b.windowBits+=16),this.err=0,this.msg="",this.ended=!1,this.chunks=[],this.strm=new l,this.strm.avail_out=0;var c=h.deflateInit2(this.strm,b.level,b.method,b.windowBits,b.memLevel,b.strategy);if(c!==p)throw new Error(k[c]);b.header&&h.deflateSetHeader(this.strm,b.header)}function e(a,b){var c=new d(b);if(c.push(a,!0),c.err)throw c.msg;return c.result}function f(a,b){return b=b||{},b.raw=!0,e(a,b)}function g(a,b){return b=b||{},b.gzip=!0,e(a,b)}var h=a("./zlib/deflate"),i=a("./utils/common"),j=a("./utils/strings"),k=a("./zlib/messages"),l=a("./zlib/zstream"),m=Object.prototype.toString,n=0,o=4,p=0,q=1,r=2,s=-1,t=0,u=8;d.prototype.push=function(a,b){var c,d,e=this.strm,f=this.options.chunkSize;if(this.ended)return!1;d=b===~~b?b:b===!0?o:n,"string"==typeof a?e.input=j.string2buf(a):"[object ArrayBuffer]"===m.call(a)?e.input=new Uint8Array(a):e.input=a,e.next_in=0,e.avail_in=e.input.length;do{if(0===e.avail_out&&(e.output=new i.Buf8(f),e.next_out=0,e.avail_out=f),c=h.deflate(e,d),c!==q&&c!==p)return this.onEnd(c),this.ended=!0,!1;0!==e.avail_out&&(0!==e.avail_in||d!==o&&d!==r)||("string"===this.options.to?this.onData(j.buf2binstring(i.shrinkBuf(e.output,e.next_out))):this.onData(i.shrinkBuf(e.output,e.next_out)))}while((e.avail_in>0||0===e.avail_out)&&c!==q);return d===o?(c=h.deflateEnd(this.strm), this.onEnd(c),this.ended=!0,c===p):d===r?(this.onEnd(p),e.avail_out=0,!0):!0},d.prototype.onData=function(a){this.chunks.push(a)},d.prototype.onEnd=function(a){a===p&&("string"===this.options.to?this.result=this.chunks.join(""):this.result=i.flattenChunks(this.chunks)),this.chunks=[],this.err=a,this.msg=this.strm.msg},c.Deflate=d,c.deflate=e,c.deflateRaw=f,c.gzip=g},{"./utils/common":86,"./utils/strings":87,"./zlib/deflate":91,"./zlib/messages":96,"./zlib/zstream":98}],85:[function(a,b,c){"use strict";function d(a){if(!(this instanceof d))return new d(a);this.options=h.assign({chunkSize:16384,windowBits:0,to:""},a||{});var b=this.options;b.raw&&b.windowBits>=0&&b.windowBits<16&&(b.windowBits=-b.windowBits,0===b.windowBits&&(b.windowBits=-15)),!(b.windowBits>=0&&b.windowBits<16)||a&&a.windowBits||(b.windowBits+=32),b.windowBits>15&&b.windowBits<48&&0===(15&b.windowBits)&&(b.windowBits|=15),this.err=0,this.msg="",this.ended=!1,this.chunks=[],this.strm=new l,this.strm.avail_out=0;var c=g.inflateInit2(this.strm,b.windowBits);if(c!==j.Z_OK)throw new Error(k[c]);this.header=new m,g.inflateGetHeader(this.strm,this.header)}function e(a,b){var c=new d(b);if(c.push(a,!0),c.err)throw c.msg;return c.result}function f(a,b){return b=b||{},b.raw=!0,e(a,b)}var g=a("./zlib/inflate"),h=a("./utils/common"),i=a("./utils/strings"),j=a("./zlib/constants"),k=a("./zlib/messages"),l=a("./zlib/zstream"),m=a("./zlib/gzheader"),n=Object.prototype.toString;d.prototype.push=function(a,b){var c,d,e,f,k,l=this.strm,m=this.options.chunkSize,o=!1;if(this.ended)return!1;d=b===~~b?b:b===!0?j.Z_FINISH:j.Z_NO_FLUSH,"string"==typeof a?l.input=i.binstring2buf(a):"[object ArrayBuffer]"===n.call(a)?l.input=new Uint8Array(a):l.input=a,l.next_in=0,l.avail_in=l.input.length;do{if(0===l.avail_out&&(l.output=new h.Buf8(m),l.next_out=0,l.avail_out=m),c=g.inflate(l,j.Z_NO_FLUSH),c===j.Z_BUF_ERROR&&o===!0&&(c=j.Z_OK,o=!1),c!==j.Z_STREAM_END&&c!==j.Z_OK)return this.onEnd(c),this.ended=!0,!1;l.next_out&&(0!==l.avail_out&&c!==j.Z_STREAM_END&&(0!==l.avail_in||d!==j.Z_FINISH&&d!==j.Z_SYNC_FLUSH)||("string"===this.options.to?(e=i.utf8border(l.output,l.next_out),f=l.next_out-e,k=i.buf2string(l.output,e),l.next_out=f,l.avail_out=m-f,f&&h.arraySet(l.output,l.output,e,f,0),this.onData(k)):this.onData(h.shrinkBuf(l.output,l.next_out)))),0===l.avail_in&&0===l.avail_out&&(o=!0)}while((l.avail_in>0||0===l.avail_out)&&c!==j.Z_STREAM_END);return c===j.Z_STREAM_END&&(d=j.Z_FINISH),d===j.Z_FINISH?(c=g.inflateEnd(this.strm),this.onEnd(c),this.ended=!0,c===j.Z_OK):d===j.Z_SYNC_FLUSH?(this.onEnd(j.Z_OK),l.avail_out=0,!0):!0},d.prototype.onData=function(a){this.chunks.push(a)},d.prototype.onEnd=function(a){a===j.Z_OK&&("string"===this.options.to?this.result=this.chunks.join(""):this.result=h.flattenChunks(this.chunks)),this.chunks=[],this.err=a,this.msg=this.strm.msg},c.Inflate=d,c.inflate=e,c.inflateRaw=f,c.ungzip=e},{"./utils/common":86,"./utils/strings":87,"./zlib/constants":89,"./zlib/gzheader":92,"./zlib/inflate":94,"./zlib/messages":96,"./zlib/zstream":98}],86:[function(a,b,c){"use strict";var d="undefined"!=typeof Uint8Array&&"undefined"!=typeof Uint16Array&&"undefined"!=typeof Int32Array;c.assign=function(a){for(var b=Array.prototype.slice.call(arguments,1);b.length;){var c=b.shift();if(c){if("object"!=typeof c)throw new TypeError(c+"must be non-object");for(var d in c)c.hasOwnProperty(d)&&(a[d]=c[d])}}return a},c.shrinkBuf=function(a,b){return a.length===b?a:a.subarray?a.subarray(0,b):(a.length=b,a)};var e={arraySet:function(a,b,c,d,e){if(b.subarray&&a.subarray)return void a.set(b.subarray(c,c+d),e);for(var f=0;d>f;f++)a[e+f]=b[c+f]},flattenChunks:function(a){var b,c,d,e,f,g;for(d=0,b=0,c=a.length;c>b;b++)d+=a[b].length;for(g=new Uint8Array(d),e=0,b=0,c=a.length;c>b;b++)f=a[b],g.set(f,e),e+=f.length;return g}},f={arraySet:function(a,b,c,d,e){for(var f=0;d>f;f++)a[e+f]=b[c+f]},flattenChunks:function(a){return[].concat.apply([],a)}};c.setTyped=function(a){a?(c.Buf8=Uint8Array,c.Buf16=Uint16Array,c.Buf32=Int32Array,c.assign(c,e)):(c.Buf8=Array,c.Buf16=Array,c.Buf32=Array,c.assign(c,f))},c.setTyped(d)},{}],87:[function(a,b,c){"use strict";function d(a,b){if(65537>b&&(a.subarray&&g||!a.subarray&&f))return String.fromCharCode.apply(null,e.shrinkBuf(a,b));for(var c="",d=0;b>d;d++)c+=String.fromCharCode(a[d]);return c}var e=a("./common"),f=!0,g=!0;try{String.fromCharCode.apply(null,[0])}catch(h){f=!1}try{String.fromCharCode.apply(null,new Uint8Array(1))}catch(h){g=!1}for(var i=new e.Buf8(256),j=0;256>j;j++)i[j]=j>=252?6:j>=248?5:j>=240?4:j>=224?3:j>=192?2:1;i[254]=i[254]=1,c.string2buf=function(a){var b,c,d,f,g,h=a.length,i=0;for(f=0;h>f;f++)c=a.charCodeAt(f),55296===(64512&c)&&h>f+1&&(d=a.charCodeAt(f+1),56320===(64512&d)&&(c=65536+(c-55296<<10)+(d-56320),f++)),i+=128>c?1:2048>c?2:65536>c?3:4;for(b=new e.Buf8(i),g=0,f=0;i>g;f++)c=a.charCodeAt(f),55296===(64512&c)&&h>f+1&&(d=a.charCodeAt(f+1),56320===(64512&d)&&(c=65536+(c-55296<<10)+(d-56320),f++)),128>c?b[g++]=c:2048>c?(b[g++]=192|c>>>6,b[g++]=128|63&c):65536>c?(b[g++]=224|c>>>12,b[g++]=128|c>>>6&63,b[g++]=128|63&c):(b[g++]=240|c>>>18,b[g++]=128|c>>>12&63,b[g++]=128|c>>>6&63,b[g++]=128|63&c);return b},c.buf2binstring=function(a){return d(a,a.length)},c.binstring2buf=function(a){for(var b=new e.Buf8(a.length),c=0,d=b.length;d>c;c++)b[c]=a.charCodeAt(c);return b},c.buf2string=function(a,b){var c,e,f,g,h=b||a.length,j=new Array(2*h);for(e=0,c=0;h>c;)if(f=a[c++],128>f)j[e++]=f;else if(g=i[f],g>4)j[e++]=65533,c+=g-1;else{for(f&=2===g?31:3===g?15:7;g>1&&h>c;)f=f<<6|63&a[c++],g--;g>1?j[e++]=65533:65536>f?j[e++]=f:(f-=65536,j[e++]=55296|f>>10&1023,j[e++]=56320|1023&f)}return d(j,e)},c.utf8border=function(a,b){var c;for(b=b||a.length,b>a.length&&(b=a.length),c=b-1;c>=0&&128===(192&a[c]);)c--;return 0>c?b:0===c?b:c+i[a[c]]>b?c:b}},{"./common":86}],88:[function(a,b,c){"use strict";function d(a,b,c,d){for(var e=65535&a|0,f=a>>>16&65535|0,g=0;0!==c;){g=c>2e3?2e3:c,c-=g;do e=e+b[d++]|0,f=f+e|0;while(--g);e%=65521,f%=65521}return e|f<<16|0}b.exports=d},{}],89:[function(a,b,c){"use strict";b.exports={Z_NO_FLUSH:0,Z_PARTIAL_FLUSH:1,Z_SYNC_FLUSH:2,Z_FULL_FLUSH:3,Z_FINISH:4,Z_BLOCK:5,Z_TREES:6,Z_OK:0,Z_STREAM_END:1,Z_NEED_DICT:2,Z_ERRNO:-1,Z_STREAM_ERROR:-2,Z_DATA_ERROR:-3,Z_BUF_ERROR:-5,Z_NO_COMPRESSION:0,Z_BEST_SPEED:1,Z_BEST_COMPRESSION:9,Z_DEFAULT_COMPRESSION:-1,Z_FILTERED:1,Z_HUFFMAN_ONLY:2,Z_RLE:3,Z_FIXED:4,Z_DEFAULT_STRATEGY:0,Z_BINARY:0,Z_TEXT:1,Z_UNKNOWN:2,Z_DEFLATED:8}},{}],90:[function(a,b,c){"use strict";function d(){for(var a,b=[],c=0;256>c;c++){a=c;for(var d=0;8>d;d++)a=1&a?3988292384^a>>>1:a>>>1;b[c]=a}return b}function e(a,b,c,d){var e=f,g=d+c;a^=-1;for(var h=d;g>h;h++)a=a>>>8^e[255&(a^b[h])];return-1^a}var f=d();b.exports=e},{}],91:[function(a,b,c){"use strict";function d(a,b){return a.msg=H[b],b}function e(a){return(a<<1)-(a>4?9:0)}function f(a){for(var b=a.length;--b>=0;)a[b]=0}function g(a){var b=a.state,c=b.pending;c>a.avail_out&&(c=a.avail_out),0!==c&&(D.arraySet(a.output,b.pending_buf,b.pending_out,c,a.next_out),a.next_out+=c,b.pending_out+=c,a.total_out+=c,a.avail_out-=c,b.pending-=c,0===b.pending&&(b.pending_out=0))}function h(a,b){E._tr_flush_block(a,a.block_start>=0?a.block_start:-1,a.strstart-a.block_start,b),a.block_start=a.strstart,g(a.strm)}function i(a,b){a.pending_buf[a.pending++]=b}function j(a,b){a.pending_buf[a.pending++]=b>>>8&255,a.pending_buf[a.pending++]=255&b}function k(a,b,c,d){var e=a.avail_in;return e>d&&(e=d),0===e?0:(a.avail_in-=e,D.arraySet(b,a.input,a.next_in,e,c),1===a.state.wrap?a.adler=F(a.adler,b,e,c):2===a.state.wrap&&(a.adler=G(a.adler,b,e,c)),a.next_in+=e,a.total_in+=e,e)}function l(a,b){var c,d,e=a.max_chain_length,f=a.strstart,g=a.prev_length,h=a.nice_match,i=a.strstart>a.w_size-ka?a.strstart-(a.w_size-ka):0,j=a.window,k=a.w_mask,l=a.prev,m=a.strstart+ja,n=j[f+g-1],o=j[f+g];a.prev_length>=a.good_match&&(e>>=2),h>a.lookahead&&(h=a.lookahead);do if(c=b,j[c+g]===o&&j[c+g-1]===n&&j[c]===j[f]&&j[++c]===j[f+1]){f+=2,c++;do;while(j[++f]===j[++c]&&j[++f]===j[++c]&&j[++f]===j[++c]&&j[++f]===j[++c]&&j[++f]===j[++c]&&j[++f]===j[++c]&&j[++f]===j[++c]&&j[++f]===j[++c]&&m>f);if(d=ja-(m-f),f=m-ja,d>g){if(a.match_start=b,g=d,d>=h)break;n=j[f+g-1],o=j[f+g]}}while((b=l[b&k])>i&&0!==--e);return g<=a.lookahead?g:a.lookahead}function m(a){var b,c,d,e,f,g=a.w_size;do{if(e=a.window_size-a.lookahead-a.strstart,a.strstart>=g+(g-ka)){D.arraySet(a.window,a.window,g,g,0),a.match_start-=g,a.strstart-=g,a.block_start-=g,c=a.hash_size,b=c;do d=a.head[--b],a.head[b]=d>=g?d-g:0;while(--c);c=g,b=c;do d=a.prev[--b],a.prev[b]=d>=g?d-g:0;while(--c);e+=g}if(0===a.strm.avail_in)break;if(c=k(a.strm,a.window,a.strstart+a.lookahead,e),a.lookahead+=c,a.lookahead+a.insert>=ia)for(f=a.strstart-a.insert,a.ins_h=a.window[f],a.ins_h=(a.ins_h<<a.hash_shift^a.window[f+1])&a.hash_mask;a.insert&&(a.ins_h=(a.ins_h<<a.hash_shift^a.window[f+ia-1])&a.hash_mask,a.prev[f&a.w_mask]=a.head[a.ins_h],a.head[a.ins_h]=f,f++,a.insert--,!(a.lookahead+a.insert<ia)););}while(a.lookahead<ka&&0!==a.strm.avail_in)}function n(a,b){var c=65535;for(c>a.pending_buf_size-5&&(c=a.pending_buf_size-5);;){if(a.lookahead<=1){if(m(a),0===a.lookahead&&b===I)return ta;if(0===a.lookahead)break}a.strstart+=a.lookahead,a.lookahead=0;var d=a.block_start+c;if((0===a.strstart||a.strstart>=d)&&(a.lookahead=a.strstart-d,a.strstart=d,h(a,!1),0===a.strm.avail_out))return ta;if(a.strstart-a.block_start>=a.w_size-ka&&(h(a,!1),0===a.strm.avail_out))return ta}return a.insert=0,b===L?(h(a,!0),0===a.strm.avail_out?va:wa):a.strstart>a.block_start&&(h(a,!1),0===a.strm.avail_out)?ta:ta}function o(a,b){for(var c,d;;){if(a.lookahead<ka){if(m(a),a.lookahead<ka&&b===I)return ta;if(0===a.lookahead)break}if(c=0,a.lookahead>=ia&&(a.ins_h=(a.ins_h<<a.hash_shift^a.window[a.strstart+ia-1])&a.hash_mask,c=a.prev[a.strstart&a.w_mask]=a.head[a.ins_h],a.head[a.ins_h]=a.strstart),0!==c&&a.strstart-c<=a.w_size-ka&&(a.match_length=l(a,c)),a.match_length>=ia)if(d=E._tr_tally(a,a.strstart-a.match_start,a.match_length-ia),a.lookahead-=a.match_length,a.match_length<=a.max_lazy_match&&a.lookahead>=ia){a.match_length--;do a.strstart++,a.ins_h=(a.ins_h<<a.hash_shift^a.window[a.strstart+ia-1])&a.hash_mask,c=a.prev[a.strstart&a.w_mask]=a.head[a.ins_h],a.head[a.ins_h]=a.strstart;while(0!==--a.match_length);a.strstart++}else a.strstart+=a.match_length,a.match_length=0,a.ins_h=a.window[a.strstart],a.ins_h=(a.ins_h<<a.hash_shift^a.window[a.strstart+1])&a.hash_mask;else d=E._tr_tally(a,0,a.window[a.strstart]),a.lookahead--,a.strstart++;if(d&&(h(a,!1),0===a.strm.avail_out))return ta}return a.insert=a.strstart<ia-1?a.strstart:ia-1,b===L?(h(a,!0),0===a.strm.avail_out?va:wa):a.last_lit&&(h(a,!1),0===a.strm.avail_out)?ta:ua}function p(a,b){for(var c,d,e;;){if(a.lookahead<ka){if(m(a),a.lookahead<ka&&b===I)return ta;if(0===a.lookahead)break}if(c=0,a.lookahead>=ia&&(a.ins_h=(a.ins_h<<a.hash_shift^a.window[a.strstart+ia-1])&a.hash_mask,c=a.prev[a.strstart&a.w_mask]=a.head[a.ins_h],a.head[a.ins_h]=a.strstart),a.prev_length=a.match_length,a.prev_match=a.match_start,a.match_length=ia-1,0!==c&&a.prev_length<a.max_lazy_match&&a.strstart-c<=a.w_size-ka&&(a.match_length=l(a,c),a.match_length<=5&&(a.strategy===T||a.match_length===ia&&a.strstart-a.match_start>4096)&&(a.match_length=ia-1)),a.prev_length>=ia&&a.match_length<=a.prev_length){e=a.strstart+a.lookahead-ia,d=E._tr_tally(a,a.strstart-1-a.prev_match,a.prev_length-ia),a.lookahead-=a.prev_length-1,a.prev_length-=2;do++a.strstart<=e&&(a.ins_h=(a.ins_h<<a.hash_shift^a.window[a.strstart+ia-1])&a.hash_mask,c=a.prev[a.strstart&a.w_mask]=a.head[a.ins_h],a.head[a.ins_h]=a.strstart);while(0!==--a.prev_length);if(a.match_available=0,a.match_length=ia-1,a.strstart++,d&&(h(a,!1),0===a.strm.avail_out))return ta}else if(a.match_available){if(d=E._tr_tally(a,0,a.window[a.strstart-1]),d&&h(a,!1),a.strstart++,a.lookahead--,0===a.strm.avail_out)return ta}else a.match_available=1,a.strstart++,a.lookahead--}return a.match_available&&(d=E._tr_tally(a,0,a.window[a.strstart-1]),a.match_available=0),a.insert=a.strstart<ia-1?a.strstart:ia-1,b===L?(h(a,!0),0===a.strm.avail_out?va:wa):a.last_lit&&(h(a,!1),0===a.strm.avail_out)?ta:ua}function q(a,b){for(var c,d,e,f,g=a.window;;){if(a.lookahead<=ja){if(m(a),a.lookahead<=ja&&b===I)return ta;if(0===a.lookahead)break}if(a.match_length=0,a.lookahead>=ia&&a.strstart>0&&(e=a.strstart-1,d=g[e],d===g[++e]&&d===g[++e]&&d===g[++e])){f=a.strstart+ja;do;while(d===g[++e]&&d===g[++e]&&d===g[++e]&&d===g[++e]&&d===g[++e]&&d===g[++e]&&d===g[++e]&&d===g[++e]&&f>e);a.match_length=ja-(f-e),a.match_length>a.lookahead&&(a.match_length=a.lookahead)}if(a.match_length>=ia?(c=E._tr_tally(a,1,a.match_length-ia),a.lookahead-=a.match_length,a.strstart+=a.match_length,a.match_length=0):(c=E._tr_tally(a,0,a.window[a.strstart]),a.lookahead--,a.strstart++),c&&(h(a,!1),0===a.strm.avail_out))return ta}return a.insert=0,b===L?(h(a,!0),0===a.strm.avail_out?va:wa):a.last_lit&&(h(a,!1),0===a.strm.avail_out)?ta:ua}function r(a,b){for(var c;;){if(0===a.lookahead&&(m(a),0===a.lookahead)){if(b===I)return ta;break}if(a.match_length=0,c=E._tr_tally(a,0,a.window[a.strstart]),a.lookahead--,a.strstart++,c&&(h(a,!1),0===a.strm.avail_out))return ta}return a.insert=0,b===L?(h(a,!0),0===a.strm.avail_out?va:wa):a.last_lit&&(h(a,!1),0===a.strm.avail_out)?ta:ua}function s(a,b,c,d,e){this.good_length=a,this.max_lazy=b,this.nice_length=c,this.max_chain=d,this.func=e}function t(a){a.window_size=2*a.w_size,f(a.head),a.max_lazy_match=C[a.level].max_lazy,a.good_match=C[a.level].good_length,a.nice_match=C[a.level].nice_length,a.max_chain_length=C[a.level].max_chain,a.strstart=0,a.block_start=0,a.lookahead=0,a.insert=0,a.match_length=a.prev_length=ia-1,a.match_available=0,a.ins_h=0}function u(){this.strm=null,this.status=0,this.pending_buf=null,this.pending_buf_size=0,this.pending_out=0,this.pending=0,this.wrap=0,this.gzhead=null,this.gzindex=0,this.method=Z,this.last_flush=-1,this.w_size=0,this.w_bits=0,this.w_mask=0,this.window=null,this.window_size=0,this.prev=null,this.head=null,this.ins_h=0,this.hash_size=0,this.hash_bits=0,this.hash_mask=0,this.hash_shift=0,this.block_start=0,this.match_length=0,this.prev_match=0,this.match_available=0,this.strstart=0,this.match_start=0,this.lookahead=0,this.prev_length=0,this.max_chain_length=0,this.max_lazy_match=0,this.level=0,this.strategy=0,this.good_match=0,this.nice_match=0,this.dyn_ltree=new D.Buf16(2*ga),this.dyn_dtree=new D.Buf16(2*(2*ea+1)),this.bl_tree=new D.Buf16(2*(2*fa+1)),f(this.dyn_ltree),f(this.dyn_dtree),f(this.bl_tree),this.l_desc=null,this.d_desc=null,this.bl_desc=null,this.bl_count=new D.Buf16(ha+1),this.heap=new D.Buf16(2*da+1),f(this.heap),this.heap_len=0,this.heap_max=0,this.depth=new D.Buf16(2*da+1),f(this.depth),this.l_buf=0,this.lit_bufsize=0,this.last_lit=0,this.d_buf=0,this.opt_len=0,this.static_len=0,this.matches=0,this.insert=0,this.bi_buf=0,this.bi_valid=0}function v(a){var b;return a&&a.state?(a.total_in=a.total_out=0,a.data_type=Y,b=a.state,b.pending=0,b.pending_out=0,b.wrap<0&&(b.wrap=-b.wrap),b.status=b.wrap?ma:ra,a.adler=2===b.wrap?0:1,b.last_flush=I,E._tr_init(b),N):d(a,P)}function w(a){var b=v(a);return b===N&&t(a.state),b}function x(a,b){return a&&a.state?2!==a.state.wrap?P:(a.state.gzhead=b,N):P}function y(a,b,c,e,f,g){if(!a)return P;var h=1;if(b===S&&(b=6),0>e?(h=0,e=-e):e>15&&(h=2,e-=16),1>f||f>$||c!==Z||8>e||e>15||0>b||b>9||0>g||g>W)return d(a,P);8===e&&(e=9);var i=new u;return a.state=i,i.strm=a,i.wrap=h,i.gzhead=null,i.w_bits=e,i.w_size=1<<i.w_bits,i.w_mask=i.w_size-1,i.hash_bits=f+7,i.hash_size=1<<i.hash_bits,i.hash_mask=i.hash_size-1,i.hash_shift=~~((i.hash_bits+ia-1)/ia),i.window=new D.Buf8(2*i.w_size),i.head=new D.Buf16(i.hash_size),i.prev=new D.Buf16(i.w_size),i.lit_bufsize=1<<f+6,i.pending_buf_size=4*i.lit_bufsize,i.pending_buf=new D.Buf8(i.pending_buf_size),i.d_buf=i.lit_bufsize>>1,i.l_buf=3*i.lit_bufsize,i.level=b,i.strategy=g,i.method=c,w(a)}function z(a,b){return y(a,b,Z,_,aa,X)}function A(a,b){var c,h,k,l;if(!a||!a.state||b>M||0>b)return a?d(a,P):P;if(h=a.state,!a.output||!a.input&&0!==a.avail_in||h.status===sa&&b!==L)return d(a,0===a.avail_out?R:P);if(h.strm=a,c=h.last_flush,h.last_flush=b,h.status===ma)if(2===h.wrap)a.adler=0,i(h,31),i(h,139),i(h,8),h.gzhead?(i(h,(h.gzhead.text?1:0)+(h.gzhead.hcrc?2:0)+(h.gzhead.extra?4:0)+(h.gzhead.name?8:0)+(h.gzhead.comment?16:0)),i(h,255&h.gzhead.time),i(h,h.gzhead.time>>8&255),i(h,h.gzhead.time>>16&255),i(h,h.gzhead.time>>24&255),i(h,9===h.level?2:h.strategy>=U||h.level<2?4:0),i(h,255&h.gzhead.os),h.gzhead.extra&&h.gzhead.extra.length&&(i(h,255&h.gzhead.extra.length),i(h,h.gzhead.extra.length>>8&255)),h.gzhead.hcrc&&(a.adler=G(a.adler,h.pending_buf,h.pending,0)),h.gzindex=0,h.status=na):(i(h,0),i(h,0),i(h,0),i(h,0),i(h,0),i(h,9===h.level?2:h.strategy>=U||h.level<2?4:0),i(h,xa),h.status=ra);else{var m=Z+(h.w_bits-8<<4)<<8,n=-1;n=h.strategy>=U||h.level<2?0:h.level<6?1:6===h.level?2:3,m|=n<<6,0!==h.strstart&&(m|=la),m+=31-m%31,h.status=ra,j(h,m),0!==h.strstart&&(j(h,a.adler>>>16),j(h,65535&a.adler)),a.adler=1}if(h.status===na)if(h.gzhead.extra){for(k=h.pending;h.gzindex<(65535&h.gzhead.extra.length)&&(h.pending!==h.pending_buf_size||(h.gzhead.hcrc&&h.pending>k&&(a.adler=G(a.adler,h.pending_buf,h.pending-k,k)),g(a),k=h.pending,h.pending!==h.pending_buf_size));)i(h,255&h.gzhead.extra[h.gzindex]),h.gzindex++;h.gzhead.hcrc&&h.pending>k&&(a.adler=G(a.adler,h.pending_buf,h.pending-k,k)),h.gzindex===h.gzhead.extra.length&&(h.gzindex=0,h.status=oa)}else h.status=oa;if(h.status===oa)if(h.gzhead.name){k=h.pending;do{if(h.pending===h.pending_buf_size&&(h.gzhead.hcrc&&h.pending>k&&(a.adler=G(a.adler,h.pending_buf,h.pending-k,k)),g(a),k=h.pending,h.pending===h.pending_buf_size)){l=1;break}l=h.gzindex<h.gzhead.name.length?255&h.gzhead.name.charCodeAt(h.gzindex++):0,i(h,l)}while(0!==l);h.gzhead.hcrc&&h.pending>k&&(a.adler=G(a.adler,h.pending_buf,h.pending-k,k)),0===l&&(h.gzindex=0,h.status=pa)}else h.status=pa;if(h.status===pa)if(h.gzhead.comment){k=h.pending;do{if(h.pending===h.pending_buf_size&&(h.gzhead.hcrc&&h.pending>k&&(a.adler=G(a.adler,h.pending_buf,h.pending-k,k)),g(a),k=h.pending,h.pending===h.pending_buf_size)){l=1;break}l=h.gzindex<h.gzhead.comment.length?255&h.gzhead.comment.charCodeAt(h.gzindex++):0,i(h,l)}while(0!==l);h.gzhead.hcrc&&h.pending>k&&(a.adler=G(a.adler,h.pending_buf,h.pending-k,k)),0===l&&(h.status=qa)}else h.status=qa;if(h.status===qa&&(h.gzhead.hcrc?(h.pending+2>h.pending_buf_size&&g(a),h.pending+2<=h.pending_buf_size&&(i(h,255&a.adler),i(h,a.adler>>8&255),a.adler=0,h.status=ra)):h.status=ra),0!==h.pending){if(g(a),0===a.avail_out)return h.last_flush=-1,N}else if(0===a.avail_in&&e(b)<=e(c)&&b!==L)return d(a,R);if(h.status===sa&&0!==a.avail_in)return d(a,R);if(0!==a.avail_in||0!==h.lookahead||b!==I&&h.status!==sa){var o=h.strategy===U?r(h,b):h.strategy===V?q(h,b):C[h.level].func(h,b);if(o!==va&&o!==wa||(h.status=sa),o===ta||o===va)return 0===a.avail_out&&(h.last_flush=-1),N;if(o===ua&&(b===J?E._tr_align(h):b!==M&&(E._tr_stored_block(h,0,0,!1),b===K&&(f(h.head),0===h.lookahead&&(h.strstart=0,h.block_start=0,h.insert=0))),g(a),0===a.avail_out))return h.last_flush=-1,N}return b!==L?N:h.wrap<=0?O:(2===h.wrap?(i(h,255&a.adler),i(h,a.adler>>8&255),i(h,a.adler>>16&255),i(h,a.adler>>24&255),i(h,255&a.total_in),i(h,a.total_in>>8&255),i(h,a.total_in>>16&255),i(h,a.total_in>>24&255)):(j(h,a.adler>>>16),j(h,65535&a.adler)),g(a),h.wrap>0&&(h.wrap=-h.wrap),0!==h.pending?N:O)}function B(a){var b;return a&&a.state?(b=a.state.status,b!==ma&&b!==na&&b!==oa&&b!==pa&&b!==qa&&b!==ra&&b!==sa?d(a,P):(a.state=null,b===ra?d(a,Q):N)):P}var C,D=a("../utils/common"),E=a("./trees"),F=a("./adler32"),G=a("./crc32"),H=a("./messages"),I=0,J=1,K=3,L=4,M=5,N=0,O=1,P=-2,Q=-3,R=-5,S=-1,T=1,U=2,V=3,W=4,X=0,Y=2,Z=8,$=9,_=15,aa=8,ba=29,ca=256,da=ca+1+ba,ea=30,fa=19,ga=2*da+1,ha=15,ia=3,ja=258,ka=ja+ia+1,la=32,ma=42,na=69,oa=73,pa=91,qa=103,ra=113,sa=666,ta=1,ua=2,va=3,wa=4,xa=3;C=[new s(0,0,0,0,n),new s(4,4,8,4,o),new s(4,5,16,8,o),new s(4,6,32,32,o),new s(4,4,16,16,p),new s(8,16,32,32,p),new s(8,16,128,128,p),new s(8,32,128,256,p),new s(32,128,258,1024,p),new s(32,258,258,4096,p)],c.deflateInit=z,c.deflateInit2=y,c.deflateReset=w,c.deflateResetKeep=v,c.deflateSetHeader=x,c.deflate=A,c.deflateEnd=B,c.deflateInfo="pako deflate (from Nodeca project)"},{"../utils/common":86,"./adler32":88,"./crc32":90,"./messages":96,"./trees":97}],92:[function(a,b,c){"use strict";function d(){this.text=0,this.time=0,this.xflags=0,this.os=0,this.extra=null,this.extra_len=0,this.name="",this.comment="",this.hcrc=0,this.done=!1}b.exports=d},{}],93:[function(a,b,c){"use strict";var d=30,e=12;b.exports=function(a,b){var c,f,g,h,i,j,k,l,m,n,o,p,q,r,s,t,u,v,w,x,y,z,A,B,C;c=a.state,f=a.next_in,B=a.input,g=f+(a.avail_in-5),h=a.next_out,C=a.output,i=h-(b-a.avail_out),j=h+(a.avail_out-257),k=c.dmax,l=c.wsize,m=c.whave,n=c.wnext,o=c.window,p=c.hold,q=c.bits,r=c.lencode,s=c.distcode,t=(1<<c.lenbits)-1,u=(1<<c.distbits)-1;a:do{15>q&&(p+=B[f++]<<q,q+=8,p+=B[f++]<<q,q+=8),v=r[p&t];b:for(;;){if(w=v>>>24,p>>>=w,q-=w,w=v>>>16&255,0===w)C[h++]=65535&v;else{if(!(16&w)){if(0===(64&w)){v=r[(65535&v)+(p&(1<<w)-1)];continue b}if(32&w){c.mode=e;break a}a.msg="invalid literal/length code",c.mode=d;break a}x=65535&v,w&=15,w&&(w>q&&(p+=B[f++]<<q,q+=8),x+=p&(1<<w)-1,p>>>=w,q-=w),15>q&&(p+=B[f++]<<q,q+=8,p+=B[f++]<<q,q+=8),v=s[p&u];c:for(;;){if(w=v>>>24,p>>>=w,q-=w,w=v>>>16&255,!(16&w)){if(0===(64&w)){v=s[(65535&v)+(p&(1<<w)-1)];continue c}a.msg="invalid distance code",c.mode=d;break a}if(y=65535&v,w&=15,w>q&&(p+=B[f++]<<q,q+=8,w>q&&(p+=B[f++]<<q,q+=8)),y+=p&(1<<w)-1,y>k){a.msg="invalid distance too far back",c.mode=d;break a}if(p>>>=w,q-=w,w=h-i,y>w){if(w=y-w,w>m&&c.sane){a.msg="invalid distance too far back",c.mode=d;break a}if(z=0,A=o,0===n){if(z+=l-w,x>w){x-=w;do C[h++]=o[z++];while(--w);z=h-y,A=C}}else if(w>n){if(z+=l+n-w,w-=n,x>w){x-=w;do C[h++]=o[z++];while(--w);if(z=0,x>n){w=n,x-=w;do C[h++]=o[z++];while(--w);z=h-y,A=C}}}else if(z+=n-w,x>w){x-=w;do C[h++]=o[z++];while(--w);z=h-y,A=C}for(;x>2;)C[h++]=A[z++],C[h++]=A[z++],C[h++]=A[z++],x-=3;x&&(C[h++]=A[z++],x>1&&(C[h++]=A[z++]))}else{z=h-y;do C[h++]=C[z++],C[h++]=C[z++],C[h++]=C[z++],x-=3;while(x>2);x&&(C[h++]=C[z++],x>1&&(C[h++]=C[z++]))}break}}break}}while(g>f&&j>h);x=q>>3,f-=x,q-=x<<3,p&=(1<<q)-1,a.next_in=f,a.next_out=h,a.avail_in=g>f?5+(g-f):5-(f-g),a.avail_out=j>h?257+(j-h):257-(h-j),c.hold=p,c.bits=q}},{}],94:[function(a,b,c){"use strict";function d(a){return(a>>>24&255)+(a>>>8&65280)+((65280&a)<<8)+((255&a)<<24)}function e(){this.mode=0,this.last=!1,this.wrap=0,this.havedict=!1,this.flags=0,this.dmax=0,this.check=0,this.total=0,this.head=null,this.wbits=0,this.wsize=0,this.whave=0,this.wnext=0,this.window=null,this.hold=0,this.bits=0,this.length=0,this.offset=0,this.extra=0,this.lencode=null,this.distcode=null,this.lenbits=0,this.distbits=0,this.ncode=0,this.nlen=0,this.ndist=0,this.have=0,this.next=null,this.lens=new r.Buf16(320),this.work=new r.Buf16(288),this.lendyn=null,this.distdyn=null,this.sane=0,this.back=0,this.was=0}function f(a){var b;return a&&a.state?(b=a.state,a.total_in=a.total_out=b.total=0,a.msg="",b.wrap&&(a.adler=1&b.wrap),b.mode=K,b.last=0,b.havedict=0,b.dmax=32768,b.head=null,b.hold=0,b.bits=0,b.lencode=b.lendyn=new r.Buf32(oa),b.distcode=b.distdyn=new r.Buf32(pa),b.sane=1,b.back=-1,C):F}function g(a){var b;return a&&a.state?(b=a.state,b.wsize=0,b.whave=0,b.wnext=0,f(a)):F}function h(a,b){var c,d;return a&&a.state?(d=a.state,0>b?(c=0,b=-b):(c=(b>>4)+1,48>b&&(b&=15)),b&&(8>b||b>15)?F:(null!==d.window&&d.wbits!==b&&(d.window=null),d.wrap=c,d.wbits=b,g(a))):F}function i(a,b){var c,d;return a?(d=new e,a.state=d,d.window=null,c=h(a,b),c!==C&&(a.state=null),c):F}function j(a){return i(a,ra)}function k(a){if(sa){var b;for(p=new r.Buf32(512),q=new r.Buf32(32),b=0;144>b;)a.lens[b++]=8;for(;256>b;)a.lens[b++]=9;for(;280>b;)a.lens[b++]=7;for(;288>b;)a.lens[b++]=8;for(v(x,a.lens,0,288,p,0,a.work,{bits:9}),b=0;32>b;)a.lens[b++]=5;v(y,a.lens,0,32,q,0,a.work,{bits:5}),sa=!1}a.lencode=p,a.lenbits=9,a.distcode=q,a.distbits=5}function l(a,b,c,d){var e,f=a.state;return null===f.window&&(f.wsize=1<<f.wbits,f.wnext=0,f.whave=0,f.window=new r.Buf8(f.wsize)),d>=f.wsize?(r.arraySet(f.window,b,c-f.wsize,f.wsize,0),f.wnext=0,f.whave=f.wsize):(e=f.wsize-f.wnext,e>d&&(e=d),r.arraySet(f.window,b,c-d,e,f.wnext),d-=e,d?(r.arraySet(f.window,b,c-d,d,0),f.wnext=d,f.whave=f.wsize):(f.wnext+=e,f.wnext===f.wsize&&(f.wnext=0),f.whave<f.wsize&&(f.whave+=e))),0}function m(a,b){var c,e,f,g,h,i,j,m,n,o,p,q,oa,pa,qa,ra,sa,ta,ua,va,wa,xa,ya,za,Aa=0,Ba=new r.Buf8(4),Ca=[16,17,18,0,8,7,9,6,10,5,11,4,12,3,13,2,14,1,15];if(!a||!a.state||!a.output||!a.input&&0!==a.avail_in)return F;c=a.state,c.mode===V&&(c.mode=W),h=a.next_out,f=a.output,j=a.avail_out,g=a.next_in,e=a.input,i=a.avail_in,m=c.hold,n=c.bits,o=i,p=j,xa=C;a:for(;;)switch(c.mode){case K:if(0===c.wrap){c.mode=W;break}for(;16>n;){if(0===i)break a;i--,m+=e[g++]<<n,n+=8}if(2&c.wrap&&35615===m){c.check=0,Ba[0]=255&m,Ba[1]=m>>>8&255,c.check=t(c.check,Ba,2,0),m=0,n=0,c.mode=L;break}if(c.flags=0,c.head&&(c.head.done=!1),!(1&c.wrap)||(((255&m)<<8)+(m>>8))%31){a.msg="incorrect header check",c.mode=la;break}if((15&m)!==J){a.msg="unknown compression method",c.mode=la;break}if(m>>>=4,n-=4,wa=(15&m)+8,0===c.wbits)c.wbits=wa;else if(wa>c.wbits){a.msg="invalid window size",c.mode=la;break}c.dmax=1<<wa,a.adler=c.check=1,c.mode=512&m?T:V,m=0,n=0;break;case L:for(;16>n;){if(0===i)break a;i--,m+=e[g++]<<n,n+=8}if(c.flags=m,(255&c.flags)!==J){a.msg="unknown compression method",c.mode=la;break}if(57344&c.flags){a.msg="unknown header flags set",c.mode=la;break}c.head&&(c.head.text=m>>8&1),512&c.flags&&(Ba[0]=255&m,Ba[1]=m>>>8&255,c.check=t(c.check,Ba,2,0)),m=0,n=0,c.mode=M;case M:for(;32>n;){if(0===i)break a;i--,m+=e[g++]<<n,n+=8}c.head&&(c.head.time=m),512&c.flags&&(Ba[0]=255&m,Ba[1]=m>>>8&255,Ba[2]=m>>>16&255,Ba[3]=m>>>24&255,c.check=t(c.check,Ba,4,0)),m=0,n=0,c.mode=N;case N:for(;16>n;){if(0===i)break a;i--,m+=e[g++]<<n,n+=8}c.head&&(c.head.xflags=255&m,c.head.os=m>>8),512&c.flags&&(Ba[0]=255&m,Ba[1]=m>>>8&255,c.check=t(c.check,Ba,2,0)),m=0,n=0,c.mode=O;case O:if(1024&c.flags){for(;16>n;){if(0===i)break a;i--,m+=e[g++]<<n,n+=8}c.length=m,c.head&&(c.head.extra_len=m),512&c.flags&&(Ba[0]=255&m,Ba[1]=m>>>8&255,c.check=t(c.check,Ba,2,0)),m=0,n=0}else c.head&&(c.head.extra=null);c.mode=P;case P:if(1024&c.flags&&(q=c.length,q>i&&(q=i),q&&(c.head&&(wa=c.head.extra_len-c.length,c.head.extra||(c.head.extra=new Array(c.head.extra_len)),r.arraySet(c.head.extra,e,g,q,wa)),512&c.flags&&(c.check=t(c.check,e,q,g)),i-=q,g+=q,c.length-=q),c.length))break a;c.length=0,c.mode=Q;case Q:if(2048&c.flags){if(0===i)break a;q=0;do wa=e[g+q++],c.head&&wa&&c.length<65536&&(c.head.name+=String.fromCharCode(wa));while(wa&&i>q);if(512&c.flags&&(c.check=t(c.check,e,q,g)),i-=q,g+=q,wa)break a}else c.head&&(c.head.name=null);c.length=0,c.mode=R;case R:if(4096&c.flags){if(0===i)break a;q=0;do wa=e[g+q++],c.head&&wa&&c.length<65536&&(c.head.comment+=String.fromCharCode(wa));while(wa&&i>q);if(512&c.flags&&(c.check=t(c.check,e,q,g)),i-=q,g+=q,wa)break a}else c.head&&(c.head.comment=null);c.mode=S;case S:if(512&c.flags){for(;16>n;){if(0===i)break a;i--,m+=e[g++]<<n,n+=8}if(m!==(65535&c.check)){a.msg="header crc mismatch",c.mode=la;break}m=0,n=0}c.head&&(c.head.hcrc=c.flags>>9&1,c.head.done=!0),a.adler=c.check=0,c.mode=V;break;case T:for(;32>n;){if(0===i)break a;i--,m+=e[g++]<<n,n+=8}a.adler=c.check=d(m),m=0,n=0,c.mode=U;case U:if(0===c.havedict)return a.next_out=h,a.avail_out=j,a.next_in=g,a.avail_in=i,c.hold=m,c.bits=n,E;a.adler=c.check=1,c.mode=V;case V:if(b===A||b===B)break a;case W:if(c.last){m>>>=7&n,n-=7&n,c.mode=ia;break}for(;3>n;){if(0===i)break a;i--,m+=e[g++]<<n,n+=8}switch(c.last=1&m,m>>>=1,n-=1,3&m){case 0:c.mode=X;break;case 1:if(k(c),c.mode=ba,b===B){m>>>=2,n-=2;break a}break;case 2:c.mode=$;break;case 3:a.msg="invalid block type",c.mode=la}m>>>=2,n-=2;break;case X:for(m>>>=7&n,n-=7&n;32>n;){if(0===i)break a;i--,m+=e[g++]<<n,n+=8}if((65535&m)!==(m>>>16^65535)){a.msg="invalid stored block lengths",c.mode=la;break}if(c.length=65535&m,m=0,n=0,c.mode=Y,b===B)break a;case Y:c.mode=Z;case Z:if(q=c.length){if(q>i&&(q=i),q>j&&(q=j),0===q)break a;r.arraySet(f,e,g,q,h),i-=q,g+=q,j-=q,h+=q,c.length-=q;break}c.mode=V;break;case $:for(;14>n;){if(0===i)break a;i--,m+=e[g++]<<n,n+=8}if(c.nlen=(31&m)+257,m>>>=5,n-=5,c.ndist=(31&m)+1,m>>>=5,n-=5,c.ncode=(15&m)+4,m>>>=4,n-=4,c.nlen>286||c.ndist>30){a.msg="too many length or distance symbols",c.mode=la;break}c.have=0,c.mode=_;case _:for(;c.have<c.ncode;){for(;3>n;){if(0===i)break a;i--,m+=e[g++]<<n,n+=8}c.lens[Ca[c.have++]]=7&m,m>>>=3,n-=3}for(;c.have<19;)c.lens[Ca[c.have++]]=0;if(c.lencode=c.lendyn,c.lenbits=7,ya={bits:c.lenbits},xa=v(w,c.lens,0,19,c.lencode,0,c.work,ya),c.lenbits=ya.bits,xa){a.msg="invalid code lengths set",c.mode=la;break}c.have=0,c.mode=aa;case aa:for(;c.have<c.nlen+c.ndist;){for(;Aa=c.lencode[m&(1<<c.lenbits)-1],qa=Aa>>>24,ra=Aa>>>16&255,sa=65535&Aa,!(n>=qa);){if(0===i)break a;i--,m+=e[g++]<<n,n+=8}if(16>sa)m>>>=qa,n-=qa,c.lens[c.have++]=sa;else{if(16===sa){for(za=qa+2;za>n;){if(0===i)break a;i--,m+=e[g++]<<n,n+=8}if(m>>>=qa,n-=qa,0===c.have){a.msg="invalid bit length repeat",c.mode=la;break}wa=c.lens[c.have-1],q=3+(3&m),m>>>=2,n-=2}else if(17===sa){for(za=qa+3;za>n;){if(0===i)break a;i--,m+=e[g++]<<n,n+=8}m>>>=qa,n-=qa,wa=0,q=3+(7&m),m>>>=3,n-=3}else{for(za=qa+7;za>n;){if(0===i)break a;i--,m+=e[g++]<<n,n+=8}m>>>=qa,n-=qa,wa=0,q=11+(127&m),m>>>=7,n-=7}if(c.have+q>c.nlen+c.ndist){a.msg="invalid bit length repeat",c.mode=la;break}for(;q--;)c.lens[c.have++]=wa}}if(c.mode===la)break;if(0===c.lens[256]){a.msg="invalid code -- missing end-of-block",c.mode=la;break}if(c.lenbits=9,ya={bits:c.lenbits},xa=v(x,c.lens,0,c.nlen,c.lencode,0,c.work,ya),c.lenbits=ya.bits,xa){a.msg="invalid literal/lengths set",c.mode=la;break}if(c.distbits=6,c.distcode=c.distdyn,ya={bits:c.distbits},xa=v(y,c.lens,c.nlen,c.ndist,c.distcode,0,c.work,ya),c.distbits=ya.bits,xa){a.msg="invalid distances set",c.mode=la;break}if(c.mode=ba,b===B)break a;case ba:c.mode=ca;case ca:if(i>=6&&j>=258){a.next_out=h,a.avail_out=j,a.next_in=g,a.avail_in=i,c.hold=m,c.bits=n,u(a,p),h=a.next_out,f=a.output,j=a.avail_out,g=a.next_in,e=a.input,i=a.avail_in,m=c.hold,n=c.bits,c.mode===V&&(c.back=-1);break}for(c.back=0;Aa=c.lencode[m&(1<<c.lenbits)-1],qa=Aa>>>24,ra=Aa>>>16&255,sa=65535&Aa,!(n>=qa);){if(0===i)break a;i--,m+=e[g++]<<n,n+=8}if(ra&&0===(240&ra)){for(ta=qa,ua=ra,va=sa;Aa=c.lencode[va+((m&(1<<ta+ua)-1)>>ta)],qa=Aa>>>24,ra=Aa>>>16&255,sa=65535&Aa,!(n>=ta+qa);){if(0===i)break a;i--,m+=e[g++]<<n,n+=8}m>>>=ta,n-=ta,c.back+=ta}if(m>>>=qa,n-=qa,c.back+=qa,c.length=sa,0===ra){c.mode=ha;break}if(32&ra){c.back=-1,c.mode=V;break}if(64&ra){a.msg="invalid literal/length code",c.mode=la;break}c.extra=15&ra,c.mode=da;case da:if(c.extra){for(za=c.extra;za>n;){if(0===i)break a;i--,m+=e[g++]<<n,n+=8}c.length+=m&(1<<c.extra)-1,m>>>=c.extra,n-=c.extra,c.back+=c.extra}c.was=c.length,c.mode=ea;case ea:for(;Aa=c.distcode[m&(1<<c.distbits)-1],qa=Aa>>>24,ra=Aa>>>16&255,sa=65535&Aa,!(n>=qa);){if(0===i)break a;i--,m+=e[g++]<<n,n+=8}if(0===(240&ra)){for(ta=qa,ua=ra,va=sa;Aa=c.distcode[va+((m&(1<<ta+ua)-1)>>ta)],qa=Aa>>>24,ra=Aa>>>16&255,sa=65535&Aa,!(n>=ta+qa);){if(0===i)break a;i--,m+=e[g++]<<n,n+=8}m>>>=ta,n-=ta,c.back+=ta}if(m>>>=qa,n-=qa,c.back+=qa,64&ra){a.msg="invalid distance code",c.mode=la;break}c.offset=sa,c.extra=15&ra,c.mode=fa;case fa:if(c.extra){for(za=c.extra;za>n;){if(0===i)break a;i--,m+=e[g++]<<n,n+=8}c.offset+=m&(1<<c.extra)-1,m>>>=c.extra,n-=c.extra,c.back+=c.extra}if(c.offset>c.dmax){a.msg="invalid distance too far back",c.mode=la;break}c.mode=ga;case ga:if(0===j)break a;if(q=p-j,c.offset>q){if(q=c.offset-q,q>c.whave&&c.sane){a.msg="invalid distance too far back",c.mode=la;break}q>c.wnext?(q-=c.wnext,oa=c.wsize-q):oa=c.wnext-q,q>c.length&&(q=c.length),pa=c.window}else pa=f,oa=h-c.offset, q=c.length;q>j&&(q=j),j-=q,c.length-=q;do f[h++]=pa[oa++];while(--q);0===c.length&&(c.mode=ca);break;case ha:if(0===j)break a;f[h++]=c.length,j--,c.mode=ca;break;case ia:if(c.wrap){for(;32>n;){if(0===i)break a;i--,m|=e[g++]<<n,n+=8}if(p-=j,a.total_out+=p,c.total+=p,p&&(a.adler=c.check=c.flags?t(c.check,f,p,h-p):s(c.check,f,p,h-p)),p=j,(c.flags?m:d(m))!==c.check){a.msg="incorrect data check",c.mode=la;break}m=0,n=0}c.mode=ja;case ja:if(c.wrap&&c.flags){for(;32>n;){if(0===i)break a;i--,m+=e[g++]<<n,n+=8}if(m!==(4294967295&c.total)){a.msg="incorrect length check",c.mode=la;break}m=0,n=0}c.mode=ka;case ka:xa=D;break a;case la:xa=G;break a;case ma:return H;case na:default:return F}return a.next_out=h,a.avail_out=j,a.next_in=g,a.avail_in=i,c.hold=m,c.bits=n,(c.wsize||p!==a.avail_out&&c.mode<la&&(c.mode<ia||b!==z))&&l(a,a.output,a.next_out,p-a.avail_out)?(c.mode=ma,H):(o-=a.avail_in,p-=a.avail_out,a.total_in+=o,a.total_out+=p,c.total+=p,c.wrap&&p&&(a.adler=c.check=c.flags?t(c.check,f,p,a.next_out-p):s(c.check,f,p,a.next_out-p)),a.data_type=c.bits+(c.last?64:0)+(c.mode===V?128:0)+(c.mode===ba||c.mode===Y?256:0),(0===o&&0===p||b===z)&&xa===C&&(xa=I),xa)}function n(a){if(!a||!a.state)return F;var b=a.state;return b.window&&(b.window=null),a.state=null,C}function o(a,b){var c;return a&&a.state?(c=a.state,0===(2&c.wrap)?F:(c.head=b,b.done=!1,C)):F}var p,q,r=a("../utils/common"),s=a("./adler32"),t=a("./crc32"),u=a("./inffast"),v=a("./inftrees"),w=0,x=1,y=2,z=4,A=5,B=6,C=0,D=1,E=2,F=-2,G=-3,H=-4,I=-5,J=8,K=1,L=2,M=3,N=4,O=5,P=6,Q=7,R=8,S=9,T=10,U=11,V=12,W=13,X=14,Y=15,Z=16,$=17,_=18,aa=19,ba=20,ca=21,da=22,ea=23,fa=24,ga=25,ha=26,ia=27,ja=28,ka=29,la=30,ma=31,na=32,oa=852,pa=592,qa=15,ra=qa,sa=!0;c.inflateReset=g,c.inflateReset2=h,c.inflateResetKeep=f,c.inflateInit=j,c.inflateInit2=i,c.inflate=m,c.inflateEnd=n,c.inflateGetHeader=o,c.inflateInfo="pako inflate (from Nodeca project)"},{"../utils/common":86,"./adler32":88,"./crc32":90,"./inffast":93,"./inftrees":95}],95:[function(a,b,c){"use strict";var d=a("../utils/common"),e=15,f=852,g=592,h=0,i=1,j=2,k=[3,4,5,6,7,8,9,10,11,13,15,17,19,23,27,31,35,43,51,59,67,83,99,115,131,163,195,227,258,0,0],l=[16,16,16,16,16,16,16,16,17,17,17,17,18,18,18,18,19,19,19,19,20,20,20,20,21,21,21,21,16,72,78],m=[1,2,3,4,5,7,9,13,17,25,33,49,65,97,129,193,257,385,513,769,1025,1537,2049,3073,4097,6145,8193,12289,16385,24577,0,0],n=[16,16,16,16,17,17,18,18,19,19,20,20,21,21,22,22,23,23,24,24,25,25,26,26,27,27,28,28,29,29,64,64];b.exports=function(a,b,c,o,p,q,r,s){var t,u,v,w,x,y,z,A,B,C=s.bits,D=0,E=0,F=0,G=0,H=0,I=0,J=0,K=0,L=0,M=0,N=null,O=0,P=new d.Buf16(e+1),Q=new d.Buf16(e+1),R=null,S=0;for(D=0;e>=D;D++)P[D]=0;for(E=0;o>E;E++)P[b[c+E]]++;for(H=C,G=e;G>=1&&0===P[G];G--);if(H>G&&(H=G),0===G)return p[q++]=20971520,p[q++]=20971520,s.bits=1,0;for(F=1;G>F&&0===P[F];F++);for(F>H&&(H=F),K=1,D=1;e>=D;D++)if(K<<=1,K-=P[D],0>K)return-1;if(K>0&&(a===h||1!==G))return-1;for(Q[1]=0,D=1;e>D;D++)Q[D+1]=Q[D]+P[D];for(E=0;o>E;E++)0!==b[c+E]&&(r[Q[b[c+E]]++]=E);if(a===h?(N=R=r,y=19):a===i?(N=k,O-=257,R=l,S-=257,y=256):(N=m,R=n,y=-1),M=0,E=0,D=F,x=q,I=H,J=0,v=-1,L=1<<H,w=L-1,a===i&&L>f||a===j&&L>g)return 1;for(var T=0;;){T++,z=D-J,r[E]<y?(A=0,B=r[E]):r[E]>y?(A=R[S+r[E]],B=N[O+r[E]]):(A=96,B=0),t=1<<D-J,u=1<<I,F=u;do u-=t,p[x+(M>>J)+u]=z<<24|A<<16|B|0;while(0!==u);for(t=1<<D-1;M&t;)t>>=1;if(0!==t?(M&=t-1,M+=t):M=0,E++,0===--P[D]){if(D===G)break;D=b[c+r[E]]}if(D>H&&(M&w)!==v){for(0===J&&(J=H),x+=F,I=D-J,K=1<<I;G>I+J&&(K-=P[I+J],!(0>=K));)I++,K<<=1;if(L+=1<<I,a===i&&L>f||a===j&&L>g)return 1;v=M&w,p[v]=H<<24|I<<16|x-q|0}}return 0!==M&&(p[x+M]=D-J<<24|64<<16|0),s.bits=H,0}},{"../utils/common":86}],96:[function(a,b,c){"use strict";b.exports={2:"need dictionary",1:"stream end",0:"","-1":"file error","-2":"stream error","-3":"data error","-4":"insufficient memory","-5":"buffer error","-6":"incompatible version"}},{}],97:[function(a,b,c){"use strict";function d(a){for(var b=a.length;--b>=0;)a[b]=0}function e(a,b,c,d,e){this.static_tree=a,this.extra_bits=b,this.extra_base=c,this.elems=d,this.max_length=e,this.has_stree=a&&a.length}function f(a,b){this.dyn_tree=a,this.max_code=0,this.stat_desc=b}function g(a){return 256>a?ia[a]:ia[256+(a>>>7)]}function h(a,b){a.pending_buf[a.pending++]=255&b,a.pending_buf[a.pending++]=b>>>8&255}function i(a,b,c){a.bi_valid>X-c?(a.bi_buf|=b<<a.bi_valid&65535,h(a,a.bi_buf),a.bi_buf=b>>X-a.bi_valid,a.bi_valid+=c-X):(a.bi_buf|=b<<a.bi_valid&65535,a.bi_valid+=c)}function j(a,b,c){i(a,c[2*b],c[2*b+1])}function k(a,b){var c=0;do c|=1&a,a>>>=1,c<<=1;while(--b>0);return c>>>1}function l(a){16===a.bi_valid?(h(a,a.bi_buf),a.bi_buf=0,a.bi_valid=0):a.bi_valid>=8&&(a.pending_buf[a.pending++]=255&a.bi_buf,a.bi_buf>>=8,a.bi_valid-=8)}function m(a,b){var c,d,e,f,g,h,i=b.dyn_tree,j=b.max_code,k=b.stat_desc.static_tree,l=b.stat_desc.has_stree,m=b.stat_desc.extra_bits,n=b.stat_desc.extra_base,o=b.stat_desc.max_length,p=0;for(f=0;W>=f;f++)a.bl_count[f]=0;for(i[2*a.heap[a.heap_max]+1]=0,c=a.heap_max+1;V>c;c++)d=a.heap[c],f=i[2*i[2*d+1]+1]+1,f>o&&(f=o,p++),i[2*d+1]=f,d>j||(a.bl_count[f]++,g=0,d>=n&&(g=m[d-n]),h=i[2*d],a.opt_len+=h*(f+g),l&&(a.static_len+=h*(k[2*d+1]+g)));if(0!==p){do{for(f=o-1;0===a.bl_count[f];)f--;a.bl_count[f]--,a.bl_count[f+1]+=2,a.bl_count[o]--,p-=2}while(p>0);for(f=o;0!==f;f--)for(d=a.bl_count[f];0!==d;)e=a.heap[--c],e>j||(i[2*e+1]!==f&&(a.opt_len+=(f-i[2*e+1])*i[2*e],i[2*e+1]=f),d--)}}function n(a,b,c){var d,e,f=new Array(W+1),g=0;for(d=1;W>=d;d++)f[d]=g=g+c[d-1]<<1;for(e=0;b>=e;e++){var h=a[2*e+1];0!==h&&(a[2*e]=k(f[h]++,h))}}function o(){var a,b,c,d,f,g=new Array(W+1);for(c=0,d=0;Q-1>d;d++)for(ka[d]=c,a=0;a<1<<ba[d];a++)ja[c++]=d;for(ja[c-1]=d,f=0,d=0;16>d;d++)for(la[d]=f,a=0;a<1<<ca[d];a++)ia[f++]=d;for(f>>=7;T>d;d++)for(la[d]=f<<7,a=0;a<1<<ca[d]-7;a++)ia[256+f++]=d;for(b=0;W>=b;b++)g[b]=0;for(a=0;143>=a;)ga[2*a+1]=8,a++,g[8]++;for(;255>=a;)ga[2*a+1]=9,a++,g[9]++;for(;279>=a;)ga[2*a+1]=7,a++,g[7]++;for(;287>=a;)ga[2*a+1]=8,a++,g[8]++;for(n(ga,S+1,g),a=0;T>a;a++)ha[2*a+1]=5,ha[2*a]=k(a,5);ma=new e(ga,ba,R+1,S,W),na=new e(ha,ca,0,T,W),oa=new e(new Array(0),da,0,U,Y)}function p(a){var b;for(b=0;S>b;b++)a.dyn_ltree[2*b]=0;for(b=0;T>b;b++)a.dyn_dtree[2*b]=0;for(b=0;U>b;b++)a.bl_tree[2*b]=0;a.dyn_ltree[2*Z]=1,a.opt_len=a.static_len=0,a.last_lit=a.matches=0}function q(a){a.bi_valid>8?h(a,a.bi_buf):a.bi_valid>0&&(a.pending_buf[a.pending++]=a.bi_buf),a.bi_buf=0,a.bi_valid=0}function r(a,b,c,d){q(a),d&&(h(a,c),h(a,~c)),G.arraySet(a.pending_buf,a.window,b,c,a.pending),a.pending+=c}function s(a,b,c,d){var e=2*b,f=2*c;return a[e]<a[f]||a[e]===a[f]&&d[b]<=d[c]}function t(a,b,c){for(var d=a.heap[c],e=c<<1;e<=a.heap_len&&(e<a.heap_len&&s(b,a.heap[e+1],a.heap[e],a.depth)&&e++,!s(b,d,a.heap[e],a.depth));)a.heap[c]=a.heap[e],c=e,e<<=1;a.heap[c]=d}function u(a,b,c){var d,e,f,h,k=0;if(0!==a.last_lit)do d=a.pending_buf[a.d_buf+2*k]<<8|a.pending_buf[a.d_buf+2*k+1],e=a.pending_buf[a.l_buf+k],k++,0===d?j(a,e,b):(f=ja[e],j(a,f+R+1,b),h=ba[f],0!==h&&(e-=ka[f],i(a,e,h)),d--,f=g(d),j(a,f,c),h=ca[f],0!==h&&(d-=la[f],i(a,d,h)));while(k<a.last_lit);j(a,Z,b)}function v(a,b){var c,d,e,f=b.dyn_tree,g=b.stat_desc.static_tree,h=b.stat_desc.has_stree,i=b.stat_desc.elems,j=-1;for(a.heap_len=0,a.heap_max=V,c=0;i>c;c++)0!==f[2*c]?(a.heap[++a.heap_len]=j=c,a.depth[c]=0):f[2*c+1]=0;for(;a.heap_len<2;)e=a.heap[++a.heap_len]=2>j?++j:0,f[2*e]=1,a.depth[e]=0,a.opt_len--,h&&(a.static_len-=g[2*e+1]);for(b.max_code=j,c=a.heap_len>>1;c>=1;c--)t(a,f,c);e=i;do c=a.heap[1],a.heap[1]=a.heap[a.heap_len--],t(a,f,1),d=a.heap[1],a.heap[--a.heap_max]=c,a.heap[--a.heap_max]=d,f[2*e]=f[2*c]+f[2*d],a.depth[e]=(a.depth[c]>=a.depth[d]?a.depth[c]:a.depth[d])+1,f[2*c+1]=f[2*d+1]=e,a.heap[1]=e++,t(a,f,1);while(a.heap_len>=2);a.heap[--a.heap_max]=a.heap[1],m(a,b),n(f,j,a.bl_count)}function w(a,b,c){var d,e,f=-1,g=b[1],h=0,i=7,j=4;for(0===g&&(i=138,j=3),b[2*(c+1)+1]=65535,d=0;c>=d;d++)e=g,g=b[2*(d+1)+1],++h<i&&e===g||(j>h?a.bl_tree[2*e]+=h:0!==e?(e!==f&&a.bl_tree[2*e]++,a.bl_tree[2*$]++):10>=h?a.bl_tree[2*_]++:a.bl_tree[2*aa]++,h=0,f=e,0===g?(i=138,j=3):e===g?(i=6,j=3):(i=7,j=4))}function x(a,b,c){var d,e,f=-1,g=b[1],h=0,k=7,l=4;for(0===g&&(k=138,l=3),d=0;c>=d;d++)if(e=g,g=b[2*(d+1)+1],!(++h<k&&e===g)){if(l>h){do j(a,e,a.bl_tree);while(0!==--h)}else 0!==e?(e!==f&&(j(a,e,a.bl_tree),h--),j(a,$,a.bl_tree),i(a,h-3,2)):10>=h?(j(a,_,a.bl_tree),i(a,h-3,3)):(j(a,aa,a.bl_tree),i(a,h-11,7));h=0,f=e,0===g?(k=138,l=3):e===g?(k=6,l=3):(k=7,l=4)}}function y(a){var b;for(w(a,a.dyn_ltree,a.l_desc.max_code),w(a,a.dyn_dtree,a.d_desc.max_code),v(a,a.bl_desc),b=U-1;b>=3&&0===a.bl_tree[2*ea[b]+1];b--);return a.opt_len+=3*(b+1)+5+5+4,b}function z(a,b,c,d){var e;for(i(a,b-257,5),i(a,c-1,5),i(a,d-4,4),e=0;d>e;e++)i(a,a.bl_tree[2*ea[e]+1],3);x(a,a.dyn_ltree,b-1),x(a,a.dyn_dtree,c-1)}function A(a){var b,c=4093624447;for(b=0;31>=b;b++,c>>>=1)if(1&c&&0!==a.dyn_ltree[2*b])return I;if(0!==a.dyn_ltree[18]||0!==a.dyn_ltree[20]||0!==a.dyn_ltree[26])return J;for(b=32;R>b;b++)if(0!==a.dyn_ltree[2*b])return J;return I}function B(a){pa||(o(),pa=!0),a.l_desc=new f(a.dyn_ltree,ma),a.d_desc=new f(a.dyn_dtree,na),a.bl_desc=new f(a.bl_tree,oa),a.bi_buf=0,a.bi_valid=0,p(a)}function C(a,b,c,d){i(a,(L<<1)+(d?1:0),3),r(a,b,c,!0)}function D(a){i(a,M<<1,3),j(a,Z,ga),l(a)}function E(a,b,c,d){var e,f,g=0;a.level>0?(a.strm.data_type===K&&(a.strm.data_type=A(a)),v(a,a.l_desc),v(a,a.d_desc),g=y(a),e=a.opt_len+3+7>>>3,f=a.static_len+3+7>>>3,e>=f&&(e=f)):e=f=c+5,e>=c+4&&-1!==b?C(a,b,c,d):a.strategy===H||f===e?(i(a,(M<<1)+(d?1:0),3),u(a,ga,ha)):(i(a,(N<<1)+(d?1:0),3),z(a,a.l_desc.max_code+1,a.d_desc.max_code+1,g+1),u(a,a.dyn_ltree,a.dyn_dtree)),p(a),d&&q(a)}function F(a,b,c){return a.pending_buf[a.d_buf+2*a.last_lit]=b>>>8&255,a.pending_buf[a.d_buf+2*a.last_lit+1]=255&b,a.pending_buf[a.l_buf+a.last_lit]=255&c,a.last_lit++,0===b?a.dyn_ltree[2*c]++:(a.matches++,b--,a.dyn_ltree[2*(ja[c]+R+1)]++,a.dyn_dtree[2*g(b)]++),a.last_lit===a.lit_bufsize-1}var G=a("../utils/common"),H=4,I=0,J=1,K=2,L=0,M=1,N=2,O=3,P=258,Q=29,R=256,S=R+1+Q,T=30,U=19,V=2*S+1,W=15,X=16,Y=7,Z=256,$=16,_=17,aa=18,ba=[0,0,0,0,0,0,0,0,1,1,1,1,2,2,2,2,3,3,3,3,4,4,4,4,5,5,5,5,0],ca=[0,0,0,0,1,1,2,2,3,3,4,4,5,5,6,6,7,7,8,8,9,9,10,10,11,11,12,12,13,13],da=[0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,2,3,7],ea=[16,17,18,0,8,7,9,6,10,5,11,4,12,3,13,2,14,1,15],fa=512,ga=new Array(2*(S+2));d(ga);var ha=new Array(2*T);d(ha);var ia=new Array(fa);d(ia);var ja=new Array(P-O+1);d(ja);var ka=new Array(Q);d(ka);var la=new Array(T);d(la);var ma,na,oa,pa=!1;c._tr_init=B,c._tr_stored_block=C,c._tr_flush_block=E,c._tr_tally=F,c._tr_align=D},{"../utils/common":86}],98:[function(a,b,c){"use strict";function d(){this.input=null,this.next_in=0,this.avail_in=0,this.total_in=0,this.output=null,this.next_out=0,this.avail_out=0,this.total_out=0,this.msg="",this.state=null,this.data_type=2,this.adler=0}b.exports=d},{}],99:[function(a,b,c){function d(){k=!1,h.length?j=h.concat(j):l=-1,j.length&&e()}function e(){if(!k){var a=setTimeout(d);k=!0;for(var b=j.length;b;){for(h=j,j=[];++l<b;)h&&h[l].run();l=-1,b=j.length}h=null,k=!1,clearTimeout(a)}}function f(a,b){this.fun=a,this.array=b}function g(){}var h,i=b.exports={},j=[],k=!1,l=-1;i.nextTick=function(a){var b=new Array(arguments.length-1);if(arguments.length>1)for(var c=1;c<arguments.length;c++)b[c-1]=arguments[c];j.push(new f(a,b)),1!==j.length||k||setTimeout(e,0)},f.prototype.run=function(){this.fun.apply(null,this.array)},i.title="browser",i.browser=!0,i.env={},i.argv=[],i.version="",i.versions={},i.on=g,i.addListener=g,i.once=g,i.off=g,i.removeListener=g,i.removeAllListeners=g,i.emit=g,i.binding=function(a){throw new Error("process.binding is not supported")},i.cwd=function(){return"/"},i.chdir=function(a){throw new Error("process.chdir is not supported")},i.umask=function(){return 0}},{}],100:[function(a,b,c){"use strict";function d(a){function b(a){return null===j?void l.push(a):void g(function(){var b=j?a.onFulfilled:a.onRejected;if(null===b)return void(j?a.resolve:a.reject)(k);var c;try{c=b(k)}catch(d){return void a.reject(d)}a.resolve(c)})}function c(a){try{if(a===m)throw new TypeError("A promise cannot be resolved with itself.");if(a&&("object"==typeof a||"function"==typeof a)){var b=a.then;if("function"==typeof b)return void f(b.bind(a),c,h)}j=!0,k=a,i()}catch(d){h(d)}}function h(a){j=!1,k=a,i()}function i(){for(var a=0,c=l.length;c>a;a++)b(l[a]);l=null}if("object"!=typeof this)throw new TypeError("Promises must be constructed via new");if("function"!=typeof a)throw new TypeError("not a function");var j=null,k=null,l=[],m=this;this.then=function(a,c){return new d(function(d,f){b(new e(a,c,d,f))})},f(a,c,h)}function e(a,b,c,d){this.onFulfilled="function"==typeof a?a:null,this.onRejected="function"==typeof b?b:null,this.resolve=c,this.reject=d}function f(a,b,c){var d=!1;try{a(function(a){d||(d=!0,b(a))},function(a){d||(d=!0,c(a))})}catch(e){if(d)return;d=!0,c(e)}}var g=a("asap");b.exports=d},{asap:42}],101:[function(a,b,c){"use strict";function d(a){this.then=function(b){return"function"!=typeof b?this:new e(function(c,d){f(function(){try{c(b(a))}catch(e){d(e)}})})}}var e=a("./core.js"),f=a("asap");b.exports=e,d.prototype=Object.create(e.prototype);var g=new d(!0),h=new d(!1),i=new d(null),j=new d(void 0),k=new d(0),l=new d("");e.resolve=function(a){if(a instanceof e)return a;if(null===a)return i;if(void 0===a)return j;if(a===!0)return g;if(a===!1)return h;if(0===a)return k;if(""===a)return l;if("object"==typeof a||"function"==typeof a)try{var b=a.then;if("function"==typeof b)return new e(b.bind(a))}catch(c){return new e(function(a,b){b(c)})}return new d(a)},e.from=e.cast=function(a){var b=new Error("Promise.from and Promise.cast are deprecated, use Promise.resolve instead");return b.name="Warning",console.warn(b.stack),e.resolve(a)},e.denodeify=function(a,b){return b=b||1/0,function(){var c=this,d=Array.prototype.slice.call(arguments);return new e(function(e,f){for(;d.length&&d.length>b;)d.pop();d.push(function(a,b){a?f(a):e(b)}),a.apply(c,d)})}},e.nodeify=function(a){return function(){var b=Array.prototype.slice.call(arguments),c="function"==typeof b[b.length-1]?b.pop():null;try{return a.apply(this,arguments).nodeify(c)}catch(d){if(null===c||"undefined"==typeof c)return new e(function(a,b){b(d)});f(function(){c(d)})}}},e.all=function(){var a=1===arguments.length&&Array.isArray(arguments[0]),b=Array.prototype.slice.call(a?arguments[0]:arguments);if(!a){var c=new Error("Promise.all should be called with a single array, calling it with multiple arguments is deprecated");c.name="Warning",console.warn(c.stack)}return new e(function(a,c){function d(f,g){try{if(g&&("object"==typeof g||"function"==typeof g)){var h=g.then;if("function"==typeof h)return void h.call(g,function(a){d(f,a)},c)}b[f]=g,0===--e&&a(b)}catch(i){c(i)}}if(0===b.length)return a([]);for(var e=b.length,f=0;f<b.length;f++)d(f,b[f])})},e.reject=function(a){return new e(function(b,c){c(a)})},e.race=function(a){return new e(function(b,c){a.forEach(function(a){e.resolve(a).then(b,c)})})},e.prototype.done=function(a,b){var c=arguments.length?this.then.apply(this,arguments):this;c.then(null,function(a){f(function(){throw a})})},e.prototype.nodeify=function(a){return"function"!=typeof a?this:void this.then(function(b){f(function(){a(null,b)})},function(b){f(function(){a(b)})})},e.prototype["catch"]=function(a){return this.then(null,a)}},{"./core.js":100,asap:42}]},{},[1]);
src/containers/App.js
CasperLaiTW/react-boilerplate
import React from 'react'; export default class App extends React.Component { render() { return ( <div> <h1>App</h1> {this.props.children} </div> ); } }
src/components/tabbar/tabbar.js
vinej/react-portal
import React, { Component } from 'react'; import { observer } from "mobx-react";; import { Link } from 'react-router'; import { tabbarStore } from '../../stores/tabbar_store'; import { dispatch } from '../../helpers/dispatcher'; import { tabbarClose, tabbarSelect } from '../../actions/tabbar_actions'; @observer class TabBarItem extends Component { constructor() { super() this.handleOnClick = this.handleOnClick.bind(this) this.handleOnClose = this.handleOnClose.bind(this) } handleOnClick(event) { if (event.target.value == null) { return } dispatch(tabbarSelect(this.props.componentId)) } handleOnClose() { dispatch(tabbarClose(this.props.componentId)) } renderClose(visible){ if (visible === true ){ return ( <sup><span style={{ 'marginLeft' : '5px' }} /><a className='fa fa-close fa-sm' onClick={ this.handleOnClose } style={{ 'color': 'red'}}></a></sup> ) } } render() { return ( <li onClick={ this.handleOnClick } key={this.props.componentId} value={this.props.componentId} > {this.props.title} { this.renderClose(this.props.visible) } </li> ) } } @observer class TabBar extends Component { render() { const stores = tabbarStore.getStores() const count = stores.length - 1 return ( <div className='rp-tabbar-content'> <ul className="rp-tabbar"> { stores.map( (store, idx) => <TabBarItem key={store.componentId} componentId={store.componentId} title={store.title} visible={ store.display === 'block'} /> ) } </ul> </div> ) } } export default TabBar;
ajax/libs/rxjs/2.3.14/rx.lite.compat.js
callumacrae/cdnjs
// Copyright (c) Microsoft Open Technologies, Inc. All rights reserved. See License.txt in the project root for license information. ;(function (undefined) { var objectTypes = { 'boolean': false, 'function': true, 'object': true, 'number': false, 'string': false, 'undefined': false }; var root = (objectTypes[typeof window] && window) || this, freeExports = objectTypes[typeof exports] && exports && !exports.nodeType && exports, freeModule = objectTypes[typeof module] && module && !module.nodeType && module, moduleExports = freeModule && freeModule.exports === freeExports && freeExports, freeGlobal = objectTypes[typeof global] && global; if (freeGlobal && (freeGlobal.global === freeGlobal || freeGlobal.window === freeGlobal)) { root = freeGlobal; } var Rx = { internals: {}, config: { Promise: root.Promise // Detect if promise exists }, helpers: { } }; // Defaults var noop = Rx.helpers.noop = function () { }, notDefined = Rx.helpers.notDefined = function (x) { return typeof x === 'undefined'; }, isScheduler = Rx.helpers.isScheduler = function (x) { return x instanceof Rx.Scheduler; }, identity = Rx.helpers.identity = function (x) { return x; }, pluck = Rx.helpers.pluck = function (property) { return function (x) { return x[property]; }; }, just = Rx.helpers.just = function (value) { return function () { return value; }; }, defaultNow = Rx.helpers.defaultNow = (function () { return !!Date.now ? Date.now : function () { return +new Date; }; }()), defaultComparer = Rx.helpers.defaultComparer = function (x, y) { return isEqual(x, y); }, defaultSubComparer = Rx.helpers.defaultSubComparer = function (x, y) { return x > y ? 1 : (x < y ? -1 : 0); }, defaultKeySerializer = Rx.helpers.defaultKeySerializer = function (x) { return x.toString(); }, defaultError = Rx.helpers.defaultError = function (err) { throw err; }, isPromise = Rx.helpers.isPromise = function (p) { return !!p && typeof p.then === 'function'; }, asArray = Rx.helpers.asArray = function () { return Array.prototype.slice.call(arguments); }, not = Rx.helpers.not = function (a) { return !a; }, isFunction = Rx.helpers.isFunction = (function () { var isFn = function (value) { return typeof value == 'function' || false; } // fallback for older versions of Chrome and Safari if (isFn(/x/)) { isFn = function(value) { return typeof value == 'function' && toString.call(value) == '[object Function]'; }; } return isFn; }()); // Errors var sequenceContainsNoElements = 'Sequence contains no elements.'; var argumentOutOfRange = 'Argument out of range'; var objectDisposed = 'Object has been disposed'; function checkDisposed() { if (this.isDisposed) { throw new Error(objectDisposed); } } // Shim in iterator support var $iterator$ = (typeof Symbol === 'function' && Symbol.iterator) || '_es6shim_iterator_'; // Bug for mozilla version if (root.Set && typeof new root.Set()['@@iterator'] === 'function') { $iterator$ = '@@iterator'; } var doneEnumerator = Rx.doneEnumerator = { done: true, value: undefined }; Rx.iterator = $iterator$; /** `Object#toString` result shortcuts */ var argsClass = '[object Arguments]', arrayClass = '[object Array]', boolClass = '[object Boolean]', dateClass = '[object Date]', errorClass = '[object Error]', funcClass = '[object Function]', numberClass = '[object Number]', objectClass = '[object Object]', regexpClass = '[object RegExp]', stringClass = '[object String]'; var toString = Object.prototype.toString, hasOwnProperty = Object.prototype.hasOwnProperty, supportsArgsClass = toString.call(arguments) == argsClass, // For less <IE9 && FF<4 suportNodeClass, errorProto = Error.prototype, objectProto = Object.prototype, propertyIsEnumerable = objectProto.propertyIsEnumerable; try { suportNodeClass = !(toString.call(document) == objectClass && !({ 'toString': 0 } + '')); } catch(e) { suportNodeClass = true; } var shadowedProps = [ 'constructor', 'hasOwnProperty', 'isPrototypeOf', 'propertyIsEnumerable', 'toLocaleString', 'toString', 'valueOf' ]; var nonEnumProps = {}; nonEnumProps[arrayClass] = nonEnumProps[dateClass] = nonEnumProps[numberClass] = { 'constructor': true, 'toLocaleString': true, 'toString': true, 'valueOf': true }; nonEnumProps[boolClass] = nonEnumProps[stringClass] = { 'constructor': true, 'toString': true, 'valueOf': true }; nonEnumProps[errorClass] = nonEnumProps[funcClass] = nonEnumProps[regexpClass] = { 'constructor': true, 'toString': true }; nonEnumProps[objectClass] = { 'constructor': true }; var support = {}; (function () { var ctor = function() { this.x = 1; }, props = []; ctor.prototype = { 'valueOf': 1, 'y': 1 }; for (var key in new ctor) { props.push(key); } for (key in arguments) { } // Detect if `name` or `message` properties of `Error.prototype` are enumerable by default. support.enumErrorProps = propertyIsEnumerable.call(errorProto, 'message') || propertyIsEnumerable.call(errorProto, 'name'); // Detect if `prototype` properties are enumerable by default. support.enumPrototypes = propertyIsEnumerable.call(ctor, 'prototype'); // Detect if `arguments` object indexes are non-enumerable support.nonEnumArgs = key != 0; // Detect if properties shadowing those on `Object.prototype` are non-enumerable. support.nonEnumShadows = !/valueOf/.test(props); }(1)); function isObject(value) { // check if the value is the ECMAScript language type of Object // http://es5.github.io/#x8 // and avoid a V8 bug // https://code.google.com/p/v8/issues/detail?id=2291 var type = typeof value; return value && (type == 'function' || type == 'object') || false; } function keysIn(object) { var result = []; if (!isObject(object)) { return result; } if (support.nonEnumArgs && object.length && isArguments(object)) { object = slice.call(object); } var skipProto = support.enumPrototypes && typeof object == 'function', skipErrorProps = support.enumErrorProps && (object === errorProto || object instanceof Error); for (var key in object) { if (!(skipProto && key == 'prototype') && !(skipErrorProps && (key == 'message' || key == 'name'))) { result.push(key); } } if (support.nonEnumShadows && object !== objectProto) { var ctor = object.constructor, index = -1, length = shadowedProps.length; if (object === (ctor && ctor.prototype)) { var className = object === stringProto ? stringClass : object === errorProto ? errorClass : toString.call(object), nonEnum = nonEnumProps[className]; } while (++index < length) { key = shadowedProps[index]; if (!(nonEnum && nonEnum[key]) && hasOwnProperty.call(object, key)) { result.push(key); } } } return result; } function internalFor(object, callback, keysFunc) { var index = -1, props = keysFunc(object), length = props.length; while (++index < length) { var key = props[index]; if (callback(object[key], key, object) === false) { break; } } return object; } function internalForIn(object, callback) { return internalFor(object, callback, keysIn); } function isNode(value) { // IE < 9 presents DOM nodes as `Object` objects except they have `toString` // methods that are `typeof` "string" and still can coerce nodes to strings return typeof value.toString != 'function' && typeof (value + '') == 'string'; } function isArguments(value) { return (value && typeof value == 'object') ? toString.call(value) == argsClass : false; } // fallback for browsers that can't detect `arguments` objects by [[Class]] if (!supportsArgsClass) { isArguments = function(value) { return (value && typeof value == 'object') ? hasOwnProperty.call(value, 'callee') : false; }; } var isEqual = Rx.internals.isEqual = function (x, y) { return deepEquals(x, y, [], []); }; /** @private * Used for deep comparison **/ function deepEquals(a, b, stackA, stackB) { // exit early for identical values if (a === b) { // treat `+0` vs. `-0` as not equal return a !== 0 || (1 / a == 1 / b); } var type = typeof a, otherType = typeof b; // exit early for unlike primitive values if (a === a && (a == null || b == null || (type != 'function' && type != 'object' && otherType != 'function' && otherType != 'object'))) { return false; } // compare [[Class]] names var className = toString.call(a), otherClass = toString.call(b); if (className == argsClass) { className = objectClass; } if (otherClass == argsClass) { otherClass = objectClass; } if (className != otherClass) { return false; } switch (className) { case boolClass: case dateClass: // coerce dates and booleans to numbers, dates to milliseconds and booleans // to `1` or `0` treating invalid dates coerced to `NaN` as not equal return +a == +b; case numberClass: // treat `NaN` vs. `NaN` as equal return (a != +a) ? b != +b // but treat `-0` vs. `+0` as not equal : (a == 0 ? (1 / a == 1 / b) : a == +b); case regexpClass: case stringClass: // coerce regexes to strings (http://es5.github.io/#x15.10.6.4) // treat string primitives and their corresponding object instances as equal return a == String(b); } var isArr = className == arrayClass; if (!isArr) { // exit for functions and DOM nodes if (className != objectClass || (!support.nodeClass && (isNode(a) || isNode(b)))) { return false; } // in older versions of Opera, `arguments` objects have `Array` constructors var ctorA = !support.argsObject && isArguments(a) ? Object : a.constructor, ctorB = !support.argsObject && isArguments(b) ? Object : b.constructor; // non `Object` object instances with different constructors are not equal if (ctorA != ctorB && !(hasOwnProperty.call(a, 'constructor') && hasOwnProperty.call(b, 'constructor')) && !(isFunction(ctorA) && ctorA instanceof ctorA && isFunction(ctorB) && ctorB instanceof ctorB) && ('constructor' in a && 'constructor' in b) ) { return false; } } // assume cyclic structures are equal // the algorithm for detecting cyclic structures is adapted from ES 5.1 // section 15.12.3, abstract operation `JO` (http://es5.github.io/#x15.12.3) var initedStack = !stackA; stackA || (stackA = []); stackB || (stackB = []); var length = stackA.length; while (length--) { if (stackA[length] == a) { return stackB[length] == b; } } var size = 0; var result = true; // add `a` and `b` to the stack of traversed objects stackA.push(a); stackB.push(b); // recursively compare objects and arrays (susceptible to call stack limits) if (isArr) { // compare lengths to determine if a deep comparison is necessary length = a.length; size = b.length; result = size == length; if (result) { // deep compare the contents, ignoring non-numeric properties while (size--) { var index = length, value = b[size]; if (!(result = deepEquals(a[size], value, stackA, stackB))) { break; } } } } else { // deep compare objects using `forIn`, instead of `forOwn`, to avoid `Object.keys` // which, in this case, is more costly internalForIn(b, function(value, key, b) { if (hasOwnProperty.call(b, key)) { // count the number of properties. size++; // deep compare each property value. return (result = hasOwnProperty.call(a, key) && deepEquals(a[key], value, stackA, stackB)); } }); if (result) { // ensure both objects have the same number of properties internalForIn(a, function(value, key, a) { if (hasOwnProperty.call(a, key)) { // `size` will be `-1` if `a` has more properties than `b` return (result = --size > -1); } }); } } stackA.pop(); stackB.pop(); return result; } var slice = Array.prototype.slice; function argsOrArray(args, idx) { return args.length === 1 && Array.isArray(args[idx]) ? args[idx] : slice.call(args); } var hasProp = {}.hasOwnProperty; var inherits = this.inherits = Rx.internals.inherits = function (child, parent) { function __() { this.constructor = child; } __.prototype = parent.prototype; child.prototype = new __(); }; var addProperties = Rx.internals.addProperties = function (obj) { var sources = slice.call(arguments, 1); for (var i = 0, len = sources.length; i < len; i++) { var source = sources[i]; for (var prop in source) { obj[prop] = source[prop]; } } }; // Rx Utils var addRef = Rx.internals.addRef = function (xs, r) { return new AnonymousObservable(function (observer) { return new CompositeDisposable(r.getDisposable(), xs.subscribe(observer)); }); }; function arrayInitialize(count, factory) { var a = new Array(count); for (var i = 0; i < count; i++) { a[i] = factory(); } return a; } // Utilities if (!Function.prototype.bind) { Function.prototype.bind = function (that) { var target = this, args = slice.call(arguments, 1); var bound = function () { if (this instanceof bound) { function F() { } F.prototype = target.prototype; var self = new F(); var result = target.apply(self, args.concat(slice.call(arguments))); if (Object(result) === result) { return result; } return self; } else { return target.apply(that, args.concat(slice.call(arguments))); } }; return bound; }; } if (!Array.prototype.forEach) { Array.prototype.forEach = function (callback, thisArg) { var T, k; if (this == null) { throw new TypeError(" this is null or not defined"); } var O = Object(this); var len = O.length >>> 0; if (typeof callback !== "function") { throw new TypeError(callback + " is not a function"); } if (arguments.length > 1) { T = thisArg; } k = 0; while (k < len) { var kValue; if (k in O) { kValue = O[k]; callback.call(T, kValue, k, O); } k++; } }; } var boxedString = Object("a"), splitString = boxedString[0] != "a" || !(0 in boxedString); if (!Array.prototype.every) { Array.prototype.every = function every(fun /*, thisp */) { var object = Object(this), self = splitString && {}.toString.call(this) == stringClass ? this.split("") : object, length = self.length >>> 0, thisp = arguments[1]; if ({}.toString.call(fun) != funcClass) { throw new TypeError(fun + " is not a function"); } for (var i = 0; i < length; i++) { if (i in self && !fun.call(thisp, self[i], i, object)) { return false; } } return true; }; } if (!Array.prototype.map) { Array.prototype.map = function map(fun /*, thisp*/) { var object = Object(this), self = splitString && {}.toString.call(this) == stringClass ? this.split("") : object, length = self.length >>> 0, result = Array(length), thisp = arguments[1]; if ({}.toString.call(fun) != funcClass) { throw new TypeError(fun + " is not a function"); } for (var i = 0; i < length; i++) { if (i in self) { result[i] = fun.call(thisp, self[i], i, object); } } return result; }; } if (!Array.prototype.filter) { Array.prototype.filter = function (predicate) { var results = [], item, t = new Object(this); for (var i = 0, len = t.length >>> 0; i < len; i++) { item = t[i]; if (i in t && predicate.call(arguments[1], item, i, t)) { results.push(item); } } return results; }; } if (!Array.isArray) { Array.isArray = function (arg) { return {}.toString.call(arg) == arrayClass; }; } if (!Array.prototype.indexOf) { Array.prototype.indexOf = function indexOf(searchElement) { var t = Object(this); var len = t.length >>> 0; if (len === 0) { return -1; } var n = 0; if (arguments.length > 1) { n = Number(arguments[1]); if (n !== n) { n = 0; } else if (n !== 0 && n != Infinity && n !== -Infinity) { n = (n > 0 || -1) * Math.floor(Math.abs(n)); } } if (n >= len) { return -1; } var k = n >= 0 ? n : Math.max(len - Math.abs(n), 0); for (; k < len; k++) { if (k in t && t[k] === searchElement) { return k; } } return -1; }; } // Collections function IndexedItem(id, value) { this.id = id; this.value = value; } IndexedItem.prototype.compareTo = function (other) { var c = this.value.compareTo(other.value); c === 0 && (c = this.id - other.id); return c; }; // Priority Queue for Scheduling var PriorityQueue = Rx.internals.PriorityQueue = function (capacity) { this.items = new Array(capacity); this.length = 0; }; var priorityProto = PriorityQueue.prototype; priorityProto.isHigherPriority = function (left, right) { return this.items[left].compareTo(this.items[right]) < 0; }; priorityProto.percolate = function (index) { if (index >= this.length || index < 0) { return; } var parent = index - 1 >> 1; if (parent < 0 || parent === index) { return; } if (this.isHigherPriority(index, parent)) { var temp = this.items[index]; this.items[index] = this.items[parent]; this.items[parent] = temp; this.percolate(parent); } }; priorityProto.heapify = function (index) { +index || (index = 0); if (index >= this.length || index < 0) { return; } var left = 2 * index + 1, right = 2 * index + 2, first = index; if (left < this.length && this.isHigherPriority(left, first)) { first = left; } if (right < this.length && this.isHigherPriority(right, first)) { first = right; } if (first !== index) { var temp = this.items[index]; this.items[index] = this.items[first]; this.items[first] = temp; this.heapify(first); } }; priorityProto.peek = function () { return this.items[0].value; }; priorityProto.removeAt = function (index) { this.items[index] = this.items[--this.length]; delete this.items[this.length]; this.heapify(); }; priorityProto.dequeue = function () { var result = this.peek(); this.removeAt(0); return result; }; priorityProto.enqueue = function (item) { var index = this.length++; this.items[index] = new IndexedItem(PriorityQueue.count++, item); this.percolate(index); }; priorityProto.remove = function (item) { for (var i = 0; i < this.length; i++) { if (this.items[i].value === item) { this.removeAt(i); return true; } } return false; }; PriorityQueue.count = 0; /** * Represents a group of disposable resources that are disposed together. * @constructor */ var CompositeDisposable = Rx.CompositeDisposable = function () { this.disposables = argsOrArray(arguments, 0); this.isDisposed = false; this.length = this.disposables.length; }; var CompositeDisposablePrototype = CompositeDisposable.prototype; /** * Adds a disposable to the CompositeDisposable or disposes the disposable if the CompositeDisposable is disposed. * @param {Mixed} item Disposable to add. */ CompositeDisposablePrototype.add = function (item) { if (this.isDisposed) { item.dispose(); } else { this.disposables.push(item); this.length++; } }; /** * Removes and disposes the first occurrence of a disposable from the CompositeDisposable. * @param {Mixed} item Disposable to remove. * @returns {Boolean} true if found; false otherwise. */ CompositeDisposablePrototype.remove = function (item) { var shouldDispose = false; if (!this.isDisposed) { var idx = this.disposables.indexOf(item); if (idx !== -1) { shouldDispose = true; this.disposables.splice(idx, 1); this.length--; item.dispose(); } } return shouldDispose; }; /** * Disposes all disposables in the group and removes them from the group. */ CompositeDisposablePrototype.dispose = function () { if (!this.isDisposed) { this.isDisposed = true; var currentDisposables = this.disposables.slice(0); this.disposables = []; this.length = 0; for (var i = 0, len = currentDisposables.length; i < len; i++) { currentDisposables[i].dispose(); } } }; /** * Converts the existing CompositeDisposable to an array of disposables * @returns {Array} An array of disposable objects. */ CompositeDisposablePrototype.toArray = function () { return this.disposables.slice(0); }; /** * Provides a set of static methods for creating Disposables. * * @constructor * @param {Function} dispose Action to run during the first call to dispose. The action is guaranteed to be run at most once. */ var Disposable = Rx.Disposable = function (action) { this.isDisposed = false; this.action = action || noop; }; /** Performs the task of cleaning up resources. */ Disposable.prototype.dispose = function () { if (!this.isDisposed) { this.action(); this.isDisposed = true; } }; /** * Creates a disposable object that invokes the specified action when disposed. * @param {Function} dispose Action to run during the first call to dispose. The action is guaranteed to be run at most once. * @return {Disposable} The disposable object that runs the given action upon disposal. */ var disposableCreate = Disposable.create = function (action) { return new Disposable(action); }; /** * Gets the disposable that does nothing when disposed. */ var disposableEmpty = Disposable.empty = { dispose: noop }; var SingleAssignmentDisposable = Rx.SingleAssignmentDisposable = (function () { function BooleanDisposable () { this.isDisposed = false; this.current = null; } var booleanDisposablePrototype = BooleanDisposable.prototype; /** * Gets the underlying disposable. * @return The underlying disposable. */ booleanDisposablePrototype.getDisposable = function () { return this.current; }; /** * Sets the underlying disposable. * @param {Disposable} value The new underlying disposable. */ booleanDisposablePrototype.setDisposable = function (value) { var shouldDispose = this.isDisposed, old; if (!shouldDispose) { old = this.current; this.current = value; } old && old.dispose(); shouldDispose && value && value.dispose(); }; /** * Disposes the underlying disposable as well as all future replacements. */ booleanDisposablePrototype.dispose = function () { var old; if (!this.isDisposed) { this.isDisposed = true; old = this.current; this.current = null; } old && old.dispose(); }; return BooleanDisposable; }()); var SerialDisposable = Rx.SerialDisposable = SingleAssignmentDisposable; /** * Represents a disposable resource that only disposes its underlying disposable resource when all dependent disposable objects have been disposed. */ var RefCountDisposable = Rx.RefCountDisposable = (function () { function InnerDisposable(disposable) { this.disposable = disposable; this.disposable.count++; this.isInnerDisposed = false; } InnerDisposable.prototype.dispose = function () { if (!this.disposable.isDisposed) { if (!this.isInnerDisposed) { this.isInnerDisposed = true; this.disposable.count--; if (this.disposable.count === 0 && this.disposable.isPrimaryDisposed) { this.disposable.isDisposed = true; this.disposable.underlyingDisposable.dispose(); } } } }; /** * Initializes a new instance of the RefCountDisposable with the specified disposable. * @constructor * @param {Disposable} disposable Underlying disposable. */ function RefCountDisposable(disposable) { this.underlyingDisposable = disposable; this.isDisposed = false; this.isPrimaryDisposed = false; this.count = 0; } /** * Disposes the underlying disposable only when all dependent disposables have been disposed */ RefCountDisposable.prototype.dispose = function () { if (!this.isDisposed) { if (!this.isPrimaryDisposed) { this.isPrimaryDisposed = true; if (this.count === 0) { this.isDisposed = true; this.underlyingDisposable.dispose(); } } } }; /** * Returns a dependent disposable that when disposed decreases the refcount on the underlying disposable. * @returns {Disposable} A dependent disposable contributing to the reference count that manages the underlying disposable's lifetime. */ RefCountDisposable.prototype.getDisposable = function () { return this.isDisposed ? disposableEmpty : new InnerDisposable(this); }; return RefCountDisposable; })(); var ScheduledItem = Rx.internals.ScheduledItem = function (scheduler, state, action, dueTime, comparer) { this.scheduler = scheduler; this.state = state; this.action = action; this.dueTime = dueTime; this.comparer = comparer || defaultSubComparer; this.disposable = new SingleAssignmentDisposable(); } ScheduledItem.prototype.invoke = function () { this.disposable.setDisposable(this.invokeCore()); }; ScheduledItem.prototype.compareTo = function (other) { return this.comparer(this.dueTime, other.dueTime); }; ScheduledItem.prototype.isCancelled = function () { return this.disposable.isDisposed; }; ScheduledItem.prototype.invokeCore = function () { return this.action(this.scheduler, this.state); }; /** Provides a set of static properties to access commonly used schedulers. */ var Scheduler = Rx.Scheduler = (function () { function Scheduler(now, schedule, scheduleRelative, scheduleAbsolute) { this.now = now; this._schedule = schedule; this._scheduleRelative = scheduleRelative; this._scheduleAbsolute = scheduleAbsolute; } function invokeAction(scheduler, action) { action(); return disposableEmpty; } var schedulerProto = Scheduler.prototype; /** * Schedules an action to be executed. * @param {Function} action Action to execute. * @returns {Disposable} The disposable object used to cancel the scheduled action (best effort). */ schedulerProto.schedule = function (action) { return this._schedule(action, invokeAction); }; /** * Schedules an action to be executed. * @param state State passed to the action to be executed. * @param {Function} action Action to be executed. * @returns {Disposable} The disposable object used to cancel the scheduled action (best effort). */ schedulerProto.scheduleWithState = function (state, action) { return this._schedule(state, action); }; /** * Schedules an action to be executed after the specified relative due time. * @param {Function} action Action to execute. * @param {Number} dueTime Relative time after which to execute the action. * @returns {Disposable} The disposable object used to cancel the scheduled action (best effort). */ schedulerProto.scheduleWithRelative = function (dueTime, action) { return this._scheduleRelative(action, dueTime, invokeAction); }; /** * Schedules an action to be executed after dueTime. * @param state State passed to the action to be executed. * @param {Function} action Action to be executed. * @param {Number} dueTime Relative time after which to execute the action. * @returns {Disposable} The disposable object used to cancel the scheduled action (best effort). */ schedulerProto.scheduleWithRelativeAndState = function (state, dueTime, action) { return this._scheduleRelative(state, dueTime, action); }; /** * Schedules an action to be executed at the specified absolute due time. * @param {Function} action Action to execute. * @param {Number} dueTime Absolute time at which to execute the action. * @returns {Disposable} The disposable object used to cancel the scheduled action (best effort). */ schedulerProto.scheduleWithAbsolute = function (dueTime, action) { return this._scheduleAbsolute(action, dueTime, invokeAction); }; /** * Schedules an action to be executed at dueTime. * @param {Mixed} state State passed to the action to be executed. * @param {Function} action Action to be executed. * @param {Number}dueTime Absolute time at which to execute the action. * @returns {Disposable} The disposable object used to cancel the scheduled action (best effort). */ schedulerProto.scheduleWithAbsoluteAndState = function (state, dueTime, action) { return this._scheduleAbsolute(state, dueTime, action); }; /** Gets the current time according to the local machine's system clock. */ Scheduler.now = defaultNow; /** * Normalizes the specified TimeSpan value to a positive value. * @param {Number} timeSpan The time span value to normalize. * @returns {Number} The specified TimeSpan value if it is zero or positive; otherwise, 0 */ Scheduler.normalize = function (timeSpan) { timeSpan < 0 && (timeSpan = 0); return timeSpan; }; return Scheduler; }()); var normalizeTime = Scheduler.normalize; (function (schedulerProto) { function invokeRecImmediate(scheduler, pair) { var state = pair.first, action = pair.second, group = new CompositeDisposable(), recursiveAction = function (state1) { action(state1, function (state2) { var isAdded = false, isDone = false, d = scheduler.scheduleWithState(state2, function (scheduler1, state3) { if (isAdded) { group.remove(d); } else { isDone = true; } recursiveAction(state3); return disposableEmpty; }); if (!isDone) { group.add(d); isAdded = true; } }); }; recursiveAction(state); return group; } function invokeRecDate(scheduler, pair, method) { var state = pair.first, action = pair.second, group = new CompositeDisposable(), recursiveAction = function (state1) { action(state1, function (state2, dueTime1) { var isAdded = false, isDone = false, d = scheduler[method].call(scheduler, state2, dueTime1, function (scheduler1, state3) { if (isAdded) { group.remove(d); } else { isDone = true; } recursiveAction(state3); return disposableEmpty; }); if (!isDone) { group.add(d); isAdded = true; } }); }; recursiveAction(state); return group; } function scheduleInnerRecursive(action, self) { action(function(dt) { self(action, dt); }); } /** * Schedules an action to be executed recursively. * @param {Function} action Action to execute recursively. The parameter passed to the action is used to trigger recursive scheduling of the action. * @returns {Disposable} The disposable object used to cancel the scheduled action (best effort). */ schedulerProto.scheduleRecursive = function (action) { return this.scheduleRecursiveWithState(action, function (_action, self) { _action(function () { self(_action); }); }); }; /** * Schedules an action to be executed recursively. * @param {Mixed} state State passed to the action to be executed. * @param {Function} action Action to execute recursively. The last parameter passed to the action is used to trigger recursive scheduling of the action, passing in recursive invocation state. * @returns {Disposable} The disposable object used to cancel the scheduled action (best effort). */ schedulerProto.scheduleRecursiveWithState = function (state, action) { return this.scheduleWithState({ first: state, second: action }, invokeRecImmediate); }; /** * Schedules an action to be executed recursively after a specified relative due time. * @param {Function} action Action to execute recursively. The parameter passed to the action is used to trigger recursive scheduling of the action at the specified relative time. * @param {Number}dueTime Relative time after which to execute the action for the first time. * @returns {Disposable} The disposable object used to cancel the scheduled action (best effort). */ schedulerProto.scheduleRecursiveWithRelative = function (dueTime, action) { return this.scheduleRecursiveWithRelativeAndState(action, dueTime, scheduleInnerRecursive); }; /** * Schedules an action to be executed recursively after a specified relative due time. * @param {Mixed} state State passed to the action to be executed. * @param {Function} action Action to execute recursively. The last parameter passed to the action is used to trigger recursive scheduling of the action, passing in the recursive due time and invocation state. * @param {Number}dueTime Relative time after which to execute the action for the first time. * @returns {Disposable} The disposable object used to cancel the scheduled action (best effort). */ schedulerProto.scheduleRecursiveWithRelativeAndState = function (state, dueTime, action) { return this._scheduleRelative({ first: state, second: action }, dueTime, function (s, p) { return invokeRecDate(s, p, 'scheduleWithRelativeAndState'); }); }; /** * Schedules an action to be executed recursively at a specified absolute due time. * @param {Function} action Action to execute recursively. The parameter passed to the action is used to trigger recursive scheduling of the action at the specified absolute time. * @param {Number}dueTime Absolute time at which to execute the action for the first time. * @returns {Disposable} The disposable object used to cancel the scheduled action (best effort). */ schedulerProto.scheduleRecursiveWithAbsolute = function (dueTime, action) { return this.scheduleRecursiveWithAbsoluteAndState(action, dueTime, scheduleInnerRecursive); }; /** * Schedules an action to be executed recursively at a specified absolute due time. * @param {Mixed} state State passed to the action to be executed. * @param {Function} action Action to execute recursively. The last parameter passed to the action is used to trigger recursive scheduling of the action, passing in the recursive due time and invocation state. * @param {Number}dueTime Absolute time at which to execute the action for the first time. * @returns {Disposable} The disposable object used to cancel the scheduled action (best effort). */ schedulerProto.scheduleRecursiveWithAbsoluteAndState = function (state, dueTime, action) { return this._scheduleAbsolute({ first: state, second: action }, dueTime, function (s, p) { return invokeRecDate(s, p, 'scheduleWithAbsoluteAndState'); }); }; }(Scheduler.prototype)); (function (schedulerProto) { /** * Schedules a periodic piece of work by dynamically discovering the scheduler's capabilities. The periodic task will be scheduled using window.setInterval for the base implementation. * @param {Number} period Period for running the work periodically. * @param {Function} action Action to be executed. * @returns {Disposable} The disposable object used to cancel the scheduled recurring action (best effort). */ Scheduler.prototype.schedulePeriodic = function (period, action) { return this.schedulePeriodicWithState(null, period, action); }; /** * Schedules a periodic piece of work by dynamically discovering the scheduler's capabilities. The periodic task will be scheduled using window.setInterval for the base implementation. * @param {Mixed} state Initial state passed to the action upon the first iteration. * @param {Number} period Period for running the work periodically. * @param {Function} action Action to be executed, potentially updating the state. * @returns {Disposable} The disposable object used to cancel the scheduled recurring action (best effort). */ Scheduler.prototype.schedulePeriodicWithState = function(state, period, action) { if (typeof root.setInterval === 'undefined') { throw new Error('Periodic scheduling not supported.'); } var s = state; var id = root.setInterval(function () { s = action(s); }, period); return disposableCreate(function () { root.clearInterval(id); }); }; }(Scheduler.prototype)); /** * Gets a scheduler that schedules work immediately on the current thread. */ var immediateScheduler = Scheduler.immediate = (function () { function scheduleNow(state, action) { return action(this, state); } function scheduleRelative(state, dueTime, action) { var dt = normalizeTime(dt); while (dt - this.now() > 0) { } return action(this, state); } function scheduleAbsolute(state, dueTime, action) { return this.scheduleWithRelativeAndState(state, dueTime - this.now(), action); } return new Scheduler(defaultNow, scheduleNow, scheduleRelative, scheduleAbsolute); }()); /** * Gets a scheduler that schedules work as soon as possible on the current thread. */ var currentThreadScheduler = Scheduler.currentThread = (function () { var queue; function runTrampoline (q) { var item; while (q.length > 0) { item = q.dequeue(); if (!item.isCancelled()) { // Note, do not schedule blocking work! while (item.dueTime - Scheduler.now() > 0) { } if (!item.isCancelled()) { item.invoke(); } } } } function scheduleNow(state, action) { return this.scheduleWithRelativeAndState(state, 0, action); } function scheduleRelative(state, dueTime, action) { var dt = this.now() + Scheduler.normalize(dueTime), si = new ScheduledItem(this, state, action, dt); if (!queue) { queue = new PriorityQueue(4); queue.enqueue(si); try { runTrampoline(queue); } catch (e) { throw e; } finally { queue = null; } } else { queue.enqueue(si); } return si.disposable; } function scheduleAbsolute(state, dueTime, action) { return this.scheduleWithRelativeAndState(state, dueTime - this.now(), action); } var currentScheduler = new Scheduler(defaultNow, scheduleNow, scheduleRelative, scheduleAbsolute); currentScheduler.scheduleRequired = function () { return !queue; }; currentScheduler.ensureTrampoline = function (action) { if (!queue) { this.schedule(action); } else { action(); } }; return currentScheduler; }()); var SchedulePeriodicRecursive = Rx.internals.SchedulePeriodicRecursive = (function () { function tick(command, recurse) { recurse(0, this._period); try { this._state = this._action(this._state); } catch (e) { this._cancel.dispose(); throw e; } } function SchedulePeriodicRecursive(scheduler, state, period, action) { this._scheduler = scheduler; this._state = state; this._period = period; this._action = action; } SchedulePeriodicRecursive.prototype.start = function () { var d = new SingleAssignmentDisposable(); this._cancel = d; d.setDisposable(this._scheduler.scheduleRecursiveWithRelativeAndState(0, this._period, tick.bind(this))); return d; }; return SchedulePeriodicRecursive; }()); var scheduleMethod, clearMethod = noop; var localTimer = (function () { var localSetTimeout, localClearTimeout = noop; if ('WScript' in this) { localSetTimeout = function (fn, time) { WScript.Sleep(time); fn(); }; } else if (!!root.setTimeout) { localSetTimeout = root.setTimeout; localClearTimeout = root.clearTimeout; } else { throw new Error('No concurrency detected!'); } return { setTimeout: localSetTimeout, clearTimeout: localClearTimeout }; }()); var localSetTimeout = localTimer.setTimeout, localClearTimeout = localTimer.clearTimeout; (function () { var reNative = RegExp('^' + String(toString) .replace(/[.*+?^${}()|[\]\\]/g, '\\$&') .replace(/toString| for [^\]]+/g, '.*?') + '$' ); var setImmediate = typeof (setImmediate = freeGlobal && moduleExports && freeGlobal.setImmediate) == 'function' && !reNative.test(setImmediate) && setImmediate, clearImmediate = typeof (clearImmediate = freeGlobal && moduleExports && freeGlobal.clearImmediate) == 'function' && !reNative.test(clearImmediate) && clearImmediate; function postMessageSupported () { // Ensure not in a worker if (!root.postMessage || root.importScripts) { return false; } var isAsync = false, oldHandler = root.onmessage; // Test for async root.onmessage = function () { isAsync = true; }; root.postMessage('','*'); root.onmessage = oldHandler; return isAsync; } // Use in order, nextTick, setImmediate, postMessage, MessageChannel, script readystatechanged, setTimeout if (typeof process !== 'undefined' && {}.toString.call(process) === '[object process]') { scheduleMethod = process.nextTick; } else if (typeof setImmediate === 'function') { scheduleMethod = setImmediate; clearMethod = clearImmediate; } else if (postMessageSupported()) { var MSG_PREFIX = 'ms.rx.schedule' + Math.random(), tasks = {}, taskId = 0; function onGlobalPostMessage(event) { // Only if we're a match to avoid any other global events if (typeof event.data === 'string' && event.data.substring(0, MSG_PREFIX.length) === MSG_PREFIX) { var handleId = event.data.substring(MSG_PREFIX.length), action = tasks[handleId]; action(); delete tasks[handleId]; } } if (root.addEventListener) { root.addEventListener('message', onGlobalPostMessage, false); } else { root.attachEvent('onmessage', onGlobalPostMessage, false); } scheduleMethod = function (action) { var currentId = taskId++; tasks[currentId] = action; root.postMessage(MSG_PREFIX + currentId, '*'); }; } else if (!!root.MessageChannel) { var channel = new root.MessageChannel(), channelTasks = {}, channelTaskId = 0; channel.port1.onmessage = function (event) { var id = event.data, action = channelTasks[id]; action(); delete channelTasks[id]; }; scheduleMethod = function (action) { var id = channelTaskId++; channelTasks[id] = action; channel.port2.postMessage(id); }; } else if ('document' in root && 'onreadystatechange' in root.document.createElement('script')) { scheduleMethod = function (action) { var scriptElement = root.document.createElement('script'); scriptElement.onreadystatechange = function () { action(); scriptElement.onreadystatechange = null; scriptElement.parentNode.removeChild(scriptElement); scriptElement = null; }; root.document.documentElement.appendChild(scriptElement); }; } else { scheduleMethod = function (action) { return localSetTimeout(action, 0); }; clearMethod = localClearTimeout; } }()); /** * Gets a scheduler that schedules work via a timed callback based upon platform. */ var timeoutScheduler = Scheduler.timeout = (function () { function scheduleNow(state, action) { var scheduler = this, disposable = new SingleAssignmentDisposable(); var id = scheduleMethod(function () { if (!disposable.isDisposed) { disposable.setDisposable(action(scheduler, state)); } }); return new CompositeDisposable(disposable, disposableCreate(function () { clearMethod(id); })); } function scheduleRelative(state, dueTime, action) { var scheduler = this, dt = Scheduler.normalize(dueTime); if (dt === 0) { return scheduler.scheduleWithState(state, action); } var disposable = new SingleAssignmentDisposable(); var id = localSetTimeout(function () { if (!disposable.isDisposed) { disposable.setDisposable(action(scheduler, state)); } }, dt); return new CompositeDisposable(disposable, disposableCreate(function () { localClearTimeout(id); })); } function scheduleAbsolute(state, dueTime, action) { return this.scheduleWithRelativeAndState(state, dueTime - this.now(), action); } return new Scheduler(defaultNow, scheduleNow, scheduleRelative, scheduleAbsolute); })(); /** * Represents a notification to an observer. */ var Notification = Rx.Notification = (function () { function Notification(kind, hasValue) { this.hasValue = hasValue == null ? false : hasValue; this.kind = kind; } /** * Invokes the delegate corresponding to the notification or the observer's method corresponding to the notification and returns the produced result. * * @memberOf Notification * @param {Any} observerOrOnNext Delegate to invoke for an OnNext notification or Observer to invoke the notification on.. * @param {Function} onError Delegate to invoke for an OnError notification. * @param {Function} onCompleted Delegate to invoke for an OnCompleted notification. * @returns {Any} Result produced by the observation. */ Notification.prototype.accept = function (observerOrOnNext, onError, onCompleted) { return observerOrOnNext && typeof observerOrOnNext === 'object' ? this._acceptObservable(observerOrOnNext) : this._accept(observerOrOnNext, onError, onCompleted); }; /** * Returns an observable sequence with a single notification. * * @memberOf Notifications * @param {Scheduler} [scheduler] Scheduler to send out the notification calls on. * @returns {Observable} The observable sequence that surfaces the behavior of the notification upon subscription. */ Notification.prototype.toObservable = function (scheduler) { var notification = this; isScheduler(scheduler) || (scheduler = immediateScheduler); return new AnonymousObservable(function (observer) { return scheduler.schedule(function () { notification._acceptObservable(observer); notification.kind === 'N' && observer.onCompleted(); }); }); }; return Notification; })(); /** * Creates an object that represents an OnNext notification to an observer. * @param {Any} value The value contained in the notification. * @returns {Notification} The OnNext notification containing the value. */ var notificationCreateOnNext = Notification.createOnNext = (function () { function _accept (onNext) { return onNext(this.value); } function _acceptObservable(observer) { return observer.onNext(this.value); } function toString () { return 'OnNext(' + this.value + ')'; } return function (value) { var notification = new Notification('N', true); notification.value = value; notification._accept = _accept; notification._acceptObservable = _acceptObservable; notification.toString = toString; return notification; }; }()); /** * Creates an object that represents an OnError notification to an observer. * @param {Any} error The exception contained in the notification. * @returns {Notification} The OnError notification containing the exception. */ var notificationCreateOnError = Notification.createOnError = (function () { function _accept (onNext, onError) { return onError(this.exception); } function _acceptObservable(observer) { return observer.onError(this.exception); } function toString () { return 'OnError(' + this.exception + ')'; } return function (e) { var notification = new Notification('E'); notification.exception = e; notification._accept = _accept; notification._acceptObservable = _acceptObservable; notification.toString = toString; return notification; }; }()); /** * Creates an object that represents an OnCompleted notification to an observer. * @returns {Notification} The OnCompleted notification. */ var notificationCreateOnCompleted = Notification.createOnCompleted = (function () { function _accept (onNext, onError, onCompleted) { return onCompleted(); } function _acceptObservable(observer) { return observer.onCompleted(); } function toString () { return 'OnCompleted()'; } return function () { var notification = new Notification('C'); notification._accept = _accept; notification._acceptObservable = _acceptObservable; notification.toString = toString; return notification; }; }()); var Enumerator = Rx.internals.Enumerator = function (next) { this._next = next; }; Enumerator.prototype.next = function () { return this._next(); }; Enumerator.prototype[$iterator$] = function () { return this; } var Enumerable = Rx.internals.Enumerable = function (iterator) { this._iterator = iterator; }; Enumerable.prototype[$iterator$] = function () { return this._iterator(); }; Enumerable.prototype.concat = function () { var sources = this; return new AnonymousObservable(function (observer) { var e; try { e = sources[$iterator$](); } catch(err) { observer.onError(); return; } var isDisposed, subscription = new SerialDisposable(); var cancelable = immediateScheduler.scheduleRecursive(function (self) { var currentItem; if (isDisposed) { return; } try { currentItem = e.next(); } catch (ex) { observer.onError(ex); return; } if (currentItem.done) { observer.onCompleted(); return; } // Check if promise var currentValue = currentItem.value; isPromise(currentValue) && (currentValue = observableFromPromise(currentValue)); var d = new SingleAssignmentDisposable(); subscription.setDisposable(d); d.setDisposable(currentValue.subscribe( observer.onNext.bind(observer), observer.onError.bind(observer), function () { self(); }) ); }); return new CompositeDisposable(subscription, cancelable, disposableCreate(function () { isDisposed = true; })); }); }; Enumerable.prototype.catchException = function () { var sources = this; return new AnonymousObservable(function (observer) { var e; try { e = sources[$iterator$](); } catch(err) { observer.onError(); return; } var isDisposed, lastException, subscription = new SerialDisposable(); var cancelable = immediateScheduler.scheduleRecursive(function (self) { if (isDisposed) { return; } var currentItem; try { currentItem = e.next(); } catch (ex) { observer.onError(ex); return; } if (currentItem.done) { if (lastException) { observer.onError(lastException); } else { observer.onCompleted(); } return; } // Check if promise var currentValue = currentItem.value; isPromise(currentValue) && (currentValue = observableFromPromise(currentValue)); var d = new SingleAssignmentDisposable(); subscription.setDisposable(d); d.setDisposable(currentValue.subscribe( observer.onNext.bind(observer), function (exn) { lastException = exn; self(); }, observer.onCompleted.bind(observer))); }); return new CompositeDisposable(subscription, cancelable, disposableCreate(function () { isDisposed = true; })); }); }; var enumerableRepeat = Enumerable.repeat = function (value, repeatCount) { if (repeatCount == null) { repeatCount = -1; } return new Enumerable(function () { var left = repeatCount; return new Enumerator(function () { if (left === 0) { return doneEnumerator; } if (left > 0) { left--; } return { done: false, value: value }; }); }); }; var enumerableOf = Enumerable.of = function (source, selector, thisArg) { selector || (selector = identity); return new Enumerable(function () { var index = -1; return new Enumerator( function () { return ++index < source.length ? { done: false, value: selector.call(thisArg, source[index], index, source) } : doneEnumerator; }); }); }; /** * Supports push-style iteration over an observable sequence. */ var Observer = Rx.Observer = function () { }; /** * Creates a notification callback from an observer. * @returns The action that forwards its input notification to the underlying observer. */ Observer.prototype.toNotifier = function () { var observer = this; return function (n) { return n.accept(observer); }; }; /** * Hides the identity of an observer. * @returns An observer that hides the identity of the specified observer. */ Observer.prototype.asObserver = function () { return new AnonymousObserver(this.onNext.bind(this), this.onError.bind(this), this.onCompleted.bind(this)); }; /** * Creates an observer from the specified OnNext, along with optional OnError, and OnCompleted actions. * @param {Function} [onNext] Observer's OnNext action implementation. * @param {Function} [onError] Observer's OnError action implementation. * @param {Function} [onCompleted] Observer's OnCompleted action implementation. * @returns {Observer} The observer object implemented using the given actions. */ var observerCreate = Observer.create = function (onNext, onError, onCompleted) { onNext || (onNext = noop); onError || (onError = defaultError); onCompleted || (onCompleted = noop); return new AnonymousObserver(onNext, onError, onCompleted); }; /** * Creates an observer from a notification callback. * @param {Function} handler Action that handles a notification. * @returns The observer object that invokes the specified handler using a notification corresponding to each message it receives. */ Observer.fromNotifier = function (handler, thisArg) { return new AnonymousObserver(function (x) { return handler.call(thisArg, notificationCreateOnNext(x)); }, function (e) { return handler.call(thisArg, notificationCreateOnError(e)); }, function () { return handler.call(thisArg, notificationCreateOnCompleted()); }); }; /** * Abstract base class for implementations of the Observer class. * This base class enforces the grammar of observers where OnError and OnCompleted are terminal messages. */ var AbstractObserver = Rx.internals.AbstractObserver = (function (__super__) { inherits(AbstractObserver, __super__); /** * Creates a new observer in a non-stopped state. */ function AbstractObserver() { this.isStopped = false; __super__.call(this); } /** * Notifies the observer of a new element in the sequence. * @param {Any} value Next element in the sequence. */ AbstractObserver.prototype.onNext = function (value) { if (!this.isStopped) { this.next(value); } }; /** * Notifies the observer that an exception has occurred. * @param {Any} error The error that has occurred. */ AbstractObserver.prototype.onError = function (error) { if (!this.isStopped) { this.isStopped = true; this.error(error); } }; /** * Notifies the observer of the end of the sequence. */ AbstractObserver.prototype.onCompleted = function () { if (!this.isStopped) { this.isStopped = true; this.completed(); } }; /** * Disposes the observer, causing it to transition to the stopped state. */ AbstractObserver.prototype.dispose = function () { this.isStopped = true; }; AbstractObserver.prototype.fail = function (e) { if (!this.isStopped) { this.isStopped = true; this.error(e); return true; } return false; }; return AbstractObserver; }(Observer)); /** * Class to create an Observer instance from delegate-based implementations of the on* methods. */ var AnonymousObserver = Rx.AnonymousObserver = (function (__super__) { inherits(AnonymousObserver, __super__); /** * Creates an observer from the specified OnNext, OnError, and OnCompleted actions. * @param {Any} onNext Observer's OnNext action implementation. * @param {Any} onError Observer's OnError action implementation. * @param {Any} onCompleted Observer's OnCompleted action implementation. */ function AnonymousObserver(onNext, onError, onCompleted) { __super__.call(this); this._onNext = onNext; this._onError = onError; this._onCompleted = onCompleted; } /** * Calls the onNext action. * @param {Any} value Next element in the sequence. */ AnonymousObserver.prototype.next = function (value) { this._onNext(value); }; /** * Calls the onError action. * @param {Any} error The error that has occurred. */ AnonymousObserver.prototype.error = function (error) { this._onError(error); }; /** * Calls the onCompleted action. */ AnonymousObserver.prototype.completed = function () { this._onCompleted(); }; return AnonymousObserver; }(AbstractObserver)); var observableProto; /** * Represents a push-style collection. */ var Observable = Rx.Observable = (function () { function Observable(subscribe) { this._subscribe = subscribe; } observableProto = Observable.prototype; /** * Subscribes an observer to the observable sequence. * @param {Mixed} [observerOrOnNext] The object that is to receive notifications or an action to invoke for each element in the observable sequence. * @param {Function} [onError] Action to invoke upon exceptional termination of the observable sequence. * @param {Function} [onCompleted] Action to invoke upon graceful termination of the observable sequence. * @returns {Diposable} A disposable handling the subscriptions and unsubscriptions. */ observableProto.subscribe = observableProto.forEach = function (observerOrOnNext, onError, onCompleted) { return this._subscribe(typeof observerOrOnNext === 'object' ? observerOrOnNext : observerCreate(observerOrOnNext, onError, onCompleted)); }; /** * Subscribes to the next value in the sequence with an optional "this" argument. * @param {Function} onNext The function to invoke on each element in the observable sequence. * @param {Any} [thisArg] Object to use as this when executing callback. * @returns {Disposable} A disposable handling the subscriptions and unsubscriptions. */ observableProto.subscribeOnNext = function (onNext, thisArg) { return this._subscribe(observerCreate(arguments.length === 2 ? function(x) { onNext.call(thisArg, x); } : onNext)); }; /** * Subscribes to an exceptional condition in the sequence with an optional "this" argument. * @param {Function} onError The function to invoke upon exceptional termination of the observable sequence. * @param {Any} [thisArg] Object to use as this when executing callback. * @returns {Disposable} A disposable handling the subscriptions and unsubscriptions. */ observableProto.subscribeOnError = function (onError, thisArg) { return this._subscribe(observerCreate(null, arguments.length === 2 ? function(e) { onError.call(thisArg, e); } : onError)); }; /** * Subscribes to the next value in the sequence with an optional "this" argument. * @param {Function} onCompleted The function to invoke upon graceful termination of the observable sequence. * @param {Any} [thisArg] Object to use as this when executing callback. * @returns {Disposable} A disposable handling the subscriptions and unsubscriptions. */ observableProto.subscribeOnCompleted = function (onCompleted, thisArg) { return this._subscribe(observerCreate(null, null, arguments.length === 2 ? function() { onCompleted.call(thisArg); } : onCompleted)); }; return Observable; })(); var ScheduledObserver = Rx.internals.ScheduledObserver = (function (__super__) { inherits(ScheduledObserver, __super__); function ScheduledObserver(scheduler, observer) { __super__.call(this); this.scheduler = scheduler; this.observer = observer; this.isAcquired = false; this.hasFaulted = false; this.queue = []; this.disposable = new SerialDisposable(); } ScheduledObserver.prototype.next = function (value) { var self = this; this.queue.push(function () { self.observer.onNext(value); }); }; ScheduledObserver.prototype.error = function (err) { var self = this; this.queue.push(function () { self.observer.onError(err); }); }; ScheduledObserver.prototype.completed = function () { var self = this; this.queue.push(function () { self.observer.onCompleted(); }); }; ScheduledObserver.prototype.ensureActive = function () { var isOwner = false, parent = this; if (!this.hasFaulted && this.queue.length > 0) { isOwner = !this.isAcquired; this.isAcquired = true; } if (isOwner) { this.disposable.setDisposable(this.scheduler.scheduleRecursive(function (self) { var work; if (parent.queue.length > 0) { work = parent.queue.shift(); } else { parent.isAcquired = false; return; } try { work(); } catch (ex) { parent.queue = []; parent.hasFaulted = true; throw ex; } self(); })); } }; ScheduledObserver.prototype.dispose = function () { __super__.prototype.dispose.call(this); this.disposable.dispose(); }; return ScheduledObserver; }(AbstractObserver)); /** * Creates a list from an observable sequence. * @returns An observable sequence containing a single element with a list containing all the elements of the source sequence. */ observableProto.toArray = function () { var self = this; return new AnonymousObservable(function(observer) { var arr = []; return self.subscribe( arr.push.bind(arr), observer.onError.bind(observer), function () { observer.onNext(arr); observer.onCompleted(); }); }); }; /** * Creates an observable sequence from a specified subscribe method implementation. * * @example * var res = Rx.Observable.create(function (observer) { return function () { } ); * var res = Rx.Observable.create(function (observer) { return Rx.Disposable.empty; } ); * var res = Rx.Observable.create(function (observer) { } ); * * @param {Function} subscribe Implementation of the resulting observable sequence's subscribe method, returning a function that will be wrapped in a Disposable. * @returns {Observable} The observable sequence with the specified implementation for the Subscribe method. */ Observable.create = Observable.createWithDisposable = function (subscribe) { return new AnonymousObservable(subscribe); }; /** * Returns an observable sequence that invokes the specified factory function whenever a new observer subscribes. * * @example * var res = Rx.Observable.defer(function () { return Rx.Observable.fromArray([1,2,3]); }); * @param {Function} observableFactory Observable factory function to invoke for each observer that subscribes to the resulting sequence or Promise. * @returns {Observable} An observable sequence whose observers trigger an invocation of the given observable factory function. */ var observableDefer = Observable.defer = function (observableFactory) { return new AnonymousObservable(function (observer) { var result; try { result = observableFactory(); } catch (e) { return observableThrow(e).subscribe(observer); } isPromise(result) && (result = observableFromPromise(result)); return result.subscribe(observer); }); }; /** * Returns an empty observable sequence, using the specified scheduler to send out the single OnCompleted message. * * @example * var res = Rx.Observable.empty(); * var res = Rx.Observable.empty(Rx.Scheduler.timeout); * @param {Scheduler} [scheduler] Scheduler to send the termination call on. * @returns {Observable} An observable sequence with no elements. */ var observableEmpty = Observable.empty = function (scheduler) { isScheduler(scheduler) || (scheduler = immediateScheduler); return new AnonymousObservable(function (observer) { return scheduler.schedule(function () { observer.onCompleted(); }); }); }; var maxSafeInteger = Math.pow(2, 53) - 1; function numberIsFinite(value) { return typeof value === 'number' && root.isFinite(value); } function isNan(n) { return n !== n; } function isIterable(o) { return o[$iterator$] !== undefined; } function sign(value) { var number = +value; if (number === 0) { return number; } if (isNaN(number)) { return number; } return number < 0 ? -1 : 1; } function toLength(o) { var len = +o.length; if (isNaN(len)) { return 0; } if (len === 0 || !numberIsFinite(len)) { return len; } len = sign(len) * Math.floor(Math.abs(len)); if (len <= 0) { return 0; } if (len > maxSafeInteger) { return maxSafeInteger; } return len; } function isCallable(f) { return Object.prototype.toString.call(f) === '[object Function]' && typeof f === 'function'; } /** * This method creates a new Observable sequence from an array-like or iterable object. * @param {Any} arrayLike An array-like or iterable object to convert to an Observable sequence. * @param {Function} [mapFn] Map function to call on every element of the array. * @param {Any} [thisArg] The context to use calling the mapFn if provided. * @param {Scheduler} [scheduler] Optional scheduler to use for scheduling. If not provided, defaults to Scheduler.currentThread. */ var observableFrom = Observable.from = function (iterable, mapFn, thisArg, scheduler) { if (iterable == null) { throw new Error('iterable cannot be null.') } if (mapFn && !isCallable(mapFn)) { throw new Error('mapFn when provided must be a function'); } isScheduler(scheduler) || (scheduler = currentThreadScheduler); return new AnonymousObservable(function (observer) { var list = Object(iterable), objIsIterable = isIterable(list), len = objIsIterable ? 0 : toLength(list), it = objIsIterable ? list[$iterator$]() : null, i = 0; return scheduler.scheduleRecursive(function (self) { if (i < len || objIsIterable) { var result; if (objIsIterable) { var next; try { next = it.next(); } catch (e) { observer.onError(e); return; } if (next.done) { observer.onCompleted(); return; } result = next.value; } else { result = !!list.charAt ? list.charAt(i) : list[i]; } if (mapFn && isCallable(mapFn)) { try { result = thisArg ? mapFn.call(thisArg, result, i) : mapFn(result, i); } catch (e) { observer.onError(e); return; } } observer.onNext(result); i++; self(); } else { observer.onCompleted(); } }); }); }; /** * Converts an array to an observable sequence, using an optional scheduler to enumerate the array. * * @example * var res = Rx.Observable.fromArray([1,2,3]); * var res = Rx.Observable.fromArray([1,2,3], Rx.Scheduler.timeout); * @param {Scheduler} [scheduler] Scheduler to run the enumeration of the input sequence on. * @returns {Observable} The observable sequence whose elements are pulled from the given enumerable sequence. */ var observableFromArray = Observable.fromArray = function (array, scheduler) { isScheduler(scheduler) || (scheduler = currentThreadScheduler); return new AnonymousObservable(function (observer) { var count = 0, len = array.length; return scheduler.scheduleRecursive(function (self) { if (count < len) { observer.onNext(array[count++]); self(); } else { observer.onCompleted(); } }); }); }; /** * Returns a non-terminating observable sequence, which can be used to denote an infinite duration (e.g. when using reactive joins). * @returns {Observable} An observable sequence whose observers will never get called. */ var observableNever = Observable.never = function () { return new AnonymousObservable(function () { return disposableEmpty; }); }; /** * This method creates a new Observable instance with a variable number of arguments, regardless of number or type of the arguments. * @example * var res = Rx.Observable.of(1,2,3); * @returns {Observable} The observable sequence whose elements are pulled from the given arguments. */ Observable.of = function () { var len = arguments.length, args = new Array(len); for(var i = 0; i < len; i++) { args[i] = arguments[i]; } return observableFromArray(args); }; /** * This method creates a new Observable instance with a variable number of arguments, regardless of number or type of the arguments. * @example * var res = Rx.Observable.of(1,2,3); * @param {Scheduler} scheduler A scheduler to use for scheduling the arguments. * @returns {Observable} The observable sequence whose elements are pulled from the given arguments. */ var observableOf = Observable.ofWithScheduler = function (scheduler) { var len = arguments.length - 1, args = new Array(len); for(var i = 0; i < len; i++) { args[i] = arguments[i + 1]; } return observableFromArray(args, scheduler); }; /** * Generates an observable sequence of integral numbers within a specified range, using the specified scheduler to send out observer messages. * * @example * var res = Rx.Observable.range(0, 10); * var res = Rx.Observable.range(0, 10, Rx.Scheduler.timeout); * @param {Number} start The value of the first integer in the sequence. * @param {Number} count The number of sequential integers to generate. * @param {Scheduler} [scheduler] Scheduler to run the generator loop on. If not specified, defaults to Scheduler.currentThread. * @returns {Observable} An observable sequence that contains a range of sequential integral numbers. */ Observable.range = function (start, count, scheduler) { isScheduler(scheduler) || (scheduler = currentThreadScheduler); return new AnonymousObservable(function (observer) { return scheduler.scheduleRecursiveWithState(0, function (i, self) { if (i < count) { observer.onNext(start + i); self(i + 1); } else { observer.onCompleted(); } }); }); }; /** * Generates an observable sequence that repeats the given element the specified number of times, using the specified scheduler to send out observer messages. * * @example * var res = Rx.Observable.repeat(42); * var res = Rx.Observable.repeat(42, 4); * 3 - res = Rx.Observable.repeat(42, 4, Rx.Scheduler.timeout); * 4 - res = Rx.Observable.repeat(42, null, Rx.Scheduler.timeout); * @param {Mixed} value Element to repeat. * @param {Number} repeatCount [Optiona] Number of times to repeat the element. If not specified, repeats indefinitely. * @param {Scheduler} scheduler Scheduler to run the producer loop on. If not specified, defaults to Scheduler.immediate. * @returns {Observable} An observable sequence that repeats the given element the specified number of times. */ Observable.repeat = function (value, repeatCount, scheduler) { isScheduler(scheduler) || (scheduler = currentThreadScheduler); return observableReturn(value, scheduler).repeat(repeatCount == null ? -1 : repeatCount); }; /** * Returns an observable sequence that contains a single element, using the specified scheduler to send out observer messages. * There is an alias called 'just', and 'returnValue' for browsers <IE9. * * @example * var res = Rx.Observable.return(42); * var res = Rx.Observable.return(42, Rx.Scheduler.timeout); * @param {Mixed} value Single element in the resulting observable sequence. * @param {Scheduler} scheduler Scheduler to send the single element on. If not specified, defaults to Scheduler.immediate. * @returns {Observable} An observable sequence containing the single specified element. */ var observableReturn = Observable['return'] = Observable.returnValue = Observable.just = function (value, scheduler) { isScheduler(scheduler) || (scheduler = immediateScheduler); return new AnonymousObservable(function (observer) { return scheduler.schedule(function () { observer.onNext(value); observer.onCompleted(); }); }); }; /** * Returns an observable sequence that terminates with an exception, using the specified scheduler to send out the single onError message. * There is an alias to this method called 'throwError' for browsers <IE9. * @param {Mixed} exception An object used for the sequence's termination. * @param {Scheduler} scheduler Scheduler to send the exceptional termination call on. If not specified, defaults to Scheduler.immediate. * @returns {Observable} The observable sequence that terminates exceptionally with the specified exception object. */ var observableThrow = Observable['throw'] = Observable.throwException = Observable.throwError = function (exception, scheduler) { isScheduler(scheduler) || (scheduler = immediateScheduler); return new AnonymousObservable(function (observer) { return scheduler.schedule(function () { observer.onError(exception); }); }); }; function observableCatchHandler(source, handler) { return new AnonymousObservable(function (observer) { var d1 = new SingleAssignmentDisposable(), subscription = new SerialDisposable(); subscription.setDisposable(d1); d1.setDisposable(source.subscribe(observer.onNext.bind(observer), function (exception) { var d, result; try { result = handler(exception); } catch (ex) { observer.onError(ex); return; } isPromise(result) && (result = observableFromPromise(result)); d = new SingleAssignmentDisposable(); subscription.setDisposable(d); d.setDisposable(result.subscribe(observer)); }, observer.onCompleted.bind(observer))); return subscription; }); } /** * Continues an observable sequence that is terminated by an exception with the next observable sequence. * @example * 1 - xs.catchException(ys) * 2 - xs.catchException(function (ex) { return ys(ex); }) * @param {Mixed} handlerOrSecond Exception handler function that returns an observable sequence given the error that occurred in the first sequence, or a second observable sequence used to produce results when an error occurred in the first sequence. * @returns {Observable} An observable sequence containing the first sequence's elements, followed by the elements of the handler sequence in case an exception occurred. */ observableProto['catch'] = observableProto.catchError = observableProto.catchException = function (handlerOrSecond) { return typeof handlerOrSecond === 'function' ? observableCatchHandler(this, handlerOrSecond) : observableCatch([this, handlerOrSecond]); }; /** * Continues an observable sequence that is terminated by an exception with the next observable sequence. * @param {Array | Arguments} args Arguments or an array to use as the next sequence if an error occurs. * @returns {Observable} An observable sequence containing elements from consecutive source sequences until a source sequence terminates successfully. */ var observableCatch = Observable.catchException = Observable.catchError = Observable['catch'] = function () { return enumerableOf(argsOrArray(arguments, 0)).catchException(); }; /** * Merges the specified observable sequences into one observable sequence by using the selector function whenever any of the observable sequences or Promises produces an element. * This can be in the form of an argument list of observables or an array. * * @example * 1 - obs = observable.combineLatest(obs1, obs2, obs3, function (o1, o2, o3) { return o1 + o2 + o3; }); * 2 - obs = observable.combineLatest([obs1, obs2, obs3], function (o1, o2, o3) { return o1 + o2 + o3; }); * @returns {Observable} An observable sequence containing the result of combining elements of the sources using the specified result selector function. */ observableProto.combineLatest = function () { var args = slice.call(arguments); if (Array.isArray(args[0])) { args[0].unshift(this); } else { args.unshift(this); } return combineLatest.apply(this, args); }; /** * Merges the specified observable sequences into one observable sequence by using the selector function whenever any of the observable sequences or Promises produces an element. * * @example * 1 - obs = Rx.Observable.combineLatest(obs1, obs2, obs3, function (o1, o2, o3) { return o1 + o2 + o3; }); * 2 - obs = Rx.Observable.combineLatest([obs1, obs2, obs3], function (o1, o2, o3) { return o1 + o2 + o3; }); * @returns {Observable} An observable sequence containing the result of combining elements of the sources using the specified result selector function. */ var combineLatest = Observable.combineLatest = function () { var args = slice.call(arguments), resultSelector = args.pop(); if (Array.isArray(args[0])) { args = args[0]; } return new AnonymousObservable(function (observer) { var falseFactory = function () { return false; }, n = args.length, hasValue = arrayInitialize(n, falseFactory), hasValueAll = false, isDone = arrayInitialize(n, falseFactory), values = new Array(n); function next(i) { var res; hasValue[i] = true; if (hasValueAll || (hasValueAll = hasValue.every(identity))) { try { res = resultSelector.apply(null, values); } catch (ex) { observer.onError(ex); return; } observer.onNext(res); } else if (isDone.filter(function (x, j) { return j !== i; }).every(identity)) { observer.onCompleted(); } } function done (i) { isDone[i] = true; if (isDone.every(identity)) { observer.onCompleted(); } } var subscriptions = new Array(n); for (var idx = 0; idx < n; idx++) { (function (i) { var source = args[i], sad = new SingleAssignmentDisposable(); isPromise(source) && (source = observableFromPromise(source)); sad.setDisposable(source.subscribe(function (x) { values[i] = x; next(i); }, observer.onError.bind(observer), function () { done(i); })); subscriptions[i] = sad; }(idx)); } return new CompositeDisposable(subscriptions); }); }; /** * Concatenates all the observable sequences. This takes in either an array or variable arguments to concatenate. * * @example * 1 - concatenated = xs.concat(ys, zs); * 2 - concatenated = xs.concat([ys, zs]); * @returns {Observable} An observable sequence that contains the elements of each given sequence, in sequential order. */ observableProto.concat = function () { var items = slice.call(arguments, 0); items.unshift(this); return observableConcat.apply(this, items); }; /** * Concatenates all the observable sequences. * @param {Array | Arguments} args Arguments or an array to concat to the observable sequence. * @returns {Observable} An observable sequence that contains the elements of each given sequence, in sequential order. */ var observableConcat = Observable.concat = function () { return enumerableOf(argsOrArray(arguments, 0)).concat(); }; /** * Concatenates an observable sequence of observable sequences. * @returns {Observable} An observable sequence that contains the elements of each observed inner sequence, in sequential order. */ observableProto.concatObservable = observableProto.concatAll =function () { return this.merge(1); }; /** * Merges an observable sequence of observable sequences into an observable sequence, limiting the number of concurrent subscriptions to inner sequences. * Or merges two observable sequences into a single observable sequence. * * @example * 1 - merged = sources.merge(1); * 2 - merged = source.merge(otherSource); * @param {Mixed} [maxConcurrentOrOther] Maximum number of inner observable sequences being subscribed to concurrently or the second observable sequence. * @returns {Observable} The observable sequence that merges the elements of the inner sequences. */ observableProto.merge = function (maxConcurrentOrOther) { if (typeof maxConcurrentOrOther !== 'number') { return observableMerge(this, maxConcurrentOrOther); } var sources = this; return new AnonymousObservable(function (observer) { var activeCount = 0, group = new CompositeDisposable(), isStopped = false, q = []; function subscribe(xs) { var subscription = new SingleAssignmentDisposable(); group.add(subscription); // Check for promises support isPromise(xs) && (xs = observableFromPromise(xs)); subscription.setDisposable(xs.subscribe(observer.onNext.bind(observer), observer.onError.bind(observer), function () { group.remove(subscription); if (q.length > 0) { subscribe(q.shift()); } else { activeCount--; isStopped && activeCount === 0 && observer.onCompleted(); } })); } group.add(sources.subscribe(function (innerSource) { if (activeCount < maxConcurrentOrOther) { activeCount++; subscribe(innerSource); } else { q.push(innerSource); } }, observer.onError.bind(observer), function () { isStopped = true; activeCount === 0 && observer.onCompleted(); })); return group; }); }; /** * Merges all the observable sequences into a single observable sequence. * The scheduler is optional and if not specified, the immediate scheduler is used. * * @example * 1 - merged = Rx.Observable.merge(xs, ys, zs); * 2 - merged = Rx.Observable.merge([xs, ys, zs]); * 3 - merged = Rx.Observable.merge(scheduler, xs, ys, zs); * 4 - merged = Rx.Observable.merge(scheduler, [xs, ys, zs]); * @returns {Observable} The observable sequence that merges the elements of the observable sequences. */ var observableMerge = Observable.merge = function () { var scheduler, sources; if (!arguments[0]) { scheduler = immediateScheduler; sources = slice.call(arguments, 1); } else if (arguments[0].now) { scheduler = arguments[0]; sources = slice.call(arguments, 1); } else { scheduler = immediateScheduler; sources = slice.call(arguments, 0); } if (Array.isArray(sources[0])) { sources = sources[0]; } return observableFromArray(sources, scheduler).mergeObservable(); }; /** * Merges an observable sequence of observable sequences into an observable sequence. * @returns {Observable} The observable sequence that merges the elements of the inner sequences. */ observableProto.mergeObservable = observableProto.mergeAll = function () { var sources = this; return new AnonymousObservable(function (observer) { var group = new CompositeDisposable(), isStopped = false, m = new SingleAssignmentDisposable(); group.add(m); m.setDisposable(sources.subscribe(function (innerSource) { var innerSubscription = new SingleAssignmentDisposable(); group.add(innerSubscription); // Check for promises support isPromise(innerSource) && (innerSource = observableFromPromise(innerSource)); innerSubscription.setDisposable(innerSource.subscribe(observer.onNext.bind(observer), observer.onError.bind(observer), function () { group.remove(innerSubscription); isStopped && group.length === 1 && observer.onCompleted(); })); }, observer.onError.bind(observer), function () { isStopped = true; group.length === 1 && observer.onCompleted(); })); return group; }); }; /** * Returns the values from the source observable sequence only after the other observable sequence produces a value. * @param {Observable | Promise} other The observable sequence or Promise that triggers propagation of elements of the source sequence. * @returns {Observable} An observable sequence containing the elements of the source sequence starting from the point the other sequence triggered propagation. */ observableProto.skipUntil = function (other) { var source = this; return new AnonymousObservable(function (observer) { var isOpen = false; var disposables = new CompositeDisposable(source.subscribe(function (left) { isOpen && observer.onNext(left); }, observer.onError.bind(observer), function () { isOpen && observer.onCompleted(); })); isPromise(other) && (other = observableFromPromise(other)); var rightSubscription = new SingleAssignmentDisposable(); disposables.add(rightSubscription); rightSubscription.setDisposable(other.subscribe(function () { isOpen = true; rightSubscription.dispose(); }, observer.onError.bind(observer), function () { rightSubscription.dispose(); })); return disposables; }); }; /** * Transforms an observable sequence of observable sequences into an observable sequence producing values only from the most recent observable sequence. * @returns {Observable} The observable sequence that at any point in time produces the elements of the most recent inner observable sequence that has been received. */ observableProto['switch'] = observableProto.switchLatest = function () { var sources = this; return new AnonymousObservable(function (observer) { var hasLatest = false, innerSubscription = new SerialDisposable(), isStopped = false, latest = 0, subscription = sources.subscribe( function (innerSource) { var d = new SingleAssignmentDisposable(), id = ++latest; hasLatest = true; innerSubscription.setDisposable(d); // Check if Promise or Observable isPromise(innerSource) && (innerSource = observableFromPromise(innerSource)); d.setDisposable(innerSource.subscribe( function (x) { latest === id && observer.onNext(x); }, function (e) { latest === id && observer.onError(e); }, function () { if (latest === id) { hasLatest = false; isStopped && observer.onCompleted(); } })); }, observer.onError.bind(observer), function () { isStopped = true; !hasLatest && observer.onCompleted(); }); return new CompositeDisposable(subscription, innerSubscription); }); }; /** * Returns the values from the source observable sequence until the other observable sequence produces a value. * @param {Observable | Promise} other Observable sequence or Promise that terminates propagation of elements of the source sequence. * @returns {Observable} An observable sequence containing the elements of the source sequence up to the point the other sequence interrupted further propagation. */ observableProto.takeUntil = function (other) { var source = this; return new AnonymousObservable(function (observer) { isPromise(other) && (other = observableFromPromise(other)); return new CompositeDisposable( source.subscribe(observer), other.subscribe(observer.onCompleted.bind(observer), observer.onError.bind(observer), noop) ); }); }; function zipArray(second, resultSelector) { var first = this; return new AnonymousObservable(function (observer) { var index = 0, len = second.length; return first.subscribe(function (left) { if (index < len) { var right = second[index++], result; try { result = resultSelector(left, right); } catch (e) { observer.onError(e); return; } observer.onNext(result); } else { observer.onCompleted(); } }, observer.onError.bind(observer), observer.onCompleted.bind(observer)); }); } /** * Merges the specified observable sequences into one observable sequence by using the selector function whenever all of the observable sequences or an array have produced an element at a corresponding index. * The last element in the arguments must be a function to invoke for each series of elements at corresponding indexes in the sources. * * @example * 1 - res = obs1.zip(obs2, fn); * 1 - res = x1.zip([1,2,3], fn); * @returns {Observable} An observable sequence containing the result of combining elements of the sources using the specified result selector function. */ observableProto.zip = function () { if (Array.isArray(arguments[0])) { return zipArray.apply(this, arguments); } var parent = this, sources = slice.call(arguments), resultSelector = sources.pop(); sources.unshift(parent); return new AnonymousObservable(function (observer) { var n = sources.length, queues = arrayInitialize(n, function () { return []; }), isDone = arrayInitialize(n, function () { return false; }); function next(i) { var res, queuedValues; if (queues.every(function (x) { return x.length > 0; })) { try { queuedValues = queues.map(function (x) { return x.shift(); }); res = resultSelector.apply(parent, queuedValues); } catch (ex) { observer.onError(ex); return; } observer.onNext(res); } else if (isDone.filter(function (x, j) { return j !== i; }).every(identity)) { observer.onCompleted(); } }; function done(i) { isDone[i] = true; if (isDone.every(function (x) { return x; })) { observer.onCompleted(); } } var subscriptions = new Array(n); for (var idx = 0; idx < n; idx++) { (function (i) { var source = sources[i], sad = new SingleAssignmentDisposable(); isPromise(source) && (source = observableFromPromise(source)); sad.setDisposable(source.subscribe(function (x) { queues[i].push(x); next(i); }, observer.onError.bind(observer), function () { done(i); })); subscriptions[i] = sad; })(idx); } return new CompositeDisposable(subscriptions); }); }; /** * Merges the specified observable sequences into one observable sequence by using the selector function whenever all of the observable sequences have produced an element at a corresponding index. * @param arguments Observable sources. * @param {Function} resultSelector Function to invoke for each series of elements at corresponding indexes in the sources. * @returns {Observable} An observable sequence containing the result of combining elements of the sources using the specified result selector function. */ Observable.zip = function () { var args = slice.call(arguments, 0), first = args.shift(); return first.zip.apply(first, args); }; /** * Merges the specified observable sequences into one observable sequence by emitting a list with the elements of the observable sequences at corresponding indexes. * @param arguments Observable sources. * @returns {Observable} An observable sequence containing lists of elements at corresponding indexes. */ Observable.zipArray = function () { var sources = argsOrArray(arguments, 0); return new AnonymousObservable(function (observer) { var n = sources.length, queues = arrayInitialize(n, function () { return []; }), isDone = arrayInitialize(n, function () { return false; }); function next(i) { if (queues.every(function (x) { return x.length > 0; })) { var res = queues.map(function (x) { return x.shift(); }); observer.onNext(res); } else if (isDone.filter(function (x, j) { return j !== i; }).every(identity)) { observer.onCompleted(); return; } }; function done(i) { isDone[i] = true; if (isDone.every(identity)) { observer.onCompleted(); return; } } var subscriptions = new Array(n); for (var idx = 0; idx < n; idx++) { (function (i) { subscriptions[i] = new SingleAssignmentDisposable(); subscriptions[i].setDisposable(sources[i].subscribe(function (x) { queues[i].push(x); next(i); }, observer.onError.bind(observer), function () { done(i); })); })(idx); } var compositeDisposable = new CompositeDisposable(subscriptions); compositeDisposable.add(disposableCreate(function () { for (var qIdx = 0, qLen = queues.length; qIdx < qLen; qIdx++) { queues[qIdx] = []; } })); return compositeDisposable; }); }; /** * Hides the identity of an observable sequence. * @returns {Observable} An observable sequence that hides the identity of the source sequence. */ observableProto.asObservable = function () { return new AnonymousObservable(this.subscribe.bind(this)); }; /** * Dematerializes the explicit notification values of an observable sequence as implicit notifications. * @returns {Observable} An observable sequence exhibiting the behavior corresponding to the source sequence's notification values. */ observableProto.dematerialize = function () { var source = this; return new AnonymousObservable(function (observer) { return source.subscribe(function (x) { return x.accept(observer); }, observer.onError.bind(observer), observer.onCompleted.bind(observer)); }); }; /** * Returns an observable sequence that contains only distinct contiguous elements according to the keySelector and the comparer. * * var obs = observable.distinctUntilChanged(); * var obs = observable.distinctUntilChanged(function (x) { return x.id; }); * var obs = observable.distinctUntilChanged(function (x) { return x.id; }, function (x, y) { return x === y; }); * * @param {Function} [keySelector] A function to compute the comparison key for each element. If not provided, it projects the value. * @param {Function} [comparer] Equality comparer for computed key values. If not provided, defaults to an equality comparer function. * @returns {Observable} An observable sequence only containing the distinct contiguous elements, based on a computed key value, from the source sequence. */ observableProto.distinctUntilChanged = function (keySelector, comparer) { var source = this; keySelector || (keySelector = identity); comparer || (comparer = defaultComparer); return new AnonymousObservable(function (observer) { var hasCurrentKey = false, currentKey; return source.subscribe(function (value) { var comparerEquals = false, key; try { key = keySelector(value); } catch (exception) { observer.onError(exception); return; } if (hasCurrentKey) { try { comparerEquals = comparer(currentKey, key); } catch (exception) { observer.onError(exception); return; } } if (!hasCurrentKey || !comparerEquals) { hasCurrentKey = true; currentKey = key; observer.onNext(value); } }, observer.onError.bind(observer), observer.onCompleted.bind(observer)); }); }; /** * Invokes an action for each element in the observable sequence and invokes an action upon graceful or exceptional termination of the observable sequence. * This method can be used for debugging, logging, etc. of query behavior by intercepting the message stream to run arbitrary actions for messages on the pipeline. * @param {Function | Observer} observerOrOnNext Action to invoke for each element in the observable sequence or an observer. * @param {Function} [onError] Action to invoke upon exceptional termination of the observable sequence. Used if only the observerOrOnNext parameter is also a function. * @param {Function} [onCompleted] Action to invoke upon graceful termination of the observable sequence. Used if only the observerOrOnNext parameter is also a function. * @returns {Observable} The source sequence with the side-effecting behavior applied. */ observableProto['do'] = observableProto.doAction = observableProto.tap = function (observerOrOnNext, onError, onCompleted) { var source = this, onNextFunc; if (typeof observerOrOnNext === 'function') { onNextFunc = observerOrOnNext; } else { onNextFunc = observerOrOnNext.onNext.bind(observerOrOnNext); onError = observerOrOnNext.onError.bind(observerOrOnNext); onCompleted = observerOrOnNext.onCompleted.bind(observerOrOnNext); } return new AnonymousObservable(function (observer) { return source.subscribe(function (x) { try { onNextFunc(x); } catch (e) { observer.onError(e); } observer.onNext(x); }, function (err) { if (onError) { try { onError(err); } catch (e) { observer.onError(e); } } observer.onError(err); }, function () { if (onCompleted) { try { onCompleted(); } catch (e) { observer.onError(e); } } observer.onCompleted(); }); }); }; /** * Invokes an action for each element in the observable sequence. * This method can be used for debugging, logging, etc. of query behavior by intercepting the message stream to run arbitrary actions for messages on the pipeline. * @param {Function} onNext Action to invoke for each element in the observable sequence. * @param {Any} [thisArg] Object to use as this when executing callback. * @returns {Observable} The source sequence with the side-effecting behavior applied. */ observableProto.doOnNext = observableProto.tapOnNext = function (onNext, thisArg) { return this.tap(arguments.length === 2 ? function (x) { onNext.call(thisArg, x); } : onNext); }; /** * Invokes an action upon exceptional termination of the observable sequence. * This method can be used for debugging, logging, etc. of query behavior by intercepting the message stream to run arbitrary actions for messages on the pipeline. * @param {Function} onError Action to invoke upon exceptional termination of the observable sequence. * @param {Any} [thisArg] Object to use as this when executing callback. * @returns {Observable} The source sequence with the side-effecting behavior applied. */ observableProto.doOnError = observableProto.tapOnError = function (onError, thisArg) { return this.tap(noop, arguments.length === 2 ? function (e) { onError.call(thisArg, e); } : onError); }; /** * Invokes an action upon graceful termination of the observable sequence. * This method can be used for debugging, logging, etc. of query behavior by intercepting the message stream to run arbitrary actions for messages on the pipeline. * @param {Function} onCompleted Action to invoke upon graceful termination of the observable sequence. * @param {Any} [thisArg] Object to use as this when executing callback. * @returns {Observable} The source sequence with the side-effecting behavior applied. */ observableProto.doOnCompleted = observableProto.tapOnCompleted = function (onCompleted, thisArg) { return this.tap(noop, null, arguments.length === 2 ? function () { onCompleted.call(thisArg); } : onCompleted); }; /** * Invokes a specified action after the source observable sequence terminates gracefully or exceptionally. * * @example * var res = observable.finallyAction(function () { console.log('sequence ended'; }); * @param {Function} finallyAction Action to invoke after the source observable sequence terminates. * @returns {Observable} Source sequence with the action-invoking termination behavior applied. */ observableProto['finally'] = observableProto.finallyAction = function (action) { var source = this; return new AnonymousObservable(function (observer) { var subscription; try { subscription = source.subscribe(observer); } catch (e) { action(); throw e; } return disposableCreate(function () { try { subscription.dispose(); } catch (e) { throw e; } finally { action(); } }); }); }; /** * Ignores all elements in an observable sequence leaving only the termination messages. * @returns {Observable} An empty observable sequence that signals termination, successful or exceptional, of the source sequence. */ observableProto.ignoreElements = function () { var source = this; return new AnonymousObservable(function (observer) { return source.subscribe(noop, observer.onError.bind(observer), observer.onCompleted.bind(observer)); }); }; /** * Materializes the implicit notifications of an observable sequence as explicit notification values. * @returns {Observable} An observable sequence containing the materialized notification values from the source sequence. */ observableProto.materialize = function () { var source = this; return new AnonymousObservable(function (observer) { return source.subscribe(function (value) { observer.onNext(notificationCreateOnNext(value)); }, function (e) { observer.onNext(notificationCreateOnError(e)); observer.onCompleted(); }, function () { observer.onNext(notificationCreateOnCompleted()); observer.onCompleted(); }); }); }; /** * Repeats the observable sequence a specified number of times. If the repeat count is not specified, the sequence repeats indefinitely. * * @example * var res = repeated = source.repeat(); * var res = repeated = source.repeat(42); * @param {Number} [repeatCount] Number of times to repeat the sequence. If not provided, repeats the sequence indefinitely. * @returns {Observable} The observable sequence producing the elements of the given sequence repeatedly. */ observableProto.repeat = function (repeatCount) { return enumerableRepeat(this, repeatCount).concat(); }; /** * Repeats the source observable sequence the specified number of times or until it successfully terminates. If the retry count is not specified, it retries indefinitely. * Note if you encounter an error and want it to retry once, then you must use .retry(2); * * @example * var res = retried = retry.repeat(); * var res = retried = retry.repeat(2); * @param {Number} [retryCount] Number of times to retry the sequence. If not provided, retry the sequence indefinitely. * @returns {Observable} An observable sequence producing the elements of the given sequence repeatedly until it terminates successfully. */ observableProto.retry = function (retryCount) { return enumerableRepeat(this, retryCount).catchException(); }; /** * Applies an accumulator function over an observable sequence and returns each intermediate result. The optional seed value is used as the initial accumulator value. * For aggregation behavior with no intermediate results, see Observable.aggregate. * @example * var res = source.scan(function (acc, x) { return acc + x; }); * var res = source.scan(0, function (acc, x) { return acc + x; }); * @param {Mixed} [seed] The initial accumulator value. * @param {Function} accumulator An accumulator function to be invoked on each element. * @returns {Observable} An observable sequence containing the accumulated values. */ observableProto.scan = function () { var hasSeed = false, seed, accumulator, source = this; if (arguments.length === 2) { hasSeed = true; seed = arguments[0]; accumulator = arguments[1]; } else { accumulator = arguments[0]; } return new AnonymousObservable(function (observer) { var hasAccumulation, accumulation, hasValue; return source.subscribe ( function (x) { !hasValue && (hasValue = true); try { if (hasAccumulation) { accumulation = accumulator(accumulation, x); } else { accumulation = hasSeed ? accumulator(seed, x) : x; hasAccumulation = true; } } catch (e) { observer.onError(e); return; } observer.onNext(accumulation); }, observer.onError.bind(observer), function () { !hasValue && hasSeed && observer.onNext(seed); observer.onCompleted(); } ); }); }; /** * Bypasses a specified number of elements at the end of an observable sequence. * @description * This operator accumulates a queue with a length enough to store the first `count` elements. As more elements are * received, elements are taken from the front of the queue and produced on the result sequence. This causes elements to be delayed. * @param count Number of elements to bypass at the end of the source sequence. * @returns {Observable} An observable sequence containing the source sequence elements except for the bypassed ones at the end. */ observableProto.skipLast = function (count) { var source = this; return new AnonymousObservable(function (observer) { var q = []; return source.subscribe(function (x) { q.push(x); q.length > count && observer.onNext(q.shift()); }, observer.onError.bind(observer), observer.onCompleted.bind(observer)); }); }; /** * Prepends a sequence of values to an observable sequence with an optional scheduler and an argument list of values to prepend. * @example * var res = source.startWith(1, 2, 3); * var res = source.startWith(Rx.Scheduler.timeout, 1, 2, 3); * @param {Arguments} args The specified values to prepend to the observable sequence * @returns {Observable} The source sequence prepended with the specified values. */ observableProto.startWith = function () { var values, scheduler, start = 0; if (!!arguments.length && isScheduler(arguments[0])) { scheduler = arguments[0]; start = 1; } else { scheduler = immediateScheduler; } values = slice.call(arguments, start); return enumerableOf([observableFromArray(values, scheduler), this]).concat(); }; /** * Returns a specified number of contiguous elements from the end of an observable sequence. * @description * This operator accumulates a buffer with a length enough to store elements count elements. Upon completion of * the source sequence, this buffer is drained on the result sequence. This causes the elements to be delayed. * @param {Number} count Number of elements to take from the end of the source sequence. * @returns {Observable} An observable sequence containing the specified number of elements from the end of the source sequence. */ observableProto.takeLast = function (count) { var source = this; return new AnonymousObservable(function (observer) { var q = []; return source.subscribe(function (x) { q.push(x); q.length > count && q.shift(); }, observer.onError.bind(observer), function () { while(q.length > 0) { observer.onNext(q.shift()); } observer.onCompleted(); }); }); }; function concatMap(source, selector, thisArg) { return source.map(function (x, i) { var result = selector.call(thisArg, x, i, source); isPromise(result) && (result = observableFromPromise(result)); (Array.isArray(result) || isIterable(result)) && (result = observableFrom(result)); return result; }).concatAll(); } /** * One of the Following: * Projects each element of an observable sequence to an observable sequence and merges the resulting observable sequences into one observable sequence. * * @example * var res = source.concatMap(function (x) { return Rx.Observable.range(0, x); }); * Or: * Projects each element of an observable sequence to an observable sequence, invokes the result selector for the source element and each of the corresponding inner sequence's elements, and merges the results into one observable sequence. * * var res = source.concatMap(function (x) { return Rx.Observable.range(0, x); }, function (x, y) { return x + y; }); * Or: * Projects each element of the source observable sequence to the other observable sequence and merges the resulting observable sequences into one observable sequence. * * var res = source.concatMap(Rx.Observable.fromArray([1,2,3])); * @param {Function} selector A transform function to apply to each element or an observable sequence to project each element from the * source sequence onto which could be either an observable or Promise. * @param {Function} [resultSelector] A transform function to apply to each element of the intermediate sequence. * @returns {Observable} An observable sequence whose elements are the result of invoking the one-to-many transform function collectionSelector on each element of the input sequence and then mapping each of those sequence elements and their corresponding source element to a result element. */ observableProto.selectConcat = observableProto.concatMap = function (selector, resultSelector, thisArg) { if (typeof selector === 'function' && typeof resultSelector === 'function') { return this.concatMap(function (x, i) { var selectorResult = selector(x, i); isPromise(selectorResult) && (selectorResult = observableFromPromise(selectorResult)); (Array.isArray(selectorResult) || isIterable(selectorResult)) && (selectorResult = observableFrom(selectorResult)); return selectorResult.map(function (y, i2) { return resultSelector(x, y, i, i2); }); }); } return typeof selector === 'function' ? concatMap(this, selector, thisArg) : concatMap(this, function () { return selector; }); }; /** * Projects each element of an observable sequence into a new form by incorporating the element's index. * @param {Function} selector A transform function to apply to each source element; the second parameter of the function represents the index of the source element. * @param {Any} [thisArg] Object to use as this when executing callback. * @returns {Observable} An observable sequence whose elements are the result of invoking the transform function on each element of source. */ observableProto.select = observableProto.map = function (selector, thisArg) { var parent = this; return new AnonymousObservable(function (observer) { var count = 0; return parent.subscribe(function (value) { var result; try { result = selector.call(thisArg, value, count++, parent); } catch (e) { observer.onError(e); return; } observer.onNext(result); }, observer.onError.bind(observer), observer.onCompleted.bind(observer)); }); }; /** * Retrieves the value of a specified property from all elements in the Observable sequence. * @param {String} prop The property to pluck. * @returns {Observable} Returns a new Observable sequence of property values. */ observableProto.pluck = function (prop) { return this.map(function (x) { return x[prop]; }); }; function flatMap(source, selector, thisArg) { return source.map(function (x, i) { var result = selector.call(thisArg, x, i, source); isPromise(result) && (result = observableFromPromise(result)); (Array.isArray(result) || isIterable(result)) && (result = observableFrom(result)); return result; }).mergeObservable(); } /** * One of the Following: * Projects each element of an observable sequence to an observable sequence and merges the resulting observable sequences into one observable sequence. * * @example * var res = source.selectMany(function (x) { return Rx.Observable.range(0, x); }); * Or: * Projects each element of an observable sequence to an observable sequence, invokes the result selector for the source element and each of the corresponding inner sequence's elements, and merges the results into one observable sequence. * * var res = source.selectMany(function (x) { return Rx.Observable.range(0, x); }, function (x, y) { return x + y; }); * Or: * Projects each element of the source observable sequence to the other observable sequence and merges the resulting observable sequences into one observable sequence. * * var res = source.selectMany(Rx.Observable.fromArray([1,2,3])); * @param {Function} selector A transform function to apply to each element or an observable sequence to project each element from the source sequence onto which could be either an observable or Promise. * @param {Function} [resultSelector] A transform function to apply to each element of the intermediate sequence. * @param {Any} [thisArg] Object to use as this when executing callback. * @returns {Observable} An observable sequence whose elements are the result of invoking the one-to-many transform function collectionSelector on each element of the input sequence and then mapping each of those sequence elements and their corresponding source element to a result element. */ observableProto.selectMany = observableProto.flatMap = function (selector, resultSelector, thisArg) { if (typeof selector === 'function' && typeof resultSelector === 'function') { return this.flatMap(function (x, i) { var selectorResult = selector(x, i); isPromise(selectorResult) && (selectorResult = observableFromPromise(selectorResult)); (Array.isArray(selectorResult) || isIterable(selectorResult)) && (selectorResult = observableFrom(selectorResult)); return selectorResult.map(function (y, i2) { return resultSelector(x, y, i, i2); }); }, thisArg); } return typeof selector === 'function' ? flatMap(this, selector, thisArg) : flatMap(this, function () { return selector; }); }; /** * Projects each element of an observable sequence into a new sequence of observable sequences by incorporating the element's index and then * transforms an observable sequence of observable sequences into an observable sequence producing values only from the most recent observable sequence. * @param {Function} selector A transform function to apply to each source element; the second parameter of the function represents the index of the source element. * @param {Any} [thisArg] Object to use as this when executing callback. * @returns {Observable} An observable sequence whose elements are the result of invoking the transform function on each element of source producing an Observable of Observable sequences * and that at any point in time produces the elements of the most recent inner observable sequence that has been received. */ observableProto.selectSwitch = observableProto.flatMapLatest = observableProto.switchMap = function (selector, thisArg) { return this.select(selector, thisArg).switchLatest(); }; /** * Bypasses a specified number of elements in an observable sequence and then returns the remaining elements. * @param {Number} count The number of elements to skip before returning the remaining elements. * @returns {Observable} An observable sequence that contains the elements that occur after the specified index in the input sequence. */ observableProto.skip = function (count) { if (count < 0) { throw new Error(argumentOutOfRange); } var source = this; return new AnonymousObservable(function (observer) { var remaining = count; return source.subscribe(function (x) { if (remaining <= 0) { observer.onNext(x); } else { remaining--; } }, observer.onError.bind(observer), observer.onCompleted.bind(observer)); }); }; /** * Bypasses elements in an observable sequence as long as a specified condition is true and then returns the remaining elements. * The element's index is used in the logic of the predicate function. * * var res = source.skipWhile(function (value) { return value < 10; }); * var res = source.skipWhile(function (value, index) { return value < 10 || index < 10; }); * @param {Function} predicate A function to test each element for a condition; the second parameter of the function represents the index of the source element. * @param {Any} [thisArg] Object to use as this when executing callback. * @returns {Observable} An observable sequence that contains the elements from the input sequence starting at the first element in the linear series that does not pass the test specified by predicate. */ observableProto.skipWhile = function (predicate, thisArg) { var source = this; return new AnonymousObservable(function (observer) { var i = 0, running = false; return source.subscribe(function (x) { if (!running) { try { running = !predicate.call(thisArg, x, i++, source); } catch (e) { observer.onError(e); return; } } running && observer.onNext(x); }, observer.onError.bind(observer), observer.onCompleted.bind(observer)); }); }; /** * Returns a specified number of contiguous elements from the start of an observable sequence, using the specified scheduler for the edge case of take(0). * * var res = source.take(5); * var res = source.take(0, Rx.Scheduler.timeout); * @param {Number} count The number of elements to return. * @param {Scheduler} [scheduler] Scheduler used to produce an OnCompleted message in case <paramref name="count count</paramref> is set to 0. * @returns {Observable} An observable sequence that contains the specified number of elements from the start of the input sequence. */ observableProto.take = function (count, scheduler) { if (count < 0) { throw new RangeError(argumentOutOfRange); } if (count === 0) { return observableEmpty(scheduler); } var observable = this; return new AnonymousObservable(function (observer) { var remaining = count; return observable.subscribe(function (x) { if (remaining-- > 0) { observer.onNext(x); remaining === 0 && observer.onCompleted(); } }, observer.onError.bind(observer), observer.onCompleted.bind(observer)); }); }; /** * Returns elements from an observable sequence as long as a specified condition is true. * The element's index is used in the logic of the predicate function. * @param {Function} predicate A function to test each element for a condition; the second parameter of the function represents the index of the source element. * @param {Any} [thisArg] Object to use as this when executing callback. * @returns {Observable} An observable sequence that contains the elements from the input sequence that occur before the element at which the test no longer passes. */ observableProto.takeWhile = function (predicate, thisArg) { var observable = this; return new AnonymousObservable(function (observer) { var i = 0, running = true; return observable.subscribe(function (x) { if (running) { try { running = predicate.call(thisArg, x, i++, observable); } catch (e) { observer.onError(e); return; } if (running) { observer.onNext(x); } else { observer.onCompleted(); } } }, observer.onError.bind(observer), observer.onCompleted.bind(observer)); }); }; /** * Filters the elements of an observable sequence based on a predicate by incorporating the element's index. * * @example * var res = source.where(function (value) { return value < 10; }); * var res = source.where(function (value, index) { return value < 10 || index < 10; }); * @param {Function} predicate A function to test each source element for a condition; the second parameter of the function represents the index of the source element. * @param {Any} [thisArg] Object to use as this when executing callback. * @returns {Observable} An observable sequence that contains elements from the input sequence that satisfy the condition. */ observableProto.where = observableProto.filter = function (predicate, thisArg) { var parent = this; return new AnonymousObservable(function (observer) { var count = 0; return parent.subscribe(function (value) { var shouldRun; try { shouldRun = predicate.call(thisArg, value, count++, parent); } catch (e) { observer.onError(e); return; } shouldRun && observer.onNext(value); }, observer.onError.bind(observer), observer.onCompleted.bind(observer)); }); }; /** * Converts a callback function to an observable sequence. * * @param {Function} function Function with a callback as the last parameter to convert to an Observable sequence. * @param {Mixed} [context] The context for the func parameter to be executed. If not specified, defaults to undefined. * @param {Function} [selector] A selector which takes the arguments from the callback to produce a single item to yield on next. * @returns {Function} A function, when executed with the required parameters minus the callback, produces an Observable sequence with a single value of the arguments to the callback as an array. */ Observable.fromCallback = function (func, context, selector) { return function () { var args = slice.call(arguments, 0); return new AnonymousObservable(function (observer) { function handler(e) { var results = e; if (selector) { try { results = selector(arguments); } catch (err) { observer.onError(err); return; } observer.onNext(results); } else { if (results.length <= 1) { observer.onNext.apply(observer, results); } else { observer.onNext(results); } } observer.onCompleted(); } args.push(handler); func.apply(context, args); }).publishLast().refCount(); }; }; /** * Converts a Node.js callback style function to an observable sequence. This must be in function (err, ...) format. * @param {Function} func The function to call * @param {Mixed} [context] The context for the func parameter to be executed. If not specified, defaults to undefined. * @param {Function} [selector] A selector which takes the arguments from the callback minus the error to produce a single item to yield on next. * @returns {Function} An async function which when applied, returns an observable sequence with the callback arguments as an array. */ Observable.fromNodeCallback = function (func, context, selector) { return function () { var args = slice.call(arguments, 0); return new AnonymousObservable(function (observer) { function handler(err) { if (err) { observer.onError(err); return; } var results = slice.call(arguments, 1); if (selector) { try { results = selector(results); } catch (e) { observer.onError(e); return; } observer.onNext(results); } else { if (results.length <= 1) { observer.onNext.apply(observer, results); } else { observer.onNext(results); } } observer.onCompleted(); } args.push(handler); func.apply(context, args); }).publishLast().refCount(); }; }; function fixEvent(event) { var stopPropagation = function () { this.cancelBubble = true; }; var preventDefault = function () { this.bubbledKeyCode = this.keyCode; if (this.ctrlKey) { try { this.keyCode = 0; } catch (e) { } } this.defaultPrevented = true; this.returnValue = false; this.modified = true; }; event || (event = root.event); if (!event.target) { event.target = event.target || event.srcElement; if (event.type == 'mouseover') { event.relatedTarget = event.fromElement; } if (event.type == 'mouseout') { event.relatedTarget = event.toElement; } // Adding stopPropogation and preventDefault to IE if (!event.stopPropagation){ event.stopPropagation = stopPropagation; event.preventDefault = preventDefault; } // Normalize key events switch(event.type){ case 'keypress': var c = ('charCode' in event ? event.charCode : event.keyCode); if (c == 10) { c = 0; event.keyCode = 13; } else if (c == 13 || c == 27) { c = 0; } else if (c == 3) { c = 99; } event.charCode = c; event.keyChar = event.charCode ? String.fromCharCode(event.charCode) : ''; break; } } return event; } function createListener (element, name, handler) { // Standards compliant if (element.addEventListener) { element.addEventListener(name, handler, false); return disposableCreate(function () { element.removeEventListener(name, handler, false); }); } if (element.attachEvent) { // IE Specific var innerHandler = function (event) { handler(fixEvent(event)); }; element.attachEvent('on' + name, innerHandler); return disposableCreate(function () { element.detachEvent('on' + name, innerHandler); }); } // Level 1 DOM Events element['on' + name] = handler; return disposableCreate(function () { element['on' + name] = null; }); } function createEventListener (el, eventName, handler) { var disposables = new CompositeDisposable(); // Asume NodeList if (Object.prototype.toString.call(el) === '[object NodeList]') { for (var i = 0, len = el.length; i < len; i++) { disposables.add(createEventListener(el.item(i), eventName, handler)); } } else if (el) { disposables.add(createListener(el, eventName, handler)); } return disposables; } /** * Configuration option to determine whether to use native events only */ Rx.config.useNativeEvents = false; // Check for Angular/jQuery/Zepto support var jq = !!root.angular && !!angular.element ? angular.element : (!!root.jQuery ? root.jQuery : ( !!root.Zepto ? root.Zepto : null)); // Check for ember var ember = !!root.Ember && typeof root.Ember.addListener === 'function'; // Check for Backbone.Marionette. Note if using AMD add Marionette as a dependency of rxjs // for proper loading order! var marionette = !!root.Backbone && !!root.Backbone.Marionette; /** * Creates an observable sequence by adding an event listener to the matching DOMElement or each item in the NodeList. * * @example * var source = Rx.Observable.fromEvent(element, 'mouseup'); * * @param {Object} element The DOMElement or NodeList to attach a listener. * @param {String} eventName The event name to attach the observable sequence. * @param {Function} [selector] A selector which takes the arguments from the event handler to produce a single item to yield on next. * @returns {Observable} An observable sequence of events from the specified element and the specified event. */ Observable.fromEvent = function (element, eventName, selector) { // Node.js specific if (element.addListener) { return fromEventPattern( function (h) { element.addListener(eventName, h); }, function (h) { element.removeListener(eventName, h); }, selector); } // Use only if non-native events are allowed if (!Rx.config.useNativeEvents) { if (marionette) { return fromEventPattern( function (h) { element.on(eventName, h); }, function (h) { element.off(eventName, h); }, selector); } if (ember) { return fromEventPattern( function (h) { Ember.addListener(element, eventName, h); }, function (h) { Ember.removeListener(element, eventName, h); }, selector); } if (jq) { var $elem = jq(element); return fromEventPattern( function (h) { $elem.on(eventName, h); }, function (h) { $elem.off(eventName, h); }, selector); } } return new AnonymousObservable(function (observer) { return createEventListener( element, eventName, function handler (e) { var results = e; if (selector) { try { results = selector(arguments); } catch (err) { observer.onError(err); return } } observer.onNext(results); }); }).publish().refCount(); }; /** * Creates an observable sequence from an event emitter via an addHandler/removeHandler pair. * @param {Function} addHandler The function to add a handler to the emitter. * @param {Function} [removeHandler] The optional function to remove a handler from an emitter. * @param {Function} [selector] A selector which takes the arguments from the event handler to produce a single item to yield on next. * @returns {Observable} An observable sequence which wraps an event from an event emitter */ var fromEventPattern = Observable.fromEventPattern = function (addHandler, removeHandler, selector) { return new AnonymousObservable(function (observer) { function innerHandler (e) { var result = e; if (selector) { try { result = selector(arguments); } catch (err) { observer.onError(err); return; } } observer.onNext(result); } var returnValue = addHandler(innerHandler); return disposableCreate(function () { if (removeHandler) { removeHandler(innerHandler, returnValue); } }); }).publish().refCount(); }; /** * Converts a Promise to an Observable sequence * @param {Promise} An ES6 Compliant promise. * @returns {Observable} An Observable sequence which wraps the existing promise success and failure. */ var observableFromPromise = Observable.fromPromise = function (promise) { return observableDefer(function () { var subject = new Rx.AsyncSubject(); promise.then( function (value) { if (!subject.isDisposed) { subject.onNext(value); subject.onCompleted(); } }, subject.onError.bind(subject)); return subject; }); }; /* * Converts an existing observable sequence to an ES6 Compatible Promise * @example * var promise = Rx.Observable.return(42).toPromise(RSVP.Promise); * * // With config * Rx.config.Promise = RSVP.Promise; * var promise = Rx.Observable.return(42).toPromise(); * @param {Function} [promiseCtor] The constructor of the promise. If not provided, it looks for it in Rx.config.Promise. * @returns {Promise} An ES6 compatible promise with the last value from the observable sequence. */ observableProto.toPromise = function (promiseCtor) { promiseCtor || (promiseCtor = Rx.config.Promise); if (!promiseCtor) { throw new TypeError('Promise type not provided nor in Rx.config.Promise'); } var source = this; return new promiseCtor(function (resolve, reject) { // No cancellation can be done var value, hasValue = false; source.subscribe(function (v) { value = v; hasValue = true; }, reject, function () { hasValue && resolve(value); }); }); }; /** * Invokes the asynchronous function, surfacing the result through an observable sequence. * @param {Function} functionAsync Asynchronous function which returns a Promise to run. * @returns {Observable} An observable sequence exposing the function's result value, or an exception. */ Observable.startAsync = function (functionAsync) { var promise; try { promise = functionAsync(); } catch (e) { return observableThrow(e); } return observableFromPromise(promise); } /** * Multicasts the source sequence notifications through an instantiated subject into all uses of the sequence within a selector function. Each * subscription to the resulting sequence causes a separate multicast invocation, exposing the sequence resulting from the selector function's * invocation. For specializations with fixed subject types, see Publish, PublishLast, and Replay. * * @example * 1 - res = source.multicast(observable); * 2 - res = source.multicast(function () { return new Subject(); }, function (x) { return x; }); * * @param {Function|Subject} subjectOrSubjectSelector * Factory function to create an intermediate subject through which the source sequence's elements will be multicast to the selector function. * Or: * Subject to push source elements into. * * @param {Function} [selector] Optional selector function which can use the multicasted source sequence subject to the policies enforced by the created subject. Specified only if <paramref name="subjectOrSubjectSelector" is a factory function. * @returns {Observable} An observable sequence that contains the elements of a sequence produced by multicasting the source sequence within a selector function. */ observableProto.multicast = function (subjectOrSubjectSelector, selector) { var source = this; return typeof subjectOrSubjectSelector === 'function' ? new AnonymousObservable(function (observer) { var connectable = source.multicast(subjectOrSubjectSelector()); return new CompositeDisposable(selector(connectable).subscribe(observer), connectable.connect()); }) : new ConnectableObservable(source, subjectOrSubjectSelector); }; /** * Returns an observable sequence that is the result of invoking the selector on a connectable observable sequence that shares a single subscription to the underlying sequence. * This operator is a specialization of Multicast using a regular Subject. * * @example * var resres = source.publish(); * var res = source.publish(function (x) { return x; }); * * @param {Function} [selector] Selector function which can use the multicasted source sequence as many times as needed, without causing multiple subscriptions to the source sequence. Subscribers to the given source will receive all notifications of the source from the time of the subscription on. * @returns {Observable} An observable sequence that contains the elements of a sequence produced by multicasting the source sequence within a selector function. */ observableProto.publish = function (selector) { return selector && isFunction(selector) ? this.multicast(function () { return new Subject(); }, selector) : this.multicast(new Subject()); }; /** * Returns an observable sequence that shares a single subscription to the underlying sequence. * This operator is a specialization of publish which creates a subscription when the number of observers goes from zero to one, then shares that subscription with all subsequent observers until the number of observers returns to zero, at which point the subscription is disposed. * * @example * var res = source.share(); * * @returns {Observable} An observable sequence that contains the elements of a sequence produced by multicasting the source sequence. */ observableProto.share = function () { return this.publish().refCount(); }; /** * Returns an observable sequence that is the result of invoking the selector on a connectable observable sequence that shares a single subscription to the underlying sequence containing only the last notification. * This operator is a specialization of Multicast using a AsyncSubject. * * @example * var res = source.publishLast(); * var res = source.publishLast(function (x) { return x; }); * * @param selector [Optional] Selector function which can use the multicasted source sequence as many times as needed, without causing multiple subscriptions to the source sequence. Subscribers to the given source will only receive the last notification of the source. * @returns {Observable} An observable sequence that contains the elements of a sequence produced by multicasting the source sequence within a selector function. */ observableProto.publishLast = function (selector) { return selector && isFunction(selector) ? this.multicast(function () { return new AsyncSubject(); }, selector) : this.multicast(new AsyncSubject()); }; /** * Returns an observable sequence that is the result of invoking the selector on a connectable observable sequence that shares a single subscription to the underlying sequence and starts with initialValue. * This operator is a specialization of Multicast using a BehaviorSubject. * * @example * var res = source.publishValue(42); * var res = source.publishValue(function (x) { return x.select(function (y) { return y * y; }) }, 42); * * @param {Function} [selector] Optional selector function which can use the multicasted source sequence as many times as needed, without causing multiple subscriptions to the source sequence. Subscribers to the given source will receive immediately receive the initial value, followed by all notifications of the source from the time of the subscription on. * @param {Mixed} initialValue Initial value received by observers upon subscription. * @returns {Observable} An observable sequence that contains the elements of a sequence produced by multicasting the source sequence within a selector function. */ observableProto.publishValue = function (initialValueOrSelector, initialValue) { return arguments.length === 2 ? this.multicast(function () { return new BehaviorSubject(initialValue); }, initialValueOrSelector) : this.multicast(new BehaviorSubject(initialValueOrSelector)); }; /** * Returns an observable sequence that shares a single subscription to the underlying sequence and starts with an initialValue. * This operator is a specialization of publishValue which creates a subscription when the number of observers goes from zero to one, then shares that subscription with all subsequent observers until the number of observers returns to zero, at which point the subscription is disposed. * * @example * var res = source.shareValue(42); * * @param {Mixed} initialValue Initial value received by observers upon subscription. * @returns {Observable} An observable sequence that contains the elements of a sequence produced by multicasting the source sequence. */ observableProto.shareValue = function (initialValue) { return this.publishValue(initialValue).refCount(); }; /** * Returns an observable sequence that is the result of invoking the selector on a connectable observable sequence that shares a single subscription to the underlying sequence replaying notifications subject to a maximum time length for the replay buffer. * This operator is a specialization of Multicast using a ReplaySubject. * * @example * var res = source.replay(null, 3); * var res = source.replay(null, 3, 500); * var res = source.replay(null, 3, 500, scheduler); * var res = source.replay(function (x) { return x.take(6).repeat(); }, 3, 500, scheduler); * * @param selector [Optional] Selector function which can use the multicasted source sequence as many times as needed, without causing multiple subscriptions to the source sequence. Subscribers to the given source will receive all the notifications of the source subject to the specified replay buffer trimming policy. * @param bufferSize [Optional] Maximum element count of the replay buffer. * @param window [Optional] Maximum time length of the replay buffer. * @param scheduler [Optional] Scheduler where connected observers within the selector function will be invoked on. * @returns {Observable} An observable sequence that contains the elements of a sequence produced by multicasting the source sequence within a selector function. */ observableProto.replay = function (selector, bufferSize, window, scheduler) { return selector && isFunction(selector) ? this.multicast(function () { return new ReplaySubject(bufferSize, window, scheduler); }, selector) : this.multicast(new ReplaySubject(bufferSize, window, scheduler)); }; /** * Returns an observable sequence that shares a single subscription to the underlying sequence replaying notifications subject to a maximum time length for the replay buffer. * This operator is a specialization of replay which creates a subscription when the number of observers goes from zero to one, then shares that subscription with all subsequent observers until the number of observers returns to zero, at which point the subscription is disposed. * * @example * var res = source.shareReplay(3); * var res = source.shareReplay(3, 500); * var res = source.shareReplay(3, 500, scheduler); * * @param bufferSize [Optional] Maximum element count of the replay buffer. * @param window [Optional] Maximum time length of the replay buffer. * @param scheduler [Optional] Scheduler where connected observers within the selector function will be invoked on. * @returns {Observable} An observable sequence that contains the elements of a sequence produced by multicasting the source sequence. */ observableProto.shareReplay = function (bufferSize, window, scheduler) { return this.replay(null, bufferSize, window, scheduler).refCount(); }; var ConnectableObservable = Rx.ConnectableObservable = (function (__super__) { inherits(ConnectableObservable, __super__); function ConnectableObservable(source, subject) { var hasSubscription = false, subscription, sourceObservable = source.asObservable(); this.connect = function () { if (!hasSubscription) { hasSubscription = true; subscription = new CompositeDisposable(sourceObservable.subscribe(subject), disposableCreate(function () { hasSubscription = false; })); } return subscription; }; __super__.call(this, subject.subscribe.bind(subject)); } ConnectableObservable.prototype.refCount = function () { var connectableSubscription, count = 0, source = this; return new AnonymousObservable(function (observer) { var shouldConnect = ++count === 1, subscription = source.subscribe(observer); shouldConnect && (connectableSubscription = source.connect()); return function () { subscription.dispose(); --count === 0 && connectableSubscription.dispose(); }; }); }; return ConnectableObservable; }(Observable)); function observableTimerDate(dueTime, scheduler) { return new AnonymousObservable(function (observer) { return scheduler.scheduleWithAbsolute(dueTime, function () { observer.onNext(0); observer.onCompleted(); }); }); } function observableTimerDateAndPeriod(dueTime, period, scheduler) { return new AnonymousObservable(function (observer) { var count = 0, d = dueTime, p = normalizeTime(period); return scheduler.scheduleRecursiveWithAbsolute(d, function (self) { if (p > 0) { var now = scheduler.now(); d = d + p; d <= now && (d = now + p); } observer.onNext(count++); self(d); }); }); } function observableTimerTimeSpan(dueTime, scheduler) { return new AnonymousObservable(function (observer) { return scheduler.scheduleWithRelative(normalizeTime(dueTime), function () { observer.onNext(0); observer.onCompleted(); }); }); } function observableTimerTimeSpanAndPeriod(dueTime, period, scheduler) { return dueTime === period ? new AnonymousObservable(function (observer) { return scheduler.schedulePeriodicWithState(0, period, function (count) { observer.onNext(count); return count + 1; }); }) : observableDefer(function () { return observableTimerDateAndPeriod(scheduler.now() + dueTime, period, scheduler); }); } /** * Returns an observable sequence that produces a value after each period. * * @example * 1 - res = Rx.Observable.interval(1000); * 2 - res = Rx.Observable.interval(1000, Rx.Scheduler.timeout); * * @param {Number} period Period for producing the values in the resulting sequence (specified as an integer denoting milliseconds). * @param {Scheduler} [scheduler] Scheduler to run the timer on. If not specified, Rx.Scheduler.timeout is used. * @returns {Observable} An observable sequence that produces a value after each period. */ var observableinterval = Observable.interval = function (period, scheduler) { return observableTimerTimeSpanAndPeriod(period, period, isScheduler(scheduler) ? scheduler : timeoutScheduler); }; /** * Returns an observable sequence that produces a value after dueTime has elapsed and then after each period. * @param {Number} dueTime Absolute (specified as a Date object) or relative time (specified as an integer denoting milliseconds) at which to produce the first value. * @param {Mixed} [periodOrScheduler] Period to produce subsequent values (specified as an integer denoting milliseconds), or the scheduler to run the timer on. If not specified, the resulting timer is not recurring. * @param {Scheduler} [scheduler] Scheduler to run the timer on. If not specified, the timeout scheduler is used. * @returns {Observable} An observable sequence that produces a value after due time has elapsed and then each period. */ var observableTimer = Observable.timer = function (dueTime, periodOrScheduler, scheduler) { var period; isScheduler(scheduler) || (scheduler = timeoutScheduler); if (periodOrScheduler !== undefined && typeof periodOrScheduler === 'number') { period = periodOrScheduler; } else if (isScheduler(periodOrScheduler)) { scheduler = periodOrScheduler; } if (dueTime instanceof Date && period === undefined) { return observableTimerDate(dueTime.getTime(), scheduler); } if (dueTime instanceof Date && period !== undefined) { period = periodOrScheduler; return observableTimerDateAndPeriod(dueTime.getTime(), period, scheduler); } return period === undefined ? observableTimerTimeSpan(dueTime, scheduler) : observableTimerTimeSpanAndPeriod(dueTime, period, scheduler); }; function observableDelayTimeSpan(source, dueTime, scheduler) { return new AnonymousObservable(function (observer) { var active = false, cancelable = new SerialDisposable(), exception = null, q = [], running = false, subscription; subscription = source.materialize().timestamp(scheduler).subscribe(function (notification) { var d, shouldRun; if (notification.value.kind === 'E') { q = []; q.push(notification); exception = notification.value.exception; shouldRun = !running; } else { q.push({ value: notification.value, timestamp: notification.timestamp + dueTime }); shouldRun = !active; active = true; } if (shouldRun) { if (exception !== null) { observer.onError(exception); } else { d = new SingleAssignmentDisposable(); cancelable.setDisposable(d); d.setDisposable(scheduler.scheduleRecursiveWithRelative(dueTime, function (self) { var e, recurseDueTime, result, shouldRecurse; if (exception !== null) { return; } running = true; do { result = null; if (q.length > 0 && q[0].timestamp - scheduler.now() <= 0) { result = q.shift().value; } if (result !== null) { result.accept(observer); } } while (result !== null); shouldRecurse = false; recurseDueTime = 0; if (q.length > 0) { shouldRecurse = true; recurseDueTime = Math.max(0, q[0].timestamp - scheduler.now()); } else { active = false; } e = exception; running = false; if (e !== null) { observer.onError(e); } else if (shouldRecurse) { self(recurseDueTime); } })); } } }); return new CompositeDisposable(subscription, cancelable); }); } function observableDelayDate(source, dueTime, scheduler) { return observableDefer(function () { return observableDelayTimeSpan(source, dueTime - scheduler.now(), scheduler); }); } /** * Time shifts the observable sequence by dueTime. The relative time intervals between the values are preserved. * * @example * 1 - res = Rx.Observable.delay(new Date()); * 2 - res = Rx.Observable.delay(new Date(), Rx.Scheduler.timeout); * * 3 - res = Rx.Observable.delay(5000); * 4 - res = Rx.Observable.delay(5000, 1000, Rx.Scheduler.timeout); * @memberOf Observable# * @param {Number} dueTime Absolute (specified as a Date object) or relative time (specified as an integer denoting milliseconds) by which to shift the observable sequence. * @param {Scheduler} [scheduler] Scheduler to run the delay timers on. If not specified, the timeout scheduler is used. * @returns {Observable} Time-shifted sequence. */ observableProto.delay = function (dueTime, scheduler) { isScheduler(scheduler) || (scheduler = timeoutScheduler); return dueTime instanceof Date ? observableDelayDate(this, dueTime.getTime(), scheduler) : observableDelayTimeSpan(this, dueTime, scheduler); }; /** * Ignores values from an observable sequence which are followed by another value before dueTime. * * @example * 1 - res = source.throttle(5000); // 5 seconds * 2 - res = source.throttle(5000, scheduler); * * @param {Number} dueTime Duration of the throttle period for each value (specified as an integer denoting milliseconds). * @param {Scheduler} [scheduler] Scheduler to run the throttle timers on. If not specified, the timeout scheduler is used. * @returns {Observable} The throttled sequence. */ observableProto.throttle = function (dueTime, scheduler) { isScheduler(scheduler) || (scheduler = timeoutScheduler); var source = this; return new AnonymousObservable(function (observer) { var cancelable = new SerialDisposable(), hasvalue = false, value, id = 0; var subscription = source.subscribe( function (x) { hasvalue = true; value = x; id++; var currentId = id, d = new SingleAssignmentDisposable(); cancelable.setDisposable(d); d.setDisposable(scheduler.scheduleWithRelative(dueTime, function () { hasvalue && id === currentId && observer.onNext(value); hasvalue = false; })); }, function (e) { cancelable.dispose(); observer.onError(e); hasvalue = false; id++; }, function () { cancelable.dispose(); hasvalue && observer.onNext(value); observer.onCompleted(); hasvalue = false; id++; }); return new CompositeDisposable(subscription, cancelable); }); }; /** * Records the timestamp for each value in an observable sequence. * * @example * 1 - res = source.timestamp(); // produces { value: x, timestamp: ts } * 2 - res = source.timestamp(Rx.Scheduler.timeout); * * @param {Scheduler} [scheduler] Scheduler used to compute timestamps. If not specified, the timeout scheduler is used. * @returns {Observable} An observable sequence with timestamp information on values. */ observableProto.timestamp = function (scheduler) { isScheduler(scheduler) || (scheduler = timeoutScheduler); return this.map(function (x) { return { value: x, timestamp: scheduler.now() }; }); }; function sampleObservable(source, sampler) { return new AnonymousObservable(function (observer) { var atEnd, value, hasValue; function sampleSubscribe() { if (hasValue) { hasValue = false; observer.onNext(value); } atEnd && observer.onCompleted(); } return new CompositeDisposable( source.subscribe(function (newValue) { hasValue = true; value = newValue; }, observer.onError.bind(observer), function () { atEnd = true; }), sampler.subscribe(sampleSubscribe, observer.onError.bind(observer), sampleSubscribe) ); }); } /** * Samples the observable sequence at each interval. * * @example * 1 - res = source.sample(sampleObservable); // Sampler tick sequence * 2 - res = source.sample(5000); // 5 seconds * 2 - res = source.sample(5000, Rx.Scheduler.timeout); // 5 seconds * * @param {Mixed} intervalOrSampler Interval at which to sample (specified as an integer denoting milliseconds) or Sampler Observable. * @param {Scheduler} [scheduler] Scheduler to run the sampling timer on. If not specified, the timeout scheduler is used. * @returns {Observable} Sampled observable sequence. */ observableProto.sample = function (intervalOrSampler, scheduler) { isScheduler(scheduler) || (scheduler = timeoutScheduler); return typeof intervalOrSampler === 'number' ? sampleObservable(this, observableinterval(intervalOrSampler, scheduler)) : sampleObservable(this, intervalOrSampler); }; /** * Returns the source observable sequence or the other observable sequence if dueTime elapses. * @param {Number} dueTime Absolute (specified as a Date object) or relative time (specified as an integer denoting milliseconds) when a timeout occurs. * @param {Observable} [other] Sequence to return in case of a timeout. If not specified, a timeout error throwing sequence will be used. * @param {Scheduler} [scheduler] Scheduler to run the timeout timers on. If not specified, the timeout scheduler is used. * @returns {Observable} The source sequence switching to the other sequence in case of a timeout. */ observableProto.timeout = function (dueTime, other, scheduler) { (other == null || typeof other === 'string') && (other = observableThrow(new Error(other || 'Timeout'))); isScheduler(scheduler) || (scheduler = timeoutScheduler); var source = this, schedulerMethod = dueTime instanceof Date ? 'scheduleWithAbsolute' : 'scheduleWithRelative'; return new AnonymousObservable(function (observer) { var id = 0, original = new SingleAssignmentDisposable(), subscription = new SerialDisposable(), switched = false, timer = new SerialDisposable(); subscription.setDisposable(original); function createTimer() { var myId = id; timer.setDisposable(scheduler[schedulerMethod](dueTime, function () { if (id === myId) { isPromise(other) && (other = observableFromPromise(other)); subscription.setDisposable(other.subscribe(observer)); } })); } createTimer(); original.setDisposable(source.subscribe(function (x) { if (!switched) { id++; observer.onNext(x); createTimer(); } }, function (e) { if (!switched) { id++; observer.onError(e); } }, function () { if (!switched) { id++; observer.onCompleted(); } })); return new CompositeDisposable(subscription, timer); }); }; var PausableObservable = (function (_super) { inherits(PausableObservable, _super); function subscribe(observer) { var conn = this.source.publish(), subscription = conn.subscribe(observer), connection = disposableEmpty; var pausable = this.pauser.distinctUntilChanged().subscribe(function (b) { if (b) { connection = conn.connect(); } else { connection.dispose(); connection = disposableEmpty; } }); return new CompositeDisposable(subscription, connection, pausable); } function PausableObservable(source, pauser) { this.source = source; this.controller = new Subject(); if (pauser && pauser.subscribe) { this.pauser = this.controller.merge(pauser); } else { this.pauser = this.controller; } _super.call(this, subscribe); } PausableObservable.prototype.pause = function () { this.controller.onNext(false); }; PausableObservable.prototype.resume = function () { this.controller.onNext(true); }; return PausableObservable; }(Observable)); /** * Pauses the underlying observable sequence based upon the observable sequence which yields true/false. * @example * var pauser = new Rx.Subject(); * var source = Rx.Observable.interval(100).pausable(pauser); * @param {Observable} pauser The observable sequence used to pause the underlying sequence. * @returns {Observable} The observable sequence which is paused based upon the pauser. */ observableProto.pausable = function (pauser) { return new PausableObservable(this, pauser); }; function combineLatestSource(source, subject, resultSelector) { return new AnonymousObservable(function (observer) { var n = 2, hasValue = [false, false], hasValueAll = false, isDone = false, values = new Array(n); function next(x, i) { values[i] = x var res; hasValue[i] = true; if (hasValueAll || (hasValueAll = hasValue.every(identity))) { try { res = resultSelector.apply(null, values); } catch (ex) { observer.onError(ex); return; } observer.onNext(res); } else if (isDone) { observer.onCompleted(); } } return new CompositeDisposable( source.subscribe( function (x) { next(x, 0); }, observer.onError.bind(observer), function () { isDone = true; observer.onCompleted(); }), subject.subscribe( function (x) { next(x, 1); }, observer.onError.bind(observer)) ); }); } var PausableBufferedObservable = (function (_super) { inherits(PausableBufferedObservable, _super); function subscribe(observer) { var q = [], previousShouldFire; var subscription = combineLatestSource( this.source, this.pauser.distinctUntilChanged().startWith(false), function (data, shouldFire) { return { data: data, shouldFire: shouldFire }; }) .subscribe( function (results) { if (previousShouldFire !== undefined && results.shouldFire != previousShouldFire) { previousShouldFire = results.shouldFire; // change in shouldFire if (results.shouldFire) { while (q.length > 0) { observer.onNext(q.shift()); } } } else { previousShouldFire = results.shouldFire; // new data if (results.shouldFire) { observer.onNext(results.data); } else { q.push(results.data); } } }, function (err) { // Empty buffer before sending error while (q.length > 0) { observer.onNext(q.shift()); } observer.onError(err); }, function () { // Empty buffer before sending completion while (q.length > 0) { observer.onNext(q.shift()); } observer.onCompleted(); } ); return subscription; } function PausableBufferedObservable(source, pauser) { this.source = source; this.controller = new Subject(); if (pauser && pauser.subscribe) { this.pauser = this.controller.merge(pauser); } else { this.pauser = this.controller; } _super.call(this, subscribe); } PausableBufferedObservable.prototype.pause = function () { this.controller.onNext(false); }; PausableBufferedObservable.prototype.resume = function () { this.controller.onNext(true); }; return PausableBufferedObservable; }(Observable)); /** * Pauses the underlying observable sequence based upon the observable sequence which yields true/false, * and yields the values that were buffered while paused. * @example * var pauser = new Rx.Subject(); * var source = Rx.Observable.interval(100).pausableBuffered(pauser); * @param {Observable} pauser The observable sequence used to pause the underlying sequence. * @returns {Observable} The observable sequence which is paused based upon the pauser. */ observableProto.pausableBuffered = function (subject) { return new PausableBufferedObservable(this, subject); }; /** * Attaches a controller to the observable sequence with the ability to queue. * @example * var source = Rx.Observable.interval(100).controlled(); * source.request(3); // Reads 3 values * @param {Observable} pauser The observable sequence used to pause the underlying sequence. * @returns {Observable} The observable sequence which is paused based upon the pauser. */ observableProto.controlled = function (enableQueue) { if (enableQueue == null) { enableQueue = true; } return new ControlledObservable(this, enableQueue); }; var ControlledObservable = (function (_super) { inherits(ControlledObservable, _super); function subscribe (observer) { return this.source.subscribe(observer); } function ControlledObservable (source, enableQueue) { _super.call(this, subscribe); this.subject = new ControlledSubject(enableQueue); this.source = source.multicast(this.subject).refCount(); } ControlledObservable.prototype.request = function (numberOfItems) { if (numberOfItems == null) { numberOfItems = -1; } return this.subject.request(numberOfItems); }; return ControlledObservable; }(Observable)); var ControlledSubject = Rx.ControlledSubject = (function (_super) { function subscribe (observer) { return this.subject.subscribe(observer); } inherits(ControlledSubject, _super); function ControlledSubject(enableQueue) { if (enableQueue == null) { enableQueue = true; } _super.call(this, subscribe); this.subject = new Subject(); this.enableQueue = enableQueue; this.queue = enableQueue ? [] : null; this.requestedCount = 0; this.requestedDisposable = disposableEmpty; this.error = null; this.hasFailed = false; this.hasCompleted = false; this.controlledDisposable = disposableEmpty; } addProperties(ControlledSubject.prototype, Observer, { onCompleted: function () { checkDisposed.call(this); this.hasCompleted = true; if (!this.enableQueue || this.queue.length === 0) { this.subject.onCompleted(); } }, onError: function (error) { checkDisposed.call(this); this.hasFailed = true; this.error = error; if (!this.enableQueue || this.queue.length === 0) { this.subject.onError(error); } }, onNext: function (value) { checkDisposed.call(this); var hasRequested = false; if (this.requestedCount === 0) { if (this.enableQueue) { this.queue.push(value); } } else { if (this.requestedCount !== -1) { if (this.requestedCount-- === 0) { this.disposeCurrentRequest(); } } hasRequested = true; } if (hasRequested) { this.subject.onNext(value); } }, _processRequest: function (numberOfItems) { if (this.enableQueue) { //console.log('queue length', this.queue.length); while (this.queue.length >= numberOfItems && numberOfItems > 0) { //console.log('number of items', numberOfItems); this.subject.onNext(this.queue.shift()); numberOfItems--; } if (this.queue.length !== 0) { return { numberOfItems: numberOfItems, returnValue: true }; } else { return { numberOfItems: numberOfItems, returnValue: false }; } } if (this.hasFailed) { this.subject.onError(this.error); this.controlledDisposable.dispose(); this.controlledDisposable = disposableEmpty; } else if (this.hasCompleted) { this.subject.onCompleted(); this.controlledDisposable.dispose(); this.controlledDisposable = disposableEmpty; } return { numberOfItems: numberOfItems, returnValue: false }; }, request: function (number) { checkDisposed.call(this); this.disposeCurrentRequest(); var self = this, r = this._processRequest(number); number = r.numberOfItems; if (!r.returnValue) { this.requestedCount = number; this.requestedDisposable = disposableCreate(function () { self.requestedCount = 0; }); return this.requestedDisposable } else { return disposableEmpty; } }, disposeCurrentRequest: function () { this.requestedDisposable.dispose(); this.requestedDisposable = disposableEmpty; }, dispose: function () { this.isDisposed = true; this.error = null; this.subject.dispose(); this.requestedDisposable.dispose(); } }); return ControlledSubject; }(Observable)); /** * Executes a transducer to transform the observable sequence * @param {Transducer} transducer A transducer to execute * @returns {Observable} An Observable sequence containing the results from the transducer. */ observableProto.transduce = function(transducer) { var source = this; function transformForObserver(observer) { return { init: function() { return observer; }, step: function(obs, input) { return obs.onNext(input); }, result: function(obs) { return obs.onCompleted(); } }; } return new AnonymousObservable(function(observer) { var xform = transducer(transformForObserver(observer)); return source.subscribe( function(v) { try { xform.step(observer, v); } catch (e) { observer.onError(e); } }, observer.onError.bind(observer), function() { xform.result(observer); } ); }); }; var AnonymousObservable = Rx.AnonymousObservable = (function (__super__) { inherits(AnonymousObservable, __super__); // Fix subscriber to check for undefined or function returned to decorate as Disposable function fixSubscriber(subscriber) { if (subscriber && typeof subscriber.dispose === 'function') { return subscriber; } return typeof subscriber === 'function' ? disposableCreate(subscriber) : disposableEmpty; } function AnonymousObservable(subscribe) { if (!(this instanceof AnonymousObservable)) { return new AnonymousObservable(subscribe); } function s(observer) { var setDisposable = function () { try { autoDetachObserver.setDisposable(fixSubscriber(subscribe(autoDetachObserver))); } catch (e) { if (!autoDetachObserver.fail(e)) { throw e; } } }; var autoDetachObserver = new AutoDetachObserver(observer); if (currentThreadScheduler.scheduleRequired()) { currentThreadScheduler.schedule(setDisposable); } else { setDisposable(); } return autoDetachObserver; } __super__.call(this, s); } return AnonymousObservable; }(Observable)); /** @private */ var AutoDetachObserver = (function (_super) { inherits(AutoDetachObserver, _super); function AutoDetachObserver(observer) { _super.call(this); this.observer = observer; this.m = new SingleAssignmentDisposable(); } var AutoDetachObserverPrototype = AutoDetachObserver.prototype; AutoDetachObserverPrototype.next = function (value) { var noError = false; try { this.observer.onNext(value); noError = true; } catch (e) { throw e; } finally { if (!noError) { this.dispose(); } } }; AutoDetachObserverPrototype.error = function (exn) { try { this.observer.onError(exn); } catch (e) { throw e; } finally { this.dispose(); } }; AutoDetachObserverPrototype.completed = function () { try { this.observer.onCompleted(); } catch (e) { throw e; } finally { this.dispose(); } }; AutoDetachObserverPrototype.setDisposable = function (value) { this.m.setDisposable(value); }; AutoDetachObserverPrototype.getDisposable = function (value) { return this.m.getDisposable(); }; /* @private */ AutoDetachObserverPrototype.disposable = function (value) { return arguments.length ? this.getDisposable() : setDisposable(value); }; AutoDetachObserverPrototype.dispose = function () { _super.prototype.dispose.call(this); this.m.dispose(); }; return AutoDetachObserver; }(AbstractObserver)); /** @private */ var InnerSubscription = function (subject, observer) { this.subject = subject; this.observer = observer; }; /** * @private * @memberOf InnerSubscription */ InnerSubscription.prototype.dispose = function () { if (!this.subject.isDisposed && this.observer !== null) { var idx = this.subject.observers.indexOf(this.observer); this.subject.observers.splice(idx, 1); this.observer = null; } }; /** * Represents an object that is both an observable sequence as well as an observer. * Each notification is broadcasted to all subscribed observers. */ var Subject = Rx.Subject = (function (_super) { function subscribe(observer) { checkDisposed.call(this); if (!this.isStopped) { this.observers.push(observer); return new InnerSubscription(this, observer); } if (this.exception) { observer.onError(this.exception); return disposableEmpty; } observer.onCompleted(); return disposableEmpty; } inherits(Subject, _super); /** * Creates a subject. * @constructor */ function Subject() { _super.call(this, subscribe); this.isDisposed = false, this.isStopped = false, this.observers = []; } addProperties(Subject.prototype, Observer, { /** * Indicates whether the subject has observers subscribed to it. * @returns {Boolean} Indicates whether the subject has observers subscribed to it. */ hasObservers: function () { return this.observers.length > 0; }, /** * Notifies all subscribed observers about the end of the sequence. */ onCompleted: function () { checkDisposed.call(this); if (!this.isStopped) { var os = this.observers.slice(0); this.isStopped = true; for (var i = 0, len = os.length; i < len; i++) { os[i].onCompleted(); } this.observers = []; } }, /** * Notifies all subscribed observers about the exception. * @param {Mixed} error The exception to send to all observers. */ onError: function (exception) { checkDisposed.call(this); if (!this.isStopped) { var os = this.observers.slice(0); this.isStopped = true; this.exception = exception; for (var i = 0, len = os.length; i < len; i++) { os[i].onError(exception); } this.observers = []; } }, /** * Notifies all subscribed observers about the arrival of the specified element in the sequence. * @param {Mixed} value The value to send to all observers. */ onNext: function (value) { checkDisposed.call(this); if (!this.isStopped) { var os = this.observers.slice(0); for (var i = 0, len = os.length; i < len; i++) { os[i].onNext(value); } } }, /** * Unsubscribe all observers and release resources. */ dispose: function () { this.isDisposed = true; this.observers = null; } }); /** * Creates a subject from the specified observer and observable. * @param {Observer} observer The observer used to send messages to the subject. * @param {Observable} observable The observable used to subscribe to messages sent from the subject. * @returns {Subject} Subject implemented using the given observer and observable. */ Subject.create = function (observer, observable) { return new AnonymousSubject(observer, observable); }; return Subject; }(Observable)); /** * Represents the result of an asynchronous operation. * The last value before the OnCompleted notification, or the error received through OnError, is sent to all subscribed observers. */ var AsyncSubject = Rx.AsyncSubject = (function (__super__) { function subscribe(observer) { checkDisposed.call(this); if (!this.isStopped) { this.observers.push(observer); return new InnerSubscription(this, observer); } var ex = this.exception, hv = this.hasValue, v = this.value; if (ex) { observer.onError(ex); } else if (hv) { observer.onNext(v); observer.onCompleted(); } else { observer.onCompleted(); } return disposableEmpty; } inherits(AsyncSubject, __super__); /** * Creates a subject that can only receive one value and that value is cached for all future observations. * @constructor */ function AsyncSubject() { __super__.call(this, subscribe); this.isDisposed = false; this.isStopped = false; this.value = null; this.hasValue = false; this.observers = []; this.exception = null; } addProperties(AsyncSubject.prototype, Observer, { /** * Indicates whether the subject has observers subscribed to it. * @returns {Boolean} Indicates whether the subject has observers subscribed to it. */ hasObservers: function () { checkDisposed.call(this); return this.observers.length > 0; }, /** * Notifies all subscribed observers about the end of the sequence, also causing the last received value to be sent out (if any). */ onCompleted: function () { var o, i, len; checkDisposed.call(this); if (!this.isStopped) { this.isStopped = true; var os = this.observers.slice(0), v = this.value, hv = this.hasValue; if (hv) { for (i = 0, len = os.length; i < len; i++) { o = os[i]; o.onNext(v); o.onCompleted(); } } else { for (i = 0, len = os.length; i < len; i++) { os[i].onCompleted(); } } this.observers = []; } }, /** * Notifies all subscribed observers about the error. * @param {Mixed} error The Error to send to all observers. */ onError: function (error) { checkDisposed.call(this); if (!this.isStopped) { var os = this.observers.slice(0); this.isStopped = true; this.exception = error; for (var i = 0, len = os.length; i < len; i++) { os[i].onError(error); } this.observers = []; } }, /** * Sends a value to the subject. The last value received before successful termination will be sent to all subscribed and future observers. * @param {Mixed} value The value to store in the subject. */ onNext: function (value) { checkDisposed.call(this); if (this.isStopped) { return; } this.value = value; this.hasValue = true; }, /** * Unsubscribe all observers and release resources. */ dispose: function () { this.isDisposed = true; this.observers = null; this.exception = null; this.value = null; } }); return AsyncSubject; }(Observable)); var AnonymousSubject = Rx.AnonymousSubject = (function (__super__) { inherits(AnonymousSubject, __super__); function AnonymousSubject(observer, observable) { this.observer = observer; this.observable = observable; __super__.call(this, this.observable.subscribe.bind(this.observable)); } addProperties(AnonymousSubject.prototype, Observer, { onCompleted: function () { this.observer.onCompleted(); }, onError: function (exception) { this.observer.onError(exception); }, onNext: function (value) { this.observer.onNext(value); } }); return AnonymousSubject; }(Observable)); /** * Represents a value that changes over time. * Observers can subscribe to the subject to receive the last (or initial) value and all subsequent notifications. */ var BehaviorSubject = Rx.BehaviorSubject = (function (__super__) { function subscribe(observer) { checkDisposed.call(this); if (!this.isStopped) { this.observers.push(observer); observer.onNext(this.value); return new InnerSubscription(this, observer); } var ex = this.exception; if (ex) { observer.onError(ex); } else { observer.onCompleted(); } return disposableEmpty; } inherits(BehaviorSubject, __super__); /** * @constructor * Initializes a new instance of the BehaviorSubject class which creates a subject that caches its last value and starts with the specified value. * @param {Mixed} value Initial value sent to observers when no other value has been received by the subject yet. */ function BehaviorSubject(value) { __super__.call(this, subscribe); this.value = value, this.observers = [], this.isDisposed = false, this.isStopped = false, this.exception = null; } addProperties(BehaviorSubject.prototype, Observer, { /** * Indicates whether the subject has observers subscribed to it. * @returns {Boolean} Indicates whether the subject has observers subscribed to it. */ hasObservers: function () { return this.observers.length > 0; }, /** * Notifies all subscribed observers about the end of the sequence. */ onCompleted: function () { checkDisposed.call(this); if (this.isStopped) { return; } this.isStopped = true; for (var i = 0, os = this.observers.slice(0), len = os.length; i < len; i++) { os[i].onCompleted(); } this.observers = []; }, /** * Notifies all subscribed observers about the exception. * @param {Mixed} error The exception to send to all observers. */ onError: function (error) { checkDisposed.call(this); if (this.isStopped) { return; } this.isStopped = true; this.exception = error; for (var i = 0, os = this.observers.slice(0), len = os.length; i < len; i++) { os[i].onError(error); } this.observers = []; }, /** * Notifies all subscribed observers about the arrival of the specified element in the sequence. * @param {Mixed} value The value to send to all observers. */ onNext: function (value) { checkDisposed.call(this); if (this.isStopped) { return; } this.value = value; for (var i = 0, os = this.observers.slice(0), len = os.length; i < len; i++) { os[i].onNext(value); } }, /** * Unsubscribe all observers and release resources. */ dispose: function () { this.isDisposed = true; this.observers = null; this.value = null; this.exception = null; } }); return BehaviorSubject; }(Observable)); /** * Represents an object that is both an observable sequence as well as an observer. * Each notification is broadcasted to all subscribed and future observers, subject to buffer trimming policies. */ var ReplaySubject = Rx.ReplaySubject = (function (__super__) { function createRemovableDisposable(subject, observer) { return disposableCreate(function () { observer.dispose(); !subject.isDisposed && subject.observers.splice(subject.observers.indexOf(observer), 1); }); } function subscribe(observer) { var so = new ScheduledObserver(this.scheduler, observer), subscription = createRemovableDisposable(this, so); checkDisposed.call(this); this._trim(this.scheduler.now()); this.observers.push(so); var n = this.q.length; for (var i = 0, len = this.q.length; i < len; i++) { so.onNext(this.q[i].value); } if (this.hasError) { n++; so.onError(this.error); } else if (this.isStopped) { n++; so.onCompleted(); } so.ensureActive(n); return subscription; } inherits(ReplaySubject, __super__); /** * Initializes a new instance of the ReplaySubject class with the specified buffer size, window size and scheduler. * @param {Number} [bufferSize] Maximum element count of the replay buffer. * @param {Number} [windowSize] Maximum time length of the replay buffer. * @param {Scheduler} [scheduler] Scheduler the observers are invoked on. */ function ReplaySubject(bufferSize, windowSize, scheduler) { this.bufferSize = bufferSize == null ? Number.MAX_VALUE : bufferSize; this.windowSize = windowSize == null ? Number.MAX_VALUE : windowSize; this.scheduler = scheduler || currentThreadScheduler; this.q = []; this.observers = []; this.isStopped = false; this.isDisposed = false; this.hasError = false; this.error = null; __super__.call(this, subscribe); } addProperties(ReplaySubject.prototype, Observer, { /** * Indicates whether the subject has observers subscribed to it. * @returns {Boolean} Indicates whether the subject has observers subscribed to it. */ hasObservers: function () { return this.observers.length > 0; }, _trim: function (now) { while (this.q.length > this.bufferSize) { this.q.shift(); } while (this.q.length > 0 && (now - this.q[0].interval) > this.windowSize) { this.q.shift(); } }, /** * Notifies all subscribed observers about the arrival of the specified element in the sequence. * @param {Mixed} value The value to send to all observers. */ onNext: function (value) { checkDisposed.call(this); if (this.isStopped) { return; } var now = this.scheduler.now(); this.q.push({ interval: now, value: value }); this._trim(now); var o = this.observers.slice(0); for (var i = 0, len = o.length; i < len; i++) { var observer = o[i]; observer.onNext(value); observer.ensureActive(); } }, /** * Notifies all subscribed observers about the exception. * @param {Mixed} error The exception to send to all observers. */ onError: function (error) { checkDisposed.call(this); if (this.isStopped) { return; } this.isStopped = true; this.error = error; this.hasError = true; var now = this.scheduler.now(); this._trim(now); var o = this.observers.slice(0); for (var i = 0, len = o.length; i < len; i++) { var observer = o[i]; observer.onError(error); observer.ensureActive(); } this.observers = []; }, /** * Notifies all subscribed observers about the end of the sequence. */ onCompleted: function () { checkDisposed.call(this); if (this.isStopped) { return; } this.isStopped = true; var now = this.scheduler.now(); this._trim(now); var o = this.observers.slice(0); for (var i = 0, len = o.length; i < len; i++) { var observer = o[i]; observer.onCompleted(); observer.ensureActive(); } this.observers = []; }, /** * Unsubscribe all observers and release resources. */ dispose: function () { this.isDisposed = true; this.observers = null; } }); return ReplaySubject; }(Observable)); if (typeof define == 'function' && typeof define.amd == 'object' && define.amd) { root.Rx = Rx; define(function() { return Rx; }); } else if (freeExports && freeModule) { // in Node.js or RingoJS if (moduleExports) { (freeModule.exports = Rx).Rx = Rx; } else { freeExports.Rx = Rx; } } else { // in a browser or Rhino root.Rx = Rx; } }.call(this));
src/containers/__tests__/aboutview-test.js
elarasu/roverz-chat
/** * Test to check if the component renders correctly */ /* global it expect */ import 'react-native'; import React from 'react'; import renderer from 'react-test-renderer'; import AboutView from '@containers/about/AboutView'; it('AboutView renders correctly', () => { const tree = renderer.create( <AboutView />, ).toJSON(); expect(tree).toMatchSnapshot(); });
src/js/shared/components/errors-field.js
akornatskyy/sample-blog-react
import React from 'react'; import PropTypes from 'prop-types'; class ErrorsField extends React.Component { render() { let errors = this.props.errors || this.context.errors; if (!errors) { return null; } errors = errors[this.props.name]; if (!errors) { return null; } if (Array.isArray(errors)) { errors = errors[errors.length - 1]; } return ( <div className="invalid-feedback"> <i className="fa fa-exclamation"></i> {errors} </div> ); } } ErrorsField.propTypes = { name: PropTypes.string.isRequired, errors: PropTypes.object }; ErrorsField.contextTypes = { errors: ErrorsField.propTypes.errors }; export default ErrorsField;
components/Table/Holders/Better/ChipBetter.js
mattbajorek/blackJackReact
import React, { Component } from 'react'; import ReactDOM from 'react-dom'; import './ChipBetter.scss'; import ChipImage from '../Chips/Chip/ChipImage'; import calWin from '../Card/calWin'; import actions from '../../../../redux/actions'; class ChipBetter extends Component { constructor() { super(); this.state = { winner: null, ran: false }; } componentDidMount() { if (this.props.toAnimate === 'chipAnimation') this.animation(); } animation() { let dispatch = this.props.dispatch; let winner = this.state.winner; let animatedChip = ReactDOM.findDOMNode(this.refs.chipAnimation); animatedChip.addEventListener('webkitAnimationEnd', function() { // Animate chip in toggle dispatch(actions.animateChipIn()); }); } // Check for round end to calculate scores and componentWillReceiveProps(newProps) { if (newProps.roundEnd === true && this.state.ran === false) { let player = newProps.playerScore; let dealer = newProps.dealerScore; // Send scores to calculate winner let results = calWin(player,dealer); // Set the winner state to animate proper chip out direction // Increment state so this logic won't be called again this.setState({ winner: results.winner, ran: true }); // Show message let dispatch = this.props.dispatch; dispatch(actions.message(results.result)); // Restart round setTimeout(function() { dispatch(actions.result(results.winner, results.multiply)); },3000); } } render() { let className; let winner = this.state.winner; if (this.props.animateChip === true && winner === null) { className = "chip-absolute animation-chip-in"; } else if (winner === 'player' || winner === 'tie') { className = "chip-absolute-out animation-chip-player"; } else if (winner === 'dealer') { className = "chip-absolute-out animation-chip-dealer"; } else { className = "chip-absolute"; } return ( <div ref={this.props.toAnimate} className={className}> <ChipImage chip={this.props.chip} /> </div> ) } } export default ChipBetter
examples/js/custom/insert-modal/default-custom-insert-modal-header.js
AllenFang/react-bootstrap-table
/* eslint max-len: 0 */ /* eslint no-unused-vars: 0 */ /* eslint no-alert: 0 */ /* eslint no-console: 0 */ import React from 'react'; import { BootstrapTable, TableHeaderColumn, InsertModalHeader } from 'react-bootstrap-table'; const products = []; function addProducts(quantity) { const startId = products.length; for (let i = 0; i < quantity; i++) { const id = startId + i; products.push({ id: id, name: 'Item name ' + id, price: 2100 + i }); } } addProducts(5); export default class DefaultCustomInsertModalHeaderTable extends React.Component { beforeClose(e) { alert(`[Custom Event]: Before modal close event triggered!`); } handleModalClose(closeModal) { // Custom your onCloseModal event here, // it's not necessary to implement this function if you have no any process before modal close console.log('This is my custom function for modal close event'); closeModal(); } createCustomModalHeader = (closeModal, save) => { return ( <InsertModalHeader className='my-custom-class' title='This is my custom title' beforeClose={ this.beforeClose } onModalClose={ () => this.handleModalClose(closeModal) }/> // hideClose={ true } to hide the close button ); // If you want have more power to custom the child of InsertModalHeader, // you can do it like following // return ( // <InsertModalHeader // beforeClose={ this.beforeClose } // onModalClose={ () => this.handleModalClose(closeModal) }> // { ... } // </InsertModalHeader> // ); } render() { const options = { insertModalHeader: this.createCustomModalHeader }; return ( <BootstrapTable data={ products } options={ options } insertRow> <TableHeaderColumn dataField='id' isKey={ true }>Product ID</TableHeaderColumn> <TableHeaderColumn dataField='name'>Product Name</TableHeaderColumn> <TableHeaderColumn dataField='price'>Product Price</TableHeaderColumn> </BootstrapTable> ); } }
src/rsg-components/Section/SectionRenderer.js
bluetidepro/react-styleguidist
import React from 'react'; import PropTypes from 'prop-types'; import Styled from 'rsg-components/Styled'; import SectionHeading from 'rsg-components/SectionHeading'; import Markdown from 'rsg-components/Markdown'; const styles = ({ space }) => ({ root: { marginBottom: space[4], }, }); export function SectionRenderer(allProps) { const { classes, name, slug, content, components, sections, depth, description, pagePerSection, } = allProps; return ( <section className={classes.root}> {name && ( <SectionHeading depth={depth} id={slug} slotName="sectionToolbar" pagePerSection={pagePerSection} slotProps={allProps} > {name} </SectionHeading> )} {description && <Markdown text={description} />} {content} {sections} {components} </section> ); } SectionRenderer.propTypes = { classes: PropTypes.object.isRequired, name: PropTypes.string, description: PropTypes.string, slug: PropTypes.string, filepath: PropTypes.string, content: PropTypes.node, components: PropTypes.node, sections: PropTypes.node, isolated: PropTypes.bool, depth: PropTypes.number.isRequired, pagePerSection: PropTypes.bool, }; export default Styled(styles)(SectionRenderer);
src/Table.js
albertojacini/react-bootstrap
import React from 'react'; import classNames from 'classnames'; const Table = React.createClass({ propTypes: { striped: React.PropTypes.bool, bordered: React.PropTypes.bool, condensed: React.PropTypes.bool, hover: React.PropTypes.bool, responsive: React.PropTypes.bool }, getDefaultProps() { return { bordered: false, condensed: false, hover: false, responsive: false, striped: false }; }, render() { let classes = { 'table': true, 'table-striped': this.props.striped, 'table-bordered': this.props.bordered, 'table-condensed': this.props.condensed, 'table-hover': this.props.hover }; let table = ( <table {...this.props} className={classNames(this.props.className, classes)}> {this.props.children} </table> ); return this.props.responsive ? ( <div className="table-responsive"> {table} </div> ) : table; } }); export default Table;
src/js/index.js
mariouhrin/simple-react-redux-starter
import React from 'react' import ReactDOM from 'react-dom' import { AppContainer } from 'react-hot-loader' import App from './app' import './../styles/styles.scss' const rootElement = document.getElementById('root') /* eslint-disable react/no-render-return-value */ const render = Component => ReactDOM.render( <AppContainer> <Component /> </AppContainer>, rootElement, ) render(App) // Webpack Hot Module Replacement API if (module.hot) { module.hot.accept('./app', () => { render(App) }) }
src/client/admin/hometiles/homeTiles.js
r3dDoX/geekplanet
import PropTypes from 'prop-types'; import React from 'react'; import Dragula from 'react-dragula'; import 'react-dragula/dist/dragula.css'; import { connect } from 'react-redux'; import { Link } from 'react-router-dom'; import { createLoadHomeTiles } from '../../actions'; import HomeTile from '../../home/homeTile'; import HomeTileContainer from '../../home/homeTilesContainer'; import { HomeTilePropType } from '../../propTypes'; import PrivateRoute from '../../router/privateRoute'; import Xhr from '../../xhr'; import AddHomeTile from './addHomeTile'; import HomeTileDialog from './homeTileDialog'; class HomeTiles extends React.Component { componentWillMount() { if (!this.props.tiles.length) { this.props.loadHomeTiles(); } } componentDidMount() { const drake = Dragula([this.dragulaContainer], {}); drake.on('drop', (element, target, source, sibling) => Xhr.post('/api/home/tiles/order', { element: element.dataset.id, sibling: sibling && sibling.dataset.id, }).then(this.props.loadHomeTiles) ); } render() { return ( <HomeTileContainer innerRef={(element) => { this.dragulaContainer = element; }}> {this.props.tiles.map(tile => ( <HomeTile key={tile._id} id={tile._id} tile={tile} link={`/admin/hometiles/${tile._id}`} /> ))} <Link to="/admin/hometiles/new"> <AddHomeTile /> </Link> <PrivateRoute path="/admin/hometiles/:id" allowedRoles={['admin']} component={HomeTileDialog} /> </HomeTileContainer> ); } } HomeTiles.propTypes = { tiles: HomeTilePropType.isRequired, loadHomeTiles: PropTypes.func.isRequired, }; export default connect( state => ({ tiles: state.home.tiles, }), dispatch => ({ loadHomeTiles() { dispatch(createLoadHomeTiles()); }, }) )(HomeTiles);
ios_ReactSideMenu/app/styles/style.js
mitrais-cdc-mobile/react-pocs
"use strict"; import React, { StyleSheet, Dimensions } from 'react-native'; var width = Dimensions.get('window').width; var height = Dimensions.get('window').height; const styles = StyleSheet.create({ container: { flex: 1, justifyContent: 'center', alignItems: 'center', backgroundColor: '#F5FCFF', }, menuContent : { height:100, backgroundColor: 'black' }, navBarContent : { top:60 }, welcome: { fontSize: 20, textAlign: 'center', margin: 10, }, instructions: { textAlign: 'center', color: '#333333', marginBottom: 5, }, whiteBoldText: { color: 'white', fontWeight: 'bold' }, button: { alignSelf: 'center', padding: 10, borderRadius: 10, backgroundColor: '#48BBEC', margin: 10 }, buttonFull: { width: width - 40, alignItems: 'center' }, buttonPress: { alignSelf: 'center', padding: 10, borderRadius: 10, backgroundColor: 'black' }, textInput: { height: 40, borderColor: 'gray', borderWidth: 1, marginRight: 20, marginLeft: 20, marginTop: 5, marginBottom: 5, borderRadius: 5, padding: 5 }, navbar: { backgroundColor: '#48BBEC', borderBottomWidth: 1, borderBottomColor: '#f2f2f2' }, navbarTitle: { color: 'white', fontSize: 16, marginTop: 15, fontWeight: 'bold' } }); export default styles;
app/components/Image.js
Byte-Code/lm-digital-store-private-test
import React, { Component } from 'react'; import PropTypes from 'prop-types'; import glamorous from 'glamorous'; import ImageZoom from 'react-medium-image-zoom'; import getUrl from '../utils/cloudinary'; const Img = glamorous.img({ backgroundColor: '#fff' }); export default class Image extends Component { static propTypes = { imageID: PropTypes.string.isRequired, fixBrightColor: PropTypes.bool, alt: PropTypes.string.isRequired, imageOptions: PropTypes.shape({ height: PropTypes.number, width: PropTypes.number }), zoomable: PropTypes.bool }; static defaultProps = { imageOptions: {}, fixBrightColor: false, zoomable: false }; render() { const { imageID, alt, imageOptions, fixBrightColor, zoomable } = this.props; const overlayZoomStyle = { overlay: { opacity: 0.7 } }; let options = { ...imageOptions }; if (fixBrightColor) { options = { ...options, dpr: 'auto', fetch_format: 'auto', flags: ['lossy'] }; } const src = getUrl(imageID, options); return zoomable ? <ImageZoom defaultStyles={overlayZoomStyle} image={{ src, alt }} zoomImage={{ src, alt }} /> : <Img src={src} alt={alt} />; } }
webapp/app/components/SaveHistory/Buttons/index.js
EIP-SAM/SAM-Solution-Node-js
// // List buttons page history save by user // import React from 'react'; import { ButtonToolbar } from 'react-bootstrap'; import LinkContainerButton from 'components/Button'; import styles from 'components/SaveHistory/Buttons/styles.css'; const moment = require('moment'); /* eslint-disable react/prefer-stateless-function */ export default class SaveHistoryButtons extends React.Component { handleClick() { this.props.dateSave(moment().format('DD/MM/YYYY')); this.props.dateDisabled(true); this.props.timeSave(moment().format('HH:mm')); this.props.timeDisabled(true); this.props.frequencySave('No Repeat'); this.props.frequencyDisabled(true); } render() { return ( <ButtonToolbar className={styles.toolbar}> <LinkContainerButton buttonBsStyle="info" className={styles.button} buttonText="Launch save" link="/create-save" onClick={() => this.handleClick()} /> <LinkContainerButton buttonBsStyle="info" className={styles.button} buttonText="Program save" link="/create-save" /> </ButtonToolbar> ); } } SaveHistoryButtons.propTypes = { dateSave: React.PropTypes.func, dateDisabled: React.PropTypes.func, timeSave: React.PropTypes.func, timeDisabled: React.PropTypes.func, frequencySave: React.PropTypes.func, frequencyDisabled: React.PropTypes.func, };
src/components/Sidebar/index.js
joelvoss/react-gmaps
import React, { Component } from 'react'; import PropTypes from 'prop-types'; import Wrapper from './Wrapper'; import Autocomplete from 'components/Autocomplete'; /** * This component represents a list of items. */ class Sidebar extends Component { static propTypes = { config: PropTypes.object.isRequired, globalState: PropTypes.object }; render() { const { config, globalState } = this.props; const location = { lat: globalState.position.lat, lng: globalState.position.lng }; const radius = globalState.position.radius; return ( <Wrapper> {/* Content */} <Autocomplete config={config} location={location} radius={radius} /> </Wrapper> ); } } export default Sidebar;
src/svg-icons/navigation/arrow-drop-down-circle.js
lawrence-yu/material-ui
import React from 'react'; import pure from 'recompose/pure'; import SvgIcon from '../../SvgIcon'; let NavigationArrowDropDownCircle = (props) => ( <SvgIcon {...props}> <path d="M12 2C6.48 2 2 6.48 2 12s4.48 10 10 10 10-4.48 10-10S17.52 2 12 2zm0 12l-4-4h8l-4 4z"/> </SvgIcon> ); NavigationArrowDropDownCircle = pure(NavigationArrowDropDownCircle); NavigationArrowDropDownCircle.displayName = 'NavigationArrowDropDownCircle'; NavigationArrowDropDownCircle.muiName = 'SvgIcon'; export default NavigationArrowDropDownCircle;
monkey/monkey_island/cc/ui/src/components/report-components/security/issues/StrongUsersOnCritIssue.js
guardicore/monkey
import React from 'react'; import CollapsibleWellComponent from '../CollapsibleWell'; export function strongUsersOnCritIssueReport(issue) { return ( <> This critical machine is open to attacks via strong users with access to it. <CollapsibleWellComponent> The services: {this.generateInfoBadges(issue.services)} have been found on the machine thus classifying it as a critical machine. These users has access to it: {this.generateInfoBadges(issue.threatening_users)}. </CollapsibleWellComponent> </> ); }
SmartDemo/ReactComponent/SmartHome/Community/Community.js
HarrisLee/React-Native-Express
/** * Sample React Native App * https://github.com/facebook/react-native * @flow */ import React, { Component } from 'react'; import { StyleSheet, Text, View, Navigator, Platform, WebView, } from 'react-native'; const DEFAULT_URL_COMMUNITY = 'https://sale.suning.com/znjj2/sns/1/sns.html?source=smart'; export default class Community extends Component { constructor(props) { super(props); this.state = { }; } requestShould(request){ console.log(request.url); var url = request.url.indexOf('jsbridge:'); if (url >= 0) { console.log('has contain jsbridge '+ url); return false; } return true; } render() { return (<View style={styles.container}> <WebView style={styles.webView} source={{uri:DEFAULT_URL_COMMUNITY}} startInLoadingState={true} javaScriptEnabled={false} onLoad={()=>alert('加载成功')} onShouldStartLoadWithRequest ={(request)=>this.requestShould(request)}> </WebView> </View> ); } } const styles = StyleSheet.create({ container:{ backgroundColor: '#ffffff', flex: 1 }, webView:{ flex:1, backgroundColor:'#ffffff', } });
js/components/LoadingIndicator.react.js
mxstbr/login-flow
/** * LoadingIndicator.react.js * * A loading indicator, copied from https://github.com/tobiasahlin/SpinKit * */ import React from 'react'; // Since this component doesn't need any state, make it a stateless component function LoadingIndicator() { return ( <div>Loading <div className="sk-fading-circle"> <div className="sk-circle1 sk-circle"></div> <div className="sk-circle2 sk-circle"></div> <div className="sk-circle3 sk-circle"></div> <div className="sk-circle4 sk-circle"></div> <div className="sk-circle5 sk-circle"></div> <div className="sk-circle6 sk-circle"></div> <div className="sk-circle7 sk-circle"></div> <div className="sk-circle8 sk-circle"></div> <div className="sk-circle9 sk-circle"></div> <div className="sk-circle10 sk-circle"></div> <div className="sk-circle11 sk-circle"></div> <div className="sk-circle12 sk-circle"></div> </div> </div> ) } export default LoadingIndicator;
analysis/druidferal/src/modules/spells/SwipeHitCount.js
anom0ly/WoWAnalyzer
import { t } from '@lingui/macro'; import SPELLS from 'common/SPELLS'; import { SpellLink } from 'interface'; import { ThresholdStyle } from 'parser/core/ParseResults'; import { STATISTIC_ORDER } from 'parser/ui/StatisticBox'; import React from 'react'; import HitCountAoE from '../core/HitCountAoE'; /** * Swipe shouldn't be used against a single target, the player's resources are better spent * on Shred against a single target. */ class SwipeHitCount extends HitCountAoE { get hitNoneThresholds() { return { actual: this.hitZeroPerMinute, isGreaterThan: { minor: 0, average: 0.2, major: 0.5, }, style: ThresholdStyle.NUMBER, }; } get hitJustOneThresholds() { return { actual: this.hitJustOnePerMinute, isGreaterThan: { minor: 0, average: 0.5, major: 3.0, }, style: ThresholdStyle.NUMBER, }; } static spell = SPELLS.SWIPE_CAT; statistic() { return this.generateStatistic(STATISTIC_ORDER.OPTIONAL(10)); } suggestions(when) { when(this.hitNoneThresholds).addSuggestion((suggest, actual, recommended) => suggest( <> You are using <SpellLink id={SPELLS.SWIPE_CAT.id} /> out of range of any targets. Try to get familiar with the range of your area of effect abilities so you can avoid wasting energy when they'll not hit anything. </>, ) .icon(SPELLS.SWIPE_CAT.icon) .actual( t({ id: 'druid.feral.suggestions.swipe.hitcount.outOfRange', message: `${actual.toFixed(1)} uses per minute that hit nothing.`, }), ) .recommended(`${recommended} is recommended`), ); when(this.hitJustOneThresholds).addSuggestion((suggest, actual, recommended) => suggest( <> You are using <SpellLink id={SPELLS.SWIPE_CAT.id} /> against a single target. If there's only one target in range you'll do more damage by using <SpellLink id={SPELLS.SHRED.id} />{' '} instead. </>, ) .icon(SPELLS.SWIPE_CAT.icon) .actual( t({ id: 'druid.feral.suggestions.swipe.hitcount.efficiency', message: `${actual.toFixed(1)} uses per minute that hit just one target.`, }), ) .recommended(`${recommended} is recommended`), ); } } export default SwipeHitCount;
ajax/libs/vue-chartjs/2.8.2/vue-chartjs.js
wout/cdnjs
/*! * vue-chartjs v2.8.2 * (c) 2017 Jakub Juszczak <[email protected]> * http://vue-chartjs.org */ (function webpackUniversalModuleDefinition(root, factory) { if(typeof exports === 'object' && typeof module === 'object') module.exports = factory(require("vue"), require("chart.js")); else if(typeof define === 'function' && define.amd) define("VueChartJs", ["vue", "chart.js"], factory); else if(typeof exports === 'object') exports["VueChartJs"] = factory(require("vue"), require("chart.js")); else root["VueChartJs"] = factory(root["vue"], root["chart.js"]); })(this, function(__WEBPACK_EXTERNAL_MODULE_2__, __WEBPACK_EXTERNAL_MODULE_3__) { return /******/ (function(modules) { // webpackBootstrap /******/ // The module cache /******/ var installedModules = {}; /******/ // The require function /******/ function __webpack_require__(moduleId) { /******/ // Check if module is in cache /******/ if(installedModules[moduleId]) /******/ return installedModules[moduleId].exports; /******/ // Create a new module (and put it into the cache) /******/ var module = installedModules[moduleId] = { /******/ exports: {}, /******/ id: moduleId, /******/ loaded: false /******/ }; /******/ // Execute the module function /******/ modules[moduleId].call(module.exports, module, module.exports, __webpack_require__); /******/ // Flag the module as loaded /******/ module.loaded = true; /******/ // Return the exports of the module /******/ return module.exports; /******/ } /******/ // expose the modules object (__webpack_modules__) /******/ __webpack_require__.m = modules; /******/ // expose the module cache /******/ __webpack_require__.c = installedModules; /******/ // __webpack_public_path__ /******/ __webpack_require__.p = ""; /******/ // Load entry module and return exports /******/ return __webpack_require__(0); /******/ }) /************************************************************************/ /******/ ([ /* 0 */ /***/ function(module, exports, __webpack_require__) { 'use strict'; Object.defineProperty(exports, "__esModule", { value: true }); exports.mixins = exports.Scatter = exports.Bubble = exports.Radar = exports.PolarArea = exports.Pie = exports.Line = exports.Doughnut = exports.HorizontalBar = exports.Bar = exports.VueCharts = undefined; var _Bar = __webpack_require__(1); var _Bar2 = _interopRequireDefault(_Bar); var _HorizontalBar = __webpack_require__(225); var _HorizontalBar2 = _interopRequireDefault(_HorizontalBar); var _Doughnut = __webpack_require__(226); var _Doughnut2 = _interopRequireDefault(_Doughnut); var _Line = __webpack_require__(227); var _Line2 = _interopRequireDefault(_Line); var _Pie = __webpack_require__(228); var _Pie2 = _interopRequireDefault(_Pie); var _PolarArea = __webpack_require__(229); var _PolarArea2 = _interopRequireDefault(_PolarArea); var _Radar = __webpack_require__(230); var _Radar2 = _interopRequireDefault(_Radar); var _Bubble = __webpack_require__(231); var _Bubble2 = _interopRequireDefault(_Bubble); var _Scatter = __webpack_require__(232); var _Scatter2 = _interopRequireDefault(_Scatter); var _index = __webpack_require__(233); var _index2 = _interopRequireDefault(_index); var _package = __webpack_require__(273); var _package2 = _interopRequireDefault(_package); function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } var VueCharts = { version: _package2.default.version, Bar: _Bar2.default, HorizontalBar: _HorizontalBar2.default, Doughnut: _Doughnut2.default, Line: _Line2.default, Pie: _Pie2.default, PolarArea: _PolarArea2.default, Radar: _Radar2.default, Bubble: _Bubble2.default, Scatter: _Scatter2.default, mixins: _index2.default }; exports.default = VueCharts; exports.VueCharts = VueCharts; exports.Bar = _Bar2.default; exports.HorizontalBar = _HorizontalBar2.default; exports.Doughnut = _Doughnut2.default; exports.Line = _Line2.default; exports.Pie = _Pie2.default; exports.PolarArea = _PolarArea2.default; exports.Radar = _Radar2.default; exports.Bubble = _Bubble2.default; exports.Scatter = _Scatter2.default; exports.mixins = _index2.default; /***/ }, /* 1 */ /***/ function(module, exports, __webpack_require__) { 'use strict'; Object.defineProperty(exports, "__esModule", { value: true }); var _vue = __webpack_require__(2); var _vue2 = _interopRequireDefault(_vue); var _chart = __webpack_require__(3); var _chart2 = _interopRequireDefault(_chart); var _options = __webpack_require__(4); function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } exports.default = _vue2.default.extend({ render: function render(createElement) { return createElement('div', { style: this.styles, class: this.cssClasses }, [createElement('canvas', { attrs: { id: this.chartId, width: this.width, height: this.height }, ref: 'canvas' })]); }, props: { chartId: { default: 'bar-chart', type: String }, width: { default: 400, type: Number }, height: { default: 400, type: Number }, cssClasses: { type: String, default: '' }, styles: { type: Object, default: function _default() { return { width: '100%', height: '100%', position: 'relative' }; } } }, data: function data() { return { defaultOptions: { scales: { yAxes: [{ ticks: { beginAtZero: true }, gridLines: { display: false } }], xAxes: [{ gridLines: { display: false }, categoryPercentage: 0.5, barPercentage: 0.2 }] } }, plugins: [] }; }, methods: { addPlugin: function addPlugin(plugin) { this.plugins.push(plugin); }, renderChart: function renderChart(data, options) { var chartOptions = (0, _options.mergeOptions)(this.defaultOptions, options); this._chart = new _chart2.default(this.$refs.canvas.getContext('2d'), { type: 'bar', data: data, options: chartOptions, plugins: this.plugins }); } }, beforeDestroy: function beforeDestroy() { if (this._chart) { this._chart.destroy(); } } }); /***/ }, /* 2 */ /***/ function(module, exports) { module.exports = __WEBPACK_EXTERNAL_MODULE_2__; /***/ }, /* 3 */ /***/ function(module, exports) { module.exports = __WEBPACK_EXTERNAL_MODULE_3__; /***/ }, /* 4 */ /***/ function(module, exports, __webpack_require__) { 'use strict'; Object.defineProperty(exports, "__esModule", { value: true }); exports.mergeOptions = mergeOptions; var _merge = __webpack_require__(5); var _merge2 = _interopRequireDefault(_merge); function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } function mergeOptions(obj, src) { return (0, _merge2.default)(obj, src); } /***/ }, /* 5 */ /***/ function(module, exports, __webpack_require__) { var convert = __webpack_require__(6), func = convert('merge', __webpack_require__(213)); func.placeholder = __webpack_require__(9); module.exports = func; /***/ }, /* 6 */ /***/ function(module, exports, __webpack_require__) { var baseConvert = __webpack_require__(7), util = __webpack_require__(10); /** * Converts `func` of `name` to an immutable auto-curried iteratee-first data-last * version with conversion `options` applied. If `name` is an object its methods * will be converted. * * @param {string} name The name of the function to wrap. * @param {Function} [func] The function to wrap. * @param {Object} [options] The options object. See `baseConvert` for more details. * @returns {Function|Object} Returns the converted function or object. */ function convert(name, func, options) { return baseConvert(util, name, func, options); } module.exports = convert; /***/ }, /* 7 */ /***/ function(module, exports, __webpack_require__) { var mapping = __webpack_require__(8), fallbackHolder = __webpack_require__(9); /** Built-in value reference. */ var push = Array.prototype.push; /** * Creates a function, with an arity of `n`, that invokes `func` with the * arguments it receives. * * @private * @param {Function} func The function to wrap. * @param {number} n The arity of the new function. * @returns {Function} Returns the new function. */ function baseArity(func, n) { return n == 2 ? function(a, b) { return func.apply(undefined, arguments); } : function(a) { return func.apply(undefined, arguments); }; } /** * Creates a function that invokes `func`, with up to `n` arguments, ignoring * any additional arguments. * * @private * @param {Function} func The function to cap arguments for. * @param {number} n The arity cap. * @returns {Function} Returns the new function. */ function baseAry(func, n) { return n == 2 ? function(a, b) { return func(a, b); } : function(a) { return func(a); }; } /** * Creates a clone of `array`. * * @private * @param {Array} array The array to clone. * @returns {Array} Returns the cloned array. */ function cloneArray(array) { var length = array ? array.length : 0, result = Array(length); while (length--) { result[length] = array[length]; } return result; } /** * Creates a function that clones a given object using the assignment `func`. * * @private * @param {Function} func The assignment function. * @returns {Function} Returns the new cloner function. */ function createCloner(func) { return function(object) { return func({}, object); }; } /** * A specialized version of `_.spread` which flattens the spread array into * the arguments of the invoked `func`. * * @private * @param {Function} func The function to spread arguments over. * @param {number} start The start position of the spread. * @returns {Function} Returns the new function. */ function flatSpread(func, start) { return function() { var length = arguments.length, lastIndex = length - 1, args = Array(length); while (length--) { args[length] = arguments[length]; } var array = args[start], otherArgs = args.slice(0, start); if (array) { push.apply(otherArgs, array); } if (start != lastIndex) { push.apply(otherArgs, args.slice(start + 1)); } return func.apply(this, otherArgs); }; } /** * Creates a function that wraps `func` and uses `cloner` to clone the first * argument it receives. * * @private * @param {Function} func The function to wrap. * @param {Function} cloner The function to clone arguments. * @returns {Function} Returns the new immutable function. */ function wrapImmutable(func, cloner) { return function() { var length = arguments.length; if (!length) { return; } var args = Array(length); while (length--) { args[length] = arguments[length]; } var result = args[0] = cloner.apply(undefined, args); func.apply(undefined, args); return result; }; } /** * The base implementation of `convert` which accepts a `util` object of methods * required to perform conversions. * * @param {Object} util The util object. * @param {string} name The name of the function to convert. * @param {Function} func The function to convert. * @param {Object} [options] The options object. * @param {boolean} [options.cap=true] Specify capping iteratee arguments. * @param {boolean} [options.curry=true] Specify currying. * @param {boolean} [options.fixed=true] Specify fixed arity. * @param {boolean} [options.immutable=true] Specify immutable operations. * @param {boolean} [options.rearg=true] Specify rearranging arguments. * @returns {Function|Object} Returns the converted function or object. */ function baseConvert(util, name, func, options) { var setPlaceholder, isLib = typeof name == 'function', isObj = name === Object(name); if (isObj) { options = func; func = name; name = undefined; } if (func == null) { throw new TypeError; } options || (options = {}); var config = { 'cap': 'cap' in options ? options.cap : true, 'curry': 'curry' in options ? options.curry : true, 'fixed': 'fixed' in options ? options.fixed : true, 'immutable': 'immutable' in options ? options.immutable : true, 'rearg': 'rearg' in options ? options.rearg : true }; var forceCurry = ('curry' in options) && options.curry, forceFixed = ('fixed' in options) && options.fixed, forceRearg = ('rearg' in options) && options.rearg, placeholder = isLib ? func : fallbackHolder, pristine = isLib ? func.runInContext() : undefined; var helpers = isLib ? func : { 'ary': util.ary, 'assign': util.assign, 'clone': util.clone, 'curry': util.curry, 'forEach': util.forEach, 'isArray': util.isArray, 'isFunction': util.isFunction, 'iteratee': util.iteratee, 'keys': util.keys, 'rearg': util.rearg, 'toInteger': util.toInteger, 'toPath': util.toPath }; var ary = helpers.ary, assign = helpers.assign, clone = helpers.clone, curry = helpers.curry, each = helpers.forEach, isArray = helpers.isArray, isFunction = helpers.isFunction, keys = helpers.keys, rearg = helpers.rearg, toInteger = helpers.toInteger, toPath = helpers.toPath; var aryMethodKeys = keys(mapping.aryMethod); var wrappers = { 'castArray': function(castArray) { return function() { var value = arguments[0]; return isArray(value) ? castArray(cloneArray(value)) : castArray.apply(undefined, arguments); }; }, 'iteratee': function(iteratee) { return function() { var func = arguments[0], arity = arguments[1], result = iteratee(func, arity), length = result.length; if (config.cap && typeof arity == 'number') { arity = arity > 2 ? (arity - 2) : 1; return (length && length <= arity) ? result : baseAry(result, arity); } return result; }; }, 'mixin': function(mixin) { return function(source) { var func = this; if (!isFunction(func)) { return mixin(func, Object(source)); } var pairs = []; each(keys(source), function(key) { if (isFunction(source[key])) { pairs.push([key, func.prototype[key]]); } }); mixin(func, Object(source)); each(pairs, function(pair) { var value = pair[1]; if (isFunction(value)) { func.prototype[pair[0]] = value; } else { delete func.prototype[pair[0]]; } }); return func; }; }, 'nthArg': function(nthArg) { return function(n) { var arity = n < 0 ? 1 : (toInteger(n) + 1); return curry(nthArg(n), arity); }; }, 'rearg': function(rearg) { return function(func, indexes) { var arity = indexes ? indexes.length : 0; return curry(rearg(func, indexes), arity); }; }, 'runInContext': function(runInContext) { return function(context) { return baseConvert(util, runInContext(context), options); }; } }; /*--------------------------------------------------------------------------*/ /** * Casts `func` to a function with an arity capped iteratee if needed. * * @private * @param {string} name The name of the function to inspect. * @param {Function} func The function to inspect. * @returns {Function} Returns the cast function. */ function castCap(name, func) { if (config.cap) { var indexes = mapping.iterateeRearg[name]; if (indexes) { return iterateeRearg(func, indexes); } var n = !isLib && mapping.iterateeAry[name]; if (n) { return iterateeAry(func, n); } } return func; } /** * Casts `func` to a curried function if needed. * * @private * @param {string} name The name of the function to inspect. * @param {Function} func The function to inspect. * @param {number} n The arity of `func`. * @returns {Function} Returns the cast function. */ function castCurry(name, func, n) { return (forceCurry || (config.curry && n > 1)) ? curry(func, n) : func; } /** * Casts `func` to a fixed arity function if needed. * * @private * @param {string} name The name of the function to inspect. * @param {Function} func The function to inspect. * @param {number} n The arity cap. * @returns {Function} Returns the cast function. */ function castFixed(name, func, n) { if (config.fixed && (forceFixed || !mapping.skipFixed[name])) { var data = mapping.methodSpread[name], start = data && data.start; return start === undefined ? ary(func, n) : flatSpread(func, start); } return func; } /** * Casts `func` to an rearged function if needed. * * @private * @param {string} name The name of the function to inspect. * @param {Function} func The function to inspect. * @param {number} n The arity of `func`. * @returns {Function} Returns the cast function. */ function castRearg(name, func, n) { return (config.rearg && n > 1 && (forceRearg || !mapping.skipRearg[name])) ? rearg(func, mapping.methodRearg[name] || mapping.aryRearg[n]) : func; } /** * Creates a clone of `object` by `path`. * * @private * @param {Object} object The object to clone. * @param {Array|string} path The path to clone by. * @returns {Object} Returns the cloned object. */ function cloneByPath(object, path) { path = toPath(path); var index = -1, length = path.length, lastIndex = length - 1, result = clone(Object(object)), nested = result; while (nested != null && ++index < length) { var key = path[index], value = nested[key]; if (value != null) { nested[path[index]] = clone(index == lastIndex ? value : Object(value)); } nested = nested[key]; } return result; } /** * Converts `lodash` to an immutable auto-curried iteratee-first data-last * version with conversion `options` applied. * * @param {Object} [options] The options object. See `baseConvert` for more details. * @returns {Function} Returns the converted `lodash`. */ function convertLib(options) { return _.runInContext.convert(options)(undefined); } /** * Create a converter function for `func` of `name`. * * @param {string} name The name of the function to convert. * @param {Function} func The function to convert. * @returns {Function} Returns the new converter function. */ function createConverter(name, func) { var realName = mapping.aliasToReal[name] || name, methodName = mapping.remap[realName] || realName, oldOptions = options; return function(options) { var newUtil = isLib ? pristine : helpers, newFunc = isLib ? pristine[methodName] : func, newOptions = assign(assign({}, oldOptions), options); return baseConvert(newUtil, realName, newFunc, newOptions); }; } /** * Creates a function that wraps `func` to invoke its iteratee, with up to `n` * arguments, ignoring any additional arguments. * * @private * @param {Function} func The function to cap iteratee arguments for. * @param {number} n The arity cap. * @returns {Function} Returns the new function. */ function iterateeAry(func, n) { return overArg(func, function(func) { return typeof func == 'function' ? baseAry(func, n) : func; }); } /** * Creates a function that wraps `func` to invoke its iteratee with arguments * arranged according to the specified `indexes` where the argument value at * the first index is provided as the first argument, the argument value at * the second index is provided as the second argument, and so on. * * @private * @param {Function} func The function to rearrange iteratee arguments for. * @param {number[]} indexes The arranged argument indexes. * @returns {Function} Returns the new function. */ function iterateeRearg(func, indexes) { return overArg(func, function(func) { var n = indexes.length; return baseArity(rearg(baseAry(func, n), indexes), n); }); } /** * Creates a function that invokes `func` with its first argument transformed. * * @private * @param {Function} func The function to wrap. * @param {Function} transform The argument transform. * @returns {Function} Returns the new function. */ function overArg(func, transform) { return function() { var length = arguments.length; if (!length) { return func(); } var args = Array(length); while (length--) { args[length] = arguments[length]; } var index = config.rearg ? 0 : (length - 1); args[index] = transform(args[index]); return func.apply(undefined, args); }; } /** * Creates a function that wraps `func` and applys the conversions * rules by `name`. * * @private * @param {string} name The name of the function to wrap. * @param {Function} func The function to wrap. * @returns {Function} Returns the converted function. */ function wrap(name, func) { var result, realName = mapping.aliasToReal[name] || name, wrapped = func, wrapper = wrappers[realName]; if (wrapper) { wrapped = wrapper(func); } else if (config.immutable) { if (mapping.mutate.array[realName]) { wrapped = wrapImmutable(func, cloneArray); } else if (mapping.mutate.object[realName]) { wrapped = wrapImmutable(func, createCloner(func)); } else if (mapping.mutate.set[realName]) { wrapped = wrapImmutable(func, cloneByPath); } } each(aryMethodKeys, function(aryKey) { each(mapping.aryMethod[aryKey], function(otherName) { if (realName == otherName) { var data = mapping.methodSpread[realName], afterRearg = data && data.afterRearg; result = afterRearg ? castFixed(realName, castRearg(realName, wrapped, aryKey), aryKey) : castRearg(realName, castFixed(realName, wrapped, aryKey), aryKey); result = castCap(realName, result); result = castCurry(realName, result, aryKey); return false; } }); return !result; }); result || (result = wrapped); if (result == func) { result = forceCurry ? curry(result, 1) : function() { return func.apply(this, arguments); }; } result.convert = createConverter(realName, func); if (mapping.placeholder[realName]) { setPlaceholder = true; result.placeholder = func.placeholder = placeholder; } return result; } /*--------------------------------------------------------------------------*/ if (!isObj) { return wrap(name, func); } var _ = func; // Convert methods by ary cap. var pairs = []; each(aryMethodKeys, function(aryKey) { each(mapping.aryMethod[aryKey], function(key) { var func = _[mapping.remap[key] || key]; if (func) { pairs.push([key, wrap(key, func)]); } }); }); // Convert remaining methods. each(keys(_), function(key) { var func = _[key]; if (typeof func == 'function') { var length = pairs.length; while (length--) { if (pairs[length][0] == key) { return; } } func.convert = createConverter(key, func); pairs.push([key, func]); } }); // Assign to `_` leaving `_.prototype` unchanged to allow chaining. each(pairs, function(pair) { _[pair[0]] = pair[1]; }); _.convert = convertLib; if (setPlaceholder) { _.placeholder = placeholder; } // Assign aliases. each(keys(_), function(key) { each(mapping.realToAlias[key] || [], function(alias) { _[alias] = _[key]; }); }); return _; } module.exports = baseConvert; /***/ }, /* 8 */ /***/ function(module, exports) { /** Used to map aliases to their real names. */ exports.aliasToReal = { // Lodash aliases. 'each': 'forEach', 'eachRight': 'forEachRight', 'entries': 'toPairs', 'entriesIn': 'toPairsIn', 'extend': 'assignIn', 'extendAll': 'assignInAll', 'extendAllWith': 'assignInAllWith', 'extendWith': 'assignInWith', 'first': 'head', // Methods that are curried variants of others. 'conforms': 'conformsTo', 'matches': 'isMatch', 'property': 'get', // Ramda aliases. '__': 'placeholder', 'F': 'stubFalse', 'T': 'stubTrue', 'all': 'every', 'allPass': 'overEvery', 'always': 'constant', 'any': 'some', 'anyPass': 'overSome', 'apply': 'spread', 'assoc': 'set', 'assocPath': 'set', 'complement': 'negate', 'compose': 'flowRight', 'contains': 'includes', 'dissoc': 'unset', 'dissocPath': 'unset', 'dropLast': 'dropRight', 'dropLastWhile': 'dropRightWhile', 'equals': 'isEqual', 'identical': 'eq', 'indexBy': 'keyBy', 'init': 'initial', 'invertObj': 'invert', 'juxt': 'over', 'omitAll': 'omit', 'nAry': 'ary', 'path': 'get', 'pathEq': 'matchesProperty', 'pathOr': 'getOr', 'paths': 'at', 'pickAll': 'pick', 'pipe': 'flow', 'pluck': 'map', 'prop': 'get', 'propEq': 'matchesProperty', 'propOr': 'getOr', 'props': 'at', 'symmetricDifference': 'xor', 'symmetricDifferenceBy': 'xorBy', 'symmetricDifferenceWith': 'xorWith', 'takeLast': 'takeRight', 'takeLastWhile': 'takeRightWhile', 'unapply': 'rest', 'unnest': 'flatten', 'useWith': 'overArgs', 'where': 'conformsTo', 'whereEq': 'isMatch', 'zipObj': 'zipObject' }; /** Used to map ary to method names. */ exports.aryMethod = { '1': [ 'assignAll', 'assignInAll', 'attempt', 'castArray', 'ceil', 'create', 'curry', 'curryRight', 'defaultsAll', 'defaultsDeepAll', 'floor', 'flow', 'flowRight', 'fromPairs', 'invert', 'iteratee', 'memoize', 'method', 'mergeAll', 'methodOf', 'mixin', 'nthArg', 'over', 'overEvery', 'overSome','rest', 'reverse', 'round', 'runInContext', 'spread', 'template', 'trim', 'trimEnd', 'trimStart', 'uniqueId', 'words', 'zipAll' ], '2': [ 'add', 'after', 'ary', 'assign', 'assignAllWith', 'assignIn', 'assignInAllWith', 'at', 'before', 'bind', 'bindAll', 'bindKey', 'chunk', 'cloneDeepWith', 'cloneWith', 'concat', 'conformsTo', 'countBy', 'curryN', 'curryRightN', 'debounce', 'defaults', 'defaultsDeep', 'defaultTo', 'delay', 'difference', 'divide', 'drop', 'dropRight', 'dropRightWhile', 'dropWhile', 'endsWith', 'eq', 'every', 'filter', 'find', 'findIndex', 'findKey', 'findLast', 'findLastIndex', 'findLastKey', 'flatMap', 'flatMapDeep', 'flattenDepth', 'forEach', 'forEachRight', 'forIn', 'forInRight', 'forOwn', 'forOwnRight', 'get', 'groupBy', 'gt', 'gte', 'has', 'hasIn', 'includes', 'indexOf', 'intersection', 'invertBy', 'invoke', 'invokeMap', 'isEqual', 'isMatch', 'join', 'keyBy', 'lastIndexOf', 'lt', 'lte', 'map', 'mapKeys', 'mapValues', 'matchesProperty', 'maxBy', 'meanBy', 'merge', 'mergeAllWith', 'minBy', 'multiply', 'nth', 'omit', 'omitBy', 'overArgs', 'pad', 'padEnd', 'padStart', 'parseInt', 'partial', 'partialRight', 'partition', 'pick', 'pickBy', 'propertyOf', 'pull', 'pullAll', 'pullAt', 'random', 'range', 'rangeRight', 'rearg', 'reject', 'remove', 'repeat', 'restFrom', 'result', 'sampleSize', 'some', 'sortBy', 'sortedIndex', 'sortedIndexOf', 'sortedLastIndex', 'sortedLastIndexOf', 'sortedUniqBy', 'split', 'spreadFrom', 'startsWith', 'subtract', 'sumBy', 'take', 'takeRight', 'takeRightWhile', 'takeWhile', 'tap', 'throttle', 'thru', 'times', 'trimChars', 'trimCharsEnd', 'trimCharsStart', 'truncate', 'union', 'uniqBy', 'uniqWith', 'unset', 'unzipWith', 'without', 'wrap', 'xor', 'zip', 'zipObject', 'zipObjectDeep' ], '3': [ 'assignInWith', 'assignWith', 'clamp', 'differenceBy', 'differenceWith', 'findFrom', 'findIndexFrom', 'findLastFrom', 'findLastIndexFrom', 'getOr', 'includesFrom', 'indexOfFrom', 'inRange', 'intersectionBy', 'intersectionWith', 'invokeArgs', 'invokeArgsMap', 'isEqualWith', 'isMatchWith', 'flatMapDepth', 'lastIndexOfFrom', 'mergeWith', 'orderBy', 'padChars', 'padCharsEnd', 'padCharsStart', 'pullAllBy', 'pullAllWith', 'rangeStep', 'rangeStepRight', 'reduce', 'reduceRight', 'replace', 'set', 'slice', 'sortedIndexBy', 'sortedLastIndexBy', 'transform', 'unionBy', 'unionWith', 'update', 'xorBy', 'xorWith', 'zipWith' ], '4': [ 'fill', 'setWith', 'updateWith' ] }; /** Used to map ary to rearg configs. */ exports.aryRearg = { '2': [1, 0], '3': [2, 0, 1], '4': [3, 2, 0, 1] }; /** Used to map method names to their iteratee ary. */ exports.iterateeAry = { 'dropRightWhile': 1, 'dropWhile': 1, 'every': 1, 'filter': 1, 'find': 1, 'findFrom': 1, 'findIndex': 1, 'findIndexFrom': 1, 'findKey': 1, 'findLast': 1, 'findLastFrom': 1, 'findLastIndex': 1, 'findLastIndexFrom': 1, 'findLastKey': 1, 'flatMap': 1, 'flatMapDeep': 1, 'flatMapDepth': 1, 'forEach': 1, 'forEachRight': 1, 'forIn': 1, 'forInRight': 1, 'forOwn': 1, 'forOwnRight': 1, 'map': 1, 'mapKeys': 1, 'mapValues': 1, 'partition': 1, 'reduce': 2, 'reduceRight': 2, 'reject': 1, 'remove': 1, 'some': 1, 'takeRightWhile': 1, 'takeWhile': 1, 'times': 1, 'transform': 2 }; /** Used to map method names to iteratee rearg configs. */ exports.iterateeRearg = { 'mapKeys': [1], 'reduceRight': [1, 0] }; /** Used to map method names to rearg configs. */ exports.methodRearg = { 'assignInAllWith': [1, 0], 'assignInWith': [1, 2, 0], 'assignAllWith': [1, 0], 'assignWith': [1, 2, 0], 'differenceBy': [1, 2, 0], 'differenceWith': [1, 2, 0], 'getOr': [2, 1, 0], 'intersectionBy': [1, 2, 0], 'intersectionWith': [1, 2, 0], 'isEqualWith': [1, 2, 0], 'isMatchWith': [2, 1, 0], 'mergeAllWith': [1, 0], 'mergeWith': [1, 2, 0], 'padChars': [2, 1, 0], 'padCharsEnd': [2, 1, 0], 'padCharsStart': [2, 1, 0], 'pullAllBy': [2, 1, 0], 'pullAllWith': [2, 1, 0], 'rangeStep': [1, 2, 0], 'rangeStepRight': [1, 2, 0], 'setWith': [3, 1, 2, 0], 'sortedIndexBy': [2, 1, 0], 'sortedLastIndexBy': [2, 1, 0], 'unionBy': [1, 2, 0], 'unionWith': [1, 2, 0], 'updateWith': [3, 1, 2, 0], 'xorBy': [1, 2, 0], 'xorWith': [1, 2, 0], 'zipWith': [1, 2, 0] }; /** Used to map method names to spread configs. */ exports.methodSpread = { 'assignAll': { 'start': 0 }, 'assignAllWith': { 'start': 0 }, 'assignInAll': { 'start': 0 }, 'assignInAllWith': { 'start': 0 }, 'defaultsAll': { 'start': 0 }, 'defaultsDeepAll': { 'start': 0 }, 'invokeArgs': { 'start': 2 }, 'invokeArgsMap': { 'start': 2 }, 'mergeAll': { 'start': 0 }, 'mergeAllWith': { 'start': 0 }, 'partial': { 'start': 1 }, 'partialRight': { 'start': 1 }, 'without': { 'start': 1 }, 'zipAll': { 'start': 0 } }; /** Used to identify methods which mutate arrays or objects. */ exports.mutate = { 'array': { 'fill': true, 'pull': true, 'pullAll': true, 'pullAllBy': true, 'pullAllWith': true, 'pullAt': true, 'remove': true, 'reverse': true }, 'object': { 'assign': true, 'assignAll': true, 'assignAllWith': true, 'assignIn': true, 'assignInAll': true, 'assignInAllWith': true, 'assignInWith': true, 'assignWith': true, 'defaults': true, 'defaultsAll': true, 'defaultsDeep': true, 'defaultsDeepAll': true, 'merge': true, 'mergeAll': true, 'mergeAllWith': true, 'mergeWith': true, }, 'set': { 'set': true, 'setWith': true, 'unset': true, 'update': true, 'updateWith': true } }; /** Used to track methods with placeholder support */ exports.placeholder = { 'bind': true, 'bindKey': true, 'curry': true, 'curryRight': true, 'partial': true, 'partialRight': true }; /** Used to map real names to their aliases. */ exports.realToAlias = (function() { var hasOwnProperty = Object.prototype.hasOwnProperty, object = exports.aliasToReal, result = {}; for (var key in object) { var value = object[key]; if (hasOwnProperty.call(result, value)) { result[value].push(key); } else { result[value] = [key]; } } return result; }()); /** Used to map method names to other names. */ exports.remap = { 'assignAll': 'assign', 'assignAllWith': 'assignWith', 'assignInAll': 'assignIn', 'assignInAllWith': 'assignInWith', 'curryN': 'curry', 'curryRightN': 'curryRight', 'defaultsAll': 'defaults', 'defaultsDeepAll': 'defaultsDeep', 'findFrom': 'find', 'findIndexFrom': 'findIndex', 'findLastFrom': 'findLast', 'findLastIndexFrom': 'findLastIndex', 'getOr': 'get', 'includesFrom': 'includes', 'indexOfFrom': 'indexOf', 'invokeArgs': 'invoke', 'invokeArgsMap': 'invokeMap', 'lastIndexOfFrom': 'lastIndexOf', 'mergeAll': 'merge', 'mergeAllWith': 'mergeWith', 'padChars': 'pad', 'padCharsEnd': 'padEnd', 'padCharsStart': 'padStart', 'propertyOf': 'get', 'rangeStep': 'range', 'rangeStepRight': 'rangeRight', 'restFrom': 'rest', 'spreadFrom': 'spread', 'trimChars': 'trim', 'trimCharsEnd': 'trimEnd', 'trimCharsStart': 'trimStart', 'zipAll': 'zip' }; /** Used to track methods that skip fixing their arity. */ exports.skipFixed = { 'castArray': true, 'flow': true, 'flowRight': true, 'iteratee': true, 'mixin': true, 'rearg': true, 'runInContext': true }; /** Used to track methods that skip rearranging arguments. */ exports.skipRearg = { 'add': true, 'assign': true, 'assignIn': true, 'bind': true, 'bindKey': true, 'concat': true, 'difference': true, 'divide': true, 'eq': true, 'gt': true, 'gte': true, 'isEqual': true, 'lt': true, 'lte': true, 'matchesProperty': true, 'merge': true, 'multiply': true, 'overArgs': true, 'partial': true, 'partialRight': true, 'propertyOf': true, 'random': true, 'range': true, 'rangeRight': true, 'subtract': true, 'zip': true, 'zipObject': true, 'zipObjectDeep': true }; /***/ }, /* 9 */ /***/ function(module, exports) { /** * The default argument placeholder value for methods. * * @type {Object} */ module.exports = {}; /***/ }, /* 10 */ /***/ function(module, exports, __webpack_require__) { module.exports = { 'ary': __webpack_require__(11), 'assign': __webpack_require__(80), 'clone': __webpack_require__(103), 'curry': __webpack_require__(170), 'forEach': __webpack_require__(64), 'isArray': __webpack_require__(50), 'isFunction': __webpack_require__(19), 'iteratee': __webpack_require__(171), 'keys': __webpack_require__(98), 'rearg': __webpack_require__(206), 'toInteger': __webpack_require__(76), 'toPath': __webpack_require__(212) }; /***/ }, /* 11 */ /***/ function(module, exports, __webpack_require__) { var createWrap = __webpack_require__(12); /** Used to compose bitmasks for function metadata. */ var WRAP_ARY_FLAG = 128; /** * Creates a function that invokes `func`, with up to `n` arguments, * ignoring any additional arguments. * * @static * @memberOf _ * @since 3.0.0 * @category Function * @param {Function} func The function to cap arguments for. * @param {number} [n=func.length] The arity cap. * @param- {Object} [guard] Enables use as an iteratee for methods like `_.map`. * @returns {Function} Returns the new capped function. * @example * * _.map(['6', '8', '10'], _.ary(parseInt, 1)); * // => [6, 8, 10] */ function ary(func, n, guard) { n = guard ? undefined : n; n = (func && n == null) ? func.length : n; return createWrap(func, WRAP_ARY_FLAG, undefined, undefined, undefined, undefined, n); } module.exports = ary; /***/ }, /* 12 */ /***/ function(module, exports, __webpack_require__) { var baseSetData = __webpack_require__(13), createBind = __webpack_require__(31), createCurry = __webpack_require__(34), createHybrid = __webpack_require__(36), createPartial = __webpack_require__(74), getData = __webpack_require__(44), mergeData = __webpack_require__(75), setData = __webpack_require__(54), setWrapToString = __webpack_require__(56), toInteger = __webpack_require__(76); /** Error message constants. */ var FUNC_ERROR_TEXT = 'Expected a function'; /** Used to compose bitmasks for function metadata. */ var WRAP_BIND_FLAG = 1, WRAP_BIND_KEY_FLAG = 2, WRAP_CURRY_FLAG = 8, WRAP_CURRY_RIGHT_FLAG = 16, WRAP_PARTIAL_FLAG = 32, WRAP_PARTIAL_RIGHT_FLAG = 64; /* Built-in method references for those with the same name as other `lodash` methods. */ var nativeMax = Math.max; /** * Creates a function that either curries or invokes `func` with optional * `this` binding and partially applied arguments. * * @private * @param {Function|string} func The function or method name to wrap. * @param {number} bitmask The bitmask flags. * 1 - `_.bind` * 2 - `_.bindKey` * 4 - `_.curry` or `_.curryRight` of a bound function * 8 - `_.curry` * 16 - `_.curryRight` * 32 - `_.partial` * 64 - `_.partialRight` * 128 - `_.rearg` * 256 - `_.ary` * 512 - `_.flip` * @param {*} [thisArg] The `this` binding of `func`. * @param {Array} [partials] The arguments to be partially applied. * @param {Array} [holders] The `partials` placeholder indexes. * @param {Array} [argPos] The argument positions of the new function. * @param {number} [ary] The arity cap of `func`. * @param {number} [arity] The arity of `func`. * @returns {Function} Returns the new wrapped function. */ function createWrap(func, bitmask, thisArg, partials, holders, argPos, ary, arity) { var isBindKey = bitmask & WRAP_BIND_KEY_FLAG; if (!isBindKey && typeof func != 'function') { throw new TypeError(FUNC_ERROR_TEXT); } var length = partials ? partials.length : 0; if (!length) { bitmask &= ~(WRAP_PARTIAL_FLAG | WRAP_PARTIAL_RIGHT_FLAG); partials = holders = undefined; } ary = ary === undefined ? ary : nativeMax(toInteger(ary), 0); arity = arity === undefined ? arity : toInteger(arity); length -= holders ? holders.length : 0; if (bitmask & WRAP_PARTIAL_RIGHT_FLAG) { var partialsRight = partials, holdersRight = holders; partials = holders = undefined; } var data = isBindKey ? undefined : getData(func); var newData = [ func, bitmask, thisArg, partials, holders, partialsRight, holdersRight, argPos, ary, arity ]; if (data) { mergeData(newData, data); } func = newData[0]; bitmask = newData[1]; thisArg = newData[2]; partials = newData[3]; holders = newData[4]; arity = newData[9] = newData[9] === undefined ? (isBindKey ? 0 : func.length) : nativeMax(newData[9] - length, 0); if (!arity && bitmask & (WRAP_CURRY_FLAG | WRAP_CURRY_RIGHT_FLAG)) { bitmask &= ~(WRAP_CURRY_FLAG | WRAP_CURRY_RIGHT_FLAG); } if (!bitmask || bitmask == WRAP_BIND_FLAG) { var result = createBind(func, bitmask, thisArg); } else if (bitmask == WRAP_CURRY_FLAG || bitmask == WRAP_CURRY_RIGHT_FLAG) { result = createCurry(func, bitmask, arity); } else if ((bitmask == WRAP_PARTIAL_FLAG || bitmask == (WRAP_BIND_FLAG | WRAP_PARTIAL_FLAG)) && !holders.length) { result = createPartial(func, bitmask, thisArg, partials); } else { result = createHybrid.apply(undefined, newData); } var setter = data ? baseSetData : setData; return setWrapToString(setter(result, newData), func, bitmask); } module.exports = createWrap; /***/ }, /* 13 */ /***/ function(module, exports, __webpack_require__) { var identity = __webpack_require__(14), metaMap = __webpack_require__(15); /** * The base implementation of `setData` without support for hot loop shorting. * * @private * @param {Function} func The function to associate metadata with. * @param {*} data The metadata. * @returns {Function} Returns `func`. */ var baseSetData = !metaMap ? identity : function(func, data) { metaMap.set(func, data); return func; }; module.exports = baseSetData; /***/ }, /* 14 */ /***/ function(module, exports) { /** * This method returns the first argument it receives. * * @static * @since 0.1.0 * @memberOf _ * @category Util * @param {*} value Any value. * @returns {*} Returns `value`. * @example * * var object = { 'a': 1 }; * * console.log(_.identity(object) === object); * // => true */ function identity(value) { return value; } module.exports = identity; /***/ }, /* 15 */ /***/ function(module, exports, __webpack_require__) { var WeakMap = __webpack_require__(16); /** Used to store function metadata. */ var metaMap = WeakMap && new WeakMap; module.exports = metaMap; /***/ }, /* 16 */ /***/ function(module, exports, __webpack_require__) { var getNative = __webpack_require__(17), root = __webpack_require__(22); /* Built-in method references that are verified to be native. */ var WeakMap = getNative(root, 'WeakMap'); module.exports = WeakMap; /***/ }, /* 17 */ /***/ function(module, exports, __webpack_require__) { var baseIsNative = __webpack_require__(18), getValue = __webpack_require__(30); /** * Gets the native function at `key` of `object`. * * @private * @param {Object} object The object to query. * @param {string} key The key of the method to get. * @returns {*} Returns the function if it's native, else `undefined`. */ function getNative(object, key) { var value = getValue(object, key); return baseIsNative(value) ? value : undefined; } module.exports = getNative; /***/ }, /* 18 */ /***/ function(module, exports, __webpack_require__) { var isFunction = __webpack_require__(19), isMasked = __webpack_require__(27), isObject = __webpack_require__(26), toSource = __webpack_require__(29); /** * Used to match `RegExp` * [syntax characters](http://ecma-international.org/ecma-262/7.0/#sec-patterns). */ var reRegExpChar = /[\\^$.*+?()[\]{}|]/g; /** Used to detect host constructors (Safari). */ var reIsHostCtor = /^\[object .+?Constructor\]$/; /** Used for built-in method references. */ var funcProto = Function.prototype, objectProto = Object.prototype; /** Used to resolve the decompiled source of functions. */ var funcToString = funcProto.toString; /** Used to check objects for own properties. */ var hasOwnProperty = objectProto.hasOwnProperty; /** Used to detect if a method is native. */ var reIsNative = RegExp('^' + funcToString.call(hasOwnProperty).replace(reRegExpChar, '\\$&') .replace(/hasOwnProperty|(function).*?(?=\\\()| for .+?(?=\\\])/g, '$1.*?') + '$' ); /** * The base implementation of `_.isNative` without bad shim checks. * * @private * @param {*} value The value to check. * @returns {boolean} Returns `true` if `value` is a native function, * else `false`. */ function baseIsNative(value) { if (!isObject(value) || isMasked(value)) { return false; } var pattern = isFunction(value) ? reIsNative : reIsHostCtor; return pattern.test(toSource(value)); } module.exports = baseIsNative; /***/ }, /* 19 */ /***/ function(module, exports, __webpack_require__) { var baseGetTag = __webpack_require__(20), isObject = __webpack_require__(26); /** `Object#toString` result references. */ var asyncTag = '[object AsyncFunction]', funcTag = '[object Function]', genTag = '[object GeneratorFunction]', proxyTag = '[object Proxy]'; /** * Checks if `value` is classified as a `Function` object. * * @static * @memberOf _ * @since 0.1.0 * @category Lang * @param {*} value The value to check. * @returns {boolean} Returns `true` if `value` is a function, else `false`. * @example * * _.isFunction(_); * // => true * * _.isFunction(/abc/); * // => false */ function isFunction(value) { if (!isObject(value)) { return false; } // The use of `Object#toString` avoids issues with the `typeof` operator // in Safari 9 which returns 'object' for typed arrays and other constructors. var tag = baseGetTag(value); return tag == funcTag || tag == genTag || tag == asyncTag || tag == proxyTag; } module.exports = isFunction; /***/ }, /* 20 */ /***/ function(module, exports, __webpack_require__) { var Symbol = __webpack_require__(21), getRawTag = __webpack_require__(24), objectToString = __webpack_require__(25); /** `Object#toString` result references. */ var nullTag = '[object Null]', undefinedTag = '[object Undefined]'; /** Built-in value references. */ var symToStringTag = Symbol ? Symbol.toStringTag : undefined; /** * The base implementation of `getTag` without fallbacks for buggy environments. * * @private * @param {*} value The value to query. * @returns {string} Returns the `toStringTag`. */ function baseGetTag(value) { if (value == null) { return value === undefined ? undefinedTag : nullTag; } return (symToStringTag && symToStringTag in Object(value)) ? getRawTag(value) : objectToString(value); } module.exports = baseGetTag; /***/ }, /* 21 */ /***/ function(module, exports, __webpack_require__) { var root = __webpack_require__(22); /** Built-in value references. */ var Symbol = root.Symbol; module.exports = Symbol; /***/ }, /* 22 */ /***/ function(module, exports, __webpack_require__) { var freeGlobal = __webpack_require__(23); /** Detect free variable `self`. */ var freeSelf = typeof self == 'object' && self && self.Object === Object && self; /** Used as a reference to the global object. */ var root = freeGlobal || freeSelf || Function('return this')(); module.exports = root; /***/ }, /* 23 */ /***/ function(module, exports) { /* WEBPACK VAR INJECTION */(function(global) {/** Detect free variable `global` from Node.js. */ var freeGlobal = typeof global == 'object' && global && global.Object === Object && global; module.exports = freeGlobal; /* WEBPACK VAR INJECTION */}.call(exports, (function() { return this; }()))) /***/ }, /* 24 */ /***/ function(module, exports, __webpack_require__) { var Symbol = __webpack_require__(21); /** Used for built-in method references. */ var objectProto = Object.prototype; /** Used to check objects for own properties. */ var hasOwnProperty = objectProto.hasOwnProperty; /** * Used to resolve the * [`toStringTag`](http://ecma-international.org/ecma-262/7.0/#sec-object.prototype.tostring) * of values. */ var nativeObjectToString = objectProto.toString; /** Built-in value references. */ var symToStringTag = Symbol ? Symbol.toStringTag : undefined; /** * A specialized version of `baseGetTag` which ignores `Symbol.toStringTag` values. * * @private * @param {*} value The value to query. * @returns {string} Returns the raw `toStringTag`. */ function getRawTag(value) { var isOwn = hasOwnProperty.call(value, symToStringTag), tag = value[symToStringTag]; try { value[symToStringTag] = undefined; var unmasked = true; } catch (e) {} var result = nativeObjectToString.call(value); if (unmasked) { if (isOwn) { value[symToStringTag] = tag; } else { delete value[symToStringTag]; } } return result; } module.exports = getRawTag; /***/ }, /* 25 */ /***/ function(module, exports) { /** Used for built-in method references. */ var objectProto = Object.prototype; /** * Used to resolve the * [`toStringTag`](http://ecma-international.org/ecma-262/7.0/#sec-object.prototype.tostring) * of values. */ var nativeObjectToString = objectProto.toString; /** * Converts `value` to a string using `Object.prototype.toString`. * * @private * @param {*} value The value to convert. * @returns {string} Returns the converted string. */ function objectToString(value) { return nativeObjectToString.call(value); } module.exports = objectToString; /***/ }, /* 26 */ /***/ function(module, exports) { /** * Checks if `value` is the * [language type](http://www.ecma-international.org/ecma-262/7.0/#sec-ecmascript-language-types) * of `Object`. (e.g. arrays, functions, objects, regexes, `new Number(0)`, and `new String('')`) * * @static * @memberOf _ * @since 0.1.0 * @category Lang * @param {*} value The value to check. * @returns {boolean} Returns `true` if `value` is an object, else `false`. * @example * * _.isObject({}); * // => true * * _.isObject([1, 2, 3]); * // => true * * _.isObject(_.noop); * // => true * * _.isObject(null); * // => false */ function isObject(value) { var type = typeof value; return value != null && (type == 'object' || type == 'function'); } module.exports = isObject; /***/ }, /* 27 */ /***/ function(module, exports, __webpack_require__) { var coreJsData = __webpack_require__(28); /** Used to detect methods masquerading as native. */ var maskSrcKey = (function() { var uid = /[^.]+$/.exec(coreJsData && coreJsData.keys && coreJsData.keys.IE_PROTO || ''); return uid ? ('Symbol(src)_1.' + uid) : ''; }()); /** * Checks if `func` has its source masked. * * @private * @param {Function} func The function to check. * @returns {boolean} Returns `true` if `func` is masked, else `false`. */ function isMasked(func) { return !!maskSrcKey && (maskSrcKey in func); } module.exports = isMasked; /***/ }, /* 28 */ /***/ function(module, exports, __webpack_require__) { var root = __webpack_require__(22); /** Used to detect overreaching core-js shims. */ var coreJsData = root['__core-js_shared__']; module.exports = coreJsData; /***/ }, /* 29 */ /***/ function(module, exports) { /** Used for built-in method references. */ var funcProto = Function.prototype; /** Used to resolve the decompiled source of functions. */ var funcToString = funcProto.toString; /** * Converts `func` to its source code. * * @private * @param {Function} func The function to convert. * @returns {string} Returns the source code. */ function toSource(func) { if (func != null) { try { return funcToString.call(func); } catch (e) {} try { return (func + ''); } catch (e) {} } return ''; } module.exports = toSource; /***/ }, /* 30 */ /***/ function(module, exports) { /** * Gets the value at `key` of `object`. * * @private * @param {Object} [object] The object to query. * @param {string} key The key of the property to get. * @returns {*} Returns the property value. */ function getValue(object, key) { return object == null ? undefined : object[key]; } module.exports = getValue; /***/ }, /* 31 */ /***/ function(module, exports, __webpack_require__) { var createCtor = __webpack_require__(32), root = __webpack_require__(22); /** Used to compose bitmasks for function metadata. */ var WRAP_BIND_FLAG = 1; /** * Creates a function that wraps `func` to invoke it with the optional `this` * binding of `thisArg`. * * @private * @param {Function} func The function to wrap. * @param {number} bitmask The bitmask flags. See `createWrap` for more details. * @param {*} [thisArg] The `this` binding of `func`. * @returns {Function} Returns the new wrapped function. */ function createBind(func, bitmask, thisArg) { var isBind = bitmask & WRAP_BIND_FLAG, Ctor = createCtor(func); function wrapper() { var fn = (this && this !== root && this instanceof wrapper) ? Ctor : func; return fn.apply(isBind ? thisArg : this, arguments); } return wrapper; } module.exports = createBind; /***/ }, /* 32 */ /***/ function(module, exports, __webpack_require__) { var baseCreate = __webpack_require__(33), isObject = __webpack_require__(26); /** * Creates a function that produces an instance of `Ctor` regardless of * whether it was invoked as part of a `new` expression or by `call` or `apply`. * * @private * @param {Function} Ctor The constructor to wrap. * @returns {Function} Returns the new wrapped function. */ function createCtor(Ctor) { return function() { // Use a `switch` statement to work with class constructors. See // http://ecma-international.org/ecma-262/7.0/#sec-ecmascript-function-objects-call-thisargument-argumentslist // for more details. var args = arguments; switch (args.length) { case 0: return new Ctor; case 1: return new Ctor(args[0]); case 2: return new Ctor(args[0], args[1]); case 3: return new Ctor(args[0], args[1], args[2]); case 4: return new Ctor(args[0], args[1], args[2], args[3]); case 5: return new Ctor(args[0], args[1], args[2], args[3], args[4]); case 6: return new Ctor(args[0], args[1], args[2], args[3], args[4], args[5]); case 7: return new Ctor(args[0], args[1], args[2], args[3], args[4], args[5], args[6]); } var thisBinding = baseCreate(Ctor.prototype), result = Ctor.apply(thisBinding, args); // Mimic the constructor's `return` behavior. // See https://es5.github.io/#x13.2.2 for more details. return isObject(result) ? result : thisBinding; }; } module.exports = createCtor; /***/ }, /* 33 */ /***/ function(module, exports, __webpack_require__) { var isObject = __webpack_require__(26); /** Built-in value references. */ var objectCreate = Object.create; /** * The base implementation of `_.create` without support for assigning * properties to the created object. * * @private * @param {Object} proto The object to inherit from. * @returns {Object} Returns the new object. */ var baseCreate = (function() { function object() {} return function(proto) { if (!isObject(proto)) { return {}; } if (objectCreate) { return objectCreate(proto); } object.prototype = proto; var result = new object; object.prototype = undefined; return result; }; }()); module.exports = baseCreate; /***/ }, /* 34 */ /***/ function(module, exports, __webpack_require__) { var apply = __webpack_require__(35), createCtor = __webpack_require__(32), createHybrid = __webpack_require__(36), createRecurry = __webpack_require__(40), getHolder = __webpack_require__(70), replaceHolders = __webpack_require__(73), root = __webpack_require__(22); /** * Creates a function that wraps `func` to enable currying. * * @private * @param {Function} func The function to wrap. * @param {number} bitmask The bitmask flags. See `createWrap` for more details. * @param {number} arity The arity of `func`. * @returns {Function} Returns the new wrapped function. */ function createCurry(func, bitmask, arity) { var Ctor = createCtor(func); function wrapper() { var length = arguments.length, args = Array(length), index = length, placeholder = getHolder(wrapper); while (index--) { args[index] = arguments[index]; } var holders = (length < 3 && args[0] !== placeholder && args[length - 1] !== placeholder) ? [] : replaceHolders(args, placeholder); length -= holders.length; if (length < arity) { return createRecurry( func, bitmask, createHybrid, wrapper.placeholder, undefined, args, holders, undefined, undefined, arity - length); } var fn = (this && this !== root && this instanceof wrapper) ? Ctor : func; return apply(fn, this, args); } return wrapper; } module.exports = createCurry; /***/ }, /* 35 */ /***/ function(module, exports) { /** * A faster alternative to `Function#apply`, this function invokes `func` * with the `this` binding of `thisArg` and the arguments of `args`. * * @private * @param {Function} func The function to invoke. * @param {*} thisArg The `this` binding of `func`. * @param {Array} args The arguments to invoke `func` with. * @returns {*} Returns the result of `func`. */ function apply(func, thisArg, args) { switch (args.length) { case 0: return func.call(thisArg); case 1: return func.call(thisArg, args[0]); case 2: return func.call(thisArg, args[0], args[1]); case 3: return func.call(thisArg, args[0], args[1], args[2]); } return func.apply(thisArg, args); } module.exports = apply; /***/ }, /* 36 */ /***/ function(module, exports, __webpack_require__) { var composeArgs = __webpack_require__(37), composeArgsRight = __webpack_require__(38), countHolders = __webpack_require__(39), createCtor = __webpack_require__(32), createRecurry = __webpack_require__(40), getHolder = __webpack_require__(70), reorder = __webpack_require__(71), replaceHolders = __webpack_require__(73), root = __webpack_require__(22); /** Used to compose bitmasks for function metadata. */ var WRAP_BIND_FLAG = 1, WRAP_BIND_KEY_FLAG = 2, WRAP_CURRY_FLAG = 8, WRAP_CURRY_RIGHT_FLAG = 16, WRAP_ARY_FLAG = 128, WRAP_FLIP_FLAG = 512; /** * Creates a function that wraps `func` to invoke it with optional `this` * binding of `thisArg`, partial application, and currying. * * @private * @param {Function|string} func The function or method name to wrap. * @param {number} bitmask The bitmask flags. See `createWrap` for more details. * @param {*} [thisArg] The `this` binding of `func`. * @param {Array} [partials] The arguments to prepend to those provided to * the new function. * @param {Array} [holders] The `partials` placeholder indexes. * @param {Array} [partialsRight] The arguments to append to those provided * to the new function. * @param {Array} [holdersRight] The `partialsRight` placeholder indexes. * @param {Array} [argPos] The argument positions of the new function. * @param {number} [ary] The arity cap of `func`. * @param {number} [arity] The arity of `func`. * @returns {Function} Returns the new wrapped function. */ function createHybrid(func, bitmask, thisArg, partials, holders, partialsRight, holdersRight, argPos, ary, arity) { var isAry = bitmask & WRAP_ARY_FLAG, isBind = bitmask & WRAP_BIND_FLAG, isBindKey = bitmask & WRAP_BIND_KEY_FLAG, isCurried = bitmask & (WRAP_CURRY_FLAG | WRAP_CURRY_RIGHT_FLAG), isFlip = bitmask & WRAP_FLIP_FLAG, Ctor = isBindKey ? undefined : createCtor(func); function wrapper() { var length = arguments.length, args = Array(length), index = length; while (index--) { args[index] = arguments[index]; } if (isCurried) { var placeholder = getHolder(wrapper), holdersCount = countHolders(args, placeholder); } if (partials) { args = composeArgs(args, partials, holders, isCurried); } if (partialsRight) { args = composeArgsRight(args, partialsRight, holdersRight, isCurried); } length -= holdersCount; if (isCurried && length < arity) { var newHolders = replaceHolders(args, placeholder); return createRecurry( func, bitmask, createHybrid, wrapper.placeholder, thisArg, args, newHolders, argPos, ary, arity - length ); } var thisBinding = isBind ? thisArg : this, fn = isBindKey ? thisBinding[func] : func; length = args.length; if (argPos) { args = reorder(args, argPos); } else if (isFlip && length > 1) { args.reverse(); } if (isAry && ary < length) { args.length = ary; } if (this && this !== root && this instanceof wrapper) { fn = Ctor || createCtor(fn); } return fn.apply(thisBinding, args); } return wrapper; } module.exports = createHybrid; /***/ }, /* 37 */ /***/ function(module, exports) { /* Built-in method references for those with the same name as other `lodash` methods. */ var nativeMax = Math.max; /** * Creates an array that is the composition of partially applied arguments, * placeholders, and provided arguments into a single array of arguments. * * @private * @param {Array} args The provided arguments. * @param {Array} partials The arguments to prepend to those provided. * @param {Array} holders The `partials` placeholder indexes. * @params {boolean} [isCurried] Specify composing for a curried function. * @returns {Array} Returns the new array of composed arguments. */ function composeArgs(args, partials, holders, isCurried) { var argsIndex = -1, argsLength = args.length, holdersLength = holders.length, leftIndex = -1, leftLength = partials.length, rangeLength = nativeMax(argsLength - holdersLength, 0), result = Array(leftLength + rangeLength), isUncurried = !isCurried; while (++leftIndex < leftLength) { result[leftIndex] = partials[leftIndex]; } while (++argsIndex < holdersLength) { if (isUncurried || argsIndex < argsLength) { result[holders[argsIndex]] = args[argsIndex]; } } while (rangeLength--) { result[leftIndex++] = args[argsIndex++]; } return result; } module.exports = composeArgs; /***/ }, /* 38 */ /***/ function(module, exports) { /* Built-in method references for those with the same name as other `lodash` methods. */ var nativeMax = Math.max; /** * This function is like `composeArgs` except that the arguments composition * is tailored for `_.partialRight`. * * @private * @param {Array} args The provided arguments. * @param {Array} partials The arguments to append to those provided. * @param {Array} holders The `partials` placeholder indexes. * @params {boolean} [isCurried] Specify composing for a curried function. * @returns {Array} Returns the new array of composed arguments. */ function composeArgsRight(args, partials, holders, isCurried) { var argsIndex = -1, argsLength = args.length, holdersIndex = -1, holdersLength = holders.length, rightIndex = -1, rightLength = partials.length, rangeLength = nativeMax(argsLength - holdersLength, 0), result = Array(rangeLength + rightLength), isUncurried = !isCurried; while (++argsIndex < rangeLength) { result[argsIndex] = args[argsIndex]; } var offset = argsIndex; while (++rightIndex < rightLength) { result[offset + rightIndex] = partials[rightIndex]; } while (++holdersIndex < holdersLength) { if (isUncurried || argsIndex < argsLength) { result[offset + holders[holdersIndex]] = args[argsIndex++]; } } return result; } module.exports = composeArgsRight; /***/ }, /* 39 */ /***/ function(module, exports) { /** * Gets the number of `placeholder` occurrences in `array`. * * @private * @param {Array} array The array to inspect. * @param {*} placeholder The placeholder to search for. * @returns {number} Returns the placeholder count. */ function countHolders(array, placeholder) { var length = array.length, result = 0; while (length--) { if (array[length] === placeholder) { ++result; } } return result; } module.exports = countHolders; /***/ }, /* 40 */ /***/ function(module, exports, __webpack_require__) { var isLaziable = __webpack_require__(41), setData = __webpack_require__(54), setWrapToString = __webpack_require__(56); /** Used to compose bitmasks for function metadata. */ var WRAP_BIND_FLAG = 1, WRAP_BIND_KEY_FLAG = 2, WRAP_CURRY_BOUND_FLAG = 4, WRAP_CURRY_FLAG = 8, WRAP_PARTIAL_FLAG = 32, WRAP_PARTIAL_RIGHT_FLAG = 64; /** * Creates a function that wraps `func` to continue currying. * * @private * @param {Function} func The function to wrap. * @param {number} bitmask The bitmask flags. See `createWrap` for more details. * @param {Function} wrapFunc The function to create the `func` wrapper. * @param {*} placeholder The placeholder value. * @param {*} [thisArg] The `this` binding of `func`. * @param {Array} [partials] The arguments to prepend to those provided to * the new function. * @param {Array} [holders] The `partials` placeholder indexes. * @param {Array} [argPos] The argument positions of the new function. * @param {number} [ary] The arity cap of `func`. * @param {number} [arity] The arity of `func`. * @returns {Function} Returns the new wrapped function. */ function createRecurry(func, bitmask, wrapFunc, placeholder, thisArg, partials, holders, argPos, ary, arity) { var isCurry = bitmask & WRAP_CURRY_FLAG, newHolders = isCurry ? holders : undefined, newHoldersRight = isCurry ? undefined : holders, newPartials = isCurry ? partials : undefined, newPartialsRight = isCurry ? undefined : partials; bitmask |= (isCurry ? WRAP_PARTIAL_FLAG : WRAP_PARTIAL_RIGHT_FLAG); bitmask &= ~(isCurry ? WRAP_PARTIAL_RIGHT_FLAG : WRAP_PARTIAL_FLAG); if (!(bitmask & WRAP_CURRY_BOUND_FLAG)) { bitmask &= ~(WRAP_BIND_FLAG | WRAP_BIND_KEY_FLAG); } var newData = [ func, bitmask, thisArg, newPartials, newHolders, newPartialsRight, newHoldersRight, argPos, ary, arity ]; var result = wrapFunc.apply(undefined, newData); if (isLaziable(func)) { setData(result, newData); } result.placeholder = placeholder; return setWrapToString(result, func, bitmask); } module.exports = createRecurry; /***/ }, /* 41 */ /***/ function(module, exports, __webpack_require__) { var LazyWrapper = __webpack_require__(42), getData = __webpack_require__(44), getFuncName = __webpack_require__(46), lodash = __webpack_require__(48); /** * Checks if `func` has a lazy counterpart. * * @private * @param {Function} func The function to check. * @returns {boolean} Returns `true` if `func` has a lazy counterpart, * else `false`. */ function isLaziable(func) { var funcName = getFuncName(func), other = lodash[funcName]; if (typeof other != 'function' || !(funcName in LazyWrapper.prototype)) { return false; } if (func === other) { return true; } var data = getData(other); return !!data && func === data[0]; } module.exports = isLaziable; /***/ }, /* 42 */ /***/ function(module, exports, __webpack_require__) { var baseCreate = __webpack_require__(33), baseLodash = __webpack_require__(43); /** Used as references for the maximum length and index of an array. */ var MAX_ARRAY_LENGTH = 4294967295; /** * Creates a lazy wrapper object which wraps `value` to enable lazy evaluation. * * @private * @constructor * @param {*} value The value to wrap. */ function LazyWrapper(value) { this.__wrapped__ = value; this.__actions__ = []; this.__dir__ = 1; this.__filtered__ = false; this.__iteratees__ = []; this.__takeCount__ = MAX_ARRAY_LENGTH; this.__views__ = []; } // Ensure `LazyWrapper` is an instance of `baseLodash`. LazyWrapper.prototype = baseCreate(baseLodash.prototype); LazyWrapper.prototype.constructor = LazyWrapper; module.exports = LazyWrapper; /***/ }, /* 43 */ /***/ function(module, exports) { /** * The function whose prototype chain sequence wrappers inherit from. * * @private */ function baseLodash() { // No operation performed. } module.exports = baseLodash; /***/ }, /* 44 */ /***/ function(module, exports, __webpack_require__) { var metaMap = __webpack_require__(15), noop = __webpack_require__(45); /** * Gets metadata for `func`. * * @private * @param {Function} func The function to query. * @returns {*} Returns the metadata for `func`. */ var getData = !metaMap ? noop : function(func) { return metaMap.get(func); }; module.exports = getData; /***/ }, /* 45 */ /***/ function(module, exports) { /** * This method returns `undefined`. * * @static * @memberOf _ * @since 2.3.0 * @category Util * @example * * _.times(2, _.noop); * // => [undefined, undefined] */ function noop() { // No operation performed. } module.exports = noop; /***/ }, /* 46 */ /***/ function(module, exports, __webpack_require__) { var realNames = __webpack_require__(47); /** Used for built-in method references. */ var objectProto = Object.prototype; /** Used to check objects for own properties. */ var hasOwnProperty = objectProto.hasOwnProperty; /** * Gets the name of `func`. * * @private * @param {Function} func The function to query. * @returns {string} Returns the function name. */ function getFuncName(func) { var result = (func.name + ''), array = realNames[result], length = hasOwnProperty.call(realNames, result) ? array.length : 0; while (length--) { var data = array[length], otherFunc = data.func; if (otherFunc == null || otherFunc == func) { return data.name; } } return result; } module.exports = getFuncName; /***/ }, /* 47 */ /***/ function(module, exports) { /** Used to lookup unminified function names. */ var realNames = {}; module.exports = realNames; /***/ }, /* 48 */ /***/ function(module, exports, __webpack_require__) { var LazyWrapper = __webpack_require__(42), LodashWrapper = __webpack_require__(49), baseLodash = __webpack_require__(43), isArray = __webpack_require__(50), isObjectLike = __webpack_require__(51), wrapperClone = __webpack_require__(52); /** Used for built-in method references. */ var objectProto = Object.prototype; /** Used to check objects for own properties. */ var hasOwnProperty = objectProto.hasOwnProperty; /** * Creates a `lodash` object which wraps `value` to enable implicit method * chain sequences. Methods that operate on and return arrays, collections, * and functions can be chained together. Methods that retrieve a single value * or may return a primitive value will automatically end the chain sequence * and return the unwrapped value. Otherwise, the value must be unwrapped * with `_#value`. * * Explicit chain sequences, which must be unwrapped with `_#value`, may be * enabled using `_.chain`. * * The execution of chained methods is lazy, that is, it's deferred until * `_#value` is implicitly or explicitly called. * * Lazy evaluation allows several methods to support shortcut fusion. * Shortcut fusion is an optimization to merge iteratee calls; this avoids * the creation of intermediate arrays and can greatly reduce the number of * iteratee executions. Sections of a chain sequence qualify for shortcut * fusion if the section is applied to an array and iteratees accept only * one argument. The heuristic for whether a section qualifies for shortcut * fusion is subject to change. * * Chaining is supported in custom builds as long as the `_#value` method is * directly or indirectly included in the build. * * In addition to lodash methods, wrappers have `Array` and `String` methods. * * The wrapper `Array` methods are: * `concat`, `join`, `pop`, `push`, `shift`, `sort`, `splice`, and `unshift` * * The wrapper `String` methods are: * `replace` and `split` * * The wrapper methods that support shortcut fusion are: * `at`, `compact`, `drop`, `dropRight`, `dropWhile`, `filter`, `find`, * `findLast`, `head`, `initial`, `last`, `map`, `reject`, `reverse`, `slice`, * `tail`, `take`, `takeRight`, `takeRightWhile`, `takeWhile`, and `toArray` * * The chainable wrapper methods are: * `after`, `ary`, `assign`, `assignIn`, `assignInWith`, `assignWith`, `at`, * `before`, `bind`, `bindAll`, `bindKey`, `castArray`, `chain`, `chunk`, * `commit`, `compact`, `concat`, `conforms`, `constant`, `countBy`, `create`, * `curry`, `debounce`, `defaults`, `defaultsDeep`, `defer`, `delay`, * `difference`, `differenceBy`, `differenceWith`, `drop`, `dropRight`, * `dropRightWhile`, `dropWhile`, `extend`, `extendWith`, `fill`, `filter`, * `flatMap`, `flatMapDeep`, `flatMapDepth`, `flatten`, `flattenDeep`, * `flattenDepth`, `flip`, `flow`, `flowRight`, `fromPairs`, `functions`, * `functionsIn`, `groupBy`, `initial`, `intersection`, `intersectionBy`, * `intersectionWith`, `invert`, `invertBy`, `invokeMap`, `iteratee`, `keyBy`, * `keys`, `keysIn`, `map`, `mapKeys`, `mapValues`, `matches`, `matchesProperty`, * `memoize`, `merge`, `mergeWith`, `method`, `methodOf`, `mixin`, `negate`, * `nthArg`, `omit`, `omitBy`, `once`, `orderBy`, `over`, `overArgs`, * `overEvery`, `overSome`, `partial`, `partialRight`, `partition`, `pick`, * `pickBy`, `plant`, `property`, `propertyOf`, `pull`, `pullAll`, `pullAllBy`, * `pullAllWith`, `pullAt`, `push`, `range`, `rangeRight`, `rearg`, `reject`, * `remove`, `rest`, `reverse`, `sampleSize`, `set`, `setWith`, `shuffle`, * `slice`, `sort`, `sortBy`, `splice`, `spread`, `tail`, `take`, `takeRight`, * `takeRightWhile`, `takeWhile`, `tap`, `throttle`, `thru`, `toArray`, * `toPairs`, `toPairsIn`, `toPath`, `toPlainObject`, `transform`, `unary`, * `union`, `unionBy`, `unionWith`, `uniq`, `uniqBy`, `uniqWith`, `unset`, * `unshift`, `unzip`, `unzipWith`, `update`, `updateWith`, `values`, * `valuesIn`, `without`, `wrap`, `xor`, `xorBy`, `xorWith`, `zip`, * `zipObject`, `zipObjectDeep`, and `zipWith` * * The wrapper methods that are **not** chainable by default are: * `add`, `attempt`, `camelCase`, `capitalize`, `ceil`, `clamp`, `clone`, * `cloneDeep`, `cloneDeepWith`, `cloneWith`, `conformsTo`, `deburr`, * `defaultTo`, `divide`, `each`, `eachRight`, `endsWith`, `eq`, `escape`, * `escapeRegExp`, `every`, `find`, `findIndex`, `findKey`, `findLast`, * `findLastIndex`, `findLastKey`, `first`, `floor`, `forEach`, `forEachRight`, * `forIn`, `forInRight`, `forOwn`, `forOwnRight`, `get`, `gt`, `gte`, `has`, * `hasIn`, `head`, `identity`, `includes`, `indexOf`, `inRange`, `invoke`, * `isArguments`, `isArray`, `isArrayBuffer`, `isArrayLike`, `isArrayLikeObject`, * `isBoolean`, `isBuffer`, `isDate`, `isElement`, `isEmpty`, `isEqual`, * `isEqualWith`, `isError`, `isFinite`, `isFunction`, `isInteger`, `isLength`, * `isMap`, `isMatch`, `isMatchWith`, `isNaN`, `isNative`, `isNil`, `isNull`, * `isNumber`, `isObject`, `isObjectLike`, `isPlainObject`, `isRegExp`, * `isSafeInteger`, `isSet`, `isString`, `isUndefined`, `isTypedArray`, * `isWeakMap`, `isWeakSet`, `join`, `kebabCase`, `last`, `lastIndexOf`, * `lowerCase`, `lowerFirst`, `lt`, `lte`, `max`, `maxBy`, `mean`, `meanBy`, * `min`, `minBy`, `multiply`, `noConflict`, `noop`, `now`, `nth`, `pad`, * `padEnd`, `padStart`, `parseInt`, `pop`, `random`, `reduce`, `reduceRight`, * `repeat`, `result`, `round`, `runInContext`, `sample`, `shift`, `size`, * `snakeCase`, `some`, `sortedIndex`, `sortedIndexBy`, `sortedLastIndex`, * `sortedLastIndexBy`, `startCase`, `startsWith`, `stubArray`, `stubFalse`, * `stubObject`, `stubString`, `stubTrue`, `subtract`, `sum`, `sumBy`, * `template`, `times`, `toFinite`, `toInteger`, `toJSON`, `toLength`, * `toLower`, `toNumber`, `toSafeInteger`, `toString`, `toUpper`, `trim`, * `trimEnd`, `trimStart`, `truncate`, `unescape`, `uniqueId`, `upperCase`, * `upperFirst`, `value`, and `words` * * @name _ * @constructor * @category Seq * @param {*} value The value to wrap in a `lodash` instance. * @returns {Object} Returns the new `lodash` wrapper instance. * @example * * function square(n) { * return n * n; * } * * var wrapped = _([1, 2, 3]); * * // Returns an unwrapped value. * wrapped.reduce(_.add); * // => 6 * * // Returns a wrapped value. * var squares = wrapped.map(square); * * _.isArray(squares); * // => false * * _.isArray(squares.value()); * // => true */ function lodash(value) { if (isObjectLike(value) && !isArray(value) && !(value instanceof LazyWrapper)) { if (value instanceof LodashWrapper) { return value; } if (hasOwnProperty.call(value, '__wrapped__')) { return wrapperClone(value); } } return new LodashWrapper(value); } // Ensure wrappers are instances of `baseLodash`. lodash.prototype = baseLodash.prototype; lodash.prototype.constructor = lodash; module.exports = lodash; /***/ }, /* 49 */ /***/ function(module, exports, __webpack_require__) { var baseCreate = __webpack_require__(33), baseLodash = __webpack_require__(43); /** * The base constructor for creating `lodash` wrapper objects. * * @private * @param {*} value The value to wrap. * @param {boolean} [chainAll] Enable explicit method chain sequences. */ function LodashWrapper(value, chainAll) { this.__wrapped__ = value; this.__actions__ = []; this.__chain__ = !!chainAll; this.__index__ = 0; this.__values__ = undefined; } LodashWrapper.prototype = baseCreate(baseLodash.prototype); LodashWrapper.prototype.constructor = LodashWrapper; module.exports = LodashWrapper; /***/ }, /* 50 */ /***/ function(module, exports) { /** * Checks if `value` is classified as an `Array` object. * * @static * @memberOf _ * @since 0.1.0 * @category Lang * @param {*} value The value to check. * @returns {boolean} Returns `true` if `value` is an array, else `false`. * @example * * _.isArray([1, 2, 3]); * // => true * * _.isArray(document.body.children); * // => false * * _.isArray('abc'); * // => false * * _.isArray(_.noop); * // => false */ var isArray = Array.isArray; module.exports = isArray; /***/ }, /* 51 */ /***/ function(module, exports) { /** * Checks if `value` is object-like. A value is object-like if it's not `null` * and has a `typeof` result of "object". * * @static * @memberOf _ * @since 4.0.0 * @category Lang * @param {*} value The value to check. * @returns {boolean} Returns `true` if `value` is object-like, else `false`. * @example * * _.isObjectLike({}); * // => true * * _.isObjectLike([1, 2, 3]); * // => true * * _.isObjectLike(_.noop); * // => false * * _.isObjectLike(null); * // => false */ function isObjectLike(value) { return value != null && typeof value == 'object'; } module.exports = isObjectLike; /***/ }, /* 52 */ /***/ function(module, exports, __webpack_require__) { var LazyWrapper = __webpack_require__(42), LodashWrapper = __webpack_require__(49), copyArray = __webpack_require__(53); /** * Creates a clone of `wrapper`. * * @private * @param {Object} wrapper The wrapper to clone. * @returns {Object} Returns the cloned wrapper. */ function wrapperClone(wrapper) { if (wrapper instanceof LazyWrapper) { return wrapper.clone(); } var result = new LodashWrapper(wrapper.__wrapped__, wrapper.__chain__); result.__actions__ = copyArray(wrapper.__actions__); result.__index__ = wrapper.__index__; result.__values__ = wrapper.__values__; return result; } module.exports = wrapperClone; /***/ }, /* 53 */ /***/ function(module, exports) { /** * Copies the values of `source` to `array`. * * @private * @param {Array} source The array to copy values from. * @param {Array} [array=[]] The array to copy values to. * @returns {Array} Returns `array`. */ function copyArray(source, array) { var index = -1, length = source.length; array || (array = Array(length)); while (++index < length) { array[index] = source[index]; } return array; } module.exports = copyArray; /***/ }, /* 54 */ /***/ function(module, exports, __webpack_require__) { var baseSetData = __webpack_require__(13), shortOut = __webpack_require__(55); /** * Sets metadata for `func`. * * **Note:** If this function becomes hot, i.e. is invoked a lot in a short * period of time, it will trip its breaker and transition to an identity * function to avoid garbage collection pauses in V8. See * [V8 issue 2070](https://bugs.chromium.org/p/v8/issues/detail?id=2070) * for more details. * * @private * @param {Function} func The function to associate metadata with. * @param {*} data The metadata. * @returns {Function} Returns `func`. */ var setData = shortOut(baseSetData); module.exports = setData; /***/ }, /* 55 */ /***/ function(module, exports) { /** Used to detect hot functions by number of calls within a span of milliseconds. */ var HOT_COUNT = 800, HOT_SPAN = 16; /* Built-in method references for those with the same name as other `lodash` methods. */ var nativeNow = Date.now; /** * Creates a function that'll short out and invoke `identity` instead * of `func` when it's called `HOT_COUNT` or more times in `HOT_SPAN` * milliseconds. * * @private * @param {Function} func The function to restrict. * @returns {Function} Returns the new shortable function. */ function shortOut(func) { var count = 0, lastCalled = 0; return function() { var stamp = nativeNow(), remaining = HOT_SPAN - (stamp - lastCalled); lastCalled = stamp; if (remaining > 0) { if (++count >= HOT_COUNT) { return arguments[0]; } } else { count = 0; } return func.apply(undefined, arguments); }; } module.exports = shortOut; /***/ }, /* 56 */ /***/ function(module, exports, __webpack_require__) { var getWrapDetails = __webpack_require__(57), insertWrapDetails = __webpack_require__(58), setToString = __webpack_require__(59), updateWrapDetails = __webpack_require__(63); /** * Sets the `toString` method of `wrapper` to mimic the source of `reference` * with wrapper details in a comment at the top of the source body. * * @private * @param {Function} wrapper The function to modify. * @param {Function} reference The reference function. * @param {number} bitmask The bitmask flags. See `createWrap` for more details. * @returns {Function} Returns `wrapper`. */ function setWrapToString(wrapper, reference, bitmask) { var source = (reference + ''); return setToString(wrapper, insertWrapDetails(source, updateWrapDetails(getWrapDetails(source), bitmask))); } module.exports = setWrapToString; /***/ }, /* 57 */ /***/ function(module, exports) { /** Used to match wrap detail comments. */ var reWrapDetails = /\{\n\/\* \[wrapped with (.+)\] \*/, reSplitDetails = /,? & /; /** * Extracts wrapper details from the `source` body comment. * * @private * @param {string} source The source to inspect. * @returns {Array} Returns the wrapper details. */ function getWrapDetails(source) { var match = source.match(reWrapDetails); return match ? match[1].split(reSplitDetails) : []; } module.exports = getWrapDetails; /***/ }, /* 58 */ /***/ function(module, exports) { /** Used to match wrap detail comments. */ var reWrapComment = /\{(?:\n\/\* \[wrapped with .+\] \*\/)?\n?/; /** * Inserts wrapper `details` in a comment at the top of the `source` body. * * @private * @param {string} source The source to modify. * @returns {Array} details The details to insert. * @returns {string} Returns the modified source. */ function insertWrapDetails(source, details) { var length = details.length; if (!length) { return source; } var lastIndex = length - 1; details[lastIndex] = (length > 1 ? '& ' : '') + details[lastIndex]; details = details.join(length > 2 ? ', ' : ' '); return source.replace(reWrapComment, '{\n/* [wrapped with ' + details + '] */\n'); } module.exports = insertWrapDetails; /***/ }, /* 59 */ /***/ function(module, exports, __webpack_require__) { var baseSetToString = __webpack_require__(60), shortOut = __webpack_require__(55); /** * Sets the `toString` method of `func` to return `string`. * * @private * @param {Function} func The function to modify. * @param {Function} string The `toString` result. * @returns {Function} Returns `func`. */ var setToString = shortOut(baseSetToString); module.exports = setToString; /***/ }, /* 60 */ /***/ function(module, exports, __webpack_require__) { var constant = __webpack_require__(61), defineProperty = __webpack_require__(62), identity = __webpack_require__(14); /** * The base implementation of `setToString` without support for hot loop shorting. * * @private * @param {Function} func The function to modify. * @param {Function} string The `toString` result. * @returns {Function} Returns `func`. */ var baseSetToString = !defineProperty ? identity : function(func, string) { return defineProperty(func, 'toString', { 'configurable': true, 'enumerable': false, 'value': constant(string), 'writable': true }); }; module.exports = baseSetToString; /***/ }, /* 61 */ /***/ function(module, exports) { /** * Creates a function that returns `value`. * * @static * @memberOf _ * @since 2.4.0 * @category Util * @param {*} value The value to return from the new function. * @returns {Function} Returns the new constant function. * @example * * var objects = _.times(2, _.constant({ 'a': 1 })); * * console.log(objects); * // => [{ 'a': 1 }, { 'a': 1 }] * * console.log(objects[0] === objects[1]); * // => true */ function constant(value) { return function() { return value; }; } module.exports = constant; /***/ }, /* 62 */ /***/ function(module, exports, __webpack_require__) { var getNative = __webpack_require__(17); var defineProperty = (function() { try { var func = getNative(Object, 'defineProperty'); func({}, '', {}); return func; } catch (e) {} }()); module.exports = defineProperty; /***/ }, /* 63 */ /***/ function(module, exports, __webpack_require__) { var arrayEach = __webpack_require__(64), arrayIncludes = __webpack_require__(65); /** Used to compose bitmasks for function metadata. */ var WRAP_BIND_FLAG = 1, WRAP_BIND_KEY_FLAG = 2, WRAP_CURRY_FLAG = 8, WRAP_CURRY_RIGHT_FLAG = 16, WRAP_PARTIAL_FLAG = 32, WRAP_PARTIAL_RIGHT_FLAG = 64, WRAP_ARY_FLAG = 128, WRAP_REARG_FLAG = 256, WRAP_FLIP_FLAG = 512; /** Used to associate wrap methods with their bit flags. */ var wrapFlags = [ ['ary', WRAP_ARY_FLAG], ['bind', WRAP_BIND_FLAG], ['bindKey', WRAP_BIND_KEY_FLAG], ['curry', WRAP_CURRY_FLAG], ['curryRight', WRAP_CURRY_RIGHT_FLAG], ['flip', WRAP_FLIP_FLAG], ['partial', WRAP_PARTIAL_FLAG], ['partialRight', WRAP_PARTIAL_RIGHT_FLAG], ['rearg', WRAP_REARG_FLAG] ]; /** * Updates wrapper `details` based on `bitmask` flags. * * @private * @returns {Array} details The details to modify. * @param {number} bitmask The bitmask flags. See `createWrap` for more details. * @returns {Array} Returns `details`. */ function updateWrapDetails(details, bitmask) { arrayEach(wrapFlags, function(pair) { var value = '_.' + pair[0]; if ((bitmask & pair[1]) && !arrayIncludes(details, value)) { details.push(value); } }); return details.sort(); } module.exports = updateWrapDetails; /***/ }, /* 64 */ /***/ function(module, exports) { /** * A specialized version of `_.forEach` for arrays without support for * iteratee shorthands. * * @private * @param {Array} [array] The array to iterate over. * @param {Function} iteratee The function invoked per iteration. * @returns {Array} Returns `array`. */ function arrayEach(array, iteratee) { var index = -1, length = array == null ? 0 : array.length; while (++index < length) { if (iteratee(array[index], index, array) === false) { break; } } return array; } module.exports = arrayEach; /***/ }, /* 65 */ /***/ function(module, exports, __webpack_require__) { var baseIndexOf = __webpack_require__(66); /** * A specialized version of `_.includes` for arrays without support for * specifying an index to search from. * * @private * @param {Array} [array] The array to inspect. * @param {*} target The value to search for. * @returns {boolean} Returns `true` if `target` is found, else `false`. */ function arrayIncludes(array, value) { var length = array == null ? 0 : array.length; return !!length && baseIndexOf(array, value, 0) > -1; } module.exports = arrayIncludes; /***/ }, /* 66 */ /***/ function(module, exports, __webpack_require__) { var baseFindIndex = __webpack_require__(67), baseIsNaN = __webpack_require__(68), strictIndexOf = __webpack_require__(69); /** * The base implementation of `_.indexOf` without `fromIndex` bounds checks. * * @private * @param {Array} array The array to inspect. * @param {*} value The value to search for. * @param {number} fromIndex The index to search from. * @returns {number} Returns the index of the matched value, else `-1`. */ function baseIndexOf(array, value, fromIndex) { return value === value ? strictIndexOf(array, value, fromIndex) : baseFindIndex(array, baseIsNaN, fromIndex); } module.exports = baseIndexOf; /***/ }, /* 67 */ /***/ function(module, exports) { /** * The base implementation of `_.findIndex` and `_.findLastIndex` without * support for iteratee shorthands. * * @private * @param {Array} array The array to inspect. * @param {Function} predicate The function invoked per iteration. * @param {number} fromIndex The index to search from. * @param {boolean} [fromRight] Specify iterating from right to left. * @returns {number} Returns the index of the matched value, else `-1`. */ function baseFindIndex(array, predicate, fromIndex, fromRight) { var length = array.length, index = fromIndex + (fromRight ? 1 : -1); while ((fromRight ? index-- : ++index < length)) { if (predicate(array[index], index, array)) { return index; } } return -1; } module.exports = baseFindIndex; /***/ }, /* 68 */ /***/ function(module, exports) { /** * The base implementation of `_.isNaN` without support for number objects. * * @private * @param {*} value The value to check. * @returns {boolean} Returns `true` if `value` is `NaN`, else `false`. */ function baseIsNaN(value) { return value !== value; } module.exports = baseIsNaN; /***/ }, /* 69 */ /***/ function(module, exports) { /** * A specialized version of `_.indexOf` which performs strict equality * comparisons of values, i.e. `===`. * * @private * @param {Array} array The array to inspect. * @param {*} value The value to search for. * @param {number} fromIndex The index to search from. * @returns {number} Returns the index of the matched value, else `-1`. */ function strictIndexOf(array, value, fromIndex) { var index = fromIndex - 1, length = array.length; while (++index < length) { if (array[index] === value) { return index; } } return -1; } module.exports = strictIndexOf; /***/ }, /* 70 */ /***/ function(module, exports) { /** * Gets the argument placeholder value for `func`. * * @private * @param {Function} func The function to inspect. * @returns {*} Returns the placeholder value. */ function getHolder(func) { var object = func; return object.placeholder; } module.exports = getHolder; /***/ }, /* 71 */ /***/ function(module, exports, __webpack_require__) { var copyArray = __webpack_require__(53), isIndex = __webpack_require__(72); /* Built-in method references for those with the same name as other `lodash` methods. */ var nativeMin = Math.min; /** * Reorder `array` according to the specified indexes where the element at * the first index is assigned as the first element, the element at * the second index is assigned as the second element, and so on. * * @private * @param {Array} array The array to reorder. * @param {Array} indexes The arranged array indexes. * @returns {Array} Returns `array`. */ function reorder(array, indexes) { var arrLength = array.length, length = nativeMin(indexes.length, arrLength), oldArray = copyArray(array); while (length--) { var index = indexes[length]; array[length] = isIndex(index, arrLength) ? oldArray[index] : undefined; } return array; } module.exports = reorder; /***/ }, /* 72 */ /***/ function(module, exports) { /** Used as references for various `Number` constants. */ var MAX_SAFE_INTEGER = 9007199254740991; /** Used to detect unsigned integer values. */ var reIsUint = /^(?:0|[1-9]\d*)$/; /** * Checks if `value` is a valid array-like index. * * @private * @param {*} value The value to check. * @param {number} [length=MAX_SAFE_INTEGER] The upper bounds of a valid index. * @returns {boolean} Returns `true` if `value` is a valid index, else `false`. */ function isIndex(value, length) { length = length == null ? MAX_SAFE_INTEGER : length; return !!length && (typeof value == 'number' || reIsUint.test(value)) && (value > -1 && value % 1 == 0 && value < length); } module.exports = isIndex; /***/ }, /* 73 */ /***/ function(module, exports) { /** Used as the internal argument placeholder. */ var PLACEHOLDER = '__lodash_placeholder__'; /** * Replaces all `placeholder` elements in `array` with an internal placeholder * and returns an array of their indexes. * * @private * @param {Array} array The array to modify. * @param {*} placeholder The placeholder to replace. * @returns {Array} Returns the new array of placeholder indexes. */ function replaceHolders(array, placeholder) { var index = -1, length = array.length, resIndex = 0, result = []; while (++index < length) { var value = array[index]; if (value === placeholder || value === PLACEHOLDER) { array[index] = PLACEHOLDER; result[resIndex++] = index; } } return result; } module.exports = replaceHolders; /***/ }, /* 74 */ /***/ function(module, exports, __webpack_require__) { var apply = __webpack_require__(35), createCtor = __webpack_require__(32), root = __webpack_require__(22); /** Used to compose bitmasks for function metadata. */ var WRAP_BIND_FLAG = 1; /** * Creates a function that wraps `func` to invoke it with the `this` binding * of `thisArg` and `partials` prepended to the arguments it receives. * * @private * @param {Function} func The function to wrap. * @param {number} bitmask The bitmask flags. See `createWrap` for more details. * @param {*} thisArg The `this` binding of `func`. * @param {Array} partials The arguments to prepend to those provided to * the new function. * @returns {Function} Returns the new wrapped function. */ function createPartial(func, bitmask, thisArg, partials) { var isBind = bitmask & WRAP_BIND_FLAG, Ctor = createCtor(func); function wrapper() { var argsIndex = -1, argsLength = arguments.length, leftIndex = -1, leftLength = partials.length, args = Array(leftLength + argsLength), fn = (this && this !== root && this instanceof wrapper) ? Ctor : func; while (++leftIndex < leftLength) { args[leftIndex] = partials[leftIndex]; } while (argsLength--) { args[leftIndex++] = arguments[++argsIndex]; } return apply(fn, isBind ? thisArg : this, args); } return wrapper; } module.exports = createPartial; /***/ }, /* 75 */ /***/ function(module, exports, __webpack_require__) { var composeArgs = __webpack_require__(37), composeArgsRight = __webpack_require__(38), replaceHolders = __webpack_require__(73); /** Used as the internal argument placeholder. */ var PLACEHOLDER = '__lodash_placeholder__'; /** Used to compose bitmasks for function metadata. */ var WRAP_BIND_FLAG = 1, WRAP_BIND_KEY_FLAG = 2, WRAP_CURRY_BOUND_FLAG = 4, WRAP_CURRY_FLAG = 8, WRAP_ARY_FLAG = 128, WRAP_REARG_FLAG = 256; /* Built-in method references for those with the same name as other `lodash` methods. */ var nativeMin = Math.min; /** * Merges the function metadata of `source` into `data`. * * Merging metadata reduces the number of wrappers used to invoke a function. * This is possible because methods like `_.bind`, `_.curry`, and `_.partial` * may be applied regardless of execution order. Methods like `_.ary` and * `_.rearg` modify function arguments, making the order in which they are * executed important, preventing the merging of metadata. However, we make * an exception for a safe combined case where curried functions have `_.ary` * and or `_.rearg` applied. * * @private * @param {Array} data The destination metadata. * @param {Array} source The source metadata. * @returns {Array} Returns `data`. */ function mergeData(data, source) { var bitmask = data[1], srcBitmask = source[1], newBitmask = bitmask | srcBitmask, isCommon = newBitmask < (WRAP_BIND_FLAG | WRAP_BIND_KEY_FLAG | WRAP_ARY_FLAG); var isCombo = ((srcBitmask == WRAP_ARY_FLAG) && (bitmask == WRAP_CURRY_FLAG)) || ((srcBitmask == WRAP_ARY_FLAG) && (bitmask == WRAP_REARG_FLAG) && (data[7].length <= source[8])) || ((srcBitmask == (WRAP_ARY_FLAG | WRAP_REARG_FLAG)) && (source[7].length <= source[8]) && (bitmask == WRAP_CURRY_FLAG)); // Exit early if metadata can't be merged. if (!(isCommon || isCombo)) { return data; } // Use source `thisArg` if available. if (srcBitmask & WRAP_BIND_FLAG) { data[2] = source[2]; // Set when currying a bound function. newBitmask |= bitmask & WRAP_BIND_FLAG ? 0 : WRAP_CURRY_BOUND_FLAG; } // Compose partial arguments. var value = source[3]; if (value) { var partials = data[3]; data[3] = partials ? composeArgs(partials, value, source[4]) : value; data[4] = partials ? replaceHolders(data[3], PLACEHOLDER) : source[4]; } // Compose partial right arguments. value = source[5]; if (value) { partials = data[5]; data[5] = partials ? composeArgsRight(partials, value, source[6]) : value; data[6] = partials ? replaceHolders(data[5], PLACEHOLDER) : source[6]; } // Use source `argPos` if available. value = source[7]; if (value) { data[7] = value; } // Use source `ary` if it's smaller. if (srcBitmask & WRAP_ARY_FLAG) { data[8] = data[8] == null ? source[8] : nativeMin(data[8], source[8]); } // Use source `arity` if one is not provided. if (data[9] == null) { data[9] = source[9]; } // Use source `func` and merge bitmasks. data[0] = source[0]; data[1] = newBitmask; return data; } module.exports = mergeData; /***/ }, /* 76 */ /***/ function(module, exports, __webpack_require__) { var toFinite = __webpack_require__(77); /** * Converts `value` to an integer. * * **Note:** This method is loosely based on * [`ToInteger`](http://www.ecma-international.org/ecma-262/7.0/#sec-tointeger). * * @static * @memberOf _ * @since 4.0.0 * @category Lang * @param {*} value The value to convert. * @returns {number} Returns the converted integer. * @example * * _.toInteger(3.2); * // => 3 * * _.toInteger(Number.MIN_VALUE); * // => 0 * * _.toInteger(Infinity); * // => 1.7976931348623157e+308 * * _.toInteger('3.2'); * // => 3 */ function toInteger(value) { var result = toFinite(value), remainder = result % 1; return result === result ? (remainder ? result - remainder : result) : 0; } module.exports = toInteger; /***/ }, /* 77 */ /***/ function(module, exports, __webpack_require__) { var toNumber = __webpack_require__(78); /** Used as references for various `Number` constants. */ var INFINITY = 1 / 0, MAX_INTEGER = 1.7976931348623157e+308; /** * Converts `value` to a finite number. * * @static * @memberOf _ * @since 4.12.0 * @category Lang * @param {*} value The value to convert. * @returns {number} Returns the converted number. * @example * * _.toFinite(3.2); * // => 3.2 * * _.toFinite(Number.MIN_VALUE); * // => 5e-324 * * _.toFinite(Infinity); * // => 1.7976931348623157e+308 * * _.toFinite('3.2'); * // => 3.2 */ function toFinite(value) { if (!value) { return value === 0 ? value : 0; } value = toNumber(value); if (value === INFINITY || value === -INFINITY) { var sign = (value < 0 ? -1 : 1); return sign * MAX_INTEGER; } return value === value ? value : 0; } module.exports = toFinite; /***/ }, /* 78 */ /***/ function(module, exports, __webpack_require__) { var isObject = __webpack_require__(26), isSymbol = __webpack_require__(79); /** Used as references for various `Number` constants. */ var NAN = 0 / 0; /** Used to match leading and trailing whitespace. */ var reTrim = /^\s+|\s+$/g; /** Used to detect bad signed hexadecimal string values. */ var reIsBadHex = /^[-+]0x[0-9a-f]+$/i; /** Used to detect binary string values. */ var reIsBinary = /^0b[01]+$/i; /** Used to detect octal string values. */ var reIsOctal = /^0o[0-7]+$/i; /** Built-in method references without a dependency on `root`. */ var freeParseInt = parseInt; /** * Converts `value` to a number. * * @static * @memberOf _ * @since 4.0.0 * @category Lang * @param {*} value The value to process. * @returns {number} Returns the number. * @example * * _.toNumber(3.2); * // => 3.2 * * _.toNumber(Number.MIN_VALUE); * // => 5e-324 * * _.toNumber(Infinity); * // => Infinity * * _.toNumber('3.2'); * // => 3.2 */ function toNumber(value) { if (typeof value == 'number') { return value; } if (isSymbol(value)) { return NAN; } if (isObject(value)) { var other = typeof value.valueOf == 'function' ? value.valueOf() : value; value = isObject(other) ? (other + '') : other; } if (typeof value != 'string') { return value === 0 ? value : +value; } value = value.replace(reTrim, ''); var isBinary = reIsBinary.test(value); return (isBinary || reIsOctal.test(value)) ? freeParseInt(value.slice(2), isBinary ? 2 : 8) : (reIsBadHex.test(value) ? NAN : +value); } module.exports = toNumber; /***/ }, /* 79 */ /***/ function(module, exports, __webpack_require__) { var baseGetTag = __webpack_require__(20), isObjectLike = __webpack_require__(51); /** `Object#toString` result references. */ var symbolTag = '[object Symbol]'; /** * Checks if `value` is classified as a `Symbol` primitive or object. * * @static * @memberOf _ * @since 4.0.0 * @category Lang * @param {*} value The value to check. * @returns {boolean} Returns `true` if `value` is a symbol, else `false`. * @example * * _.isSymbol(Symbol.iterator); * // => true * * _.isSymbol('abc'); * // => false */ function isSymbol(value) { return typeof value == 'symbol' || (isObjectLike(value) && baseGetTag(value) == symbolTag); } module.exports = isSymbol; /***/ }, /* 80 */ /***/ function(module, exports, __webpack_require__) { var copyObject = __webpack_require__(81), keys = __webpack_require__(85); /** * The base implementation of `_.assign` without support for multiple sources * or `customizer` functions. * * @private * @param {Object} object The destination object. * @param {Object} source The source object. * @returns {Object} Returns `object`. */ function baseAssign(object, source) { return object && copyObject(source, keys(source), object); } module.exports = baseAssign; /***/ }, /* 81 */ /***/ function(module, exports, __webpack_require__) { var assignValue = __webpack_require__(82), baseAssignValue = __webpack_require__(83); /** * Copies properties of `source` to `object`. * * @private * @param {Object} source The object to copy properties from. * @param {Array} props The property identifiers to copy. * @param {Object} [object={}] The object to copy properties to. * @param {Function} [customizer] The function to customize copied values. * @returns {Object} Returns `object`. */ function copyObject(source, props, object, customizer) { var isNew = !object; object || (object = {}); var index = -1, length = props.length; while (++index < length) { var key = props[index]; var newValue = customizer ? customizer(object[key], source[key], key, object, source) : undefined; if (newValue === undefined) { newValue = source[key]; } if (isNew) { baseAssignValue(object, key, newValue); } else { assignValue(object, key, newValue); } } return object; } module.exports = copyObject; /***/ }, /* 82 */ /***/ function(module, exports, __webpack_require__) { var baseAssignValue = __webpack_require__(83), eq = __webpack_require__(84); /** Used for built-in method references. */ var objectProto = Object.prototype; /** Used to check objects for own properties. */ var hasOwnProperty = objectProto.hasOwnProperty; /** * Assigns `value` to `key` of `object` if the existing value is not equivalent * using [`SameValueZero`](http://ecma-international.org/ecma-262/7.0/#sec-samevaluezero) * for equality comparisons. * * @private * @param {Object} object The object to modify. * @param {string} key The key of the property to assign. * @param {*} value The value to assign. */ function assignValue(object, key, value) { var objValue = object[key]; if (!(hasOwnProperty.call(object, key) && eq(objValue, value)) || (value === undefined && !(key in object))) { baseAssignValue(object, key, value); } } module.exports = assignValue; /***/ }, /* 83 */ /***/ function(module, exports, __webpack_require__) { var defineProperty = __webpack_require__(62); /** * The base implementation of `assignValue` and `assignMergeValue` without * value checks. * * @private * @param {Object} object The object to modify. * @param {string} key The key of the property to assign. * @param {*} value The value to assign. */ function baseAssignValue(object, key, value) { if (key == '__proto__' && defineProperty) { defineProperty(object, key, { 'configurable': true, 'enumerable': true, 'value': value, 'writable': true }); } else { object[key] = value; } } module.exports = baseAssignValue; /***/ }, /* 84 */ /***/ function(module, exports) { /** * Performs a * [`SameValueZero`](http://ecma-international.org/ecma-262/7.0/#sec-samevaluezero) * comparison between two values to determine if they are equivalent. * * @static * @memberOf _ * @since 4.0.0 * @category Lang * @param {*} value The value to compare. * @param {*} other The other value to compare. * @returns {boolean} Returns `true` if the values are equivalent, else `false`. * @example * * var object = { 'a': 1 }; * var other = { 'a': 1 }; * * _.eq(object, object); * // => true * * _.eq(object, other); * // => false * * _.eq('a', 'a'); * // => true * * _.eq('a', Object('a')); * // => false * * _.eq(NaN, NaN); * // => true */ function eq(value, other) { return value === other || (value !== value && other !== other); } module.exports = eq; /***/ }, /* 85 */ /***/ function(module, exports, __webpack_require__) { var arrayLikeKeys = __webpack_require__(86), baseKeys = __webpack_require__(98), isArrayLike = __webpack_require__(102); /** * Creates an array of the own enumerable property names of `object`. * * **Note:** Non-object values are coerced to objects. See the * [ES spec](http://ecma-international.org/ecma-262/7.0/#sec-object.keys) * for more details. * * @static * @since 0.1.0 * @memberOf _ * @category Object * @param {Object} object The object to query. * @returns {Array} Returns the array of property names. * @example * * function Foo() { * this.a = 1; * this.b = 2; * } * * Foo.prototype.c = 3; * * _.keys(new Foo); * // => ['a', 'b'] (iteration order is not guaranteed) * * _.keys('hi'); * // => ['0', '1'] */ function keys(object) { return isArrayLike(object) ? arrayLikeKeys(object) : baseKeys(object); } module.exports = keys; /***/ }, /* 86 */ /***/ function(module, exports, __webpack_require__) { var baseTimes = __webpack_require__(87), isArguments = __webpack_require__(88), isArray = __webpack_require__(50), isBuffer = __webpack_require__(90), isIndex = __webpack_require__(72), isTypedArray = __webpack_require__(93); /** Used for built-in method references. */ var objectProto = Object.prototype; /** Used to check objects for own properties. */ var hasOwnProperty = objectProto.hasOwnProperty; /** * Creates an array of the enumerable property names of the array-like `value`. * * @private * @param {*} value The value to query. * @param {boolean} inherited Specify returning inherited property names. * @returns {Array} Returns the array of property names. */ function arrayLikeKeys(value, inherited) { var isArr = isArray(value), isArg = !isArr && isArguments(value), isBuff = !isArr && !isArg && isBuffer(value), isType = !isArr && !isArg && !isBuff && isTypedArray(value), skipIndexes = isArr || isArg || isBuff || isType, result = skipIndexes ? baseTimes(value.length, String) : [], length = result.length; for (var key in value) { if ((inherited || hasOwnProperty.call(value, key)) && !(skipIndexes && ( // Safari 9 has enumerable `arguments.length` in strict mode. key == 'length' || // Node.js 0.10 has enumerable non-index properties on buffers. (isBuff && (key == 'offset' || key == 'parent')) || // PhantomJS 2 has enumerable non-index properties on typed arrays. (isType && (key == 'buffer' || key == 'byteLength' || key == 'byteOffset')) || // Skip index properties. isIndex(key, length) ))) { result.push(key); } } return result; } module.exports = arrayLikeKeys; /***/ }, /* 87 */ /***/ function(module, exports) { /** * The base implementation of `_.times` without support for iteratee shorthands * or max array length checks. * * @private * @param {number} n The number of times to invoke `iteratee`. * @param {Function} iteratee The function invoked per iteration. * @returns {Array} Returns the array of results. */ function baseTimes(n, iteratee) { var index = -1, result = Array(n); while (++index < n) { result[index] = iteratee(index); } return result; } module.exports = baseTimes; /***/ }, /* 88 */ /***/ function(module, exports, __webpack_require__) { var baseIsArguments = __webpack_require__(89), isObjectLike = __webpack_require__(51); /** Used for built-in method references. */ var objectProto = Object.prototype; /** Used to check objects for own properties. */ var hasOwnProperty = objectProto.hasOwnProperty; /** Built-in value references. */ var propertyIsEnumerable = objectProto.propertyIsEnumerable; /** * Checks if `value` is likely an `arguments` object. * * @static * @memberOf _ * @since 0.1.0 * @category Lang * @param {*} value The value to check. * @returns {boolean} Returns `true` if `value` is an `arguments` object, * else `false`. * @example * * _.isArguments(function() { return arguments; }()); * // => true * * _.isArguments([1, 2, 3]); * // => false */ var isArguments = baseIsArguments(function() { return arguments; }()) ? baseIsArguments : function(value) { return isObjectLike(value) && hasOwnProperty.call(value, 'callee') && !propertyIsEnumerable.call(value, 'callee'); }; module.exports = isArguments; /***/ }, /* 89 */ /***/ function(module, exports, __webpack_require__) { var baseGetTag = __webpack_require__(20), isObjectLike = __webpack_require__(51); /** `Object#toString` result references. */ var argsTag = '[object Arguments]'; /** * The base implementation of `_.isArguments`. * * @private * @param {*} value The value to check. * @returns {boolean} Returns `true` if `value` is an `arguments` object, */ function baseIsArguments(value) { return isObjectLike(value) && baseGetTag(value) == argsTag; } module.exports = baseIsArguments; /***/ }, /* 90 */ /***/ function(module, exports, __webpack_require__) { /* WEBPACK VAR INJECTION */(function(module) {var root = __webpack_require__(22), stubFalse = __webpack_require__(92); /** Detect free variable `exports`. */ var freeExports = typeof exports == 'object' && exports && !exports.nodeType && exports; /** Detect free variable `module`. */ var freeModule = freeExports && typeof module == 'object' && module && !module.nodeType && module; /** Detect the popular CommonJS extension `module.exports`. */ var moduleExports = freeModule && freeModule.exports === freeExports; /** Built-in value references. */ var Buffer = moduleExports ? root.Buffer : undefined; /* Built-in method references for those with the same name as other `lodash` methods. */ var nativeIsBuffer = Buffer ? Buffer.isBuffer : undefined; /** * Checks if `value` is a buffer. * * @static * @memberOf _ * @since 4.3.0 * @category Lang * @param {*} value The value to check. * @returns {boolean} Returns `true` if `value` is a buffer, else `false`. * @example * * _.isBuffer(new Buffer(2)); * // => true * * _.isBuffer(new Uint8Array(2)); * // => false */ var isBuffer = nativeIsBuffer || stubFalse; module.exports = isBuffer; /* WEBPACK VAR INJECTION */}.call(exports, __webpack_require__(91)(module))) /***/ }, /* 91 */ /***/ function(module, exports) { module.exports = function(module) { if(!module.webpackPolyfill) { module.deprecate = function() {}; module.paths = []; // module.parent = undefined by default module.children = []; module.webpackPolyfill = 1; } return module; } /***/ }, /* 92 */ /***/ function(module, exports) { /** * This method returns `false`. * * @static * @memberOf _ * @since 4.13.0 * @category Util * @returns {boolean} Returns `false`. * @example * * _.times(2, _.stubFalse); * // => [false, false] */ function stubFalse() { return false; } module.exports = stubFalse; /***/ }, /* 93 */ /***/ function(module, exports, __webpack_require__) { var baseIsTypedArray = __webpack_require__(94), baseUnary = __webpack_require__(96), nodeUtil = __webpack_require__(97); /* Node.js helper references. */ var nodeIsTypedArray = nodeUtil && nodeUtil.isTypedArray; /** * Checks if `value` is classified as a typed array. * * @static * @memberOf _ * @since 3.0.0 * @category Lang * @param {*} value The value to check. * @returns {boolean} Returns `true` if `value` is a typed array, else `false`. * @example * * _.isTypedArray(new Uint8Array); * // => true * * _.isTypedArray([]); * // => false */ var isTypedArray = nodeIsTypedArray ? baseUnary(nodeIsTypedArray) : baseIsTypedArray; module.exports = isTypedArray; /***/ }, /* 94 */ /***/ function(module, exports, __webpack_require__) { var baseGetTag = __webpack_require__(20), isLength = __webpack_require__(95), isObjectLike = __webpack_require__(51); /** `Object#toString` result references. */ var argsTag = '[object Arguments]', arrayTag = '[object Array]', boolTag = '[object Boolean]', dateTag = '[object Date]', errorTag = '[object Error]', funcTag = '[object Function]', mapTag = '[object Map]', numberTag = '[object Number]', objectTag = '[object Object]', regexpTag = '[object RegExp]', setTag = '[object Set]', stringTag = '[object String]', weakMapTag = '[object WeakMap]'; var arrayBufferTag = '[object ArrayBuffer]', dataViewTag = '[object DataView]', float32Tag = '[object Float32Array]', float64Tag = '[object Float64Array]', int8Tag = '[object Int8Array]', int16Tag = '[object Int16Array]', int32Tag = '[object Int32Array]', uint8Tag = '[object Uint8Array]', uint8ClampedTag = '[object Uint8ClampedArray]', uint16Tag = '[object Uint16Array]', uint32Tag = '[object Uint32Array]'; /** Used to identify `toStringTag` values of typed arrays. */ var typedArrayTags = {}; typedArrayTags[float32Tag] = typedArrayTags[float64Tag] = typedArrayTags[int8Tag] = typedArrayTags[int16Tag] = typedArrayTags[int32Tag] = typedArrayTags[uint8Tag] = typedArrayTags[uint8ClampedTag] = typedArrayTags[uint16Tag] = typedArrayTags[uint32Tag] = true; typedArrayTags[argsTag] = typedArrayTags[arrayTag] = typedArrayTags[arrayBufferTag] = typedArrayTags[boolTag] = typedArrayTags[dataViewTag] = typedArrayTags[dateTag] = typedArrayTags[errorTag] = typedArrayTags[funcTag] = typedArrayTags[mapTag] = typedArrayTags[numberTag] = typedArrayTags[objectTag] = typedArrayTags[regexpTag] = typedArrayTags[setTag] = typedArrayTags[stringTag] = typedArrayTags[weakMapTag] = false; /** * The base implementation of `_.isTypedArray` without Node.js optimizations. * * @private * @param {*} value The value to check. * @returns {boolean} Returns `true` if `value` is a typed array, else `false`. */ function baseIsTypedArray(value) { return isObjectLike(value) && isLength(value.length) && !!typedArrayTags[baseGetTag(value)]; } module.exports = baseIsTypedArray; /***/ }, /* 95 */ /***/ function(module, exports) { /** Used as references for various `Number` constants. */ var MAX_SAFE_INTEGER = 9007199254740991; /** * Checks if `value` is a valid array-like length. * * **Note:** This method is loosely based on * [`ToLength`](http://ecma-international.org/ecma-262/7.0/#sec-tolength). * * @static * @memberOf _ * @since 4.0.0 * @category Lang * @param {*} value The value to check. * @returns {boolean} Returns `true` if `value` is a valid length, else `false`. * @example * * _.isLength(3); * // => true * * _.isLength(Number.MIN_VALUE); * // => false * * _.isLength(Infinity); * // => false * * _.isLength('3'); * // => false */ function isLength(value) { return typeof value == 'number' && value > -1 && value % 1 == 0 && value <= MAX_SAFE_INTEGER; } module.exports = isLength; /***/ }, /* 96 */ /***/ function(module, exports) { /** * The base implementation of `_.unary` without support for storing metadata. * * @private * @param {Function} func The function to cap arguments for. * @returns {Function} Returns the new capped function. */ function baseUnary(func) { return function(value) { return func(value); }; } module.exports = baseUnary; /***/ }, /* 97 */ /***/ function(module, exports, __webpack_require__) { /* WEBPACK VAR INJECTION */(function(module) {var freeGlobal = __webpack_require__(23); /** Detect free variable `exports`. */ var freeExports = typeof exports == 'object' && exports && !exports.nodeType && exports; /** Detect free variable `module`. */ var freeModule = freeExports && typeof module == 'object' && module && !module.nodeType && module; /** Detect the popular CommonJS extension `module.exports`. */ var moduleExports = freeModule && freeModule.exports === freeExports; /** Detect free variable `process` from Node.js. */ var freeProcess = moduleExports && freeGlobal.process; /** Used to access faster Node.js helpers. */ var nodeUtil = (function() { try { return freeProcess && freeProcess.binding && freeProcess.binding('util'); } catch (e) {} }()); module.exports = nodeUtil; /* WEBPACK VAR INJECTION */}.call(exports, __webpack_require__(91)(module))) /***/ }, /* 98 */ /***/ function(module, exports, __webpack_require__) { var isPrototype = __webpack_require__(99), nativeKeys = __webpack_require__(100); /** Used for built-in method references. */ var objectProto = Object.prototype; /** Used to check objects for own properties. */ var hasOwnProperty = objectProto.hasOwnProperty; /** * The base implementation of `_.keys` which doesn't treat sparse arrays as dense. * * @private * @param {Object} object The object to query. * @returns {Array} Returns the array of property names. */ function baseKeys(object) { if (!isPrototype(object)) { return nativeKeys(object); } var result = []; for (var key in Object(object)) { if (hasOwnProperty.call(object, key) && key != 'constructor') { result.push(key); } } return result; } module.exports = baseKeys; /***/ }, /* 99 */ /***/ function(module, exports) { /** Used for built-in method references. */ var objectProto = Object.prototype; /** * Checks if `value` is likely a prototype object. * * @private * @param {*} value The value to check. * @returns {boolean} Returns `true` if `value` is a prototype, else `false`. */ function isPrototype(value) { var Ctor = value && value.constructor, proto = (typeof Ctor == 'function' && Ctor.prototype) || objectProto; return value === proto; } module.exports = isPrototype; /***/ }, /* 100 */ /***/ function(module, exports, __webpack_require__) { var overArg = __webpack_require__(101); /* Built-in method references for those with the same name as other `lodash` methods. */ var nativeKeys = overArg(Object.keys, Object); module.exports = nativeKeys; /***/ }, /* 101 */ /***/ function(module, exports) { /** * Creates a unary function that invokes `func` with its argument transformed. * * @private * @param {Function} func The function to wrap. * @param {Function} transform The argument transform. * @returns {Function} Returns the new function. */ function overArg(func, transform) { return function(arg) { return func(transform(arg)); }; } module.exports = overArg; /***/ }, /* 102 */ /***/ function(module, exports, __webpack_require__) { var isFunction = __webpack_require__(19), isLength = __webpack_require__(95); /** * Checks if `value` is array-like. A value is considered array-like if it's * not a function and has a `value.length` that's an integer greater than or * equal to `0` and less than or equal to `Number.MAX_SAFE_INTEGER`. * * @static * @memberOf _ * @since 4.0.0 * @category Lang * @param {*} value The value to check. * @returns {boolean} Returns `true` if `value` is array-like, else `false`. * @example * * _.isArrayLike([1, 2, 3]); * // => true * * _.isArrayLike(document.body.children); * // => true * * _.isArrayLike('abc'); * // => true * * _.isArrayLike(_.noop); * // => false */ function isArrayLike(value) { return value != null && isLength(value.length) && !isFunction(value); } module.exports = isArrayLike; /***/ }, /* 103 */ /***/ function(module, exports, __webpack_require__) { var baseClone = __webpack_require__(104); /** Used to compose bitmasks for cloning. */ var CLONE_SYMBOLS_FLAG = 4; /** * Creates a shallow clone of `value`. * * **Note:** This method is loosely based on the * [structured clone algorithm](https://mdn.io/Structured_clone_algorithm) * and supports cloning arrays, array buffers, booleans, date objects, maps, * numbers, `Object` objects, regexes, sets, strings, symbols, and typed * arrays. The own enumerable properties of `arguments` objects are cloned * as plain objects. An empty object is returned for uncloneable values such * as error objects, functions, DOM nodes, and WeakMaps. * * @static * @memberOf _ * @since 0.1.0 * @category Lang * @param {*} value The value to clone. * @returns {*} Returns the cloned value. * @see _.cloneDeep * @example * * var objects = [{ 'a': 1 }, { 'b': 2 }]; * * var shallow = _.clone(objects); * console.log(shallow[0] === objects[0]); * // => true */ function clone(value) { return baseClone(value, CLONE_SYMBOLS_FLAG); } module.exports = clone; /***/ }, /* 104 */ /***/ function(module, exports, __webpack_require__) { var Stack = __webpack_require__(105), arrayEach = __webpack_require__(64), assignValue = __webpack_require__(82), baseAssign = __webpack_require__(80), baseAssignIn = __webpack_require__(134), cloneBuffer = __webpack_require__(138), copyArray = __webpack_require__(53), copySymbols = __webpack_require__(139), copySymbolsIn = __webpack_require__(143), getAllKeys = __webpack_require__(147), getAllKeysIn = __webpack_require__(149), getTag = __webpack_require__(150), initCloneArray = __webpack_require__(154), initCloneByTag = __webpack_require__(155), initCloneObject = __webpack_require__(169), isArray = __webpack_require__(50), isBuffer = __webpack_require__(90), isObject = __webpack_require__(26), keys = __webpack_require__(85); /** Used to compose bitmasks for cloning. */ var CLONE_DEEP_FLAG = 1, CLONE_FLAT_FLAG = 2, CLONE_SYMBOLS_FLAG = 4; /** `Object#toString` result references. */ var argsTag = '[object Arguments]', arrayTag = '[object Array]', boolTag = '[object Boolean]', dateTag = '[object Date]', errorTag = '[object Error]', funcTag = '[object Function]', genTag = '[object GeneratorFunction]', mapTag = '[object Map]', numberTag = '[object Number]', objectTag = '[object Object]', regexpTag = '[object RegExp]', setTag = '[object Set]', stringTag = '[object String]', symbolTag = '[object Symbol]', weakMapTag = '[object WeakMap]'; var arrayBufferTag = '[object ArrayBuffer]', dataViewTag = '[object DataView]', float32Tag = '[object Float32Array]', float64Tag = '[object Float64Array]', int8Tag = '[object Int8Array]', int16Tag = '[object Int16Array]', int32Tag = '[object Int32Array]', uint8Tag = '[object Uint8Array]', uint8ClampedTag = '[object Uint8ClampedArray]', uint16Tag = '[object Uint16Array]', uint32Tag = '[object Uint32Array]'; /** Used to identify `toStringTag` values supported by `_.clone`. */ var cloneableTags = {}; cloneableTags[argsTag] = cloneableTags[arrayTag] = cloneableTags[arrayBufferTag] = cloneableTags[dataViewTag] = cloneableTags[boolTag] = cloneableTags[dateTag] = cloneableTags[float32Tag] = cloneableTags[float64Tag] = cloneableTags[int8Tag] = cloneableTags[int16Tag] = cloneableTags[int32Tag] = cloneableTags[mapTag] = cloneableTags[numberTag] = cloneableTags[objectTag] = cloneableTags[regexpTag] = cloneableTags[setTag] = cloneableTags[stringTag] = cloneableTags[symbolTag] = cloneableTags[uint8Tag] = cloneableTags[uint8ClampedTag] = cloneableTags[uint16Tag] = cloneableTags[uint32Tag] = true; cloneableTags[errorTag] = cloneableTags[funcTag] = cloneableTags[weakMapTag] = false; /** * The base implementation of `_.clone` and `_.cloneDeep` which tracks * traversed objects. * * @private * @param {*} value The value to clone. * @param {boolean} bitmask The bitmask flags. * 1 - Deep clone * 2 - Flatten inherited properties * 4 - Clone symbols * @param {Function} [customizer] The function to customize cloning. * @param {string} [key] The key of `value`. * @param {Object} [object] The parent object of `value`. * @param {Object} [stack] Tracks traversed objects and their clone counterparts. * @returns {*} Returns the cloned value. */ function baseClone(value, bitmask, customizer, key, object, stack) { var result, isDeep = bitmask & CLONE_DEEP_FLAG, isFlat = bitmask & CLONE_FLAT_FLAG, isFull = bitmask & CLONE_SYMBOLS_FLAG; if (customizer) { result = object ? customizer(value, key, object, stack) : customizer(value); } if (result !== undefined) { return result; } if (!isObject(value)) { return value; } var isArr = isArray(value); if (isArr) { result = initCloneArray(value); if (!isDeep) { return copyArray(value, result); } } else { var tag = getTag(value), isFunc = tag == funcTag || tag == genTag; if (isBuffer(value)) { return cloneBuffer(value, isDeep); } if (tag == objectTag || tag == argsTag || (isFunc && !object)) { result = (isFlat || isFunc) ? {} : initCloneObject(value); if (!isDeep) { return isFlat ? copySymbolsIn(value, baseAssignIn(result, value)) : copySymbols(value, baseAssign(result, value)); } } else { if (!cloneableTags[tag]) { return object ? value : {}; } result = initCloneByTag(value, tag, baseClone, isDeep); } } // Check for circular references and return its corresponding clone. stack || (stack = new Stack); var stacked = stack.get(value); if (stacked) { return stacked; } stack.set(value, result); var keysFunc = isFull ? (isFlat ? getAllKeysIn : getAllKeys) : (isFlat ? keysIn : keys); var props = isArr ? undefined : keysFunc(value); arrayEach(props || value, function(subValue, key) { if (props) { key = subValue; subValue = value[key]; } // Recursively populate clone (susceptible to call stack limits). assignValue(result, key, baseClone(subValue, bitmask, customizer, key, value, stack)); }); return result; } module.exports = baseClone; /***/ }, /* 105 */ /***/ function(module, exports, __webpack_require__) { var ListCache = __webpack_require__(106), stackClear = __webpack_require__(113), stackDelete = __webpack_require__(114), stackGet = __webpack_require__(115), stackHas = __webpack_require__(116), stackSet = __webpack_require__(117); /** * Creates a stack cache object to store key-value pairs. * * @private * @constructor * @param {Array} [entries] The key-value pairs to cache. */ function Stack(entries) { var data = this.__data__ = new ListCache(entries); this.size = data.size; } // Add methods to `Stack`. Stack.prototype.clear = stackClear; Stack.prototype['delete'] = stackDelete; Stack.prototype.get = stackGet; Stack.prototype.has = stackHas; Stack.prototype.set = stackSet; module.exports = Stack; /***/ }, /* 106 */ /***/ function(module, exports, __webpack_require__) { var listCacheClear = __webpack_require__(107), listCacheDelete = __webpack_require__(108), listCacheGet = __webpack_require__(110), listCacheHas = __webpack_require__(111), listCacheSet = __webpack_require__(112); /** * Creates an list cache object. * * @private * @constructor * @param {Array} [entries] The key-value pairs to cache. */ function ListCache(entries) { var index = -1, length = entries == null ? 0 : entries.length; this.clear(); while (++index < length) { var entry = entries[index]; this.set(entry[0], entry[1]); } } // Add methods to `ListCache`. ListCache.prototype.clear = listCacheClear; ListCache.prototype['delete'] = listCacheDelete; ListCache.prototype.get = listCacheGet; ListCache.prototype.has = listCacheHas; ListCache.prototype.set = listCacheSet; module.exports = ListCache; /***/ }, /* 107 */ /***/ function(module, exports) { /** * Removes all key-value entries from the list cache. * * @private * @name clear * @memberOf ListCache */ function listCacheClear() { this.__data__ = []; this.size = 0; } module.exports = listCacheClear; /***/ }, /* 108 */ /***/ function(module, exports, __webpack_require__) { var assocIndexOf = __webpack_require__(109); /** Used for built-in method references. */ var arrayProto = Array.prototype; /** Built-in value references. */ var splice = arrayProto.splice; /** * Removes `key` and its value from the list cache. * * @private * @name delete * @memberOf ListCache * @param {string} key The key of the value to remove. * @returns {boolean} Returns `true` if the entry was removed, else `false`. */ function listCacheDelete(key) { var data = this.__data__, index = assocIndexOf(data, key); if (index < 0) { return false; } var lastIndex = data.length - 1; if (index == lastIndex) { data.pop(); } else { splice.call(data, index, 1); } --this.size; return true; } module.exports = listCacheDelete; /***/ }, /* 109 */ /***/ function(module, exports, __webpack_require__) { var eq = __webpack_require__(84); /** * Gets the index at which the `key` is found in `array` of key-value pairs. * * @private * @param {Array} array The array to inspect. * @param {*} key The key to search for. * @returns {number} Returns the index of the matched value, else `-1`. */ function assocIndexOf(array, key) { var length = array.length; while (length--) { if (eq(array[length][0], key)) { return length; } } return -1; } module.exports = assocIndexOf; /***/ }, /* 110 */ /***/ function(module, exports, __webpack_require__) { var assocIndexOf = __webpack_require__(109); /** * Gets the list cache value for `key`. * * @private * @name get * @memberOf ListCache * @param {string} key The key of the value to get. * @returns {*} Returns the entry value. */ function listCacheGet(key) { var data = this.__data__, index = assocIndexOf(data, key); return index < 0 ? undefined : data[index][1]; } module.exports = listCacheGet; /***/ }, /* 111 */ /***/ function(module, exports, __webpack_require__) { var assocIndexOf = __webpack_require__(109); /** * Checks if a list cache value for `key` exists. * * @private * @name has * @memberOf ListCache * @param {string} key The key of the entry to check. * @returns {boolean} Returns `true` if an entry for `key` exists, else `false`. */ function listCacheHas(key) { return assocIndexOf(this.__data__, key) > -1; } module.exports = listCacheHas; /***/ }, /* 112 */ /***/ function(module, exports, __webpack_require__) { var assocIndexOf = __webpack_require__(109); /** * Sets the list cache `key` to `value`. * * @private * @name set * @memberOf ListCache * @param {string} key The key of the value to set. * @param {*} value The value to set. * @returns {Object} Returns the list cache instance. */ function listCacheSet(key, value) { var data = this.__data__, index = assocIndexOf(data, key); if (index < 0) { ++this.size; data.push([key, value]); } else { data[index][1] = value; } return this; } module.exports = listCacheSet; /***/ }, /* 113 */ /***/ function(module, exports, __webpack_require__) { var ListCache = __webpack_require__(106); /** * Removes all key-value entries from the stack. * * @private * @name clear * @memberOf Stack */ function stackClear() { this.__data__ = new ListCache; this.size = 0; } module.exports = stackClear; /***/ }, /* 114 */ /***/ function(module, exports) { /** * Removes `key` and its value from the stack. * * @private * @name delete * @memberOf Stack * @param {string} key The key of the value to remove. * @returns {boolean} Returns `true` if the entry was removed, else `false`. */ function stackDelete(key) { var data = this.__data__, result = data['delete'](key); this.size = data.size; return result; } module.exports = stackDelete; /***/ }, /* 115 */ /***/ function(module, exports) { /** * Gets the stack value for `key`. * * @private * @name get * @memberOf Stack * @param {string} key The key of the value to get. * @returns {*} Returns the entry value. */ function stackGet(key) { return this.__data__.get(key); } module.exports = stackGet; /***/ }, /* 116 */ /***/ function(module, exports) { /** * Checks if a stack value for `key` exists. * * @private * @name has * @memberOf Stack * @param {string} key The key of the entry to check. * @returns {boolean} Returns `true` if an entry for `key` exists, else `false`. */ function stackHas(key) { return this.__data__.has(key); } module.exports = stackHas; /***/ }, /* 117 */ /***/ function(module, exports, __webpack_require__) { var ListCache = __webpack_require__(106), Map = __webpack_require__(118), MapCache = __webpack_require__(119); /** Used as the size to enable large array optimizations. */ var LARGE_ARRAY_SIZE = 200; /** * Sets the stack `key` to `value`. * * @private * @name set * @memberOf Stack * @param {string} key The key of the value to set. * @param {*} value The value to set. * @returns {Object} Returns the stack cache instance. */ function stackSet(key, value) { var data = this.__data__; if (data instanceof ListCache) { var pairs = data.__data__; if (!Map || (pairs.length < LARGE_ARRAY_SIZE - 1)) { pairs.push([key, value]); this.size = ++data.size; return this; } data = this.__data__ = new MapCache(pairs); } data.set(key, value); this.size = data.size; return this; } module.exports = stackSet; /***/ }, /* 118 */ /***/ function(module, exports, __webpack_require__) { var getNative = __webpack_require__(17), root = __webpack_require__(22); /* Built-in method references that are verified to be native. */ var Map = getNative(root, 'Map'); module.exports = Map; /***/ }, /* 119 */ /***/ function(module, exports, __webpack_require__) { var mapCacheClear = __webpack_require__(120), mapCacheDelete = __webpack_require__(128), mapCacheGet = __webpack_require__(131), mapCacheHas = __webpack_require__(132), mapCacheSet = __webpack_require__(133); /** * Creates a map cache object to store key-value pairs. * * @private * @constructor * @param {Array} [entries] The key-value pairs to cache. */ function MapCache(entries) { var index = -1, length = entries == null ? 0 : entries.length; this.clear(); while (++index < length) { var entry = entries[index]; this.set(entry[0], entry[1]); } } // Add methods to `MapCache`. MapCache.prototype.clear = mapCacheClear; MapCache.prototype['delete'] = mapCacheDelete; MapCache.prototype.get = mapCacheGet; MapCache.prototype.has = mapCacheHas; MapCache.prototype.set = mapCacheSet; module.exports = MapCache; /***/ }, /* 120 */ /***/ function(module, exports, __webpack_require__) { var Hash = __webpack_require__(121), ListCache = __webpack_require__(106), Map = __webpack_require__(118); /** * Removes all key-value entries from the map. * * @private * @name clear * @memberOf MapCache */ function mapCacheClear() { this.size = 0; this.__data__ = { 'hash': new Hash, 'map': new (Map || ListCache), 'string': new Hash }; } module.exports = mapCacheClear; /***/ }, /* 121 */ /***/ function(module, exports, __webpack_require__) { var hashClear = __webpack_require__(122), hashDelete = __webpack_require__(124), hashGet = __webpack_require__(125), hashHas = __webpack_require__(126), hashSet = __webpack_require__(127); /** * Creates a hash object. * * @private * @constructor * @param {Array} [entries] The key-value pairs to cache. */ function Hash(entries) { var index = -1, length = entries == null ? 0 : entries.length; this.clear(); while (++index < length) { var entry = entries[index]; this.set(entry[0], entry[1]); } } // Add methods to `Hash`. Hash.prototype.clear = hashClear; Hash.prototype['delete'] = hashDelete; Hash.prototype.get = hashGet; Hash.prototype.has = hashHas; Hash.prototype.set = hashSet; module.exports = Hash; /***/ }, /* 122 */ /***/ function(module, exports, __webpack_require__) { var nativeCreate = __webpack_require__(123); /** * Removes all key-value entries from the hash. * * @private * @name clear * @memberOf Hash */ function hashClear() { this.__data__ = nativeCreate ? nativeCreate(null) : {}; this.size = 0; } module.exports = hashClear; /***/ }, /* 123 */ /***/ function(module, exports, __webpack_require__) { var getNative = __webpack_require__(17); /* Built-in method references that are verified to be native. */ var nativeCreate = getNative(Object, 'create'); module.exports = nativeCreate; /***/ }, /* 124 */ /***/ function(module, exports) { /** * Removes `key` and its value from the hash. * * @private * @name delete * @memberOf Hash * @param {Object} hash The hash to modify. * @param {string} key The key of the value to remove. * @returns {boolean} Returns `true` if the entry was removed, else `false`. */ function hashDelete(key) { var result = this.has(key) && delete this.__data__[key]; this.size -= result ? 1 : 0; return result; } module.exports = hashDelete; /***/ }, /* 125 */ /***/ function(module, exports, __webpack_require__) { var nativeCreate = __webpack_require__(123); /** Used to stand-in for `undefined` hash values. */ var HASH_UNDEFINED = '__lodash_hash_undefined__'; /** Used for built-in method references. */ var objectProto = Object.prototype; /** Used to check objects for own properties. */ var hasOwnProperty = objectProto.hasOwnProperty; /** * Gets the hash value for `key`. * * @private * @name get * @memberOf Hash * @param {string} key The key of the value to get. * @returns {*} Returns the entry value. */ function hashGet(key) { var data = this.__data__; if (nativeCreate) { var result = data[key]; return result === HASH_UNDEFINED ? undefined : result; } return hasOwnProperty.call(data, key) ? data[key] : undefined; } module.exports = hashGet; /***/ }, /* 126 */ /***/ function(module, exports, __webpack_require__) { var nativeCreate = __webpack_require__(123); /** Used for built-in method references. */ var objectProto = Object.prototype; /** Used to check objects for own properties. */ var hasOwnProperty = objectProto.hasOwnProperty; /** * Checks if a hash value for `key` exists. * * @private * @name has * @memberOf Hash * @param {string} key The key of the entry to check. * @returns {boolean} Returns `true` if an entry for `key` exists, else `false`. */ function hashHas(key) { var data = this.__data__; return nativeCreate ? (data[key] !== undefined) : hasOwnProperty.call(data, key); } module.exports = hashHas; /***/ }, /* 127 */ /***/ function(module, exports, __webpack_require__) { var nativeCreate = __webpack_require__(123); /** Used to stand-in for `undefined` hash values. */ var HASH_UNDEFINED = '__lodash_hash_undefined__'; /** * Sets the hash `key` to `value`. * * @private * @name set * @memberOf Hash * @param {string} key The key of the value to set. * @param {*} value The value to set. * @returns {Object} Returns the hash instance. */ function hashSet(key, value) { var data = this.__data__; this.size += this.has(key) ? 0 : 1; data[key] = (nativeCreate && value === undefined) ? HASH_UNDEFINED : value; return this; } module.exports = hashSet; /***/ }, /* 128 */ /***/ function(module, exports, __webpack_require__) { var getMapData = __webpack_require__(129); /** * Removes `key` and its value from the map. * * @private * @name delete * @memberOf MapCache * @param {string} key The key of the value to remove. * @returns {boolean} Returns `true` if the entry was removed, else `false`. */ function mapCacheDelete(key) { var result = getMapData(this, key)['delete'](key); this.size -= result ? 1 : 0; return result; } module.exports = mapCacheDelete; /***/ }, /* 129 */ /***/ function(module, exports, __webpack_require__) { var isKeyable = __webpack_require__(130); /** * Gets the data for `map`. * * @private * @param {Object} map The map to query. * @param {string} key The reference key. * @returns {*} Returns the map data. */ function getMapData(map, key) { var data = map.__data__; return isKeyable(key) ? data[typeof key == 'string' ? 'string' : 'hash'] : data.map; } module.exports = getMapData; /***/ }, /* 130 */ /***/ function(module, exports) { /** * Checks if `value` is suitable for use as unique object key. * * @private * @param {*} value The value to check. * @returns {boolean} Returns `true` if `value` is suitable, else `false`. */ function isKeyable(value) { var type = typeof value; return (type == 'string' || type == 'number' || type == 'symbol' || type == 'boolean') ? (value !== '__proto__') : (value === null); } module.exports = isKeyable; /***/ }, /* 131 */ /***/ function(module, exports, __webpack_require__) { var getMapData = __webpack_require__(129); /** * Gets the map value for `key`. * * @private * @name get * @memberOf MapCache * @param {string} key The key of the value to get. * @returns {*} Returns the entry value. */ function mapCacheGet(key) { return getMapData(this, key).get(key); } module.exports = mapCacheGet; /***/ }, /* 132 */ /***/ function(module, exports, __webpack_require__) { var getMapData = __webpack_require__(129); /** * Checks if a map value for `key` exists. * * @private * @name has * @memberOf MapCache * @param {string} key The key of the entry to check. * @returns {boolean} Returns `true` if an entry for `key` exists, else `false`. */ function mapCacheHas(key) { return getMapData(this, key).has(key); } module.exports = mapCacheHas; /***/ }, /* 133 */ /***/ function(module, exports, __webpack_require__) { var getMapData = __webpack_require__(129); /** * Sets the map `key` to `value`. * * @private * @name set * @memberOf MapCache * @param {string} key The key of the value to set. * @param {*} value The value to set. * @returns {Object} Returns the map cache instance. */ function mapCacheSet(key, value) { var data = getMapData(this, key), size = data.size; data.set(key, value); this.size += data.size == size ? 0 : 1; return this; } module.exports = mapCacheSet; /***/ }, /* 134 */ /***/ function(module, exports, __webpack_require__) { var copyObject = __webpack_require__(81), keysIn = __webpack_require__(135); /** * The base implementation of `_.assignIn` without support for multiple sources * or `customizer` functions. * * @private * @param {Object} object The destination object. * @param {Object} source The source object. * @returns {Object} Returns `object`. */ function baseAssignIn(object, source) { return object && copyObject(source, keysIn(source), object); } module.exports = baseAssignIn; /***/ }, /* 135 */ /***/ function(module, exports, __webpack_require__) { var arrayLikeKeys = __webpack_require__(86), baseKeysIn = __webpack_require__(136), isArrayLike = __webpack_require__(102); /** * Creates an array of the own and inherited enumerable property names of `object`. * * **Note:** Non-object values are coerced to objects. * * @static * @memberOf _ * @since 3.0.0 * @category Object * @param {Object} object The object to query. * @returns {Array} Returns the array of property names. * @example * * function Foo() { * this.a = 1; * this.b = 2; * } * * Foo.prototype.c = 3; * * _.keysIn(new Foo); * // => ['a', 'b', 'c'] (iteration order is not guaranteed) */ function keysIn(object) { return isArrayLike(object) ? arrayLikeKeys(object, true) : baseKeysIn(object); } module.exports = keysIn; /***/ }, /* 136 */ /***/ function(module, exports, __webpack_require__) { var isObject = __webpack_require__(26), isPrototype = __webpack_require__(99), nativeKeysIn = __webpack_require__(137); /** Used for built-in method references. */ var objectProto = Object.prototype; /** Used to check objects for own properties. */ var hasOwnProperty = objectProto.hasOwnProperty; /** * The base implementation of `_.keysIn` which doesn't treat sparse arrays as dense. * * @private * @param {Object} object The object to query. * @returns {Array} Returns the array of property names. */ function baseKeysIn(object) { if (!isObject(object)) { return nativeKeysIn(object); } var isProto = isPrototype(object), result = []; for (var key in object) { if (!(key == 'constructor' && (isProto || !hasOwnProperty.call(object, key)))) { result.push(key); } } return result; } module.exports = baseKeysIn; /***/ }, /* 137 */ /***/ function(module, exports) { /** * This function is like * [`Object.keys`](http://ecma-international.org/ecma-262/7.0/#sec-object.keys) * except that it includes inherited enumerable properties. * * @private * @param {Object} object The object to query. * @returns {Array} Returns the array of property names. */ function nativeKeysIn(object) { var result = []; if (object != null) { for (var key in Object(object)) { result.push(key); } } return result; } module.exports = nativeKeysIn; /***/ }, /* 138 */ /***/ function(module, exports, __webpack_require__) { /* WEBPACK VAR INJECTION */(function(module) {var root = __webpack_require__(22); /** Detect free variable `exports`. */ var freeExports = typeof exports == 'object' && exports && !exports.nodeType && exports; /** Detect free variable `module`. */ var freeModule = freeExports && typeof module == 'object' && module && !module.nodeType && module; /** Detect the popular CommonJS extension `module.exports`. */ var moduleExports = freeModule && freeModule.exports === freeExports; /** Built-in value references. */ var Buffer = moduleExports ? root.Buffer : undefined, allocUnsafe = Buffer ? Buffer.allocUnsafe : undefined; /** * Creates a clone of `buffer`. * * @private * @param {Buffer} buffer The buffer to clone. * @param {boolean} [isDeep] Specify a deep clone. * @returns {Buffer} Returns the cloned buffer. */ function cloneBuffer(buffer, isDeep) { if (isDeep) { return buffer.slice(); } var length = buffer.length, result = allocUnsafe ? allocUnsafe(length) : new buffer.constructor(length); buffer.copy(result); return result; } module.exports = cloneBuffer; /* WEBPACK VAR INJECTION */}.call(exports, __webpack_require__(91)(module))) /***/ }, /* 139 */ /***/ function(module, exports, __webpack_require__) { var copyObject = __webpack_require__(81), getSymbols = __webpack_require__(140); /** * Copies own symbols of `source` to `object`. * * @private * @param {Object} source The object to copy symbols from. * @param {Object} [object={}] The object to copy symbols to. * @returns {Object} Returns `object`. */ function copySymbols(source, object) { return copyObject(source, getSymbols(source), object); } module.exports = copySymbols; /***/ }, /* 140 */ /***/ function(module, exports, __webpack_require__) { var arrayFilter = __webpack_require__(141), stubArray = __webpack_require__(142); /** Used for built-in method references. */ var objectProto = Object.prototype; /** Built-in value references. */ var propertyIsEnumerable = objectProto.propertyIsEnumerable; /* Built-in method references for those with the same name as other `lodash` methods. */ var nativeGetSymbols = Object.getOwnPropertySymbols; /** * Creates an array of the own enumerable symbols of `object`. * * @private * @param {Object} object The object to query. * @returns {Array} Returns the array of symbols. */ var getSymbols = !nativeGetSymbols ? stubArray : function(object) { if (object == null) { return []; } object = Object(object); return arrayFilter(nativeGetSymbols(object), function(symbol) { return propertyIsEnumerable.call(object, symbol); }); }; module.exports = getSymbols; /***/ }, /* 141 */ /***/ function(module, exports) { /** * A specialized version of `_.filter` for arrays without support for * iteratee shorthands. * * @private * @param {Array} [array] The array to iterate over. * @param {Function} predicate The function invoked per iteration. * @returns {Array} Returns the new filtered array. */ function arrayFilter(array, predicate) { var index = -1, length = array == null ? 0 : array.length, resIndex = 0, result = []; while (++index < length) { var value = array[index]; if (predicate(value, index, array)) { result[resIndex++] = value; } } return result; } module.exports = arrayFilter; /***/ }, /* 142 */ /***/ function(module, exports) { /** * This method returns a new empty array. * * @static * @memberOf _ * @since 4.13.0 * @category Util * @returns {Array} Returns the new empty array. * @example * * var arrays = _.times(2, _.stubArray); * * console.log(arrays); * // => [[], []] * * console.log(arrays[0] === arrays[1]); * // => false */ function stubArray() { return []; } module.exports = stubArray; /***/ }, /* 143 */ /***/ function(module, exports, __webpack_require__) { var copyObject = __webpack_require__(81), getSymbolsIn = __webpack_require__(144); /** * Copies own and inherited symbols of `source` to `object`. * * @private * @param {Object} source The object to copy symbols from. * @param {Object} [object={}] The object to copy symbols to. * @returns {Object} Returns `object`. */ function copySymbolsIn(source, object) { return copyObject(source, getSymbolsIn(source), object); } module.exports = copySymbolsIn; /***/ }, /* 144 */ /***/ function(module, exports, __webpack_require__) { var arrayPush = __webpack_require__(145), getPrototype = __webpack_require__(146), getSymbols = __webpack_require__(140), stubArray = __webpack_require__(142); /* Built-in method references for those with the same name as other `lodash` methods. */ var nativeGetSymbols = Object.getOwnPropertySymbols; /** * Creates an array of the own and inherited enumerable symbols of `object`. * * @private * @param {Object} object The object to query. * @returns {Array} Returns the array of symbols. */ var getSymbolsIn = !nativeGetSymbols ? stubArray : function(object) { var result = []; while (object) { arrayPush(result, getSymbols(object)); object = getPrototype(object); } return result; }; module.exports = getSymbolsIn; /***/ }, /* 145 */ /***/ function(module, exports) { /** * Appends the elements of `values` to `array`. * * @private * @param {Array} array The array to modify. * @param {Array} values The values to append. * @returns {Array} Returns `array`. */ function arrayPush(array, values) { var index = -1, length = values.length, offset = array.length; while (++index < length) { array[offset + index] = values[index]; } return array; } module.exports = arrayPush; /***/ }, /* 146 */ /***/ function(module, exports, __webpack_require__) { var overArg = __webpack_require__(101); /** Built-in value references. */ var getPrototype = overArg(Object.getPrototypeOf, Object); module.exports = getPrototype; /***/ }, /* 147 */ /***/ function(module, exports, __webpack_require__) { var baseGetAllKeys = __webpack_require__(148), getSymbols = __webpack_require__(140), keys = __webpack_require__(85); /** * Creates an array of own enumerable property names and symbols of `object`. * * @private * @param {Object} object The object to query. * @returns {Array} Returns the array of property names and symbols. */ function getAllKeys(object) { return baseGetAllKeys(object, keys, getSymbols); } module.exports = getAllKeys; /***/ }, /* 148 */ /***/ function(module, exports, __webpack_require__) { var arrayPush = __webpack_require__(145), isArray = __webpack_require__(50); /** * The base implementation of `getAllKeys` and `getAllKeysIn` which uses * `keysFunc` and `symbolsFunc` to get the enumerable property names and * symbols of `object`. * * @private * @param {Object} object The object to query. * @param {Function} keysFunc The function to get the keys of `object`. * @param {Function} symbolsFunc The function to get the symbols of `object`. * @returns {Array} Returns the array of property names and symbols. */ function baseGetAllKeys(object, keysFunc, symbolsFunc) { var result = keysFunc(object); return isArray(object) ? result : arrayPush(result, symbolsFunc(object)); } module.exports = baseGetAllKeys; /***/ }, /* 149 */ /***/ function(module, exports, __webpack_require__) { var baseGetAllKeys = __webpack_require__(148), getSymbolsIn = __webpack_require__(144), keysIn = __webpack_require__(135); /** * Creates an array of own and inherited enumerable property names and * symbols of `object`. * * @private * @param {Object} object The object to query. * @returns {Array} Returns the array of property names and symbols. */ function getAllKeysIn(object) { return baseGetAllKeys(object, keysIn, getSymbolsIn); } module.exports = getAllKeysIn; /***/ }, /* 150 */ /***/ function(module, exports, __webpack_require__) { var DataView = __webpack_require__(151), Map = __webpack_require__(118), Promise = __webpack_require__(152), Set = __webpack_require__(153), WeakMap = __webpack_require__(16), baseGetTag = __webpack_require__(20), toSource = __webpack_require__(29); /** `Object#toString` result references. */ var mapTag = '[object Map]', objectTag = '[object Object]', promiseTag = '[object Promise]', setTag = '[object Set]', weakMapTag = '[object WeakMap]'; var dataViewTag = '[object DataView]'; /** Used to detect maps, sets, and weakmaps. */ var dataViewCtorString = toSource(DataView), mapCtorString = toSource(Map), promiseCtorString = toSource(Promise), setCtorString = toSource(Set), weakMapCtorString = toSource(WeakMap); /** * Gets the `toStringTag` of `value`. * * @private * @param {*} value The value to query. * @returns {string} Returns the `toStringTag`. */ var getTag = baseGetTag; // Fallback for data views, maps, sets, and weak maps in IE 11 and promises in Node.js < 6. if ((DataView && getTag(new DataView(new ArrayBuffer(1))) != dataViewTag) || (Map && getTag(new Map) != mapTag) || (Promise && getTag(Promise.resolve()) != promiseTag) || (Set && getTag(new Set) != setTag) || (WeakMap && getTag(new WeakMap) != weakMapTag)) { getTag = function(value) { var result = baseGetTag(value), Ctor = result == objectTag ? value.constructor : undefined, ctorString = Ctor ? toSource(Ctor) : ''; if (ctorString) { switch (ctorString) { case dataViewCtorString: return dataViewTag; case mapCtorString: return mapTag; case promiseCtorString: return promiseTag; case setCtorString: return setTag; case weakMapCtorString: return weakMapTag; } } return result; }; } module.exports = getTag; /***/ }, /* 151 */ /***/ function(module, exports, __webpack_require__) { var getNative = __webpack_require__(17), root = __webpack_require__(22); /* Built-in method references that are verified to be native. */ var DataView = getNative(root, 'DataView'); module.exports = DataView; /***/ }, /* 152 */ /***/ function(module, exports, __webpack_require__) { var getNative = __webpack_require__(17), root = __webpack_require__(22); /* Built-in method references that are verified to be native. */ var Promise = getNative(root, 'Promise'); module.exports = Promise; /***/ }, /* 153 */ /***/ function(module, exports, __webpack_require__) { var getNative = __webpack_require__(17), root = __webpack_require__(22); /* Built-in method references that are verified to be native. */ var Set = getNative(root, 'Set'); module.exports = Set; /***/ }, /* 154 */ /***/ function(module, exports) { /** Used for built-in method references. */ var objectProto = Object.prototype; /** Used to check objects for own properties. */ var hasOwnProperty = objectProto.hasOwnProperty; /** * Initializes an array clone. * * @private * @param {Array} array The array to clone. * @returns {Array} Returns the initialized clone. */ function initCloneArray(array) { var length = array.length, result = array.constructor(length); // Add properties assigned by `RegExp#exec`. if (length && typeof array[0] == 'string' && hasOwnProperty.call(array, 'index')) { result.index = array.index; result.input = array.input; } return result; } module.exports = initCloneArray; /***/ }, /* 155 */ /***/ function(module, exports, __webpack_require__) { var cloneArrayBuffer = __webpack_require__(156), cloneDataView = __webpack_require__(158), cloneMap = __webpack_require__(159), cloneRegExp = __webpack_require__(163), cloneSet = __webpack_require__(164), cloneSymbol = __webpack_require__(167), cloneTypedArray = __webpack_require__(168); /** `Object#toString` result references. */ var boolTag = '[object Boolean]', dateTag = '[object Date]', mapTag = '[object Map]', numberTag = '[object Number]', regexpTag = '[object RegExp]', setTag = '[object Set]', stringTag = '[object String]', symbolTag = '[object Symbol]'; var arrayBufferTag = '[object ArrayBuffer]', dataViewTag = '[object DataView]', float32Tag = '[object Float32Array]', float64Tag = '[object Float64Array]', int8Tag = '[object Int8Array]', int16Tag = '[object Int16Array]', int32Tag = '[object Int32Array]', uint8Tag = '[object Uint8Array]', uint8ClampedTag = '[object Uint8ClampedArray]', uint16Tag = '[object Uint16Array]', uint32Tag = '[object Uint32Array]'; /** * Initializes an object clone based on its `toStringTag`. * * **Note:** This function only supports cloning values with tags of * `Boolean`, `Date`, `Error`, `Number`, `RegExp`, or `String`. * * @private * @param {Object} object The object to clone. * @param {string} tag The `toStringTag` of the object to clone. * @param {Function} cloneFunc The function to clone values. * @param {boolean} [isDeep] Specify a deep clone. * @returns {Object} Returns the initialized clone. */ function initCloneByTag(object, tag, cloneFunc, isDeep) { var Ctor = object.constructor; switch (tag) { case arrayBufferTag: return cloneArrayBuffer(object); case boolTag: case dateTag: return new Ctor(+object); case dataViewTag: return cloneDataView(object, isDeep); case float32Tag: case float64Tag: case int8Tag: case int16Tag: case int32Tag: case uint8Tag: case uint8ClampedTag: case uint16Tag: case uint32Tag: return cloneTypedArray(object, isDeep); case mapTag: return cloneMap(object, isDeep, cloneFunc); case numberTag: case stringTag: return new Ctor(object); case regexpTag: return cloneRegExp(object); case setTag: return cloneSet(object, isDeep, cloneFunc); case symbolTag: return cloneSymbol(object); } } module.exports = initCloneByTag; /***/ }, /* 156 */ /***/ function(module, exports, __webpack_require__) { var Uint8Array = __webpack_require__(157); /** * Creates a clone of `arrayBuffer`. * * @private * @param {ArrayBuffer} arrayBuffer The array buffer to clone. * @returns {ArrayBuffer} Returns the cloned array buffer. */ function cloneArrayBuffer(arrayBuffer) { var result = new arrayBuffer.constructor(arrayBuffer.byteLength); new Uint8Array(result).set(new Uint8Array(arrayBuffer)); return result; } module.exports = cloneArrayBuffer; /***/ }, /* 157 */ /***/ function(module, exports, __webpack_require__) { var root = __webpack_require__(22); /** Built-in value references. */ var Uint8Array = root.Uint8Array; module.exports = Uint8Array; /***/ }, /* 158 */ /***/ function(module, exports, __webpack_require__) { var cloneArrayBuffer = __webpack_require__(156); /** * Creates a clone of `dataView`. * * @private * @param {Object} dataView The data view to clone. * @param {boolean} [isDeep] Specify a deep clone. * @returns {Object} Returns the cloned data view. */ function cloneDataView(dataView, isDeep) { var buffer = isDeep ? cloneArrayBuffer(dataView.buffer) : dataView.buffer; return new dataView.constructor(buffer, dataView.byteOffset, dataView.byteLength); } module.exports = cloneDataView; /***/ }, /* 159 */ /***/ function(module, exports, __webpack_require__) { var addMapEntry = __webpack_require__(160), arrayReduce = __webpack_require__(161), mapToArray = __webpack_require__(162); /** Used to compose bitmasks for cloning. */ var CLONE_DEEP_FLAG = 1; /** * Creates a clone of `map`. * * @private * @param {Object} map The map to clone. * @param {Function} cloneFunc The function to clone values. * @param {boolean} [isDeep] Specify a deep clone. * @returns {Object} Returns the cloned map. */ function cloneMap(map, isDeep, cloneFunc) { var array = isDeep ? cloneFunc(mapToArray(map), CLONE_DEEP_FLAG) : mapToArray(map); return arrayReduce(array, addMapEntry, new map.constructor); } module.exports = cloneMap; /***/ }, /* 160 */ /***/ function(module, exports) { /** * Adds the key-value `pair` to `map`. * * @private * @param {Object} map The map to modify. * @param {Array} pair The key-value pair to add. * @returns {Object} Returns `map`. */ function addMapEntry(map, pair) { // Don't return `map.set` because it's not chainable in IE 11. map.set(pair[0], pair[1]); return map; } module.exports = addMapEntry; /***/ }, /* 161 */ /***/ function(module, exports) { /** * A specialized version of `_.reduce` for arrays without support for * iteratee shorthands. * * @private * @param {Array} [array] The array to iterate over. * @param {Function} iteratee The function invoked per iteration. * @param {*} [accumulator] The initial value. * @param {boolean} [initAccum] Specify using the first element of `array` as * the initial value. * @returns {*} Returns the accumulated value. */ function arrayReduce(array, iteratee, accumulator, initAccum) { var index = -1, length = array == null ? 0 : array.length; if (initAccum && length) { accumulator = array[++index]; } while (++index < length) { accumulator = iteratee(accumulator, array[index], index, array); } return accumulator; } module.exports = arrayReduce; /***/ }, /* 162 */ /***/ function(module, exports) { /** * Converts `map` to its key-value pairs. * * @private * @param {Object} map The map to convert. * @returns {Array} Returns the key-value pairs. */ function mapToArray(map) { var index = -1, result = Array(map.size); map.forEach(function(value, key) { result[++index] = [key, value]; }); return result; } module.exports = mapToArray; /***/ }, /* 163 */ /***/ function(module, exports) { /** Used to match `RegExp` flags from their coerced string values. */ var reFlags = /\w*$/; /** * Creates a clone of `regexp`. * * @private * @param {Object} regexp The regexp to clone. * @returns {Object} Returns the cloned regexp. */ function cloneRegExp(regexp) { var result = new regexp.constructor(regexp.source, reFlags.exec(regexp)); result.lastIndex = regexp.lastIndex; return result; } module.exports = cloneRegExp; /***/ }, /* 164 */ /***/ function(module, exports, __webpack_require__) { var addSetEntry = __webpack_require__(165), arrayReduce = __webpack_require__(161), setToArray = __webpack_require__(166); /** Used to compose bitmasks for cloning. */ var CLONE_DEEP_FLAG = 1; /** * Creates a clone of `set`. * * @private * @param {Object} set The set to clone. * @param {Function} cloneFunc The function to clone values. * @param {boolean} [isDeep] Specify a deep clone. * @returns {Object} Returns the cloned set. */ function cloneSet(set, isDeep, cloneFunc) { var array = isDeep ? cloneFunc(setToArray(set), CLONE_DEEP_FLAG) : setToArray(set); return arrayReduce(array, addSetEntry, new set.constructor); } module.exports = cloneSet; /***/ }, /* 165 */ /***/ function(module, exports) { /** * Adds `value` to `set`. * * @private * @param {Object} set The set to modify. * @param {*} value The value to add. * @returns {Object} Returns `set`. */ function addSetEntry(set, value) { // Don't return `set.add` because it's not chainable in IE 11. set.add(value); return set; } module.exports = addSetEntry; /***/ }, /* 166 */ /***/ function(module, exports) { /** * Converts `set` to an array of its values. * * @private * @param {Object} set The set to convert. * @returns {Array} Returns the values. */ function setToArray(set) { var index = -1, result = Array(set.size); set.forEach(function(value) { result[++index] = value; }); return result; } module.exports = setToArray; /***/ }, /* 167 */ /***/ function(module, exports, __webpack_require__) { var Symbol = __webpack_require__(21); /** Used to convert symbols to primitives and strings. */ var symbolProto = Symbol ? Symbol.prototype : undefined, symbolValueOf = symbolProto ? symbolProto.valueOf : undefined; /** * Creates a clone of the `symbol` object. * * @private * @param {Object} symbol The symbol object to clone. * @returns {Object} Returns the cloned symbol object. */ function cloneSymbol(symbol) { return symbolValueOf ? Object(symbolValueOf.call(symbol)) : {}; } module.exports = cloneSymbol; /***/ }, /* 168 */ /***/ function(module, exports, __webpack_require__) { var cloneArrayBuffer = __webpack_require__(156); /** * Creates a clone of `typedArray`. * * @private * @param {Object} typedArray The typed array to clone. * @param {boolean} [isDeep] Specify a deep clone. * @returns {Object} Returns the cloned typed array. */ function cloneTypedArray(typedArray, isDeep) { var buffer = isDeep ? cloneArrayBuffer(typedArray.buffer) : typedArray.buffer; return new typedArray.constructor(buffer, typedArray.byteOffset, typedArray.length); } module.exports = cloneTypedArray; /***/ }, /* 169 */ /***/ function(module, exports, __webpack_require__) { var baseCreate = __webpack_require__(33), getPrototype = __webpack_require__(146), isPrototype = __webpack_require__(99); /** * Initializes an object clone. * * @private * @param {Object} object The object to clone. * @returns {Object} Returns the initialized clone. */ function initCloneObject(object) { return (typeof object.constructor == 'function' && !isPrototype(object)) ? baseCreate(getPrototype(object)) : {}; } module.exports = initCloneObject; /***/ }, /* 170 */ /***/ function(module, exports, __webpack_require__) { var createWrap = __webpack_require__(12); /** Used to compose bitmasks for function metadata. */ var WRAP_CURRY_FLAG = 8; /** * Creates a function that accepts arguments of `func` and either invokes * `func` returning its result, if at least `arity` number of arguments have * been provided, or returns a function that accepts the remaining `func` * arguments, and so on. The arity of `func` may be specified if `func.length` * is not sufficient. * * The `_.curry.placeholder` value, which defaults to `_` in monolithic builds, * may be used as a placeholder for provided arguments. * * **Note:** This method doesn't set the "length" property of curried functions. * * @static * @memberOf _ * @since 2.0.0 * @category Function * @param {Function} func The function to curry. * @param {number} [arity=func.length] The arity of `func`. * @param- {Object} [guard] Enables use as an iteratee for methods like `_.map`. * @returns {Function} Returns the new curried function. * @example * * var abc = function(a, b, c) { * return [a, b, c]; * }; * * var curried = _.curry(abc); * * curried(1)(2)(3); * // => [1, 2, 3] * * curried(1, 2)(3); * // => [1, 2, 3] * * curried(1, 2, 3); * // => [1, 2, 3] * * // Curried with placeholders. * curried(1)(_, 3)(2); * // => [1, 2, 3] */ function curry(func, arity, guard) { arity = guard ? undefined : arity; var result = createWrap(func, WRAP_CURRY_FLAG, undefined, undefined, undefined, undefined, undefined, arity); result.placeholder = curry.placeholder; return result; } // Assign default placeholders. curry.placeholder = {}; module.exports = curry; /***/ }, /* 171 */ /***/ function(module, exports, __webpack_require__) { var baseClone = __webpack_require__(104), baseIteratee = __webpack_require__(172); /** Used to compose bitmasks for cloning. */ var CLONE_DEEP_FLAG = 1; /** * Creates a function that invokes `func` with the arguments of the created * function. If `func` is a property name, the created function returns the * property value for a given element. If `func` is an array or object, the * created function returns `true` for elements that contain the equivalent * source properties, otherwise it returns `false`. * * @static * @since 4.0.0 * @memberOf _ * @category Util * @param {*} [func=_.identity] The value to convert to a callback. * @returns {Function} Returns the callback. * @example * * var users = [ * { 'user': 'barney', 'age': 36, 'active': true }, * { 'user': 'fred', 'age': 40, 'active': false } * ]; * * // The `_.matches` iteratee shorthand. * _.filter(users, _.iteratee({ 'user': 'barney', 'active': true })); * // => [{ 'user': 'barney', 'age': 36, 'active': true }] * * // The `_.matchesProperty` iteratee shorthand. * _.filter(users, _.iteratee(['user', 'fred'])); * // => [{ 'user': 'fred', 'age': 40 }] * * // The `_.property` iteratee shorthand. * _.map(users, _.iteratee('user')); * // => ['barney', 'fred'] * * // Create custom iteratee shorthands. * _.iteratee = _.wrap(_.iteratee, function(iteratee, func) { * return !_.isRegExp(func) ? iteratee(func) : function(string) { * return func.test(string); * }; * }); * * _.filter(['abc', 'def'], /ef/); * // => ['def'] */ function iteratee(func) { return baseIteratee(typeof func == 'function' ? func : baseClone(func, CLONE_DEEP_FLAG)); } module.exports = iteratee; /***/ }, /* 172 */ /***/ function(module, exports, __webpack_require__) { var baseMatches = __webpack_require__(173), baseMatchesProperty = __webpack_require__(188), identity = __webpack_require__(14), isArray = __webpack_require__(50), property = __webpack_require__(203); /** * The base implementation of `_.iteratee`. * * @private * @param {*} [value=_.identity] The value to convert to an iteratee. * @returns {Function} Returns the iteratee. */ function baseIteratee(value) { // Don't store the `typeof` result in a variable to avoid a JIT bug in Safari 9. // See https://bugs.webkit.org/show_bug.cgi?id=156034 for more details. if (typeof value == 'function') { return value; } if (value == null) { return identity; } if (typeof value == 'object') { return isArray(value) ? baseMatchesProperty(value[0], value[1]) : baseMatches(value); } return property(value); } module.exports = baseIteratee; /***/ }, /* 173 */ /***/ function(module, exports, __webpack_require__) { var baseIsMatch = __webpack_require__(174), getMatchData = __webpack_require__(185), matchesStrictComparable = __webpack_require__(187); /** * The base implementation of `_.matches` which doesn't clone `source`. * * @private * @param {Object} source The object of property values to match. * @returns {Function} Returns the new spec function. */ function baseMatches(source) { var matchData = getMatchData(source); if (matchData.length == 1 && matchData[0][2]) { return matchesStrictComparable(matchData[0][0], matchData[0][1]); } return function(object) { return object === source || baseIsMatch(object, source, matchData); }; } module.exports = baseMatches; /***/ }, /* 174 */ /***/ function(module, exports, __webpack_require__) { var Stack = __webpack_require__(105), baseIsEqual = __webpack_require__(175); /** Used to compose bitmasks for value comparisons. */ var COMPARE_PARTIAL_FLAG = 1, COMPARE_UNORDERED_FLAG = 2; /** * The base implementation of `_.isMatch` without support for iteratee shorthands. * * @private * @param {Object} object The object to inspect. * @param {Object} source The object of property values to match. * @param {Array} matchData The property names, values, and compare flags to match. * @param {Function} [customizer] The function to customize comparisons. * @returns {boolean} Returns `true` if `object` is a match, else `false`. */ function baseIsMatch(object, source, matchData, customizer) { var index = matchData.length, length = index, noCustomizer = !customizer; if (object == null) { return !length; } object = Object(object); while (index--) { var data = matchData[index]; if ((noCustomizer && data[2]) ? data[1] !== object[data[0]] : !(data[0] in object) ) { return false; } } while (++index < length) { data = matchData[index]; var key = data[0], objValue = object[key], srcValue = data[1]; if (noCustomizer && data[2]) { if (objValue === undefined && !(key in object)) { return false; } } else { var stack = new Stack; if (customizer) { var result = customizer(objValue, srcValue, key, object, source, stack); } if (!(result === undefined ? baseIsEqual(srcValue, objValue, COMPARE_PARTIAL_FLAG | COMPARE_UNORDERED_FLAG, customizer, stack) : result )) { return false; } } } return true; } module.exports = baseIsMatch; /***/ }, /* 175 */ /***/ function(module, exports, __webpack_require__) { var baseIsEqualDeep = __webpack_require__(176), isObjectLike = __webpack_require__(51); /** * The base implementation of `_.isEqual` which supports partial comparisons * and tracks traversed objects. * * @private * @param {*} value The value to compare. * @param {*} other The other value to compare. * @param {boolean} bitmask The bitmask flags. * 1 - Unordered comparison * 2 - Partial comparison * @param {Function} [customizer] The function to customize comparisons. * @param {Object} [stack] Tracks traversed `value` and `other` objects. * @returns {boolean} Returns `true` if the values are equivalent, else `false`. */ function baseIsEqual(value, other, bitmask, customizer, stack) { if (value === other) { return true; } if (value == null || other == null || (!isObjectLike(value) && !isObjectLike(other))) { return value !== value && other !== other; } return baseIsEqualDeep(value, other, bitmask, customizer, baseIsEqual, stack); } module.exports = baseIsEqual; /***/ }, /* 176 */ /***/ function(module, exports, __webpack_require__) { var Stack = __webpack_require__(105), equalArrays = __webpack_require__(177), equalByTag = __webpack_require__(183), equalObjects = __webpack_require__(184), getTag = __webpack_require__(150), isArray = __webpack_require__(50), isBuffer = __webpack_require__(90), isTypedArray = __webpack_require__(93); /** Used to compose bitmasks for value comparisons. */ var COMPARE_PARTIAL_FLAG = 1; /** `Object#toString` result references. */ var argsTag = '[object Arguments]', arrayTag = '[object Array]', objectTag = '[object Object]'; /** Used for built-in method references. */ var objectProto = Object.prototype; /** Used to check objects for own properties. */ var hasOwnProperty = objectProto.hasOwnProperty; /** * A specialized version of `baseIsEqual` for arrays and objects which performs * deep comparisons and tracks traversed objects enabling objects with circular * references to be compared. * * @private * @param {Object} object The object to compare. * @param {Object} other The other object to compare. * @param {number} bitmask The bitmask flags. See `baseIsEqual` for more details. * @param {Function} customizer The function to customize comparisons. * @param {Function} equalFunc The function to determine equivalents of values. * @param {Object} [stack] Tracks traversed `object` and `other` objects. * @returns {boolean} Returns `true` if the objects are equivalent, else `false`. */ function baseIsEqualDeep(object, other, bitmask, customizer, equalFunc, stack) { var objIsArr = isArray(object), othIsArr = isArray(other), objTag = objIsArr ? arrayTag : getTag(object), othTag = othIsArr ? arrayTag : getTag(other); objTag = objTag == argsTag ? objectTag : objTag; othTag = othTag == argsTag ? objectTag : othTag; var objIsObj = objTag == objectTag, othIsObj = othTag == objectTag, isSameTag = objTag == othTag; if (isSameTag && isBuffer(object)) { if (!isBuffer(other)) { return false; } objIsArr = true; objIsObj = false; } if (isSameTag && !objIsObj) { stack || (stack = new Stack); return (objIsArr || isTypedArray(object)) ? equalArrays(object, other, bitmask, customizer, equalFunc, stack) : equalByTag(object, other, objTag, bitmask, customizer, equalFunc, stack); } if (!(bitmask & COMPARE_PARTIAL_FLAG)) { var objIsWrapped = objIsObj && hasOwnProperty.call(object, '__wrapped__'), othIsWrapped = othIsObj && hasOwnProperty.call(other, '__wrapped__'); if (objIsWrapped || othIsWrapped) { var objUnwrapped = objIsWrapped ? object.value() : object, othUnwrapped = othIsWrapped ? other.value() : other; stack || (stack = new Stack); return equalFunc(objUnwrapped, othUnwrapped, bitmask, customizer, stack); } } if (!isSameTag) { return false; } stack || (stack = new Stack); return equalObjects(object, other, bitmask, customizer, equalFunc, stack); } module.exports = baseIsEqualDeep; /***/ }, /* 177 */ /***/ function(module, exports, __webpack_require__) { var SetCache = __webpack_require__(178), arraySome = __webpack_require__(181), cacheHas = __webpack_require__(182); /** Used to compose bitmasks for value comparisons. */ var COMPARE_PARTIAL_FLAG = 1, COMPARE_UNORDERED_FLAG = 2; /** * A specialized version of `baseIsEqualDeep` for arrays with support for * partial deep comparisons. * * @private * @param {Array} array The array to compare. * @param {Array} other The other array to compare. * @param {number} bitmask The bitmask flags. See `baseIsEqual` for more details. * @param {Function} customizer The function to customize comparisons. * @param {Function} equalFunc The function to determine equivalents of values. * @param {Object} stack Tracks traversed `array` and `other` objects. * @returns {boolean} Returns `true` if the arrays are equivalent, else `false`. */ function equalArrays(array, other, bitmask, customizer, equalFunc, stack) { var isPartial = bitmask & COMPARE_PARTIAL_FLAG, arrLength = array.length, othLength = other.length; if (arrLength != othLength && !(isPartial && othLength > arrLength)) { return false; } // Assume cyclic values are equal. var stacked = stack.get(array); if (stacked && stack.get(other)) { return stacked == other; } var index = -1, result = true, seen = (bitmask & COMPARE_UNORDERED_FLAG) ? new SetCache : undefined; stack.set(array, other); stack.set(other, array); // Ignore non-index properties. while (++index < arrLength) { var arrValue = array[index], othValue = other[index]; if (customizer) { var compared = isPartial ? customizer(othValue, arrValue, index, other, array, stack) : customizer(arrValue, othValue, index, array, other, stack); } if (compared !== undefined) { if (compared) { continue; } result = false; break; } // Recursively compare arrays (susceptible to call stack limits). if (seen) { if (!arraySome(other, function(othValue, othIndex) { if (!cacheHas(seen, othIndex) && (arrValue === othValue || equalFunc(arrValue, othValue, bitmask, customizer, stack))) { return seen.push(othIndex); } })) { result = false; break; } } else if (!( arrValue === othValue || equalFunc(arrValue, othValue, bitmask, customizer, stack) )) { result = false; break; } } stack['delete'](array); stack['delete'](other); return result; } module.exports = equalArrays; /***/ }, /* 178 */ /***/ function(module, exports, __webpack_require__) { var MapCache = __webpack_require__(119), setCacheAdd = __webpack_require__(179), setCacheHas = __webpack_require__(180); /** * * Creates an array cache object to store unique values. * * @private * @constructor * @param {Array} [values] The values to cache. */ function SetCache(values) { var index = -1, length = values == null ? 0 : values.length; this.__data__ = new MapCache; while (++index < length) { this.add(values[index]); } } // Add methods to `SetCache`. SetCache.prototype.add = SetCache.prototype.push = setCacheAdd; SetCache.prototype.has = setCacheHas; module.exports = SetCache; /***/ }, /* 179 */ /***/ function(module, exports) { /** Used to stand-in for `undefined` hash values. */ var HASH_UNDEFINED = '__lodash_hash_undefined__'; /** * Adds `value` to the array cache. * * @private * @name add * @memberOf SetCache * @alias push * @param {*} value The value to cache. * @returns {Object} Returns the cache instance. */ function setCacheAdd(value) { this.__data__.set(value, HASH_UNDEFINED); return this; } module.exports = setCacheAdd; /***/ }, /* 180 */ /***/ function(module, exports) { /** * Checks if `value` is in the array cache. * * @private * @name has * @memberOf SetCache * @param {*} value The value to search for. * @returns {number} Returns `true` if `value` is found, else `false`. */ function setCacheHas(value) { return this.__data__.has(value); } module.exports = setCacheHas; /***/ }, /* 181 */ /***/ function(module, exports) { /** * A specialized version of `_.some` for arrays without support for iteratee * shorthands. * * @private * @param {Array} [array] The array to iterate over. * @param {Function} predicate The function invoked per iteration. * @returns {boolean} Returns `true` if any element passes the predicate check, * else `false`. */ function arraySome(array, predicate) { var index = -1, length = array == null ? 0 : array.length; while (++index < length) { if (predicate(array[index], index, array)) { return true; } } return false; } module.exports = arraySome; /***/ }, /* 182 */ /***/ function(module, exports) { /** * Checks if a `cache` value for `key` exists. * * @private * @param {Object} cache The cache to query. * @param {string} key The key of the entry to check. * @returns {boolean} Returns `true` if an entry for `key` exists, else `false`. */ function cacheHas(cache, key) { return cache.has(key); } module.exports = cacheHas; /***/ }, /* 183 */ /***/ function(module, exports, __webpack_require__) { var Symbol = __webpack_require__(21), Uint8Array = __webpack_require__(157), eq = __webpack_require__(84), equalArrays = __webpack_require__(177), mapToArray = __webpack_require__(162), setToArray = __webpack_require__(166); /** Used to compose bitmasks for value comparisons. */ var COMPARE_PARTIAL_FLAG = 1, COMPARE_UNORDERED_FLAG = 2; /** `Object#toString` result references. */ var boolTag = '[object Boolean]', dateTag = '[object Date]', errorTag = '[object Error]', mapTag = '[object Map]', numberTag = '[object Number]', regexpTag = '[object RegExp]', setTag = '[object Set]', stringTag = '[object String]', symbolTag = '[object Symbol]'; var arrayBufferTag = '[object ArrayBuffer]', dataViewTag = '[object DataView]'; /** Used to convert symbols to primitives and strings. */ var symbolProto = Symbol ? Symbol.prototype : undefined, symbolValueOf = symbolProto ? symbolProto.valueOf : undefined; /** * A specialized version of `baseIsEqualDeep` for comparing objects of * the same `toStringTag`. * * **Note:** This function only supports comparing values with tags of * `Boolean`, `Date`, `Error`, `Number`, `RegExp`, or `String`. * * @private * @param {Object} object The object to compare. * @param {Object} other The other object to compare. * @param {string} tag The `toStringTag` of the objects to compare. * @param {number} bitmask The bitmask flags. See `baseIsEqual` for more details. * @param {Function} customizer The function to customize comparisons. * @param {Function} equalFunc The function to determine equivalents of values. * @param {Object} stack Tracks traversed `object` and `other` objects. * @returns {boolean} Returns `true` if the objects are equivalent, else `false`. */ function equalByTag(object, other, tag, bitmask, customizer, equalFunc, stack) { switch (tag) { case dataViewTag: if ((object.byteLength != other.byteLength) || (object.byteOffset != other.byteOffset)) { return false; } object = object.buffer; other = other.buffer; case arrayBufferTag: if ((object.byteLength != other.byteLength) || !equalFunc(new Uint8Array(object), new Uint8Array(other))) { return false; } return true; case boolTag: case dateTag: case numberTag: // Coerce booleans to `1` or `0` and dates to milliseconds. // Invalid dates are coerced to `NaN`. return eq(+object, +other); case errorTag: return object.name == other.name && object.message == other.message; case regexpTag: case stringTag: // Coerce regexes to strings and treat strings, primitives and objects, // as equal. See http://www.ecma-international.org/ecma-262/7.0/#sec-regexp.prototype.tostring // for more details. return object == (other + ''); case mapTag: var convert = mapToArray; case setTag: var isPartial = bitmask & COMPARE_PARTIAL_FLAG; convert || (convert = setToArray); if (object.size != other.size && !isPartial) { return false; } // Assume cyclic values are equal. var stacked = stack.get(object); if (stacked) { return stacked == other; } bitmask |= COMPARE_UNORDERED_FLAG; // Recursively compare objects (susceptible to call stack limits). stack.set(object, other); var result = equalArrays(convert(object), convert(other), bitmask, customizer, equalFunc, stack); stack['delete'](object); return result; case symbolTag: if (symbolValueOf) { return symbolValueOf.call(object) == symbolValueOf.call(other); } } return false; } module.exports = equalByTag; /***/ }, /* 184 */ /***/ function(module, exports, __webpack_require__) { var getAllKeys = __webpack_require__(147); /** Used to compose bitmasks for value comparisons. */ var COMPARE_PARTIAL_FLAG = 1; /** Used for built-in method references. */ var objectProto = Object.prototype; /** Used to check objects for own properties. */ var hasOwnProperty = objectProto.hasOwnProperty; /** * A specialized version of `baseIsEqualDeep` for objects with support for * partial deep comparisons. * * @private * @param {Object} object The object to compare. * @param {Object} other The other object to compare. * @param {number} bitmask The bitmask flags. See `baseIsEqual` for more details. * @param {Function} customizer The function to customize comparisons. * @param {Function} equalFunc The function to determine equivalents of values. * @param {Object} stack Tracks traversed `object` and `other` objects. * @returns {boolean} Returns `true` if the objects are equivalent, else `false`. */ function equalObjects(object, other, bitmask, customizer, equalFunc, stack) { var isPartial = bitmask & COMPARE_PARTIAL_FLAG, objProps = getAllKeys(object), objLength = objProps.length, othProps = getAllKeys(other), othLength = othProps.length; if (objLength != othLength && !isPartial) { return false; } var index = objLength; while (index--) { var key = objProps[index]; if (!(isPartial ? key in other : hasOwnProperty.call(other, key))) { return false; } } // Assume cyclic values are equal. var stacked = stack.get(object); if (stacked && stack.get(other)) { return stacked == other; } var result = true; stack.set(object, other); stack.set(other, object); var skipCtor = isPartial; while (++index < objLength) { key = objProps[index]; var objValue = object[key], othValue = other[key]; if (customizer) { var compared = isPartial ? customizer(othValue, objValue, key, other, object, stack) : customizer(objValue, othValue, key, object, other, stack); } // Recursively compare objects (susceptible to call stack limits). if (!(compared === undefined ? (objValue === othValue || equalFunc(objValue, othValue, bitmask, customizer, stack)) : compared )) { result = false; break; } skipCtor || (skipCtor = key == 'constructor'); } if (result && !skipCtor) { var objCtor = object.constructor, othCtor = other.constructor; // Non `Object` object instances with different constructors are not equal. if (objCtor != othCtor && ('constructor' in object && 'constructor' in other) && !(typeof objCtor == 'function' && objCtor instanceof objCtor && typeof othCtor == 'function' && othCtor instanceof othCtor)) { result = false; } } stack['delete'](object); stack['delete'](other); return result; } module.exports = equalObjects; /***/ }, /* 185 */ /***/ function(module, exports, __webpack_require__) { var isStrictComparable = __webpack_require__(186), keys = __webpack_require__(85); /** * Gets the property names, values, and compare flags of `object`. * * @private * @param {Object} object The object to query. * @returns {Array} Returns the match data of `object`. */ function getMatchData(object) { var result = keys(object), length = result.length; while (length--) { var key = result[length], value = object[key]; result[length] = [key, value, isStrictComparable(value)]; } return result; } module.exports = getMatchData; /***/ }, /* 186 */ /***/ function(module, exports, __webpack_require__) { var isObject = __webpack_require__(26); /** * Checks if `value` is suitable for strict equality comparisons, i.e. `===`. * * @private * @param {*} value The value to check. * @returns {boolean} Returns `true` if `value` if suitable for strict * equality comparisons, else `false`. */ function isStrictComparable(value) { return value === value && !isObject(value); } module.exports = isStrictComparable; /***/ }, /* 187 */ /***/ function(module, exports) { /** * A specialized version of `matchesProperty` for source values suitable * for strict equality comparisons, i.e. `===`. * * @private * @param {string} key The key of the property to get. * @param {*} srcValue The value to match. * @returns {Function} Returns the new spec function. */ function matchesStrictComparable(key, srcValue) { return function(object) { if (object == null) { return false; } return object[key] === srcValue && (srcValue !== undefined || (key in Object(object))); }; } module.exports = matchesStrictComparable; /***/ }, /* 188 */ /***/ function(module, exports, __webpack_require__) { var baseIsEqual = __webpack_require__(175), get = __webpack_require__(189), hasIn = __webpack_require__(200), isKey = __webpack_require__(192), isStrictComparable = __webpack_require__(186), matchesStrictComparable = __webpack_require__(187), toKey = __webpack_require__(199); /** Used to compose bitmasks for value comparisons. */ var COMPARE_PARTIAL_FLAG = 1, COMPARE_UNORDERED_FLAG = 2; /** * The base implementation of `_.matchesProperty` which doesn't clone `srcValue`. * * @private * @param {string} path The path of the property to get. * @param {*} srcValue The value to match. * @returns {Function} Returns the new spec function. */ function baseMatchesProperty(path, srcValue) { if (isKey(path) && isStrictComparable(srcValue)) { return matchesStrictComparable(toKey(path), srcValue); } return function(object) { var objValue = get(object, path); return (objValue === undefined && objValue === srcValue) ? hasIn(object, path) : baseIsEqual(srcValue, objValue, COMPARE_PARTIAL_FLAG | COMPARE_UNORDERED_FLAG); }; } module.exports = baseMatchesProperty; /***/ }, /* 189 */ /***/ function(module, exports, __webpack_require__) { var baseGet = __webpack_require__(190); /** * Gets the value at `path` of `object`. If the resolved value is * `undefined`, the `defaultValue` is returned in its place. * * @static * @memberOf _ * @since 3.7.0 * @category Object * @param {Object} object The object to query. * @param {Array|string} path The path of the property to get. * @param {*} [defaultValue] The value returned for `undefined` resolved values. * @returns {*} Returns the resolved value. * @example * * var object = { 'a': [{ 'b': { 'c': 3 } }] }; * * _.get(object, 'a[0].b.c'); * // => 3 * * _.get(object, ['a', '0', 'b', 'c']); * // => 3 * * _.get(object, 'a.b.c', 'default'); * // => 'default' */ function get(object, path, defaultValue) { var result = object == null ? undefined : baseGet(object, path); return result === undefined ? defaultValue : result; } module.exports = get; /***/ }, /* 190 */ /***/ function(module, exports, __webpack_require__) { var castPath = __webpack_require__(191), toKey = __webpack_require__(199); /** * The base implementation of `_.get` without support for default values. * * @private * @param {Object} object The object to query. * @param {Array|string} path The path of the property to get. * @returns {*} Returns the resolved value. */ function baseGet(object, path) { path = castPath(path, object); var index = 0, length = path.length; while (object != null && index < length) { object = object[toKey(path[index++])]; } return (index && index == length) ? object : undefined; } module.exports = baseGet; /***/ }, /* 191 */ /***/ function(module, exports, __webpack_require__) { var isArray = __webpack_require__(50), isKey = __webpack_require__(192), stringToPath = __webpack_require__(193), toString = __webpack_require__(196); /** * Casts `value` to a path array if it's not one. * * @private * @param {*} value The value to inspect. * @param {Object} [object] The object to query keys on. * @returns {Array} Returns the cast property path array. */ function castPath(value, object) { if (isArray(value)) { return value; } return isKey(value, object) ? [value] : stringToPath(toString(value)); } module.exports = castPath; /***/ }, /* 192 */ /***/ function(module, exports, __webpack_require__) { var isArray = __webpack_require__(50), isSymbol = __webpack_require__(79); /** Used to match property names within property paths. */ var reIsDeepProp = /\.|\[(?:[^[\]]*|(["'])(?:(?!\1)[^\\]|\\.)*?\1)\]/, reIsPlainProp = /^\w*$/; /** * Checks if `value` is a property name and not a property path. * * @private * @param {*} value The value to check. * @param {Object} [object] The object to query keys on. * @returns {boolean} Returns `true` if `value` is a property name, else `false`. */ function isKey(value, object) { if (isArray(value)) { return false; } var type = typeof value; if (type == 'number' || type == 'symbol' || type == 'boolean' || value == null || isSymbol(value)) { return true; } return reIsPlainProp.test(value) || !reIsDeepProp.test(value) || (object != null && value in Object(object)); } module.exports = isKey; /***/ }, /* 193 */ /***/ function(module, exports, __webpack_require__) { var memoizeCapped = __webpack_require__(194); /** Used to match property names within property paths. */ var reLeadingDot = /^\./, rePropName = /[^.[\]]+|\[(?:(-?\d+(?:\.\d+)?)|(["'])((?:(?!\2)[^\\]|\\.)*?)\2)\]|(?=(?:\.|\[\])(?:\.|\[\]|$))/g; /** Used to match backslashes in property paths. */ var reEscapeChar = /\\(\\)?/g; /** * Converts `string` to a property path array. * * @private * @param {string} string The string to convert. * @returns {Array} Returns the property path array. */ var stringToPath = memoizeCapped(function(string) { var result = []; if (reLeadingDot.test(string)) { result.push(''); } string.replace(rePropName, function(match, number, quote, string) { result.push(quote ? string.replace(reEscapeChar, '$1') : (number || match)); }); return result; }); module.exports = stringToPath; /***/ }, /* 194 */ /***/ function(module, exports, __webpack_require__) { var memoize = __webpack_require__(195); /** Used as the maximum memoize cache size. */ var MAX_MEMOIZE_SIZE = 500; /** * A specialized version of `_.memoize` which clears the memoized function's * cache when it exceeds `MAX_MEMOIZE_SIZE`. * * @private * @param {Function} func The function to have its output memoized. * @returns {Function} Returns the new memoized function. */ function memoizeCapped(func) { var result = memoize(func, function(key) { if (cache.size === MAX_MEMOIZE_SIZE) { cache.clear(); } return key; }); var cache = result.cache; return result; } module.exports = memoizeCapped; /***/ }, /* 195 */ /***/ function(module, exports, __webpack_require__) { var MapCache = __webpack_require__(119); /** Error message constants. */ var FUNC_ERROR_TEXT = 'Expected a function'; /** * Creates a function that memoizes the result of `func`. If `resolver` is * provided, it determines the cache key for storing the result based on the * arguments provided to the memoized function. By default, the first argument * provided to the memoized function is used as the map cache key. The `func` * is invoked with the `this` binding of the memoized function. * * **Note:** The cache is exposed as the `cache` property on the memoized * function. Its creation may be customized by replacing the `_.memoize.Cache` * constructor with one whose instances implement the * [`Map`](http://ecma-international.org/ecma-262/7.0/#sec-properties-of-the-map-prototype-object) * method interface of `clear`, `delete`, `get`, `has`, and `set`. * * @static * @memberOf _ * @since 0.1.0 * @category Function * @param {Function} func The function to have its output memoized. * @param {Function} [resolver] The function to resolve the cache key. * @returns {Function} Returns the new memoized function. * @example * * var object = { 'a': 1, 'b': 2 }; * var other = { 'c': 3, 'd': 4 }; * * var values = _.memoize(_.values); * values(object); * // => [1, 2] * * values(other); * // => [3, 4] * * object.a = 2; * values(object); * // => [1, 2] * * // Modify the result cache. * values.cache.set(object, ['a', 'b']); * values(object); * // => ['a', 'b'] * * // Replace `_.memoize.Cache`. * _.memoize.Cache = WeakMap; */ function memoize(func, resolver) { if (typeof func != 'function' || (resolver != null && typeof resolver != 'function')) { throw new TypeError(FUNC_ERROR_TEXT); } var memoized = function() { var args = arguments, key = resolver ? resolver.apply(this, args) : args[0], cache = memoized.cache; if (cache.has(key)) { return cache.get(key); } var result = func.apply(this, args); memoized.cache = cache.set(key, result) || cache; return result; }; memoized.cache = new (memoize.Cache || MapCache); return memoized; } // Expose `MapCache`. memoize.Cache = MapCache; module.exports = memoize; /***/ }, /* 196 */ /***/ function(module, exports, __webpack_require__) { var baseToString = __webpack_require__(197); /** * Converts `value` to a string. An empty string is returned for `null` * and `undefined` values. The sign of `-0` is preserved. * * @static * @memberOf _ * @since 4.0.0 * @category Lang * @param {*} value The value to convert. * @returns {string} Returns the converted string. * @example * * _.toString(null); * // => '' * * _.toString(-0); * // => '-0' * * _.toString([1, 2, 3]); * // => '1,2,3' */ function toString(value) { return value == null ? '' : baseToString(value); } module.exports = toString; /***/ }, /* 197 */ /***/ function(module, exports, __webpack_require__) { var Symbol = __webpack_require__(21), arrayMap = __webpack_require__(198), isArray = __webpack_require__(50), isSymbol = __webpack_require__(79); /** Used as references for various `Number` constants. */ var INFINITY = 1 / 0; /** Used to convert symbols to primitives and strings. */ var symbolProto = Symbol ? Symbol.prototype : undefined, symbolToString = symbolProto ? symbolProto.toString : undefined; /** * The base implementation of `_.toString` which doesn't convert nullish * values to empty strings. * * @private * @param {*} value The value to process. * @returns {string} Returns the string. */ function baseToString(value) { // Exit early for strings to avoid a performance hit in some environments. if (typeof value == 'string') { return value; } if (isArray(value)) { // Recursively convert values (susceptible to call stack limits). return arrayMap(value, baseToString) + ''; } if (isSymbol(value)) { return symbolToString ? symbolToString.call(value) : ''; } var result = (value + ''); return (result == '0' && (1 / value) == -INFINITY) ? '-0' : result; } module.exports = baseToString; /***/ }, /* 198 */ /***/ function(module, exports) { /** * A specialized version of `_.map` for arrays without support for iteratee * shorthands. * * @private * @param {Array} [array] The array to iterate over. * @param {Function} iteratee The function invoked per iteration. * @returns {Array} Returns the new mapped array. */ function arrayMap(array, iteratee) { var index = -1, length = array == null ? 0 : array.length, result = Array(length); while (++index < length) { result[index] = iteratee(array[index], index, array); } return result; } module.exports = arrayMap; /***/ }, /* 199 */ /***/ function(module, exports, __webpack_require__) { var isSymbol = __webpack_require__(79); /** Used as references for various `Number` constants. */ var INFINITY = 1 / 0; /** * Converts `value` to a string key if it's not a string or symbol. * * @private * @param {*} value The value to inspect. * @returns {string|symbol} Returns the key. */ function toKey(value) { if (typeof value == 'string' || isSymbol(value)) { return value; } var result = (value + ''); return (result == '0' && (1 / value) == -INFINITY) ? '-0' : result; } module.exports = toKey; /***/ }, /* 200 */ /***/ function(module, exports, __webpack_require__) { var baseHasIn = __webpack_require__(201), hasPath = __webpack_require__(202); /** * Checks if `path` is a direct or inherited property of `object`. * * @static * @memberOf _ * @since 4.0.0 * @category Object * @param {Object} object The object to query. * @param {Array|string} path The path to check. * @returns {boolean} Returns `true` if `path` exists, else `false`. * @example * * var object = _.create({ 'a': _.create({ 'b': 2 }) }); * * _.hasIn(object, 'a'); * // => true * * _.hasIn(object, 'a.b'); * // => true * * _.hasIn(object, ['a', 'b']); * // => true * * _.hasIn(object, 'b'); * // => false */ function hasIn(object, path) { return object != null && hasPath(object, path, baseHasIn); } module.exports = hasIn; /***/ }, /* 201 */ /***/ function(module, exports) { /** * The base implementation of `_.hasIn` without support for deep paths. * * @private * @param {Object} [object] The object to query. * @param {Array|string} key The key to check. * @returns {boolean} Returns `true` if `key` exists, else `false`. */ function baseHasIn(object, key) { return object != null && key in Object(object); } module.exports = baseHasIn; /***/ }, /* 202 */ /***/ function(module, exports, __webpack_require__) { var castPath = __webpack_require__(191), isArguments = __webpack_require__(88), isArray = __webpack_require__(50), isIndex = __webpack_require__(72), isLength = __webpack_require__(95), toKey = __webpack_require__(199); /** * Checks if `path` exists on `object`. * * @private * @param {Object} object The object to query. * @param {Array|string} path The path to check. * @param {Function} hasFunc The function to check properties. * @returns {boolean} Returns `true` if `path` exists, else `false`. */ function hasPath(object, path, hasFunc) { path = castPath(path, object); var index = -1, length = path.length, result = false; while (++index < length) { var key = toKey(path[index]); if (!(result = object != null && hasFunc(object, key))) { break; } object = object[key]; } if (result || ++index != length) { return result; } length = object == null ? 0 : object.length; return !!length && isLength(length) && isIndex(key, length) && (isArray(object) || isArguments(object)); } module.exports = hasPath; /***/ }, /* 203 */ /***/ function(module, exports, __webpack_require__) { var baseProperty = __webpack_require__(204), basePropertyDeep = __webpack_require__(205), isKey = __webpack_require__(192), toKey = __webpack_require__(199); /** * Creates a function that returns the value at `path` of a given object. * * @static * @memberOf _ * @since 2.4.0 * @category Util * @param {Array|string} path The path of the property to get. * @returns {Function} Returns the new accessor function. * @example * * var objects = [ * { 'a': { 'b': 2 } }, * { 'a': { 'b': 1 } } * ]; * * _.map(objects, _.property('a.b')); * // => [2, 1] * * _.map(_.sortBy(objects, _.property(['a', 'b'])), 'a.b'); * // => [1, 2] */ function property(path) { return isKey(path) ? baseProperty(toKey(path)) : basePropertyDeep(path); } module.exports = property; /***/ }, /* 204 */ /***/ function(module, exports) { /** * The base implementation of `_.property` without support for deep paths. * * @private * @param {string} key The key of the property to get. * @returns {Function} Returns the new accessor function. */ function baseProperty(key) { return function(object) { return object == null ? undefined : object[key]; }; } module.exports = baseProperty; /***/ }, /* 205 */ /***/ function(module, exports, __webpack_require__) { var baseGet = __webpack_require__(190); /** * A specialized version of `baseProperty` which supports deep paths. * * @private * @param {Array|string} path The path of the property to get. * @returns {Function} Returns the new accessor function. */ function basePropertyDeep(path) { return function(object) { return baseGet(object, path); }; } module.exports = basePropertyDeep; /***/ }, /* 206 */ /***/ function(module, exports, __webpack_require__) { var createWrap = __webpack_require__(12), flatRest = __webpack_require__(207); /** Used to compose bitmasks for function metadata. */ var WRAP_REARG_FLAG = 256; /** * Creates a function that invokes `func` with arguments arranged according * to the specified `indexes` where the argument value at the first index is * provided as the first argument, the argument value at the second index is * provided as the second argument, and so on. * * @static * @memberOf _ * @since 3.0.0 * @category Function * @param {Function} func The function to rearrange arguments for. * @param {...(number|number[])} indexes The arranged argument indexes. * @returns {Function} Returns the new function. * @example * * var rearged = _.rearg(function(a, b, c) { * return [a, b, c]; * }, [2, 0, 1]); * * rearged('b', 'c', 'a') * // => ['a', 'b', 'c'] */ var rearg = flatRest(function(func, indexes) { return createWrap(func, WRAP_REARG_FLAG, undefined, undefined, undefined, indexes); }); module.exports = rearg; /***/ }, /* 207 */ /***/ function(module, exports, __webpack_require__) { var flatten = __webpack_require__(208), overRest = __webpack_require__(211), setToString = __webpack_require__(59); /** * A specialized version of `baseRest` which flattens the rest array. * * @private * @param {Function} func The function to apply a rest parameter to. * @returns {Function} Returns the new function. */ function flatRest(func) { return setToString(overRest(func, undefined, flatten), func + ''); } module.exports = flatRest; /***/ }, /* 208 */ /***/ function(module, exports, __webpack_require__) { var baseFlatten = __webpack_require__(209); /** * Flattens `array` a single level deep. * * @static * @memberOf _ * @since 0.1.0 * @category Array * @param {Array} array The array to flatten. * @returns {Array} Returns the new flattened array. * @example * * _.flatten([1, [2, [3, [4]], 5]]); * // => [1, 2, [3, [4]], 5] */ function flatten(array) { var length = array == null ? 0 : array.length; return length ? baseFlatten(array, 1) : []; } module.exports = flatten; /***/ }, /* 209 */ /***/ function(module, exports, __webpack_require__) { var arrayPush = __webpack_require__(145), isFlattenable = __webpack_require__(210); /** * The base implementation of `_.flatten` with support for restricting flattening. * * @private * @param {Array} array The array to flatten. * @param {number} depth The maximum recursion depth. * @param {boolean} [predicate=isFlattenable] The function invoked per iteration. * @param {boolean} [isStrict] Restrict to values that pass `predicate` checks. * @param {Array} [result=[]] The initial result value. * @returns {Array} Returns the new flattened array. */ function baseFlatten(array, depth, predicate, isStrict, result) { var index = -1, length = array.length; predicate || (predicate = isFlattenable); result || (result = []); while (++index < length) { var value = array[index]; if (depth > 0 && predicate(value)) { if (depth > 1) { // Recursively flatten arrays (susceptible to call stack limits). baseFlatten(value, depth - 1, predicate, isStrict, result); } else { arrayPush(result, value); } } else if (!isStrict) { result[result.length] = value; } } return result; } module.exports = baseFlatten; /***/ }, /* 210 */ /***/ function(module, exports, __webpack_require__) { var Symbol = __webpack_require__(21), isArguments = __webpack_require__(88), isArray = __webpack_require__(50); /** Built-in value references. */ var spreadableSymbol = Symbol ? Symbol.isConcatSpreadable : undefined; /** * Checks if `value` is a flattenable `arguments` object or array. * * @private * @param {*} value The value to check. * @returns {boolean} Returns `true` if `value` is flattenable, else `false`. */ function isFlattenable(value) { return isArray(value) || isArguments(value) || !!(spreadableSymbol && value && value[spreadableSymbol]); } module.exports = isFlattenable; /***/ }, /* 211 */ /***/ function(module, exports, __webpack_require__) { var apply = __webpack_require__(35); /* Built-in method references for those with the same name as other `lodash` methods. */ var nativeMax = Math.max; /** * A specialized version of `baseRest` which transforms the rest array. * * @private * @param {Function} func The function to apply a rest parameter to. * @param {number} [start=func.length-1] The start position of the rest parameter. * @param {Function} transform The rest array transform. * @returns {Function} Returns the new function. */ function overRest(func, start, transform) { start = nativeMax(start === undefined ? (func.length - 1) : start, 0); return function() { var args = arguments, index = -1, length = nativeMax(args.length - start, 0), array = Array(length); while (++index < length) { array[index] = args[start + index]; } index = -1; var otherArgs = Array(start + 1); while (++index < start) { otherArgs[index] = args[index]; } otherArgs[start] = transform(array); return apply(func, this, otherArgs); }; } module.exports = overRest; /***/ }, /* 212 */ /***/ function(module, exports, __webpack_require__) { var arrayMap = __webpack_require__(198), copyArray = __webpack_require__(53), isArray = __webpack_require__(50), isSymbol = __webpack_require__(79), stringToPath = __webpack_require__(193), toKey = __webpack_require__(199), toString = __webpack_require__(196); /** * Converts `value` to a property path array. * * @static * @memberOf _ * @since 4.0.0 * @category Util * @param {*} value The value to convert. * @returns {Array} Returns the new property path array. * @example * * _.toPath('a.b.c'); * // => ['a', 'b', 'c'] * * _.toPath('a[0].b.c'); * // => ['a', '0', 'b', 'c'] */ function toPath(value) { if (isArray(value)) { return arrayMap(value, toKey); } return isSymbol(value) ? [value] : copyArray(stringToPath(toString(value))); } module.exports = toPath; /***/ }, /* 213 */ /***/ function(module, exports, __webpack_require__) { var baseMerge = __webpack_require__(214), createAssigner = __webpack_require__(222); /** * This method is like `_.assign` except that it recursively merges own and * inherited enumerable string keyed properties of source objects into the * destination object. Source properties that resolve to `undefined` are * skipped if a destination value exists. Array and plain object properties * are merged recursively. Other objects and value types are overridden by * assignment. Source objects are applied from left to right. Subsequent * sources overwrite property assignments of previous sources. * * **Note:** This method mutates `object`. * * @static * @memberOf _ * @since 0.5.0 * @category Object * @param {Object} object The destination object. * @param {...Object} [sources] The source objects. * @returns {Object} Returns `object`. * @example * * var object = { * 'a': [{ 'b': 2 }, { 'd': 4 }] * }; * * var other = { * 'a': [{ 'c': 3 }, { 'e': 5 }] * }; * * _.merge(object, other); * // => { 'a': [{ 'b': 2, 'c': 3 }, { 'd': 4, 'e': 5 }] } */ var merge = createAssigner(function(object, source, srcIndex) { baseMerge(object, source, srcIndex); }); module.exports = merge; /***/ }, /* 214 */ /***/ function(module, exports, __webpack_require__) { var Stack = __webpack_require__(105), assignMergeValue = __webpack_require__(215), baseFor = __webpack_require__(216), baseMergeDeep = __webpack_require__(218), isObject = __webpack_require__(26), keysIn = __webpack_require__(135); /** * The base implementation of `_.merge` without support for multiple sources. * * @private * @param {Object} object The destination object. * @param {Object} source The source object. * @param {number} srcIndex The index of `source`. * @param {Function} [customizer] The function to customize merged values. * @param {Object} [stack] Tracks traversed source values and their merged * counterparts. */ function baseMerge(object, source, srcIndex, customizer, stack) { if (object === source) { return; } baseFor(source, function(srcValue, key) { if (isObject(srcValue)) { stack || (stack = new Stack); baseMergeDeep(object, source, key, srcIndex, baseMerge, customizer, stack); } else { var newValue = customizer ? customizer(object[key], srcValue, (key + ''), object, source, stack) : undefined; if (newValue === undefined) { newValue = srcValue; } assignMergeValue(object, key, newValue); } }, keysIn); } module.exports = baseMerge; /***/ }, /* 215 */ /***/ function(module, exports, __webpack_require__) { var baseAssignValue = __webpack_require__(83), eq = __webpack_require__(84); /** * This function is like `assignValue` except that it doesn't assign * `undefined` values. * * @private * @param {Object} object The object to modify. * @param {string} key The key of the property to assign. * @param {*} value The value to assign. */ function assignMergeValue(object, key, value) { if ((value !== undefined && !eq(object[key], value)) || (value === undefined && !(key in object))) { baseAssignValue(object, key, value); } } module.exports = assignMergeValue; /***/ }, /* 216 */ /***/ function(module, exports, __webpack_require__) { var createBaseFor = __webpack_require__(217); /** * The base implementation of `baseForOwn` which iterates over `object` * properties returned by `keysFunc` and invokes `iteratee` for each property. * Iteratee functions may exit iteration early by explicitly returning `false`. * * @private * @param {Object} object The object to iterate over. * @param {Function} iteratee The function invoked per iteration. * @param {Function} keysFunc The function to get the keys of `object`. * @returns {Object} Returns `object`. */ var baseFor = createBaseFor(); module.exports = baseFor; /***/ }, /* 217 */ /***/ function(module, exports) { /** * Creates a base function for methods like `_.forIn` and `_.forOwn`. * * @private * @param {boolean} [fromRight] Specify iterating from right to left. * @returns {Function} Returns the new base function. */ function createBaseFor(fromRight) { return function(object, iteratee, keysFunc) { var index = -1, iterable = Object(object), props = keysFunc(object), length = props.length; while (length--) { var key = props[fromRight ? length : ++index]; if (iteratee(iterable[key], key, iterable) === false) { break; } } return object; }; } module.exports = createBaseFor; /***/ }, /* 218 */ /***/ function(module, exports, __webpack_require__) { var assignMergeValue = __webpack_require__(215), cloneBuffer = __webpack_require__(138), cloneTypedArray = __webpack_require__(168), copyArray = __webpack_require__(53), initCloneObject = __webpack_require__(169), isArguments = __webpack_require__(88), isArray = __webpack_require__(50), isArrayLikeObject = __webpack_require__(219), isBuffer = __webpack_require__(90), isFunction = __webpack_require__(19), isObject = __webpack_require__(26), isPlainObject = __webpack_require__(220), isTypedArray = __webpack_require__(93), toPlainObject = __webpack_require__(221); /** * A specialized version of `baseMerge` for arrays and objects which performs * deep merges and tracks traversed objects enabling objects with circular * references to be merged. * * @private * @param {Object} object The destination object. * @param {Object} source The source object. * @param {string} key The key of the value to merge. * @param {number} srcIndex The index of `source`. * @param {Function} mergeFunc The function to merge values. * @param {Function} [customizer] The function to customize assigned values. * @param {Object} [stack] Tracks traversed source values and their merged * counterparts. */ function baseMergeDeep(object, source, key, srcIndex, mergeFunc, customizer, stack) { var objValue = object[key], srcValue = source[key], stacked = stack.get(srcValue); if (stacked) { assignMergeValue(object, key, stacked); return; } var newValue = customizer ? customizer(objValue, srcValue, (key + ''), object, source, stack) : undefined; var isCommon = newValue === undefined; if (isCommon) { var isArr = isArray(srcValue), isBuff = !isArr && isBuffer(srcValue), isTyped = !isArr && !isBuff && isTypedArray(srcValue); newValue = srcValue; if (isArr || isBuff || isTyped) { if (isArray(objValue)) { newValue = objValue; } else if (isArrayLikeObject(objValue)) { newValue = copyArray(objValue); } else if (isBuff) { isCommon = false; newValue = cloneBuffer(srcValue, true); } else if (isTyped) { isCommon = false; newValue = cloneTypedArray(srcValue, true); } else { newValue = []; } } else if (isPlainObject(srcValue) || isArguments(srcValue)) { newValue = objValue; if (isArguments(objValue)) { newValue = toPlainObject(objValue); } else if (!isObject(objValue) || (srcIndex && isFunction(objValue))) { newValue = initCloneObject(srcValue); } } else { isCommon = false; } } if (isCommon) { // Recursively merge objects and arrays (susceptible to call stack limits). stack.set(srcValue, newValue); mergeFunc(newValue, srcValue, srcIndex, customizer, stack); stack['delete'](srcValue); } assignMergeValue(object, key, newValue); } module.exports = baseMergeDeep; /***/ }, /* 219 */ /***/ function(module, exports, __webpack_require__) { var isArrayLike = __webpack_require__(102), isObjectLike = __webpack_require__(51); /** * This method is like `_.isArrayLike` except that it also checks if `value` * is an object. * * @static * @memberOf _ * @since 4.0.0 * @category Lang * @param {*} value The value to check. * @returns {boolean} Returns `true` if `value` is an array-like object, * else `false`. * @example * * _.isArrayLikeObject([1, 2, 3]); * // => true * * _.isArrayLikeObject(document.body.children); * // => true * * _.isArrayLikeObject('abc'); * // => false * * _.isArrayLikeObject(_.noop); * // => false */ function isArrayLikeObject(value) { return isObjectLike(value) && isArrayLike(value); } module.exports = isArrayLikeObject; /***/ }, /* 220 */ /***/ function(module, exports, __webpack_require__) { var baseGetTag = __webpack_require__(20), getPrototype = __webpack_require__(146), isObjectLike = __webpack_require__(51); /** `Object#toString` result references. */ var objectTag = '[object Object]'; /** Used for built-in method references. */ var funcProto = Function.prototype, objectProto = Object.prototype; /** Used to resolve the decompiled source of functions. */ var funcToString = funcProto.toString; /** Used to check objects for own properties. */ var hasOwnProperty = objectProto.hasOwnProperty; /** Used to infer the `Object` constructor. */ var objectCtorString = funcToString.call(Object); /** * Checks if `value` is a plain object, that is, an object created by the * `Object` constructor or one with a `[[Prototype]]` of `null`. * * @static * @memberOf _ * @since 0.8.0 * @category Lang * @param {*} value The value to check. * @returns {boolean} Returns `true` if `value` is a plain object, else `false`. * @example * * function Foo() { * this.a = 1; * } * * _.isPlainObject(new Foo); * // => false * * _.isPlainObject([1, 2, 3]); * // => false * * _.isPlainObject({ 'x': 0, 'y': 0 }); * // => true * * _.isPlainObject(Object.create(null)); * // => true */ function isPlainObject(value) { if (!isObjectLike(value) || baseGetTag(value) != objectTag) { return false; } var proto = getPrototype(value); if (proto === null) { return true; } var Ctor = hasOwnProperty.call(proto, 'constructor') && proto.constructor; return typeof Ctor == 'function' && Ctor instanceof Ctor && funcToString.call(Ctor) == objectCtorString; } module.exports = isPlainObject; /***/ }, /* 221 */ /***/ function(module, exports, __webpack_require__) { var copyObject = __webpack_require__(81), keysIn = __webpack_require__(135); /** * Converts `value` to a plain object flattening inherited enumerable string * keyed properties of `value` to own properties of the plain object. * * @static * @memberOf _ * @since 3.0.0 * @category Lang * @param {*} value The value to convert. * @returns {Object} Returns the converted plain object. * @example * * function Foo() { * this.b = 2; * } * * Foo.prototype.c = 3; * * _.assign({ 'a': 1 }, new Foo); * // => { 'a': 1, 'b': 2 } * * _.assign({ 'a': 1 }, _.toPlainObject(new Foo)); * // => { 'a': 1, 'b': 2, 'c': 3 } */ function toPlainObject(value) { return copyObject(value, keysIn(value)); } module.exports = toPlainObject; /***/ }, /* 222 */ /***/ function(module, exports, __webpack_require__) { var baseRest = __webpack_require__(223), isIterateeCall = __webpack_require__(224); /** * Creates a function like `_.assign`. * * @private * @param {Function} assigner The function to assign values. * @returns {Function} Returns the new assigner function. */ function createAssigner(assigner) { return baseRest(function(object, sources) { var index = -1, length = sources.length, customizer = length > 1 ? sources[length - 1] : undefined, guard = length > 2 ? sources[2] : undefined; customizer = (assigner.length > 3 && typeof customizer == 'function') ? (length--, customizer) : undefined; if (guard && isIterateeCall(sources[0], sources[1], guard)) { customizer = length < 3 ? undefined : customizer; length = 1; } object = Object(object); while (++index < length) { var source = sources[index]; if (source) { assigner(object, source, index, customizer); } } return object; }); } module.exports = createAssigner; /***/ }, /* 223 */ /***/ function(module, exports, __webpack_require__) { var identity = __webpack_require__(14), overRest = __webpack_require__(211), setToString = __webpack_require__(59); /** * The base implementation of `_.rest` which doesn't validate or coerce arguments. * * @private * @param {Function} func The function to apply a rest parameter to. * @param {number} [start=func.length-1] The start position of the rest parameter. * @returns {Function} Returns the new function. */ function baseRest(func, start) { return setToString(overRest(func, start, identity), func + ''); } module.exports = baseRest; /***/ }, /* 224 */ /***/ function(module, exports, __webpack_require__) { var eq = __webpack_require__(84), isArrayLike = __webpack_require__(102), isIndex = __webpack_require__(72), isObject = __webpack_require__(26); /** * Checks if the given arguments are from an iteratee call. * * @private * @param {*} value The potential iteratee value argument. * @param {*} index The potential iteratee index or key argument. * @param {*} object The potential iteratee object argument. * @returns {boolean} Returns `true` if the arguments are from an iteratee call, * else `false`. */ function isIterateeCall(value, index, object) { if (!isObject(object)) { return false; } var type = typeof index; if (type == 'number' ? (isArrayLike(object) && isIndex(index, object.length)) : (type == 'string' && index in object) ) { return eq(object[index], value); } return false; } module.exports = isIterateeCall; /***/ }, /* 225 */ /***/ function(module, exports, __webpack_require__) { 'use strict'; Object.defineProperty(exports, "__esModule", { value: true }); var _vue = __webpack_require__(2); var _vue2 = _interopRequireDefault(_vue); var _chart = __webpack_require__(3); var _chart2 = _interopRequireDefault(_chart); var _options = __webpack_require__(4); function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } exports.default = _vue2.default.extend({ render: function render(createElement) { return createElement('div', { style: this.styles, class: this.cssClasses }, [createElement('canvas', { attrs: { id: this.chartId, width: this.width, height: this.height }, ref: 'canvas' })]); }, props: { chartId: { default: 'horizontalbar-chart', type: String }, width: { default: 400, type: Number }, height: { default: 400, type: Number }, cssClasses: { type: String, default: '' }, styles: { type: Object, default: function _default() { return { width: '100%', height: '100%', position: 'relative' }; } } }, data: function data() { return { defaultOptions: { scales: { yAxes: [{ ticks: { beginAtZero: true }, gridLines: { display: false } }], xAxes: [{ gridLines: { display: false }, categoryPercentage: 0.5, barPercentage: 0.2 }] } }, plugins: [] }; }, methods: { addPlugin: function addPlugin(plugin) { this.plugins.push(plugin); }, renderChart: function renderChart(data, options, type) { var chartOptions = (0, _options.mergeOptions)(this.defaultOptions, options); this._chart = new _chart2.default(this.$refs.canvas.getContext('2d'), { type: 'horizontalBar', data: data, options: chartOptions, plugins: this.plugins }); } }, beforeDestroy: function beforeDestroy() { if (this._chart) { this._chart.destroy(); } } }); /***/ }, /* 226 */ /***/ function(module, exports, __webpack_require__) { 'use strict'; Object.defineProperty(exports, "__esModule", { value: true }); var _vue = __webpack_require__(2); var _vue2 = _interopRequireDefault(_vue); var _chart = __webpack_require__(3); var _chart2 = _interopRequireDefault(_chart); var _options = __webpack_require__(4); function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } exports.default = _vue2.default.extend({ render: function render(createElement) { return createElement('div', { style: this.styles, class: this.cssClasses }, [createElement('canvas', { attrs: { id: this.chartId, width: this.width, height: this.height }, ref: 'canvas' })]); }, props: { chartId: { default: 'doughnut-chart', type: String }, width: { default: 400, type: Number }, height: { default: 400, type: Number }, cssClasses: { type: String, default: '' }, styles: { type: Object, default: function _default() { return { width: '100%', height: '100%', position: 'relative' }; } } }, data: function data() { return { defaultOptions: {}, plugins: [] }; }, methods: { addPlugin: function addPlugin(plugin) { this.plugins.push(plugin); }, renderChart: function renderChart(data, options) { var chartOptions = (0, _options.mergeOptions)(this.defaultOptions, options); this._chart = new _chart2.default(this.$refs.canvas.getContext('2d'), { type: 'doughnut', data: data, options: chartOptions, plugins: this.plugins }); } }, beforeDestroy: function beforeDestroy() { if (this._chart) { this._chart.destroy(); } } }); /***/ }, /* 227 */ /***/ function(module, exports, __webpack_require__) { 'use strict'; Object.defineProperty(exports, "__esModule", { value: true }); var _vue = __webpack_require__(2); var _vue2 = _interopRequireDefault(_vue); var _chart = __webpack_require__(3); var _chart2 = _interopRequireDefault(_chart); var _options = __webpack_require__(4); function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } exports.default = _vue2.default.extend({ render: function render(createElement) { return createElement('div', { style: this.styles, class: this.cssClasses }, [createElement('canvas', { attrs: { id: this.chartId, width: this.width, height: this.height }, ref: 'canvas' })]); }, props: { chartId: { default: 'line-chart', type: String }, width: { default: 400, type: Number }, height: { default: 400, type: Number }, cssClasses: { type: String, default: '' }, styles: { type: Object, default: function _default() { return { width: '100%', height: '100%', position: 'relative' }; } } }, data: function data() { return { defaultOptions: { scales: { yAxes: [{ ticks: { beginAtZero: true }, gridLines: { display: false } }], xAxes: [{ gridLines: { display: false } }] } }, plugins: [] }; }, methods: { addPlugin: function addPlugin(plugin) { this.plugins.push(plugin); }, renderChart: function renderChart(data, options) { var chartOptions = (0, _options.mergeOptions)(this.defaultOptions, options); this._chart = new _chart2.default(this.$refs.canvas.getContext('2d'), { type: 'line', data: data, options: chartOptions, plugins: this.plugins }); } }, beforeDestroy: function beforeDestroy() { if (this._chart) { this._chart.destroy(); } } }); /***/ }, /* 228 */ /***/ function(module, exports, __webpack_require__) { 'use strict'; Object.defineProperty(exports, "__esModule", { value: true }); var _vue = __webpack_require__(2); var _vue2 = _interopRequireDefault(_vue); var _chart = __webpack_require__(3); var _chart2 = _interopRequireDefault(_chart); var _options = __webpack_require__(4); function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } exports.default = _vue2.default.extend({ render: function render(createElement) { return createElement('div', { style: this.styles, class: this.cssClasses }, [createElement('canvas', { attrs: { id: this.chartId, width: this.width, height: this.height }, ref: 'canvas' })]); }, props: { chartId: { default: 'pie-chart', type: String }, width: { default: 400, type: Number }, height: { default: 400, type: Number }, cssClasses: { type: String, default: '' }, styles: { type: Object, default: function _default() { return { width: '100%', height: '100%', position: 'relative' }; } } }, data: function data() { return { defaultOptions: {}, plugins: [] }; }, methods: { addPlugin: function addPlugin(plugin) { this.plugins.push(plugin); }, renderChart: function renderChart(data, options) { var chartOptions = (0, _options.mergeOptions)(this.defaultOptions, options); this._chart = new _chart2.default(this.$refs.canvas.getContext('2d'), { type: 'pie', data: data, options: chartOptions, plugins: this.plugins }); } }, beforeDestroy: function beforeDestroy() { if (this._chart) { this._chart.destroy(); } } }); /***/ }, /* 229 */ /***/ function(module, exports, __webpack_require__) { 'use strict'; Object.defineProperty(exports, "__esModule", { value: true }); var _vue = __webpack_require__(2); var _vue2 = _interopRequireDefault(_vue); var _chart = __webpack_require__(3); var _chart2 = _interopRequireDefault(_chart); var _options = __webpack_require__(4); function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } exports.default = _vue2.default.extend({ render: function render(createElement) { return createElement('div', { style: this.styles, class: this.cssClasses }, [createElement('canvas', { attrs: { id: this.chartId, width: this.width, height: this.height }, ref: 'canvas' })]); }, props: { chartId: { default: 'polar-chart', type: String }, width: { default: 400, type: Number }, height: { default: 400, type: Number }, cssClasses: { type: String, default: '' }, styles: { type: Object, default: function _default() { return { width: '100%', height: '100%', position: 'relative' }; } } }, data: function data() { return { defaultOptions: {}, plugins: [] }; }, methods: { addPlugin: function addPlugin(plugin) { this.plugins.push(plugin); }, renderChart: function renderChart(data, options) { var chartOptions = (0, _options.mergeOptions)(this.defaultOptions, options); this._chart = new _chart2.default(this.$refs.canvas.getContext('2d'), { type: 'polarArea', data: data, options: chartOptions, plugins: this.plugins }); } }, beforeDestroy: function beforeDestroy() { if (this._chart) { this._chart.destroy(); } } }); /***/ }, /* 230 */ /***/ function(module, exports, __webpack_require__) { 'use strict'; Object.defineProperty(exports, "__esModule", { value: true }); var _vue = __webpack_require__(2); var _vue2 = _interopRequireDefault(_vue); var _chart = __webpack_require__(3); var _chart2 = _interopRequireDefault(_chart); var _options = __webpack_require__(4); function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } exports.default = _vue2.default.extend({ render: function render(createElement) { return createElement('div', { style: this.styles, class: this.cssClasses }, [createElement('canvas', { attrs: { id: this.chartId, width: this.width, height: this.height }, ref: 'canvas' })]); }, props: { chartId: { default: 'radar-chart', type: String }, width: { default: 400, type: Number }, height: { default: 400, type: Number }, cssClasses: { type: String, default: '' }, styles: { type: Object, default: function _default() { return { width: '100%', height: '100%', position: 'relative' }; } } }, data: function data() { return { defaultOptions: {}, plugins: [] }; }, methods: { addPlugin: function addPlugin(plugin) { this.plugins.push(plugin); }, renderChart: function renderChart(data, options) { var chartOptions = (0, _options.mergeOptions)(this.defaultOptions, options); this._chart = new _chart2.default(this.$refs.canvas.getContext('2d'), { type: 'radar', data: data, options: chartOptions, plugins: this.plugins }); } }, beforeDestroy: function beforeDestroy() { if (this._chart) { this._chart.destroy(); } } }); /***/ }, /* 231 */ /***/ function(module, exports, __webpack_require__) { 'use strict'; Object.defineProperty(exports, "__esModule", { value: true }); var _vue = __webpack_require__(2); var _vue2 = _interopRequireDefault(_vue); var _chart = __webpack_require__(3); var _chart2 = _interopRequireDefault(_chart); var _options = __webpack_require__(4); function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } exports.default = _vue2.default.extend({ render: function render(createElement) { return createElement('div', { style: this.styles, class: this.cssClasses }, [createElement('canvas', { attrs: { id: this.chartId, width: this.width, height: this.height }, ref: 'canvas' })]); }, props: { chartId: { default: 'bubble-chart', type: String }, width: { default: 400, type: Number }, height: { default: 400, type: Number }, cssClasses: { type: String, default: '' }, styles: { type: Object, default: function _default() { return { width: '100%', height: '100%', position: 'relative' }; } } }, data: function data() { return { defaultOptions: { scales: { yAxes: [{ ticks: { beginAtZero: true }, gridLines: { display: false } }], xAxes: [{ gridLines: { display: false }, categoryPercentage: 0.5, barPercentage: 0.2 }] } }, plugins: [] }; }, methods: { addPlugin: function addPlugin(plugin) { this.plugins.push(plugin); }, renderChart: function renderChart(data, options) { var chartOptions = (0, _options.mergeOptions)(this.defaultOptions, options); this._chart = new _chart2.default(this.$refs.canvas.getContext('2d'), { type: 'bubble', data: data, options: chartOptions, plugins: this.plugins }); } }, beforeDestroy: function beforeDestroy() { if (this._chart) { this._chart.destroy(); } } }); /***/ }, /* 232 */ /***/ function(module, exports, __webpack_require__) { 'use strict'; Object.defineProperty(exports, "__esModule", { value: true }); var _vue = __webpack_require__(2); var _vue2 = _interopRequireDefault(_vue); var _chart = __webpack_require__(3); var _chart2 = _interopRequireDefault(_chart); var _options = __webpack_require__(4); function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } exports.default = _vue2.default.extend({ render: function render(createElement) { return createElement('div', { style: this.styles, class: this.cssClasses }, [createElement('canvas', { attrs: { id: this.chartId, width: this.width, height: this.height }, ref: 'canvas' })]); }, props: { chartId: { default: 'scatter-chart', type: String }, width: { default: 400, type: Number }, height: { default: 400, type: Number }, cssClasses: { type: String, default: '' }, styles: { type: Object, default: function _default() { return { width: '100%', height: '100%', position: 'relative' }; } } }, data: function data() { return { defaultOptions: { scales: { xAxes: [{ type: 'linear', position: 'bottom' }] } }, plugins: [] }; }, methods: { addPlugin: function addPlugin(plugin) { this.plugins.push(plugin); }, renderChart: function renderChart(data, options) { var chartOptions = (0, _options.mergeOptions)(this.defaultOptions, options); this._chart = new _chart2.default(this.$refs.canvas.getContext('2d'), { type: 'scatter', data: data, options: chartOptions, plugins: this.plugins }); } }, beforeDestroy: function beforeDestroy() { if (this._chart) { this._chart.destroy(); } } }); /***/ }, /* 233 */ /***/ function(module, exports, __webpack_require__) { 'use strict'; Object.defineProperty(exports, "__esModule", { value: true }); var _reactiveData = __webpack_require__(234); var _reactiveData2 = _interopRequireDefault(_reactiveData); var _reactiveProp = __webpack_require__(272); var _reactiveProp2 = _interopRequireDefault(_reactiveProp); function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } exports.default = { reactiveData: _reactiveData2.default, reactiveProp: _reactiveProp2.default }; /***/ }, /* 234 */ /***/ function(module, exports, __webpack_require__) { 'use strict'; var _keys = __webpack_require__(235); var _keys2 = _interopRequireDefault(_keys); var _stringify = __webpack_require__(270); var _stringify2 = _interopRequireDefault(_stringify); function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } module.exports = { data: function data() { return { chartData: null }; }, watch: { 'chartData': { handler: function handler(newData, oldData) { if (oldData) { var chart = this._chart; var newDatasetLabels = newData.datasets.map(function (dataset) { return dataset.label; }); var oldDatasetLabels = oldData.datasets.map(function (dataset) { return dataset.label; }); var oldLabels = (0, _stringify2.default)(oldDatasetLabels); var newLabels = (0, _stringify2.default)(newDatasetLabels); if (newLabels === oldLabels && oldData.datasets.length === newData.datasets.length) { newData.datasets.forEach(function (dataset, i) { var oldDatasetKeys = (0, _keys2.default)(oldData.datasets[i]); var newDatasetKeys = (0, _keys2.default)(dataset); var deletionKeys = oldDatasetKeys.filter(function (key) { return key !== '_meta' && newDatasetKeys.indexOf(key) === -1; }); deletionKeys.forEach(function (deletionKey) { delete chart.data.datasets[i][deletionKey]; }); for (var attribute in dataset) { if (dataset.hasOwnProperty(attribute)) { chart.data.datasets[i][attribute] = dataset[attribute]; } } }); if (newData.hasOwnProperty('labels')) { chart.data.labels = newData.labels; } if (newData.hasOwnProperty('xLabels')) { chart.data.xLabels = newData.xLabels; } if (newData.hasOwnProperty('yLabels')) { chart.data.yLabels = newData.yLabels; } chart.update(); } else { chart.destroy(); this.renderChart(this.chartData, this.options); } } else { this.renderChart(this.chartData, this.options); } } } } }; /***/ }, /* 235 */ /***/ function(module, exports, __webpack_require__) { module.exports = { "default": __webpack_require__(236), __esModule: true }; /***/ }, /* 236 */ /***/ function(module, exports, __webpack_require__) { __webpack_require__(237); module.exports = __webpack_require__(257).Object.keys; /***/ }, /* 237 */ /***/ function(module, exports, __webpack_require__) { // 19.1.2.14 Object.keys(O) var toObject = __webpack_require__(238) , $keys = __webpack_require__(240); __webpack_require__(255)('keys', function(){ return function keys(it){ return $keys(toObject(it)); }; }); /***/ }, /* 238 */ /***/ function(module, exports, __webpack_require__) { // 7.1.13 ToObject(argument) var defined = __webpack_require__(239); module.exports = function(it){ return Object(defined(it)); }; /***/ }, /* 239 */ /***/ function(module, exports) { // 7.2.1 RequireObjectCoercible(argument) module.exports = function(it){ if(it == undefined)throw TypeError("Can't call method on " + it); return it; }; /***/ }, /* 240 */ /***/ function(module, exports, __webpack_require__) { // 19.1.2.14 / 15.2.3.14 Object.keys(O) var $keys = __webpack_require__(241) , enumBugKeys = __webpack_require__(254); module.exports = Object.keys || function keys(O){ return $keys(O, enumBugKeys); }; /***/ }, /* 241 */ /***/ function(module, exports, __webpack_require__) { var has = __webpack_require__(242) , toIObject = __webpack_require__(243) , arrayIndexOf = __webpack_require__(246)(false) , IE_PROTO = __webpack_require__(250)('IE_PROTO'); module.exports = function(object, names){ var O = toIObject(object) , i = 0 , result = [] , key; for(key in O)if(key != IE_PROTO)has(O, key) && result.push(key); // Don't enum bug & hidden keys while(names.length > i)if(has(O, key = names[i++])){ ~arrayIndexOf(result, key) || result.push(key); } return result; }; /***/ }, /* 242 */ /***/ function(module, exports) { var hasOwnProperty = {}.hasOwnProperty; module.exports = function(it, key){ return hasOwnProperty.call(it, key); }; /***/ }, /* 243 */ /***/ function(module, exports, __webpack_require__) { // to indexed object, toObject with fallback for non-array-like ES3 strings var IObject = __webpack_require__(244) , defined = __webpack_require__(239); module.exports = function(it){ return IObject(defined(it)); }; /***/ }, /* 244 */ /***/ function(module, exports, __webpack_require__) { // fallback for non-array-like ES3 and non-enumerable old V8 strings var cof = __webpack_require__(245); module.exports = Object('z').propertyIsEnumerable(0) ? Object : function(it){ return cof(it) == 'String' ? it.split('') : Object(it); }; /***/ }, /* 245 */ /***/ function(module, exports) { var toString = {}.toString; module.exports = function(it){ return toString.call(it).slice(8, -1); }; /***/ }, /* 246 */ /***/ function(module, exports, __webpack_require__) { // false -> Array#indexOf // true -> Array#includes var toIObject = __webpack_require__(243) , toLength = __webpack_require__(247) , toIndex = __webpack_require__(249); module.exports = function(IS_INCLUDES){ return function($this, el, fromIndex){ var O = toIObject($this) , length = toLength(O.length) , index = toIndex(fromIndex, length) , value; // Array#includes uses SameValueZero equality algorithm if(IS_INCLUDES && el != el)while(length > index){ value = O[index++]; if(value != value)return true; // Array#toIndex ignores holes, Array#includes - not } else for(;length > index; index++)if(IS_INCLUDES || index in O){ if(O[index] === el)return IS_INCLUDES || index || 0; } return !IS_INCLUDES && -1; }; }; /***/ }, /* 247 */ /***/ function(module, exports, __webpack_require__) { // 7.1.15 ToLength var toInteger = __webpack_require__(248) , min = Math.min; module.exports = function(it){ return it > 0 ? min(toInteger(it), 0x1fffffffffffff) : 0; // pow(2, 53) - 1 == 9007199254740991 }; /***/ }, /* 248 */ /***/ function(module, exports) { // 7.1.4 ToInteger var ceil = Math.ceil , floor = Math.floor; module.exports = function(it){ return isNaN(it = +it) ? 0 : (it > 0 ? floor : ceil)(it); }; /***/ }, /* 249 */ /***/ function(module, exports, __webpack_require__) { var toInteger = __webpack_require__(248) , max = Math.max , min = Math.min; module.exports = function(index, length){ index = toInteger(index); return index < 0 ? max(index + length, 0) : min(index, length); }; /***/ }, /* 250 */ /***/ function(module, exports, __webpack_require__) { var shared = __webpack_require__(251)('keys') , uid = __webpack_require__(253); module.exports = function(key){ return shared[key] || (shared[key] = uid(key)); }; /***/ }, /* 251 */ /***/ function(module, exports, __webpack_require__) { var global = __webpack_require__(252) , SHARED = '__core-js_shared__' , store = global[SHARED] || (global[SHARED] = {}); module.exports = function(key){ return store[key] || (store[key] = {}); }; /***/ }, /* 252 */ /***/ function(module, exports) { // https://github.com/zloirock/core-js/issues/86#issuecomment-115759028 var global = module.exports = typeof window != 'undefined' && window.Math == Math ? window : typeof self != 'undefined' && self.Math == Math ? self : Function('return this')(); if(typeof __g == 'number')__g = global; // eslint-disable-line no-undef /***/ }, /* 253 */ /***/ function(module, exports) { var id = 0 , px = Math.random(); module.exports = function(key){ return 'Symbol('.concat(key === undefined ? '' : key, ')_', (++id + px).toString(36)); }; /***/ }, /* 254 */ /***/ function(module, exports) { // IE 8- don't enum bug keys module.exports = ( 'constructor,hasOwnProperty,isPrototypeOf,propertyIsEnumerable,toLocaleString,toString,valueOf' ).split(','); /***/ }, /* 255 */ /***/ function(module, exports, __webpack_require__) { // most Object methods by ES6 should accept primitives var $export = __webpack_require__(256) , core = __webpack_require__(257) , fails = __webpack_require__(266); module.exports = function(KEY, exec){ var fn = (core.Object || {})[KEY] || Object[KEY] , exp = {}; exp[KEY] = exec(fn); $export($export.S + $export.F * fails(function(){ fn(1); }), 'Object', exp); }; /***/ }, /* 256 */ /***/ function(module, exports, __webpack_require__) { var global = __webpack_require__(252) , core = __webpack_require__(257) , ctx = __webpack_require__(258) , hide = __webpack_require__(260) , PROTOTYPE = 'prototype'; var $export = function(type, name, source){ var IS_FORCED = type & $export.F , IS_GLOBAL = type & $export.G , IS_STATIC = type & $export.S , IS_PROTO = type & $export.P , IS_BIND = type & $export.B , IS_WRAP = type & $export.W , exports = IS_GLOBAL ? core : core[name] || (core[name] = {}) , expProto = exports[PROTOTYPE] , target = IS_GLOBAL ? global : IS_STATIC ? global[name] : (global[name] || {})[PROTOTYPE] , key, own, out; if(IS_GLOBAL)source = name; for(key in source){ // contains in native own = !IS_FORCED && target && target[key] !== undefined; if(own && key in exports)continue; // export native or passed out = own ? target[key] : source[key]; // prevent global pollution for namespaces exports[key] = IS_GLOBAL && typeof target[key] != 'function' ? source[key] // bind timers to global for call from export context : IS_BIND && own ? ctx(out, global) // wrap global constructors for prevent change them in library : IS_WRAP && target[key] == out ? (function(C){ var F = function(a, b, c){ if(this instanceof C){ switch(arguments.length){ case 0: return new C; case 1: return new C(a); case 2: return new C(a, b); } return new C(a, b, c); } return C.apply(this, arguments); }; F[PROTOTYPE] = C[PROTOTYPE]; return F; // make static versions for prototype methods })(out) : IS_PROTO && typeof out == 'function' ? ctx(Function.call, out) : out; // export proto methods to core.%CONSTRUCTOR%.methods.%NAME% if(IS_PROTO){ (exports.virtual || (exports.virtual = {}))[key] = out; // export proto methods to core.%CONSTRUCTOR%.prototype.%NAME% if(type & $export.R && expProto && !expProto[key])hide(expProto, key, out); } } }; // type bitmap $export.F = 1; // forced $export.G = 2; // global $export.S = 4; // static $export.P = 8; // proto $export.B = 16; // bind $export.W = 32; // wrap $export.U = 64; // safe $export.R = 128; // real proto method for `library` module.exports = $export; /***/ }, /* 257 */ /***/ function(module, exports) { var core = module.exports = {version: '2.4.0'}; if(typeof __e == 'number')__e = core; // eslint-disable-line no-undef /***/ }, /* 258 */ /***/ function(module, exports, __webpack_require__) { // optional / simple context binding var aFunction = __webpack_require__(259); module.exports = function(fn, that, length){ aFunction(fn); if(that === undefined)return fn; switch(length){ case 1: return function(a){ return fn.call(that, a); }; case 2: return function(a, b){ return fn.call(that, a, b); }; case 3: return function(a, b, c){ return fn.call(that, a, b, c); }; } return function(/* ...args */){ return fn.apply(that, arguments); }; }; /***/ }, /* 259 */ /***/ function(module, exports) { module.exports = function(it){ if(typeof it != 'function')throw TypeError(it + ' is not a function!'); return it; }; /***/ }, /* 260 */ /***/ function(module, exports, __webpack_require__) { var dP = __webpack_require__(261) , createDesc = __webpack_require__(269); module.exports = __webpack_require__(265) ? function(object, key, value){ return dP.f(object, key, createDesc(1, value)); } : function(object, key, value){ object[key] = value; return object; }; /***/ }, /* 261 */ /***/ function(module, exports, __webpack_require__) { var anObject = __webpack_require__(262) , IE8_DOM_DEFINE = __webpack_require__(264) , toPrimitive = __webpack_require__(268) , dP = Object.defineProperty; exports.f = __webpack_require__(265) ? Object.defineProperty : function defineProperty(O, P, Attributes){ anObject(O); P = toPrimitive(P, true); anObject(Attributes); if(IE8_DOM_DEFINE)try { return dP(O, P, Attributes); } catch(e){ /* empty */ } if('get' in Attributes || 'set' in Attributes)throw TypeError('Accessors not supported!'); if('value' in Attributes)O[P] = Attributes.value; return O; }; /***/ }, /* 262 */ /***/ function(module, exports, __webpack_require__) { var isObject = __webpack_require__(263); module.exports = function(it){ if(!isObject(it))throw TypeError(it + ' is not an object!'); return it; }; /***/ }, /* 263 */ /***/ function(module, exports) { module.exports = function(it){ return typeof it === 'object' ? it !== null : typeof it === 'function'; }; /***/ }, /* 264 */ /***/ function(module, exports, __webpack_require__) { module.exports = !__webpack_require__(265) && !__webpack_require__(266)(function(){ return Object.defineProperty(__webpack_require__(267)('div'), 'a', {get: function(){ return 7; }}).a != 7; }); /***/ }, /* 265 */ /***/ function(module, exports, __webpack_require__) { // Thank's IE8 for his funny defineProperty module.exports = !__webpack_require__(266)(function(){ return Object.defineProperty({}, 'a', {get: function(){ return 7; }}).a != 7; }); /***/ }, /* 266 */ /***/ function(module, exports) { module.exports = function(exec){ try { return !!exec(); } catch(e){ return true; } }; /***/ }, /* 267 */ /***/ function(module, exports, __webpack_require__) { var isObject = __webpack_require__(263) , document = __webpack_require__(252).document // in old IE typeof document.createElement is 'object' , is = isObject(document) && isObject(document.createElement); module.exports = function(it){ return is ? document.createElement(it) : {}; }; /***/ }, /* 268 */ /***/ function(module, exports, __webpack_require__) { // 7.1.1 ToPrimitive(input [, PreferredType]) var isObject = __webpack_require__(263); // instead of the ES6 spec version, we didn't implement @@toPrimitive case // and the second argument - flag - preferred type is a string module.exports = function(it, S){ if(!isObject(it))return it; var fn, val; if(S && typeof (fn = it.toString) == 'function' && !isObject(val = fn.call(it)))return val; if(typeof (fn = it.valueOf) == 'function' && !isObject(val = fn.call(it)))return val; if(!S && typeof (fn = it.toString) == 'function' && !isObject(val = fn.call(it)))return val; throw TypeError("Can't convert object to primitive value"); }; /***/ }, /* 269 */ /***/ function(module, exports) { module.exports = function(bitmap, value){ return { enumerable : !(bitmap & 1), configurable: !(bitmap & 2), writable : !(bitmap & 4), value : value }; }; /***/ }, /* 270 */ /***/ function(module, exports, __webpack_require__) { module.exports = { "default": __webpack_require__(271), __esModule: true }; /***/ }, /* 271 */ /***/ function(module, exports, __webpack_require__) { var core = __webpack_require__(257) , $JSON = core.JSON || (core.JSON = {stringify: JSON.stringify}); module.exports = function stringify(it){ // eslint-disable-line no-unused-vars return $JSON.stringify.apply($JSON, arguments); }; /***/ }, /* 272 */ /***/ function(module, exports, __webpack_require__) { 'use strict'; var _keys = __webpack_require__(235); var _keys2 = _interopRequireDefault(_keys); var _stringify = __webpack_require__(270); var _stringify2 = _interopRequireDefault(_stringify); function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } module.exports = { props: { chartData: { required: true } }, watch: { 'chartData': { handler: function handler(newData, oldData) { if (oldData) { var chart = this._chart; var newDatasetLabels = newData.datasets.map(function (dataset) { return dataset.label; }); var oldDatasetLabels = oldData.datasets.map(function (dataset) { return dataset.label; }); var oldLabels = (0, _stringify2.default)(oldDatasetLabels); var newLabels = (0, _stringify2.default)(newDatasetLabels); if (newLabels === oldLabels && oldData.datasets.length === newData.datasets.length) { newData.datasets.forEach(function (dataset, i) { var oldDatasetKeys = (0, _keys2.default)(oldData.datasets[i]); var newDatasetKeys = (0, _keys2.default)(dataset); var deletionKeys = oldDatasetKeys.filter(function (key) { return key !== '_meta' && newDatasetKeys.indexOf(key) === -1; }); deletionKeys.forEach(function (deletionKey) { delete chart.data.datasets[i][deletionKey]; }); for (var attribute in dataset) { if (dataset.hasOwnProperty(attribute)) { chart.data.datasets[i][attribute] = dataset[attribute]; } } }); if (newData.hasOwnProperty('labels')) { chart.data.labels = newData.labels; } if (newData.hasOwnProperty('xLabels')) { chart.data.xLabels = newData.xLabels; } if (newData.hasOwnProperty('yLabels')) { chart.data.yLabels = newData.yLabels; } chart.update(); } else { chart.destroy(); this.renderChart(this.chartData, this.options); } } else { this.renderChart(this.chartData, this.options); } } } } }; /***/ }, /* 273 */ /***/ function(module, exports) { module.exports = { "name": "vue-chartjs", "version": "2.8.2", "description": "vue.js wrapper for chart.js", "author": "Jakub Juszczak <[email protected]>", "homepage": "http://vue-chartjs.org", "license": "MIT", "contributors": [ { "name": "Thorsten Lünborg", "web": "https://github.com/LinusBorg" }, { "name": "Juan Carlos Alonso", "web": "https://github.com/jcalonso" } ], "maintainers": [ { "name": "Jakub Juszczak", "email": "[email protected]", "web": "http://www.jakubjuszczak.de" } ], "repository": { "type": "git", "url": "git+ssh://[email protected]:apertureless/vue-chartjs.git" }, "bugs": { "url": "https://github.com/apertureless/vue-chartjs/issues" }, "keywords": [ "ChartJs", "Vue", "Visualisation", "Wrapper", "Charts" ], "main": "dist/vue-chartjs.js", "unpkg": "dist/vue-chartjs.full.min.js", "module": "es/index.js", "jsnext:main": "es/index.js", "files": [ "src", "dist", "es" ], "scripts": { "dev": "node build/dev-server.js", "build": "yarn run release && yarn run build:es", "build:es": "cross-env BABEL_ENV=es babel src --out-dir es", "unit": "karma start test/unit/karma.conf.js --single-run", "e2e": "node test/e2e/runner.js", "test": "npm run unit", "lint": "eslint --ext .js,.vue src test/unit/specs test/e2e/specs", "release": "webpack --progress --hide-modules --config ./build/webpack.release.js && NODE_ENV=production webpack --progress --hide-modules --config ./build/webpack.release.min.js && webpack --progress --hide-modules --config ./build/webpack.release.full.js && NODE_ENV=production webpack --progress --hide-modules --config ./build/webpack.release.full.min.js", "prepublish": "yarn run lint && yarn run test && yarn run build" }, "dependencies": { "lodash": "^4.17.4" }, "peerDependencies": { "chart.js": "^2.6.0", "vue": "^2.4.2" }, "devDependencies": { "babel-cli": "^6.24.1", "babel-core": "^6.25.0", "babel-loader": "^7.0.0", "babel-plugin-transform-runtime": "^6.23.0", "babel-preset-es2015": "^6.24.1", "babel-preset-stage-2": "^6.24.1", "babel-runtime": "^6.23.0", "chai": "^3.5.0", "chart.js": "^2.6.0", "chromedriver": "^2.28.0", "connect-history-api-fallback": "^1.1.0", "cross-env": "^3.2.4", "cross-spawn": "^5.1.0", "css-loader": "^0.28.0", "eslint": "^3.19.0", "eslint-config-standard": "^10.2.1", "eslint-friendly-formatter": "^2.0.7", "eslint-loader": "^1.7.1", "eslint-plugin-html": "^2.0.1", "eslint-plugin-import": "^2.2.0", "eslint-plugin-node": "^4.2.2", "eslint-plugin-promise": "^3.5.0", "eslint-plugin-standard": "^3.0.1", "eventsource-polyfill": "^0.9.6", "express": "^4.15.2", "extract-text-webpack-plugin": "^1.0.1", "file-loader": "^0.10.1", "function-bind": "^1.0.2", "html-webpack-plugin": "^2.28.0", "http-proxy-middleware": "^0.17.4", "inject-loader": "^3.0.0", "isparta-loader": "^2.0.0", "jasmine-core": "^2.5.2", "json-loader": "^0.5.4", "karma": "^1.5.0", "karma-coverage": "^1.1.1", "karma-jasmine": "^1.0.2", "karma-mocha": "^1.2.0", "karma-phantomjs-launcher": "^1.0.4", "karma-sinon-chai": "^1.2.0", "karma-sourcemap-loader": "^0.3.7", "karma-spec-reporter": "0.0.30", "karma-webpack": "1.8.1", "lolex": "^1.6.0", "mocha": "^3.1.0", "nightwatch": "^0.9.14", "ora": "^1.2.0", "phantomjs-prebuilt": "^2.1.13", "selenium-server": "^3.3.1", "shelljs": "^0.7.7", "sinon": "^2.1.0", "sinon-chai": "^2.9.0", "url-loader": "^0.5.8", "vue": "^2.4.2", "vue-hot-reload-api": "^2.1.0", "vue-html-loader": "^1.2.4", "vue-loader": "^12.2.2", "vue-style-loader": "^3.0.1", "vue-template-compiler": "^2.4.2", "webpack": "^1.13.2", "webpack-dev-middleware": "^1.10.1", "webpack-hot-middleware": "^2.17.1", "webpack-merge": "1.1.1" }, "engines": { "node": ">=6.9.0" }, "babel": { "presets": [ "es2015" ] }, "browserify": { "transform": [ "babelify" ] }, "greenkeeper": { "ignore": [ "extract-text-webpack-plugin", "karma-webpack", "webpack", "webpack-merge" ] } }; /***/ } /******/ ]) }); ;
src/components/LinkButton.js
erikdesjardins/media-db
import classNames from 'classnames'; import React from 'react'; export default React.memo(function LinkButton({ className, title, disabled, onClick, children }) { const handleClick = e => { e.preventDefault(); if (!disabled) { onClick(); } }; return ( <a className={classNames('LinkButton', className)} href={disabled ? null : '#'} title={title} onClick={handleClick} > {children} </a> ); });
src/main/resources/public/js/components/dropdown_menus/member/member-dropdown-header.js
SICTIAM/ozwillo-portal
import React from 'react'; import PropTypes from 'prop-types'; import Popup from "react-popup"; import CustomTooltip from '../../custom-tooltip'; import { i18n } from "../../../config/i18n-config" import { t } from "@lingui/macro" class MemberDropdownHeader extends React.Component { static propTypes = { organization: PropTypes.object.isRequired, member: PropTypes.object.isRequired, onRemoveMemberInOrganization: PropTypes.func.isRequired, onUpdateRoleMember: PropTypes.func.isRequired, onRemoveInvitationToJoinAnOrg: PropTypes.func.isRequired }; constructor(props) { super(props); this.state = { error: '' }; this.onRemoveMemberInOrganization = this.onRemoveMemberInOrganization.bind(this); this.onRemoveInvitationToJoinAnOrg = this.onRemoveInvitationToJoinAnOrg.bind(this); this.memberRoleToggle = this.memberRoleToggle.bind(this); } onRemoveMemberInOrganization() { this.props.onRemoveMemberInOrganization(this.props.member) .catch((err) => { this.setState({error: err.error}); }); } onRemoveInvitationToJoinAnOrg() { this.props.onRemoveInvitationToJoinAnOrg(this.props.member) .catch((err) => { this.setState({error: err.error}); }); } memberRoleToggle() { this.props.onUpdateRoleMember(!this.props.member.admin) .catch((err) => { if (err.status === 403) { const error = err.error.format(this.props.member.name); Popup.create({ title: this.props.organization.name, content: <p className="alert-message"> { error.split('\n').map(line => { return <span className="line">{line}</span> }) } </p>, buttons: { right: [{ text: i18n._(t`ui.ok`), action: () => { Popup.close(); } }] } }); } }); } render() { const member = this.props.member; const isPending = !member.name; const isOrgAdmin = this.props.organization.admin; return <header className="dropdown-header"> <form className="form flex-row" onSubmit={this.onSubmit}> <p className="dropdown-name"> <span>{member.name}</span> {isOrgAdmin && <span className={`email ${(member.name && 'separator') || ''}`}>{member.email}</span> } </p> <span className="error-message">{this.state.error}</span> <div className="options flex-row end"> { isPending && <CustomTooltip title={i18n._(t`tooltip.pending`)}> <button type="button" className="btn icon"> <i className="fa fa-stopwatch option-icon loading"/> </button> </CustomTooltip> } { member.admin && isOrgAdmin && <CustomTooltip title={i18n._(t`tooltip.remove.right.admin`)}> <button type="button" className="btn icon" onClick={!isPending && isOrgAdmin && this.memberRoleToggle || null}> <i className="fa fa-chess-king option-icon"/> </button> </CustomTooltip> || member.admin && <CustomTooltip title={i18n._(t`tooltip.member.admin.info`)}> <button type="button" className="btn icon"> <i className="fa fa-chess-king option-icon"/> </button> </CustomTooltip> } { !member.admin && !isPending && isOrgAdmin && <CustomTooltip title={i18n._(t`tooltip.add.right.admin`)}> <button type="button" className="btn icon" onClick={!isPending && isOrgAdmin && this.memberRoleToggle || null}> <i className="fa fa-chess-pawn option-icon"/> </button> </CustomTooltip> || !member.admin && !isPending && <CustomTooltip title={i18n._(t`tooltip.member.no.admin.info`)}> <button type="button" className="btn icon"> <i className="fa fa-chess-pawn option-icon"/> </button> </CustomTooltip> } { isOrgAdmin && <CustomTooltip title={i18n._(t`tooltip.delete.member`)}> <button type="button" className="btn icon delete" onClick={!isPending && this.onRemoveMemberInOrganization || this.onRemoveInvitationToJoinAnOrg}> <i className="fa fa-trash option-icon delete"/> </button> </CustomTooltip> } </div> </form> </header>; } } export default MemberDropdownHeader;
examples/blog/src/index.js
velopert/redux-pender
import React from 'react'; import ReactDOM from 'react-dom'; import App from './App'; import store from './store'; import { Provider } from 'react-redux'; ReactDOM.render( <Provider store={store}> <App /> </Provider>, document.getElementById('root') );
ajax/libs/ember-data.js/2.17.0/ember-data.prod.js
jonobr1/cdnjs
(function(){ "use strict"; /*! * @overview Ember Data * @copyright Copyright 2011-2017 Tilde Inc. and contributors. * Portions Copyright 2011 LivingSocial Inc. * @license Licensed under MIT license (see license.js) * @version 2.17.0-beta.1 */ var loader, define, requireModule, require, requirejs; (function (global) { 'use strict'; function dict() { var obj = Object.create(null); obj['__'] = undefined; delete obj['__']; return obj; } // Save off the original values of these globals, so we can restore them if someone asks us to var oldGlobals = { loader: loader, define: define, requireModule: requireModule, require: require, requirejs: requirejs }; requirejs = require = requireModule = function (id) { var pending = []; var mod = findModule(id, '(require)', pending); for (var i = pending.length - 1; i >= 0; i--) { pending[i].exports(); } return mod.module.exports; }; loader = { noConflict: function (aliases) { var oldName, newName; for (oldName in aliases) { if (aliases.hasOwnProperty(oldName)) { if (oldGlobals.hasOwnProperty(oldName)) { newName = aliases[oldName]; global[newName] = global[oldName]; global[oldName] = oldGlobals[oldName]; } } } }, // Option to enable or disable the generation of default exports makeDefaultExport: true }; var registry = dict(); var seen = dict(); var uuid = 0; function unsupportedModule(length) { throw new Error('an unsupported module was defined, expected `define(id, deps, module)` instead got: `' + length + '` arguments to define`'); } var defaultDeps = ['require', 'exports', 'module']; function Module(id, deps, callback, alias) { this.uuid = uuid++; this.id = id; this.deps = !deps.length && callback.length ? defaultDeps : deps; this.module = { exports: {} }; this.callback = callback; this.hasExportsAsDep = false; this.isAlias = alias; this.reified = new Array(deps.length); /* Each module normally passes through these states, in order: new : initial state pending : this module is scheduled to be executed reifying : this module's dependencies are being executed reified : this module's dependencies finished executing successfully errored : this module's dependencies failed to execute finalized : this module executed successfully */ this.state = 'new'; } Module.prototype.makeDefaultExport = function () { var exports = this.module.exports; if (exports !== null && (typeof exports === 'object' || typeof exports === 'function') && exports['default'] === undefined && Object.isExtensible(exports)) { exports['default'] = exports; } }; Module.prototype.exports = function () { // if finalized, there is no work to do. If reifying, there is a // circular dependency so we must return our (partial) exports. if (this.state === 'finalized' || this.state === 'reifying') { return this.module.exports; } if (loader.wrapModules) { this.callback = loader.wrapModules(this.id, this.callback); } this.reify(); var result = this.callback.apply(this, this.reified); this.reified.length = 0; this.state = 'finalized'; if (!(this.hasExportsAsDep && result === undefined)) { this.module.exports = result; } if (loader.makeDefaultExport) { this.makeDefaultExport(); } return this.module.exports; }; Module.prototype.unsee = function () { this.state = 'new'; this.module = { exports: {} }; }; Module.prototype.reify = function () { if (this.state === 'reified') { return; } this.state = 'reifying'; try { this.reified = this._reify(); this.state = 'reified'; } finally { if (this.state === 'reifying') { this.state = 'errored'; } } }; Module.prototype._reify = function () { var reified = this.reified.slice(); for (var i = 0; i < reified.length; i++) { var mod = reified[i]; reified[i] = mod.exports ? mod.exports : mod.module.exports(); } return reified; }; Module.prototype.findDeps = function (pending) { if (this.state !== 'new') { return; } this.state = 'pending'; var deps = this.deps; for (var i = 0; i < deps.length; i++) { var dep = deps[i]; var entry = this.reified[i] = { exports: undefined, module: undefined }; if (dep === 'exports') { this.hasExportsAsDep = true; entry.exports = this.module.exports; } else if (dep === 'require') { entry.exports = this.makeRequire(); } else if (dep === 'module') { entry.exports = this.module; } else { entry.module = findModule(resolve(dep, this.id), this.id, pending); } } }; Module.prototype.makeRequire = function () { var id = this.id; var r = function (dep) { return require(resolve(dep, id)); }; r['default'] = r; r.moduleId = id; r.has = function (dep) { return has(resolve(dep, id)); }; return r; }; define = function (id, deps, callback) { var module = registry[id]; // If a module for this id has already been defined and is in any state // other than `new` (meaning it has been or is currently being required), // then we return early to avoid redefinition. if (module && module.state !== 'new') { return; } if (arguments.length < 2) { unsupportedModule(arguments.length); } if (!Array.isArray(deps)) { callback = deps; deps = []; } if (callback instanceof Alias) { registry[id] = new Module(callback.id, deps, callback, true); } else { registry[id] = new Module(id, deps, callback, false); } }; define.exports = function (name, defaultExport) { var module = registry[name]; // If a module for this name has already been defined and is in any state // other than `new` (meaning it has been or is currently being required), // then we return early to avoid redefinition. if (module && module.state !== 'new') { return; } module = new Module(name, [], noop, null); module.module.exports = defaultExport; module.state = 'finalized'; registry[name] = module; return module; }; function noop() {} // we don't support all of AMD // define.amd = {}; function Alias(id) { this.id = id; } define.alias = function (id, target) { if (arguments.length === 2) { return define(target, new Alias(id)); } return new Alias(id); }; function missingModule(id, referrer) { throw new Error('Could not find module `' + id + '` imported from `' + referrer + '`'); } function findModule(id, referrer, pending) { var mod = registry[id] || registry[id + '/index']; while (mod && mod.isAlias) { mod = registry[mod.id]; } if (!mod) { missingModule(id, referrer); } if (pending && mod.state !== 'pending' && mod.state !== 'finalized') { mod.findDeps(pending); pending.push(mod); } return mod; } function resolve(child, id) { if (child.charAt(0) !== '.') { return child; } var parts = child.split('/'); var nameParts = id.split('/'); var parentBase = nameParts.slice(0, -1); for (var i = 0, l = parts.length; i < l; i++) { var part = parts[i]; if (part === '..') { if (parentBase.length === 0) { throw new Error('Cannot access parent module of root'); } parentBase.pop(); } else if (part === '.') { continue; } else { parentBase.push(part); } } return parentBase.join('/'); } function has(id) { return !!(registry[id] || registry[id + '/index']); } requirejs.entries = requirejs._eak_seen = registry; requirejs.has = has; requirejs.unsee = function (id) { findModule(id, '(unsee)', false).unsee(); }; requirejs.clear = function () { requirejs.entries = requirejs._eak_seen = registry = dict(); seen = dict(); }; // This code primes the JS engine for good performance by warming the // JIT compiler for these functions. define('foo', function () {}); define('foo/bar', [], function () {}); define('foo/asdf', ['module', 'exports', 'require'], function (module, exports, require) { if (require.has('foo/bar')) { require('foo/bar'); } }); define('foo/baz', [], define.alias('foo')); define('foo/quz', define.alias('foo')); define.alias('foo', 'foo/qux'); define('foo/bar', ['foo', './quz', './baz', './asdf', './bar', '../foo'], function () {}); define('foo/main', ['foo/bar'], function () {}); define.exports('foo/exports', {}); require('foo/exports'); require('foo/main'); require.unsee('foo/bar'); requirejs.clear(); if (typeof exports === 'object' && typeof module === 'object' && module.exports) { module.exports = { require: require, define: define }; } })(this); define('ember-data/-debug', ['exports', 'ember'], function (exports, _ember) { 'use strict'; exports.__esModule = true; exports.assertPolymorphicType = undefined; exports.instrument = instrument; function instrument(method) { return method(); } /* Assert that `addedRecord` has a valid type so it can be added to the relationship of the `record`. The assert basically checks if the `addedRecord` can be added to the relationship (specified via `relationshipMeta`) of the `record`. This utility should only be used internally, as both record parameters must be an InternalModel and the `relationshipMeta` needs to be the meta information about the relationship, retrieved via `record.relationshipFor(key)`. @method assertPolymorphicType @param {InternalModel} internalModel @param {RelationshipMeta} relationshipMeta retrieved via `record.relationshipFor(key)` @param {InternalModel} addedRecord record which should be added/set for the relationship */ var assertPolymorphicType = void 0; if (false) { var checkPolymorphic = function checkPolymorphic(modelClass, addedModelClass) { if (modelClass.__isMixin) { //TODO Need to do this in order to support mixins, should convert to public api //once it exists in Ember return modelClass.__mixin.detect(addedModelClass.PrototypeMixin); } if (_ember.default.MODEL_FACTORY_INJECTIONS) { modelClass = modelClass.superclass; } return modelClass.detect(addedModelClass); }; exports.assertPolymorphicType = assertPolymorphicType = function assertPolymorphicType(parentInternalModel, relationshipMeta, addedInternalModel) { var addedModelName = addedInternalModel.modelName; var parentModelName = parentInternalModel.modelName; var key = relationshipMeta.key; var relationshipModelName = relationshipMeta.type; var relationshipClass = parentInternalModel.store.modelFor(relationshipModelName); var assertionMessage = 'You cannot add a record of modelClass \'' + addedModelName + '\' to the \'' + parentModelName + '.' + key + '\' relationship (only \'' + relationshipModelName + '\' allowed)'; (false && _ember.default.assert(assertionMessage, checkPolymorphic(relationshipClass, addedInternalModel.modelClass))); }; } exports.assertPolymorphicType = assertPolymorphicType; }); define('ember-data/-private/adapters/build-url-mixin', ['exports', 'ember', 'ember-inflector'], function (exports, _ember, _emberInflector) { 'use strict'; exports.__esModule = true; var get = _ember.default.get; /** WARNING: This interface is likely to change in order to accomodate https://github.com/emberjs/rfcs/pull/4 ## Using BuildURLMixin To use url building, include the mixin when extending an adapter, and call `buildURL` where needed. The default behaviour is designed for RESTAdapter. ### Example ```javascript export default DS.Adapter.extend(BuildURLMixin, { findRecord: function(store, type, id, snapshot) { var url = this.buildURL(type.modelName, id, snapshot, 'findRecord'); return this.ajax(url, 'GET'); } }); ``` ### Attributes The `host` and `namespace` attributes will be used if defined, and are optional. @class BuildURLMixin @namespace DS */ exports.default = _ember.default.Mixin.create({ /** Builds a URL for a given type and optional ID. By default, it pluralizes the type's name (for example, 'post' becomes 'posts' and 'person' becomes 'people'). To override the pluralization see [pathForType](#method_pathForType). If an ID is specified, it adds the ID to the path generated for the type, separated by a `/`. When called by RESTAdapter.findMany() the `id` and `snapshot` parameters will be arrays of ids and snapshots. @method buildURL @param {String} modelName @param {(String|Array|Object)} id single id or array of ids or query @param {(DS.Snapshot|Array)} snapshot single snapshot or array of snapshots @param {String} requestType @param {Object} query object of query parameters to send for query requests. @return {String} url */ buildURL: function (modelName, id, snapshot, requestType, query) { switch (requestType) { case 'findRecord': return this.urlForFindRecord(id, modelName, snapshot); case 'findAll': return this.urlForFindAll(modelName, snapshot); case 'query': return this.urlForQuery(query, modelName); case 'queryRecord': return this.urlForQueryRecord(query, modelName); case 'findMany': return this.urlForFindMany(id, modelName, snapshot); case 'findHasMany': return this.urlForFindHasMany(id, modelName, snapshot); case 'findBelongsTo': return this.urlForFindBelongsTo(id, modelName, snapshot); case 'createRecord': return this.urlForCreateRecord(modelName, snapshot); case 'updateRecord': return this.urlForUpdateRecord(id, modelName, snapshot); case 'deleteRecord': return this.urlForDeleteRecord(id, modelName, snapshot); default: return this._buildURL(modelName, id); } }, /** @method _buildURL @private @param {String} modelName @param {String} id @return {String} url */ _buildURL: function (modelName, id) { var path = void 0; var url = []; var host = get(this, 'host'); var prefix = this.urlPrefix(); if (modelName) { path = this.pathForType(modelName); if (path) { url.push(path); } } if (id) { url.push(encodeURIComponent(id)); } if (prefix) { url.unshift(prefix); } url = url.join('/'); if (!host && url && url.charAt(0) !== '/') { url = '/' + url; } return url; }, /** Builds a URL for a `store.findRecord(type, id)` call. Example: ```app/adapters/user.js import DS from 'ember-data'; export default DS.JSONAPIAdapter.extend({ urlForFindRecord(id, modelName, snapshot) { let baseUrl = this.buildURL(); return `${baseUrl}/users/${snapshot.adapterOptions.user_id}/playlists/${id}`; } }); ``` @method urlForFindRecord @param {String} id @param {String} modelName @param {DS.Snapshot} snapshot @return {String} url */ urlForFindRecord: function (id, modelName, snapshot) { return this._buildURL(modelName, id); }, /** Builds a URL for a `store.findAll(type)` call. Example: ```app/adapters/comment.js import DS from 'ember-data'; export default DS.JSONAPIAdapter.extend({ urlForFindAll(modelName, snapshot) { return 'data/comments.json'; } }); ``` @method urlForFindAll @param {String} modelName @param {DS.SnapshotRecordArray} snapshot @return {String} url */ urlForFindAll: function (modelName, snapshot) { return this._buildURL(modelName); }, /** Builds a URL for a `store.query(type, query)` call. Example: ```app/adapters/application.js import DS from 'ember-data'; export default DS.RESTAdapter.extend({ host: 'https://api.github.com', urlForQuery (query, modelName) { switch(modelName) { case 'repo': return `https://api.github.com/orgs/${query.orgId}/repos`; default: return this._super(...arguments); } } }); ``` @method urlForQuery @param {Object} query @param {String} modelName @return {String} url */ urlForQuery: function (query, modelName) { return this._buildURL(modelName); }, /** Builds a URL for a `store.queryRecord(type, query)` call. Example: ```app/adapters/application.js import DS from 'ember-data'; export default DS.RESTAdapter.extend({ urlForQueryRecord({ slug }, modelName) { let baseUrl = this.buildURL(); return `${baseUrl}/${encodeURIComponent(slug)}`; } }); ``` @method urlForQueryRecord @param {Object} query @param {String} modelName @return {String} url */ urlForQueryRecord: function (query, modelName) { return this._buildURL(modelName); }, /** Builds a URL for coalesceing multiple `store.findRecord(type, id)` records into 1 request when the adapter's `coalesceFindRequests` property is true. Example: ```app/adapters/application.js import DS from 'ember-data'; export default DS.RESTAdapter.extend({ urlForFindMany(ids, modelName) { let baseUrl = this.buildURL(); return `${baseUrl}/coalesce`; } }); ``` @method urlForFindMany @param {Array} ids @param {String} modelName @param {Array} snapshots @return {String} url */ urlForFindMany: function (ids, modelName, snapshots) { return this._buildURL(modelName); }, /** Builds a URL for fetching a async hasMany relationship when a url is not provided by the server. Example: ```app/adapters/application.js import DS from 'ember-data'; export default DS.JSONAPIAdapter.extend({ urlForFindHasMany(id, modelName, snapshot) { let baseUrl = this.buildURL(id, modelName); return `${baseUrl}/relationships`; } }); ``` @method urlForFindHasMany @param {String} id @param {String} modelName @param {DS.Snapshot} snapshot @return {String} url */ urlForFindHasMany: function (id, modelName, snapshot) { return this._buildURL(modelName, id); }, /** Builds a URL for fetching a async belongsTo relationship when a url is not provided by the server. Example: ```app/adapters/application.js import DS from 'ember-data'; export default DS.JSONAPIAdapter.extend({ urlForFindBelongsTo(id, modelName, snapshot) { let baseUrl = this.buildURL(id, modelName); return `${baseUrl}/relationships`; } }); ``` @method urlForFindBelongsTo @param {String} id @param {String} modelName @param {DS.Snapshot} snapshot @return {String} url */ urlForFindBelongsTo: function (id, modelName, snapshot) { return this._buildURL(modelName, id); }, /** Builds a URL for a `record.save()` call when the record was created locally using `store.createRecord()`. Example: ```app/adapters/application.js import DS from 'ember-data'; export default DS.RESTAdapter.extend({ urlForCreateRecord(modelName, snapshot) { return this._super(...arguments) + '/new'; } }); ``` @method urlForCreateRecord @param {String} modelName @param {DS.Snapshot} snapshot @return {String} url */ urlForCreateRecord: function (modelName, snapshot) { return this._buildURL(modelName); }, /** Builds a URL for a `record.save()` call when the record has been update locally. Example: ```app/adapters/application.js import DS from 'ember-data'; export default DS.RESTAdapter.extend({ urlForUpdateRecord(id, modelName, snapshot) { return `/${id}/feed?access_token=${snapshot.adapterOptions.token}`; } }); ``` @method urlForUpdateRecord @param {String} id @param {String} modelName @param {DS.Snapshot} snapshot @return {String} url */ urlForUpdateRecord: function (id, modelName, snapshot) { return this._buildURL(modelName, id); }, /** Builds a URL for a `record.save()` call when the record has been deleted locally. Example: ```app/adapters/application.js import DS from 'ember-data'; export default DS.RESTAdapter.extend({ urlForDeleteRecord(id, modelName, snapshot) { return this._super(...arguments) + '/destroy'; } }); ``` @method urlForDeleteRecord @param {String} id @param {String} modelName @param {DS.Snapshot} snapshot @return {String} url */ urlForDeleteRecord: function (id, modelName, snapshot) { return this._buildURL(modelName, id); }, /** @method urlPrefix @private @param {String} path @param {String} parentURL @return {String} urlPrefix */ urlPrefix: function (path, parentURL) { var host = get(this, 'host'); var namespace = get(this, 'namespace'); if (!host || host === '/') { host = ''; } if (path) { // Protocol relative url if (/^\/\//.test(path) || /http(s)?:\/\//.test(path)) { // Do nothing, the full host is already included. return path; // Absolute path } else if (path.charAt(0) === '/') { return '' + host + path; // Relative path } else { return parentURL + '/' + path; } } // No path provided var url = []; if (host) { url.push(host); } if (namespace) { url.push(namespace); } return url.join('/'); }, /** Determines the pathname for a given type. By default, it pluralizes the type's name (for example, 'post' becomes 'posts' and 'person' becomes 'people'). ### Pathname customization For example if you have an object LineItem with an endpoint of "/line_items/". ```app/adapters/application.js import DS from 'ember-data'; import { pluralize } from 'ember-inflector'; export default DS.RESTAdapter.extend({ pathForType: function(modelName) { var decamelized = Ember.String.decamelize(modelName); return pluralize(decamelized); } }); ``` @method pathForType @param {String} modelName @return {String} path **/ pathForType: function (modelName) { var camelized = _ember.default.String.camelize(modelName); return (0, _emberInflector.pluralize)(camelized); } }); }); define('ember-data/-private/adapters/errors', ['exports', 'ember'], function (exports, _ember) { 'use strict'; exports.__esModule = true; exports.ServerError = exports.ConflictError = exports.NotFoundError = exports.ForbiddenError = exports.UnauthorizedError = exports.AbortError = exports.TimeoutError = exports.InvalidError = undefined; exports.AdapterError = AdapterError; exports.errorsHashToArray = errorsHashToArray; exports.errorsArrayToHash = errorsArrayToHash; var EmberError = _ember.default.Error; var SOURCE_POINTER_REGEXP = /^\/?data\/(attributes|relationships)\/(.*)/; var SOURCE_POINTER_PRIMARY_REGEXP = /^\/?data/; var PRIMARY_ATTRIBUTE_KEY = 'base'; /** A `DS.AdapterError` is used by an adapter to signal that an error occurred during a request to an external API. It indicates a generic error, and subclasses are used to indicate specific error states. The following subclasses are provided: - `DS.InvalidError` - `DS.TimeoutError` - `DS.AbortError` - `DS.UnauthorizedError` - `DS.ForbiddenError` - `DS.NotFoundError` - `DS.ConflictError` - `DS.ServerError` To create a custom error to signal a specific error state in communicating with an external API, extend the `DS.AdapterError`. For example if the external API exclusively used HTTP `503 Service Unavailable` to indicate it was closed for maintenance: ```app/adapters/maintenance-error.js import DS from 'ember-data'; export default DS.AdapterError.extend({ message: "Down for maintenance." }); ``` This error would then be returned by an adapter's `handleResponse` method: ```app/adapters/application.js import DS from 'ember-data'; import MaintenanceError from './maintenance-error'; export default DS.JSONAPIAdapter.extend({ handleResponse(status) { if (503 === status) { return new MaintenanceError(); } return this._super(...arguments); } }); ``` And can then be detected in an application and used to send the user to an `under-maintenance` route: ```app/routes/application.js import Ember from 'ember'; import MaintenanceError from '../adapters/maintenance-error'; export default Ember.Route.extend({ actions: { error(error, transition) { if (error instanceof MaintenanceError) { this.transitionTo('under-maintenance'); return; } // ...other error handling logic } } }); ``` @class AdapterError @namespace DS */ function AdapterError(errors) { var message = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : 'Adapter operation failed'; this.isAdapterError = true; EmberError.call(this, message); this.errors = errors || [{ title: 'Adapter Error', detail: message }]; } function extendFn(ErrorClass) { return function () { var _ref = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : {}, defaultMessage = _ref.message; return extend(ErrorClass, defaultMessage); }; } function extend(ParentErrorClass, defaultMessage) { var ErrorClass = function (errors, message) { (false && _ember.default.assert('`AdapterError` expects json-api formatted errors array.', Array.isArray(errors || []))); ParentErrorClass.call(this, errors, message || defaultMessage); }; ErrorClass.prototype = Object.create(ParentErrorClass.prototype); ErrorClass.extend = extendFn(ErrorClass); return ErrorClass; } AdapterError.prototype = Object.create(EmberError.prototype); AdapterError.extend = extendFn(AdapterError); /** A `DS.InvalidError` is used by an adapter to signal the external API was unable to process a request because the content was not semantically correct or meaningful per the API. Usually this means a record failed some form of server side validation. When a promise from an adapter is rejected with a `DS.InvalidError` the record will transition to the `invalid` state and the errors will be set to the `errors` property on the record. For Ember Data to correctly map errors to their corresponding properties on the model, Ember Data expects each error to be a valid json-api error object with a `source/pointer` that matches the property name. For example if you had a Post model that looked like this. ```app/models/post.js import DS from 'ember-data'; export default DS.Model.extend({ title: DS.attr('string'), content: DS.attr('string') }); ``` To show an error from the server related to the `title` and `content` properties your adapter could return a promise that rejects with a `DS.InvalidError` object that looks like this: ```app/adapters/post.js import Ember from 'ember'; import DS from 'ember-data'; export default DS.RESTAdapter.extend({ updateRecord() { // Fictional adapter that always rejects return Ember.RSVP.reject(new DS.InvalidError([ { detail: 'Must be unique', source: { pointer: '/data/attributes/title' } }, { detail: 'Must not be blank', source: { pointer: '/data/attributes/content'} } ])); } }); ``` Your backend may use different property names for your records the store will attempt extract and normalize the errors using the serializer's `extractErrors` method before the errors get added to the the model. As a result, it is safe for the `InvalidError` to wrap the error payload unaltered. @class InvalidError @namespace DS */ var InvalidError = exports.InvalidError = extend(AdapterError, 'The adapter rejected the commit because it was invalid'); /** A `DS.TimeoutError` is used by an adapter to signal that a request to the external API has timed out. I.e. no response was received from the external API within an allowed time period. An example use case would be to warn the user to check their internet connection if an adapter operation has timed out: ```app/routes/application.js import Ember from 'ember'; import DS from 'ember-data'; const { TimeoutError } = DS; export default Ember.Route.extend({ actions: { error(error, transition) { if (error instanceof TimeoutError) { // alert the user alert('Are you still connected to the internet?'); return; } // ...other error handling logic } } }); ``` @class TimeoutError @namespace DS */ var TimeoutError = exports.TimeoutError = extend(AdapterError, 'The adapter operation timed out'); /** A `DS.AbortError` is used by an adapter to signal that a request to the external API was aborted. For example, this can occur if the user navigates away from the current page after a request to the external API has been initiated but before a response has been received. @class AbortError @namespace DS */ var AbortError = exports.AbortError = extend(AdapterError, 'The adapter operation was aborted'); /** A `DS.UnauthorizedError` equates to a HTTP `401 Unauthorized` response status. It is used by an adapter to signal that a request to the external API was rejected because authorization is required and has failed or has not yet been provided. An example use case would be to redirect the user to a log in route if a request is unauthorized: ```app/routes/application.js import Ember from 'ember'; import DS from 'ember-data'; const { UnauthorizedError } = DS; export default Ember.Route.extend({ actions: { error(error, transition) { if (error instanceof UnauthorizedError) { // go to the sign in route this.transitionTo('login'); return; } // ...other error handling logic } } }); ``` @class UnauthorizedError @namespace DS */ var UnauthorizedError = exports.UnauthorizedError = extend(AdapterError, 'The adapter operation is unauthorized'); /** A `DS.ForbiddenError` equates to a HTTP `403 Forbidden` response status. It is used by an adapter to signal that a request to the external API was valid but the server is refusing to respond to it. If authorization was provided and is valid, then the authenticated user does not have the necessary permissions for the request. @class ForbiddenError @namespace DS */ var ForbiddenError = exports.ForbiddenError = extend(AdapterError, 'The adapter operation is forbidden'); /** A `DS.NotFoundError` equates to a HTTP `404 Not Found` response status. It is used by an adapter to signal that a request to the external API was rejected because the resource could not be found on the API. An example use case would be to detect if the user has entered a route for a specific model that does not exist. For example: ```app/routes/post.js import Ember from 'ember'; import DS from 'ember-data'; const { NotFoundError } = DS; export default Ember.Route.extend({ model(params) { return this.get('store').findRecord('post', params.post_id); }, actions: { error(error, transition) { if (error instanceof NotFoundError) { // redirect to a list of all posts instead this.transitionTo('posts'); } else { // otherwise let the error bubble return true; } } } }); ``` @class NotFoundError @namespace DS */ var NotFoundError = exports.NotFoundError = extend(AdapterError, 'The adapter could not find the resource'); /** A `DS.ConflictError` equates to a HTTP `409 Conflict` response status. It is used by an adapter to indicate that the request could not be processed because of a conflict in the request. An example scenario would be when creating a record with a client generated id but that id is already known to the external API. @class ConflictError @namespace DS */ var ConflictError = exports.ConflictError = extend(AdapterError, 'The adapter operation failed due to a conflict'); /** A `DS.ServerError` equates to a HTTP `500 Internal Server Error` response status. It is used by the adapter to indicate that a request has failed because of an error in the external API. @class ServerError @namespace DS */ var ServerError = exports.ServerError = extend(AdapterError, 'The adapter operation failed due to a server error'); /** Convert an hash of errors into an array with errors in JSON-API format. ```javascript import DS from 'ember-data'; const { errorsHashToArray } = DS; let errors = { base: 'Invalid attributes on saving this record', name: 'Must be present', age: ['Must be present', 'Must be a number'] }; let errorsArray = errorsHashToArray(errors); // [ // { // title: "Invalid Document", // detail: "Invalid attributes on saving this record", // source: { pointer: "/data" } // }, // { // title: "Invalid Attribute", // detail: "Must be present", // source: { pointer: "/data/attributes/name" } // }, // { // title: "Invalid Attribute", // detail: "Must be present", // source: { pointer: "/data/attributes/age" } // }, // { // title: "Invalid Attribute", // detail: "Must be a number", // source: { pointer: "/data/attributes/age" } // } // ] ``` @method errorsHashToArray @public @namespace @for DS @param {Object} errors hash with errors as properties @return {Array} array of errors in JSON-API format */ function errorsHashToArray(errors) { var out = []; if (_ember.default.isPresent(errors)) { Object.keys(errors).forEach(function (key) { var messages = _ember.default.makeArray(errors[key]); for (var i = 0; i < messages.length; i++) { var title = 'Invalid Attribute'; var pointer = '/data/attributes/' + key; if (key === PRIMARY_ATTRIBUTE_KEY) { title = 'Invalid Document'; pointer = '/data'; } out.push({ title: title, detail: messages[i], source: { pointer: pointer } }); } }); } return out; } /** Convert an array of errors in JSON-API format into an object. ```javascript import DS from 'ember-data'; const { errorsArrayToHash } = DS; let errorsArray = [ { title: 'Invalid Attribute', detail: 'Must be present', source: { pointer: '/data/attributes/name' } }, { title: 'Invalid Attribute', detail: 'Must be present', source: { pointer: '/data/attributes/age' } }, { title: 'Invalid Attribute', detail: 'Must be a number', source: { pointer: '/data/attributes/age' } } ]; let errors = errorsArrayToHash(errorsArray); // { // "name": ["Must be present"], // "age": ["Must be present", "must be a number"] // } ``` @method errorsArrayToHash @public @namespace @for DS @param {Array} errors array of errors in JSON-API format @return {Object} */ function errorsArrayToHash(errors) { var out = {}; if (_ember.default.isPresent(errors)) { errors.forEach(function (error) { if (error.source && error.source.pointer) { var key = error.source.pointer.match(SOURCE_POINTER_REGEXP); if (key) { key = key[2]; } else if (error.source.pointer.search(SOURCE_POINTER_PRIMARY_REGEXP) !== -1) { key = PRIMARY_ATTRIBUTE_KEY; } if (key) { out[key] = out[key] || []; out[key].push(error.detail || error.title); } } }); } return out; } }); define('ember-data/-private/core', ['exports', 'ember', 'ember-data/version'], function (exports, _ember, _version) { 'use strict'; exports.__esModule = true; /** @module ember-data */ /** All Ember Data classes, methods and functions are defined inside of this namespace. @class DS @static */ /** @property VERSION @type String @static */ var DS = _ember.default.Namespace.create({ VERSION: _version.default, name: "DS" }); if (_ember.default.libraries) { _ember.default.libraries.registerCoreLibrary('Ember Data', DS.VERSION); } exports.default = DS; }); define('ember-data/-private/features', ['exports', 'ember'], function (exports, _ember) { 'use strict'; exports.__esModule = true; exports.default = isEnabled; function isEnabled() { var _Ember$FEATURES; return (_Ember$FEATURES = _ember.default.FEATURES).isEnabled.apply(_Ember$FEATURES, arguments); } }); define('ember-data/-private/global', ['exports'], function (exports) { 'use strict'; exports.__esModule = true; /* globals global, window, self */ // originally from https://github.com/emberjs/ember.js/blob/c0bd26639f50efd6a03ee5b87035fd200e313b8e/packages/ember-environment/lib/global.js // from lodash to catch fake globals function checkGlobal(value) { return value && value.Object === Object ? value : undefined; } // element ids can ruin global miss checks function checkElementIdShadowing(value) { return value && value.nodeType === undefined ? value : undefined; } // export real global exports.default = checkGlobal(checkElementIdShadowing(typeof global === 'object' && global)) || checkGlobal(typeof self === 'object' && self) || checkGlobal(typeof window === 'object' && window) || new Function('return this')(); }); define('ember-data/-private', ['exports', 'ember-data/-private/system/model/model', 'ember-data/-private/system/model/errors', 'ember-data/-private/system/store', 'ember-data/-private/core', 'ember-data/-private/system/relationships/belongs-to', 'ember-data/-private/system/relationships/has-many', 'ember-data/-private/adapters/build-url-mixin', 'ember-data/-private/system/snapshot', 'ember-data/-private/adapters/errors', 'ember-data/-private/system/normalize-model-name', 'ember-data/-private/utils', 'ember-data/-private/system/coerce-id', 'ember-data/-private/utils/parse-response-headers', 'ember-data/-private/global', 'ember-data/-private/features', 'ember-data/-private/system/model/states', 'ember-data/-private/system/model/internal-model', 'ember-data/-private/system/store/container-instance-cache', 'ember-data/-private/system/promise-proxies', 'ember-data/-private/system/record-arrays', 'ember-data/-private/system/many-array', 'ember-data/-private/system/record-array-manager', 'ember-data/-private/system/relationships/state/relationship', 'ember-data/-private/system/debug/debug-adapter', 'ember-data/-private/system/diff-array', 'ember-data/-private/system/relationships/relationship-payloads-manager', 'ember-data/-private/system/relationships/relationship-payloads', 'ember-data/-private/system/snapshot-record-array'], function (exports, _model, _errors, _store, _core, _belongsTo, _hasMany, _buildUrlMixin, _snapshot, _errors2, _normalizeModelName, _utils, _coerceId, _parseResponseHeaders, _global, _features, _states, _internalModel, _containerInstanceCache, _promiseProxies, _recordArrays, _manyArray, _recordArrayManager, _relationship, _debugAdapter, _diffArray, _relationshipPayloadsManager, _relationshipPayloads, _snapshotRecordArray) { 'use strict'; exports.__esModule = true; Object.defineProperty(exports, 'Model', { enumerable: true, get: function () { return _model.default; } }); Object.defineProperty(exports, 'Errors', { enumerable: true, get: function () { return _errors.default; } }); Object.defineProperty(exports, 'Store', { enumerable: true, get: function () { return _store.default; } }); Object.defineProperty(exports, 'DS', { enumerable: true, get: function () { return _core.default; } }); Object.defineProperty(exports, 'belongsTo', { enumerable: true, get: function () { return _belongsTo.default; } }); Object.defineProperty(exports, 'hasMany', { enumerable: true, get: function () { return _hasMany.default; } }); Object.defineProperty(exports, 'BuildURLMixin', { enumerable: true, get: function () { return _buildUrlMixin.default; } }); Object.defineProperty(exports, 'Snapshot', { enumerable: true, get: function () { return _snapshot.default; } }); Object.defineProperty(exports, 'AdapterError', { enumerable: true, get: function () { return _errors2.AdapterError; } }); Object.defineProperty(exports, 'InvalidError', { enumerable: true, get: function () { return _errors2.InvalidError; } }); Object.defineProperty(exports, 'UnauthorizedError', { enumerable: true, get: function () { return _errors2.UnauthorizedError; } }); Object.defineProperty(exports, 'ForbiddenError', { enumerable: true, get: function () { return _errors2.ForbiddenError; } }); Object.defineProperty(exports, 'NotFoundError', { enumerable: true, get: function () { return _errors2.NotFoundError; } }); Object.defineProperty(exports, 'ConflictError', { enumerable: true, get: function () { return _errors2.ConflictError; } }); Object.defineProperty(exports, 'ServerError', { enumerable: true, get: function () { return _errors2.ServerError; } }); Object.defineProperty(exports, 'TimeoutError', { enumerable: true, get: function () { return _errors2.TimeoutError; } }); Object.defineProperty(exports, 'AbortError', { enumerable: true, get: function () { return _errors2.AbortError; } }); Object.defineProperty(exports, 'errorsHashToArray', { enumerable: true, get: function () { return _errors2.errorsHashToArray; } }); Object.defineProperty(exports, 'errorsArrayToHash', { enumerable: true, get: function () { return _errors2.errorsArrayToHash; } }); Object.defineProperty(exports, 'normalizeModelName', { enumerable: true, get: function () { return _normalizeModelName.default; } }); Object.defineProperty(exports, 'getOwner', { enumerable: true, get: function () { return _utils.getOwner; } }); Object.defineProperty(exports, 'modelHasAttributeOrRelationshipNamedType', { enumerable: true, get: function () { return _utils.modelHasAttributeOrRelationshipNamedType; } }); Object.defineProperty(exports, 'coerceId', { enumerable: true, get: function () { return _coerceId.default; } }); Object.defineProperty(exports, 'parseResponseHeaders', { enumerable: true, get: function () { return _parseResponseHeaders.default; } }); Object.defineProperty(exports, 'global', { enumerable: true, get: function () { return _global.default; } }); Object.defineProperty(exports, 'isEnabled', { enumerable: true, get: function () { return _features.default; } }); Object.defineProperty(exports, 'RootState', { enumerable: true, get: function () { return _states.default; } }); Object.defineProperty(exports, 'InternalModel', { enumerable: true, get: function () { return _internalModel.default; } }); Object.defineProperty(exports, 'ContainerInstanceCache', { enumerable: true, get: function () { return _containerInstanceCache.default; } }); Object.defineProperty(exports, 'PromiseArray', { enumerable: true, get: function () { return _promiseProxies.PromiseArray; } }); Object.defineProperty(exports, 'PromiseObject', { enumerable: true, get: function () { return _promiseProxies.PromiseObject; } }); Object.defineProperty(exports, 'PromiseManyArray', { enumerable: true, get: function () { return _promiseProxies.PromiseManyArray; } }); Object.defineProperty(exports, 'RecordArray', { enumerable: true, get: function () { return _recordArrays.RecordArray; } }); Object.defineProperty(exports, 'FilteredRecordArray', { enumerable: true, get: function () { return _recordArrays.FilteredRecordArray; } }); Object.defineProperty(exports, 'AdapterPopulatedRecordArray', { enumerable: true, get: function () { return _recordArrays.AdapterPopulatedRecordArray; } }); Object.defineProperty(exports, 'ManyArray', { enumerable: true, get: function () { return _manyArray.default; } }); Object.defineProperty(exports, 'RecordArrayManager', { enumerable: true, get: function () { return _recordArrayManager.default; } }); Object.defineProperty(exports, 'Relationship', { enumerable: true, get: function () { return _relationship.default; } }); Object.defineProperty(exports, 'DebugAdapter', { enumerable: true, get: function () { return _debugAdapter.default; } }); Object.defineProperty(exports, 'diffArray', { enumerable: true, get: function () { return _diffArray.default; } }); Object.defineProperty(exports, 'RelationshipPayloadsManager', { enumerable: true, get: function () { return _relationshipPayloadsManager.default; } }); Object.defineProperty(exports, 'RelationshipPayloads', { enumerable: true, get: function () { return _relationshipPayloads.default; } }); Object.defineProperty(exports, 'SnapshotRecordArray', { enumerable: true, get: function () { return _snapshotRecordArray.default; } }); }); define("ember-data/-private/system/clone-null", ["exports"], function (exports) { "use strict"; exports.__esModule = true; exports.default = cloneNull; function cloneNull(source) { var clone = Object.create(null); for (var key in source) { clone[key] = source[key]; } return clone; } }); define('ember-data/-private/system/coerce-id', ['exports'], function (exports) { 'use strict'; exports.__esModule = true; exports.default = coerceId; // Used by the store to normalize IDs entering the store. Despite the fact // that developers may provide IDs as numbers (e.g., `store.findRecord('person', 1)`), // it is important that internally we use strings, since IDs may be serialized // and lose type information. For example, Ember's router may put a record's // ID into the URL, and if we later try to deserialize that URL and find the // corresponding record, we will not know if it is a string or a number. function coerceId(id) { if (id === null || id === undefined || id === '') { return null; } if (typeof id === 'string') { return id; } return '' + id; } }); define('ember-data/-private/system/debug/debug-adapter', ['exports', 'ember', 'ember-data/-private/system/model/model'], function (exports, _ember, _model) { 'use strict'; exports.__esModule = true; /** @module ember-data */ var capitalize = _ember.default.String.capitalize; var underscore = _ember.default.String.underscore; var assert = _ember.default.assert, get = _ember.default.get; exports.default = _ember.default.DataAdapter.extend({ getFilters: function () { return [{ name: 'isNew', desc: 'New' }, { name: 'isModified', desc: 'Modified' }, { name: 'isClean', desc: 'Clean' }]; }, detect: function (typeClass) { return typeClass !== _model.default && _model.default.detect(typeClass); }, columnsForType: function (typeClass) { var columns = [{ name: 'id', desc: 'Id' }]; var count = 0; var self = this; get(typeClass, 'attributes').forEach(function (meta, name) { if (count++ > self.attributeLimit) { return false; } var desc = capitalize(underscore(name).replace('_', ' ')); columns.push({ name: name, desc: desc }); }); return columns; }, getRecords: function (modelClass, modelName) { if (arguments.length < 2) { // Legacy Ember.js < 1.13 support var containerKey = modelClass._debugContainerKey; if (containerKey) { var match = containerKey.match(/model:(.*)/); if (match) { modelName = match[1]; } } } assert("Cannot find model name. Please upgrade to Ember.js >= 1.13 for Ember Inspector support", !!modelName); return this.get('store').peekAll(modelName); }, getRecordColumnValues: function (record) { var _this = this; var count = 0; var columnValues = { id: get(record, 'id') }; record.eachAttribute(function (key) { if (count++ > _this.attributeLimit) { return false; } columnValues[key] = get(record, key); }); return columnValues; }, getRecordKeywords: function (record) { var keywords = []; var keys = _ember.default.A(['id']); record.eachAttribute(function (key) { return keys.push(key); }); keys.forEach(function (key) { return keywords.push(get(record, key)); }); return keywords; }, getRecordFilterValues: function (record) { return { isNew: record.get('isNew'), isModified: record.get('hasDirtyAttributes') && !record.get('isNew'), isClean: !record.get('hasDirtyAttributes') }; }, getRecordColor: function (record) { var color = 'black'; if (record.get('isNew')) { color = 'green'; } else if (record.get('hasDirtyAttributes')) { color = 'blue'; } return color; }, observeRecord: function (record, recordUpdated) { var releaseMethods = _ember.default.A(); var keysToObserve = _ember.default.A(['id', 'isNew', 'hasDirtyAttributes']); record.eachAttribute(function (key) { return keysToObserve.push(key); }); var adapter = this; keysToObserve.forEach(function (key) { var handler = function () { recordUpdated(adapter.wrapRecord(record)); }; _ember.default.addObserver(record, key, handler); releaseMethods.push(function () { _ember.default.removeObserver(record, key, handler); }); }); var release = function () { releaseMethods.forEach(function (fn) { return fn(); }); }; return release; } }); }); define("ember-data/-private/system/diff-array", ["exports"], function (exports) { "use strict"; exports.__esModule = true; exports.default = diffArray; /** @namespace @method diffArray @private @param {Array} oldArray the old array @param {Array} newArray the new array @return {hash} { firstChangeIndex: <integer>, // null if no change addedCount: <integer>, // 0 if no change removedCount: <integer> // 0 if no change } */ function diffArray(oldArray, newArray) { var oldLength = oldArray.length; var newLength = newArray.length; var shortestLength = Math.min(oldLength, newLength); var firstChangeIndex = null; // null signifies no changes // find the first change for (var i = 0; i < shortestLength; i++) { // compare each item in the array if (oldArray[i] !== newArray[i]) { firstChangeIndex = i; break; } } if (firstChangeIndex === null && newLength !== oldLength) { // no change found in the overlapping block // and array lengths differ, // so change starts at end of overlap firstChangeIndex = shortestLength; } var addedCount = 0; var removedCount = 0; if (firstChangeIndex !== null) { // we found a change, find the end of the change var unchangedEndBlockLength = shortestLength - firstChangeIndex; // walk back from the end of both arrays until we find a change for (var _i = 1; _i <= shortestLength; _i++) { // compare each item in the array if (oldArray[oldLength - _i] !== newArray[newLength - _i]) { unchangedEndBlockLength = _i - 1; break; } } addedCount = newLength - unchangedEndBlockLength - firstChangeIndex; removedCount = oldLength - unchangedEndBlockLength - firstChangeIndex; } return { firstChangeIndex: firstChangeIndex, addedCount: addedCount, removedCount: removedCount }; } }); define('ember-data/-private/system/identity-map', ['exports', 'ember-data/-private/system/internal-model-map'], function (exports, _internalModelMap) { 'use strict'; exports.__esModule = true; function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } } var IdentityMap = function () { function IdentityMap() { this._map = Object.create(null); } /** Retrieves the `InternalModelMap` for a given modelName, creating one if one did not already exist. This is similar to `getWithDefault` or `get` on a `MapWithDefault` @method retrieve @param modelName a previously normalized modelName @returns {InternalModelMap} the InternalModelMap for the given modelName */ IdentityMap.prototype.retrieve = function retrieve(modelName) { var map = this._map[modelName]; if (map === undefined) { map = this._map[modelName] = new _internalModelMap.default(modelName); } return map; }; IdentityMap.prototype.clear = function clear() { var map = this._map; var keys = Object.keys(map); for (var i = 0; i < keys.length; i++) { var key = keys[i]; map[key].clear(); } }; return IdentityMap; }(); exports.default = IdentityMap; }); define('ember-data/-private/system/internal-model-map', ['exports', 'ember-data/-private/system/model/internal-model'], function (exports, _internalModel) { 'use strict'; exports.__esModule = true; function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } } var _createClass = function () { function defineProperties(target, props) { for (var i = 0; i < props.length; i++) { var descriptor = props[i]; descriptor.enumerable = descriptor.enumerable || false; descriptor.configurable = true; if ("value" in descriptor) descriptor.writable = true; Object.defineProperty(target, descriptor.key, descriptor); } } return function (Constructor, protoProps, staticProps) { if (protoProps) defineProperties(Constructor.prototype, protoProps); if (staticProps) defineProperties(Constructor, staticProps); return Constructor; }; }(); var InternalModelMap = function () { function InternalModelMap(modelName) { this.modelName = modelName; this._idToModel = Object.create(null); this._models = []; this._metadata = null; } /** * * @param id * @returns {InternalModel} */ InternalModelMap.prototype.get = function get(id) { return this._idToModel[id]; }; InternalModelMap.prototype.has = function has(id) { return !!this._idToModel[id]; }; InternalModelMap.prototype.set = function set(id, internalModel) { (false && Ember.assert('You cannot index an internalModel by an empty id\'', id)); (false && Ember.assert('You cannot set an index for an internalModel to something other than an internalModel', internalModel instanceof _internalModel.default)); (false && Ember.assert('You cannot set an index for an internalModel that is not in the InternalModelMap', this.contains(internalModel))); (false && Ember.assert('You cannot update the id index of an InternalModel once set. Attempted to update ' + id + '.', !this.has(id) || this.get(id) === internalModel)); this._idToModel[id] = internalModel; }; InternalModelMap.prototype.add = function add(internalModel, id) { (false && Ember.assert('You cannot re-add an already present InternalModel to the InternalModelMap.', !this.contains(internalModel))); if (id) { this._idToModel[id] = internalModel; } this._models.push(internalModel); }; InternalModelMap.prototype.remove = function remove(internalModel, id) { delete this._idToModel[id]; var loc = this._models.indexOf(internalModel); if (loc !== -1) { this._models.splice(loc, 1); } }; InternalModelMap.prototype.contains = function contains(internalModel) { return this._models.indexOf(internalModel) !== -1; }; InternalModelMap.prototype.clear = function clear() { var models = this._models; this._models = []; for (var i = 0; i < models.length; i++) { var model = models[i]; model.unloadRecord(); } this._metadata = null; }; _createClass(InternalModelMap, [{ key: 'length', get: function () { return this._models.length; } }, { key: 'models', get: function () { return this._models; } }, { key: 'metadata', get: function () { return this._metadata || (this._metadata = Object.create(null)); } }, { key: 'type', get: function () { throw new Error('InternalModelMap.type is no longer available'); } }]); return InternalModelMap; }(); exports.default = InternalModelMap; }); define('ember-data/-private/system/is-array-like', ['exports', 'ember'], function (exports, _ember) { 'use strict'; exports.__esModule = true; exports.default = isArrayLike; /* We're using this to detect arrays and "array-like" objects. This is a copy of the `isArray` method found in `ember-runtime/utils` as we're currently unable to import non-exposed modules. This method was previously exposed as `Ember.isArray` but since https://github.com/emberjs/ember.js/pull/11463 `Ember.isArray` is an alias of `Array.isArray` hence removing the "array-like" part. */ function isArrayLike(obj) { if (!obj || obj.setInterval) { return false; } if (Array.isArray(obj)) { return true; } if (_ember.default.Array.detect(obj)) { return true; } var type = _ember.default.typeOf(obj); if ('array' === type) { return true; } if (obj.length !== undefined && 'object' === type) { return true; } return false; } }); define('ember-data/-private/system/many-array', ['exports', 'ember', 'ember-data/-private/system/promise-proxies', 'ember-data/-private/system/store/common', 'ember-data/-private/system/diff-array'], function (exports, _ember, _promiseProxies, _common, _diffArray) { 'use strict'; exports.__esModule = true; var get = _ember.default.get; exports.default = _ember.default.Object.extend(_ember.default.MutableArray, _ember.default.Evented, { init: function () { this._super.apply(this, arguments); /** The loading state of this array @property {Boolean} isLoaded */ this.isLoaded = false; this.length = 0; /** Used for async `hasMany` arrays to keep track of when they will resolve. @property {Ember.RSVP.Promise} promise @private */ this.promise = null; /** Metadata associated with the request for async hasMany relationships. Example Given that the server returns the following JSON payload when fetching a hasMany relationship: ```js { "comments": [{ "id": 1, "comment": "This is the first comment", }, { // ... }], "meta": { "page": 1, "total": 5 } } ``` You can then access the metadata via the `meta` property: ```js post.get('comments').then(function(comments) { var meta = comments.get('meta'); // meta.page => 1 // meta.total => 5 }); ``` @property {Object} meta @public */ this.meta = this.meta || null; /** `true` if the relationship is polymorphic, `false` otherwise. @property {Boolean} isPolymorphic @private */ this.isPolymorphic = this.isPolymorphic || false; /** The relationship which manages this array. @property {ManyRelationship} relationship @private */ this.relationship = this.relationship || null; this.currentState = []; this.flushCanonical(false); }, objectAt: function (index) { var internalModel = this.currentState[index]; if (internalModel === undefined) { return; } return internalModel.getRecord(); }, flushCanonical: function () { var isInitialized = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : true; // It’s possible the parent side of the relationship may have been unloaded by this point if (!(0, _common._objectIsAlive)(this)) { return; } var toSet = this.canonicalState; //a hack for not removing new records //TODO remove once we have proper diffing var newInternalModels = this.currentState.filter( // only add new internalModels which are not yet in the canonical state of this // relationship (a new internalModel can be in the canonical state if it has // been 'acknowleged' to be in the relationship via a store.push) function (internalModel) { return internalModel.isNew() && toSet.indexOf(internalModel) === -1; }); toSet = toSet.concat(newInternalModels); // diff to find changes var diff = (0, _diffArray.default)(this.currentState, toSet); if (diff.firstChangeIndex !== null) { // it's null if no change found // we found a change this.arrayContentWillChange(diff.firstChangeIndex, diff.removedCount, diff.addedCount); this.set('length', toSet.length); this.currentState = toSet; this.arrayContentDidChange(diff.firstChangeIndex, diff.removedCount, diff.addedCount); if (isInitialized && diff.addedCount > 0) { //notify only on additions //TODO only notify if unloaded this.relationship.notifyHasManyChanged(); } } }, internalReplace: function (idx, amt, objects) { if (!objects) { objects = []; } this.arrayContentWillChange(idx, amt, objects.length); this.currentState.splice.apply(this.currentState, [idx, amt].concat(objects)); this.set('length', this.currentState.length); this.arrayContentDidChange(idx, amt, objects.length); }, //TODO(Igor) optimize _removeInternalModels: function (internalModels) { for (var i = 0; i < internalModels.length; i++) { var index = this.currentState.indexOf(internalModels[i]); this.internalReplace(index, 1); } }, //TODO(Igor) optimize _addInternalModels: function (internalModels, idx) { if (idx === undefined) { idx = this.currentState.length; } this.internalReplace(idx, 0, internalModels); }, replace: function (idx, amt, objects) { var internalModels = void 0; if (amt > 0) { internalModels = this.currentState.slice(idx, idx + amt); this.get('relationship').removeInternalModels(internalModels); } if (objects) { this.get('relationship').addInternalModels(objects.map(function (obj) { return obj._internalModel; }), idx); } }, /** Reloads all of the records in the manyArray. If the manyArray holds a relationship that was originally fetched using a links url Ember Data will revisit the original links url to repopulate the relationship. If the manyArray holds the result of a `store.query()` reload will re-run the original query. Example ```javascript var user = store.peekRecord('user', 1) user.login().then(function() { user.get('permissions').then(function(permissions) { return permissions.reload(); }); }); ``` @method reload @public */ reload: function () { return this.relationship.reload(); }, /** Saves all of the records in the `ManyArray`. Example ```javascript store.findRecord('inbox', 1).then(function(inbox) { inbox.get('messages').then(function(messages) { messages.forEach(function(message) { message.set('isRead', true); }); messages.save() }); }); ``` @method save @return {DS.PromiseArray} promise */ save: function () { var manyArray = this; var promiseLabel = 'DS: ManyArray#save ' + get(this, 'type'); var promise = _ember.default.RSVP.all(this.invoke("save"), promiseLabel).then(function () { return manyArray; }, null, 'DS: ManyArray#save return ManyArray'); return _promiseProxies.PromiseArray.create({ promise: promise }); }, /** Create a child record within the owner @method createRecord @private @param {Object} hash @return {DS.Model} record */ createRecord: function (hash) { var store = get(this, 'store'); var type = get(this, 'type'); (false && _ember.default.assert('You cannot add \'' + type.modelName + '\' records to this polymorphic relationship.', !get(this, 'isPolymorphic'))); var record = store.createRecord(type.modelName, hash); this.pushObject(record); return record; } }); }); define('ember-data/-private/system/model/errors', ['exports', 'ember'], function (exports, _ember) { 'use strict'; exports.__esModule = true; var get = _ember.default.get, set = _ember.default.set, isEmpty = _ember.default.isEmpty, makeArray = _ember.default.makeArray, MapWithDefault = _ember.default.MapWithDefault; exports.default = _ember.default.ArrayProxy.extend(_ember.default.Evented, { /** Register with target handler @method registerHandlers @param {Object} target @param {Function} becameInvalid @param {Function} becameValid @deprecated */ registerHandlers: function (target, becameInvalid, becameValid) { (false && !(false) && _ember.default.deprecate('Record errors will no longer be evented.', false, { id: 'ds.errors.registerHandlers', until: '3.0.0' })); this._registerHandlers(target, becameInvalid, becameValid); }, /** Register with target handler @method _registerHandlers @private */ _registerHandlers: function (target, becameInvalid, becameValid) { this.on('becameInvalid', target, becameInvalid); this.on('becameValid', target, becameValid); }, /** @property errorsByAttributeName @type {Ember.MapWithDefault} @private */ errorsByAttributeName: _ember.default.computed(function () { return MapWithDefault.create({ defaultValue: function () { return _ember.default.A(); } }); }), /** Returns errors for a given attribute ```javascript let user = store.createRecord('user', { username: 'tomster', email: 'invalidEmail' }); user.save().catch(function(){ user.get('errors').errorsFor('email'); // returns: // [{attribute: "email", message: "Doesn't look like a valid email."}] }); ``` @method errorsFor @param {String} attribute @return {Array} */ errorsFor: function (attribute) { return get(this, 'errorsByAttributeName').get(attribute); }, /** An array containing all of the error messages for this record. This is useful for displaying all errors to the user. ```handlebars {{#each model.errors.messages as |message|}} <div class="error"> {{message}} </div> {{/each}} ``` @property messages @type {Array} */ messages: _ember.default.computed.mapBy('content', 'message'), /** @property content @type {Array} @private */ content: _ember.default.computed(function () { return _ember.default.A(); }), /** @method unknownProperty @private */ unknownProperty: function (attribute) { var errors = this.errorsFor(attribute); if (isEmpty(errors)) { return null; } return errors; }, /** Total number of errors. @property length @type {Number} @readOnly */ /** @property isEmpty @type {Boolean} @readOnly */ isEmpty: _ember.default.computed.not('length').readOnly(), /** Adds error messages to a given attribute and sends `becameInvalid` event to the record. Example: ```javascript if (!user.get('username') { user.get('errors').add('username', 'This field is required'); } ``` @method add @param {String} attribute @param {(Array|String)} messages @deprecated */ add: function (attribute, messages) { (false && _ember.default.warn('Interacting with a record errors object will no longer change the record state.', false, { id: 'ds.errors.add' })); var wasEmpty = get(this, 'isEmpty'); this._add(attribute, messages); if (wasEmpty && !get(this, 'isEmpty')) { this.trigger('becameInvalid'); } }, /** Adds error messages to a given attribute without sending event. @method _add @private */ _add: function (attribute, messages) { messages = this._findOrCreateMessages(attribute, messages); this.addObjects(messages); get(this, 'errorsByAttributeName').get(attribute).addObjects(messages); this.notifyPropertyChange(attribute); }, /** @method _findOrCreateMessages @private */ _findOrCreateMessages: function (attribute, messages) { var errors = this.errorsFor(attribute); var messagesArray = makeArray(messages); var _messages = new Array(messagesArray.length); for (var i = 0; i < messagesArray.length; i++) { var message = messagesArray[i]; var err = errors.findBy('message', message); if (err) { _messages[i] = err; } else { _messages[i] = { attribute: attribute, message: message }; } } return _messages; }, /** Removes all error messages from the given attribute and sends `becameValid` event to the record if there no more errors left. Example: ```app/models/user.js import DS from 'ember-data'; export default DS.Model.extend({ email: DS.attr('string'), twoFactorAuth: DS.attr('boolean'), phone: DS.attr('string') }); ``` ```app/routes/user/edit.js import Ember from 'ember'; export default Ember.Route.extend({ actions: { save: function(user) { if (!user.get('twoFactorAuth')) { user.get('errors').remove('phone'); } user.save(); } } }); ``` @method remove @param {String} attribute @deprecated */ remove: function (attribute) { (false && _ember.default.warn('Interacting with a record errors object will no longer change the record state.', false, { id: 'ds.errors.remove' })); if (get(this, 'isEmpty')) { return; } this._remove(attribute); if (get(this, 'isEmpty')) { this.trigger('becameValid'); } }, /** Removes all error messages from the given attribute without sending event. @method _remove @private */ _remove: function (attribute) { if (get(this, 'isEmpty')) { return; } var content = this.rejectBy('attribute', attribute); set(this, 'content', content); get(this, 'errorsByAttributeName').delete(attribute); this.notifyPropertyChange(attribute); }, /** Removes all error messages and sends `becameValid` event to the record. Example: ```app/routes/user/edit.js import Ember from 'ember'; export default Ember.Route.extend({ actions: { retrySave: function(user) { user.get('errors').clear(); user.save(); } } }); ``` @method clear @deprecated */ clear: function () { (false && _ember.default.warn('Interacting with a record errors object will no longer change the record state.', false, { id: 'ds.errors.clear' })); if (get(this, 'isEmpty')) { return; } this._clear(); this.trigger('becameValid'); }, /** Removes all error messages. to the record. @method _clear @private */ _clear: function () { if (get(this, 'isEmpty')) { return; } var errorsByAttributeName = get(this, 'errorsByAttributeName'); var attributes = _ember.default.A(); errorsByAttributeName.forEach(function (_, attribute) { attributes.push(attribute); }); errorsByAttributeName.clear(); attributes.forEach(function (attribute) { this.notifyPropertyChange(attribute); }, this); _ember.default.ArrayProxy.prototype.clear.call(this); }, /** Checks if there is error messages for the given attribute. ```app/routes/user/edit.js import Ember from 'ember'; export default Ember.Route.extend({ actions: { save: function(user) { if (user.get('errors').has('email')) { return alert('Please update your email before attempting to save.'); } user.save(); } } }); ``` @method has @param {String} attribute @return {Boolean} true if there some errors on given attribute */ has: function (attribute) { return !isEmpty(this.errorsFor(attribute)); } }); }); define('ember-data/-private/system/model/internal-model', ['exports', 'ember', 'ember-data/-private/system/model/states', 'ember-data/-private/system/relationships/state/create', 'ember-data/-private/system/snapshot', 'ember-data/-private/features', 'ember-data/-private/system/ordered-set', 'ember-data/-private/utils', 'ember-data/-private/system/references'], function (exports, _ember, _states, _create, _snapshot, _features, _orderedSet, _utils, _references) { 'use strict'; exports.__esModule = true; function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } } var _createClass = function () { function defineProperties(target, props) { for (var i = 0; i < props.length; i++) { var descriptor = props[i]; descriptor.enumerable = descriptor.enumerable || false; descriptor.configurable = true; if ("value" in descriptor) descriptor.writable = true; Object.defineProperty(target, descriptor.key, descriptor); } } return function (Constructor, protoProps, staticProps) { if (protoProps) defineProperties(Constructor.prototype, protoProps); if (staticProps) defineProperties(Constructor, staticProps); return Constructor; }; }(); var get = _ember.default.get, set = _ember.default.set, copy = _ember.default.copy, EmberError = _ember.default.Error, inspect = _ember.default.inspect, isEmpty = _ember.default.isEmpty, isEqual = _ember.default.isEqual, setOwner = _ember.default.setOwner, run = _ember.default.run, RSVP = _ember.default.RSVP, Promise = _ember.default.RSVP.Promise; var assign = _ember.default.assign || _ember.default.merge; /* The TransitionChainMap caches the `state.enters`, `state.setups`, and final state reached when transitioning from one state to another, so that future transitions can replay the transition without needing to walk the state tree, collect these hook calls and determine the state to transition into. A future optimization would be to build a single chained method out of the collected enters and setups. It may also be faster to do a two level cache (from: { to }) instead of caching based on a key that adds the two together. */ var TransitionChainMap = Object.create(null); var _extractPivotNameCache = Object.create(null); var _splitOnDotCache = Object.create(null); function splitOnDot(name) { return _splitOnDotCache[name] || (_splitOnDotCache[name] = name.split('.')); } function extractPivotName(name) { return _extractPivotNameCache[name] || (_extractPivotNameCache[name] = splitOnDot(name)[0]); } function areAllModelsUnloaded(internalModels) { for (var i = 0; i < internalModels.length; ++i) { var record = internalModels[i]._record; if (record && !(record.get('isDestroyed') || record.get('isDestroying'))) { return false; } } return true; } function destroyRelationship(rel) { if (rel._inverseIsAsync()) { rel.removeInternalModelFromInverse(rel.inverseInternalModel); rel.removeInverseRelationships(); } else { rel.removeCompletelyFromInverse(); } } // this (and all heimdall instrumentation) will be stripped by a babel transform // https://github.com/heimdalljs/babel5-plugin-strip-heimdall var InternalModelReferenceId = 1; var nextBfsId = 1; /* `InternalModel` is the Model class that we use internally inside Ember Data to represent models. Internal ED methods should only deal with `InternalModel` objects. It is a fast, plain Javascript class. We expose `DS.Model` to application code, by materializing a `DS.Model` from `InternalModel` lazily, as a performance optimization. `InternalModel` should never be exposed to application code. At the boundaries of the system, in places like `find`, `push`, etc. we convert between Models and InternalModels. We need to make sure that the properties from `InternalModel` are correctly exposed/proxied on `Model` if they are needed. @private @class InternalModel */ var InternalModel = function () { function InternalModel(modelName, id, store, data) { this.id = id; // this ensure ordered set can quickly identify this as unique this[_ember.default.GUID_KEY] = InternalModelReferenceId++ + 'internal-model'; this.store = store; this.modelName = modelName; this._loadingPromise = null; this._record = null; this._isDestroyed = false; this.isError = false; this._isUpdatingRecordArrays = false; // used by the recordArrayManager // During dematerialization we don't want to rematerialize the record. The // reason this might happen is that dematerialization removes records from // record arrays, and Ember arrays will always `objectAt(0)` and // `objectAt(len - 1)` to test whether or not `firstObject` or `lastObject` // have changed. this._isDematerializing = false; this._scheduledDestroy = null; this.resetRecord(); if (data) { this.__data = data; } // caches for lazy getters this._modelClass = null; this.__deferredTriggers = null; this.__recordArrays = null; this._references = null; this._recordReference = null; this.__relationships = null; this.__implicitRelationships = null; // Used during the mark phase of unloading to avoid checking the same internal // model twice in the same scan this._bfsId = 0; } InternalModel.prototype.isHiddenFromRecordArrays = function isHiddenFromRecordArrays() { // During dematerialization we don't want to rematerialize the record. // recordWasDeleted can cause other records to rematerialize because it // removes the internal model from the array and Ember arrays will always // `objectAt(0)` and `objectAt(len -1)` to check whether `firstObject` or // `lastObject` have changed. When this happens we don't want those // models to rematerialize their records. return this._isDematerializing || this.isDestroyed || this.currentState.stateName === 'root.deleted.saved' || this.isEmpty(); }; InternalModel.prototype.isEmpty = function isEmpty() { return this.currentState.isEmpty; }; InternalModel.prototype.isLoading = function isLoading() { return this.currentState.isLoading; }; InternalModel.prototype.isLoaded = function isLoaded() { return this.currentState.isLoaded; }; InternalModel.prototype.hasDirtyAttributes = function hasDirtyAttributes() { return this.currentState.hasDirtyAttributes; }; InternalModel.prototype.isSaving = function isSaving() { return this.currentState.isSaving; }; InternalModel.prototype.isDeleted = function isDeleted() { return this.currentState.isDeleted; }; InternalModel.prototype.isNew = function isNew() { return this.currentState.isNew; }; InternalModel.prototype.isValid = function isValid() { return this.currentState.isValid; }; InternalModel.prototype.dirtyType = function dirtyType() { return this.currentState.dirtyType; }; InternalModel.prototype.getRecord = function getRecord(properties) { if (!this._record && !this._isDematerializing) { // lookupFactory should really return an object that creates // instances with the injections applied var createOptions = { store: this.store, _internalModel: this, id: this.id, currentState: this.currentState, isError: this.isError, adapterError: this.error }; if (typeof properties === 'object' && properties !== null) { assign(createOptions, properties); } if (setOwner) { // ensure that `getOwner(this)` works inside a model instance setOwner(createOptions, (0, _utils.getOwner)(this.store)); } else { createOptions.container = this.store.container; } this._record = this.store.modelFactoryFor(this.modelName).create(createOptions); this._triggerDeferredTriggers(); } return this._record; }; InternalModel.prototype.resetRecord = function resetRecord() { this._record = null; this.isReloading = false; this.error = null; this.currentState = _states.default.empty; this.__attributes = null; this.__inFlightAttributes = null; this._data = null; }; InternalModel.prototype.dematerializeRecord = function dematerializeRecord() { if (this._record) { this._isDematerializing = true; this._record.destroy(); this.destroyRelationships(); this.updateRecordArrays(); this.resetRecord(); } }; InternalModel.prototype.deleteRecord = function deleteRecord() { this.send('deleteRecord'); }; InternalModel.prototype.save = function save(options) { var promiseLabel = "DS: Model#save " + this; var resolver = RSVP.defer(promiseLabel); this.store.scheduleSave(this, resolver, options); return resolver.promise; }; InternalModel.prototype.startedReloading = function startedReloading() { this.isReloading = true; if (this.hasRecord) { set(this._record, 'isReloading', true); } }; InternalModel.prototype.finishedReloading = function finishedReloading() { this.isReloading = false; if (this.hasRecord) { set(this._record, 'isReloading', false); } }; InternalModel.prototype.reload = function reload() { this.startedReloading(); var internalModel = this; var promiseLabel = "DS: Model#reload of " + this; return new Promise(function (resolve) { internalModel.send('reloadRecord', resolve); }, promiseLabel).then(function () { internalModel.didCleanError(); return internalModel; }, function (error) { internalModel.didError(error); throw error; }, "DS: Model#reload complete, update flags").finally(function () { internalModel.finishedReloading(); internalModel.updateRecordArrays(); }); }; InternalModel.prototype._directlyRelatedInternalModels = function _directlyRelatedInternalModels() { var array = []; this._relationships.forEach(function (name, rel) { array = array.concat(rel.members.list, rel.canonicalMembers.list); }); return array; }; InternalModel.prototype._allRelatedInternalModels = function _allRelatedInternalModels() { var array = []; var queue = []; var bfsId = nextBfsId++; queue.push(this); this._bfsId = bfsId; while (queue.length > 0) { var node = queue.shift(); array.push(node); var related = node._directlyRelatedInternalModels(); for (var i = 0; i < related.length; ++i) { var internalModel = related[i]; (false && _ember.default.assert('Internal Error: seen a future bfs iteration', internalModel._bfsId <= bfsId)); if (internalModel._bfsId < bfsId) { queue.push(internalModel); internalModel._bfsId = bfsId; } } } return array; }; InternalModel.prototype.unloadRecord = function unloadRecord() { if (this.isDestroyed) { return; } this.send('unloadRecord'); this.dematerializeRecord(); if (this._scheduledDestroy === null) { // TODO: use run.schedule once we drop 1.13 if (!_ember.default.run.currentRunLoop) { (false && _ember.default.assert('You have turned on testing mode, which disabled the run-loop\'s autorun.\n You will need to wrap any code with asynchronous side-effects in a run', _ember.default.testing)); } this._scheduledDestroy = _ember.default.run.backburner.schedule('destroy', this, '_checkForOrphanedInternalModels'); } }; InternalModel.prototype.hasScheduledDestroy = function hasScheduledDestroy() { return !!this._scheduledDestroy; }; InternalModel.prototype.cancelDestroy = function cancelDestroy() { (false && _ember.default.assert('You cannot cancel the destruction of an InternalModel once it has already been destroyed', !this.isDestroyed)); this._isDematerializing = false; run.cancel(this._scheduledDestroy); this._scheduledDestroy = null; }; InternalModel.prototype.destroySync = function destroySync() { if (this._isDematerializing) { this.cancelDestroy(); } this._checkForOrphanedInternalModels(); if (this.isDestroyed || this.isDestroying) { return; } // just in-case we are not one of the orphaned, we should still // still destroy ourselves this.destroy(); }; InternalModel.prototype._checkForOrphanedInternalModels = function _checkForOrphanedInternalModels() { this._isDematerializing = false; this._scheduledDestroy = null; if (this.isDestroyed) { return; } this._cleanupOrphanedInternalModels(); }; InternalModel.prototype._cleanupOrphanedInternalModels = function _cleanupOrphanedInternalModels() { var relatedInternalModels = this._allRelatedInternalModels(); if (areAllModelsUnloaded(relatedInternalModels)) { for (var i = 0; i < relatedInternalModels.length; ++i) { var internalModel = relatedInternalModels[i]; if (!internalModel.isDestroyed) { internalModel.destroy(); } } } }; InternalModel.prototype.eachRelationship = function eachRelationship(callback, binding) { return this.modelClass.eachRelationship(callback, binding); }; InternalModel.prototype.destroy = function destroy() { (false && _ember.default.assert("Cannot destroy an internalModel while its record is materialized", !this._record || this._record.get('isDestroyed') || this._record.get('isDestroying'))); this.store._internalModelDestroyed(this); this._relationships.forEach(function (name, rel) { return rel.destroy(); }); this._isDestroyed = true; }; InternalModel.prototype.eachAttribute = function eachAttribute(callback, binding) { return this.modelClass.eachAttribute(callback, binding); }; InternalModel.prototype.inverseFor = function inverseFor(key) { return this.modelClass.inverseFor(key); }; InternalModel.prototype.setupData = function setupData(data) { this.store._internalModelDidReceiveRelationshipData(this.modelName, this.id, data.relationships); var changedKeys = void 0; if (this.hasRecord) { changedKeys = this._changedKeys(data.attributes); } assign(this._data, data.attributes); this.pushedData(); if (this.hasRecord) { this._record._notifyProperties(changedKeys); } }; InternalModel.prototype.createSnapshot = function createSnapshot(options) { return new _snapshot.default(this, options); }; InternalModel.prototype.loadingData = function loadingData(promise) { this.send('loadingData', promise); }; InternalModel.prototype.loadedData = function loadedData() { this.send('loadedData'); }; InternalModel.prototype.notFound = function notFound() { this.send('notFound'); }; InternalModel.prototype.pushedData = function pushedData() { this.send('pushedData'); }; InternalModel.prototype.flushChangedAttributes = function flushChangedAttributes() { this._inFlightAttributes = this._attributes; this._attributes = null; }; InternalModel.prototype.hasChangedAttributes = function hasChangedAttributes() { return this.__attributes !== null && Object.keys(this.__attributes).length > 0; }; InternalModel.prototype.updateChangedAttributes = function updateChangedAttributes() { var changedAttributes = this.changedAttributes(); var changedAttributeNames = Object.keys(changedAttributes); var attrs = this._attributes; for (var i = 0, length = changedAttributeNames.length; i < length; i++) { var attribute = changedAttributeNames[i]; var data = changedAttributes[attribute]; var oldData = data[0]; var newData = data[1]; if (oldData === newData) { delete attrs[attribute]; } } }; InternalModel.prototype.changedAttributes = function changedAttributes() { var oldData = this._data; var currentData = this._attributes; var inFlightData = this._inFlightAttributes; var newData = assign(copy(inFlightData), currentData); var diffData = Object.create(null); var newDataKeys = Object.keys(newData); for (var i = 0, length = newDataKeys.length; i < length; i++) { var key = newDataKeys[i]; diffData[key] = [oldData[key], newData[key]]; } return diffData; }; InternalModel.prototype.adapterWillCommit = function adapterWillCommit() { this.send('willCommit'); }; InternalModel.prototype.adapterDidDirty = function adapterDidDirty() { this.send('becomeDirty'); this.updateRecordArrays(); }; InternalModel.prototype.send = function send(name, context) { var currentState = this.currentState; if (!currentState[name]) { this._unhandledEvent(currentState, name, context); } return currentState[name](this, context); }; InternalModel.prototype.notifyHasManyAdded = function notifyHasManyAdded(key, record, idx) { if (this.hasRecord) { this._record.notifyHasManyAdded(key, record, idx); } }; InternalModel.prototype.notifyBelongsToChanged = function notifyBelongsToChanged(key, record) { if (this.hasRecord) { this._record.notifyBelongsToChanged(key, record); } }; InternalModel.prototype.notifyPropertyChange = function notifyPropertyChange(key) { if (this.hasRecord) { this._record.notifyPropertyChange(key); } }; InternalModel.prototype.rollbackAttributes = function rollbackAttributes() { var dirtyKeys = void 0; if (this.hasChangedAttributes()) { dirtyKeys = Object.keys(this._attributes); this._attributes = null; } if (get(this, 'isError')) { this._inFlightAttributes = null; this.didCleanError(); } if (this.isNew()) { this.removeFromInverseRelationships(true); } if (this.isValid()) { this._inFlightAttributes = null; } this.send('rolledBack'); if (dirtyKeys && dirtyKeys.length > 0) { this._record._notifyProperties(dirtyKeys); } }; InternalModel.prototype.transitionTo = function transitionTo(name) { // POSSIBLE TODO: Remove this code and replace with // always having direct reference to state objects var pivotName = extractPivotName(name); var state = this.currentState; var transitionMapId = state.stateName + '->' + name; do { if (state.exit) { state.exit(this); } state = state.parentState; } while (!state[pivotName]); var setups = void 0; var enters = void 0; var i = void 0; var l = void 0; var map = TransitionChainMap[transitionMapId]; if (map) { setups = map.setups; enters = map.enters; state = map.state; } else { setups = []; enters = []; var path = splitOnDot(name); for (i = 0, l = path.length; i < l; i++) { state = state[path[i]]; if (state.enter) { enters.push(state); } if (state.setup) { setups.push(state); } } TransitionChainMap[transitionMapId] = { setups: setups, enters: enters, state: state }; } for (i = 0, l = enters.length; i < l; i++) { enters[i].enter(this); } this.currentState = state; if (this.hasRecord) { set(this._record, 'currentState', state); } for (i = 0, l = setups.length; i < l; i++) { setups[i].setup(this); } this.updateRecordArrays(); }; InternalModel.prototype._unhandledEvent = function _unhandledEvent(state, name, context) { var errorMessage = "Attempted to handle event `" + name + "` "; errorMessage += "on " + String(this) + " while in state "; errorMessage += state.stateName + ". "; if (context !== undefined) { errorMessage += "Called with " + inspect(context) + "."; } throw new EmberError(errorMessage); }; InternalModel.prototype.triggerLater = function triggerLater() { for (var _len = arguments.length, args = Array(_len), _key = 0; _key < _len; _key++) { args[_key] = arguments[_key]; } if (this._deferredTriggers.push(args) !== 1) { return; } this.store._updateInternalModel(this); }; InternalModel.prototype._triggerDeferredTriggers = function _triggerDeferredTriggers() { //TODO: Before 1.0 we want to remove all the events that happen on the pre materialized record, //but for now, we queue up all the events triggered before the record was materialized, and flush //them once we have the record if (!this.hasRecord) { return; } var triggers = this._deferredTriggers; var record = this._record; var trigger = record.trigger; for (var i = 0, l = triggers.length; i < l; i++) { trigger.apply(record, triggers[i]); } triggers.length = 0; }; InternalModel.prototype.removeFromInverseRelationships = function removeFromInverseRelationships() { var isNew = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : false; this._relationships.forEach(function (name, rel) { rel.removeCompletelyFromInverse(); if (isNew === true) { rel.clear(); } }); var implicitRelationships = this._implicitRelationships; this.__implicitRelationships = null; Object.keys(implicitRelationships).forEach(function (key) { var rel = implicitRelationships[key]; rel.removeCompletelyFromInverse(); if (isNew === true) { rel.clear(); } }); }; InternalModel.prototype.destroyRelationships = function destroyRelationships() { var relationships = this._relationships; relationships.forEach(function (name, rel) { return destroyRelationship(rel); }); var implicitRelationships = this._implicitRelationships; this.__implicitRelationships = null; Object.keys(implicitRelationships).forEach(function (key) { var rel = implicitRelationships[key]; destroyRelationship(rel); rel.destroy(); }); }; InternalModel.prototype.preloadData = function preloadData(preload) { var _this = this; //TODO(Igor) consider the polymorphic case Object.keys(preload).forEach(function (key) { var preloadValue = get(preload, key); var relationshipMeta = _this.modelClass.metaForProperty(key); if (relationshipMeta.isRelationship) { _this._preloadRelationship(key, preloadValue); } else { _this._data[key] = preloadValue; } }); }; InternalModel.prototype._preloadRelationship = function _preloadRelationship(key, preloadValue) { var relationshipMeta = this.modelClass.metaForProperty(key); var modelClass = relationshipMeta.type; if (relationshipMeta.kind === 'hasMany') { this._preloadHasMany(key, preloadValue, modelClass); } else { this._preloadBelongsTo(key, preloadValue, modelClass); } }; InternalModel.prototype._preloadHasMany = function _preloadHasMany(key, preloadValue, modelClass) { (false && _ember.default.assert("You need to pass in an array to set a hasMany property on a record", Array.isArray(preloadValue))); var recordsToSet = new Array(preloadValue.length); for (var i = 0; i < preloadValue.length; i++) { var recordToPush = preloadValue[i]; recordsToSet[i] = this._convertStringOrNumberIntoInternalModel(recordToPush, modelClass); } //We use the pathway of setting the hasMany as if it came from the adapter //because the user told us that they know this relationships exists already this._relationships.get(key).updateInternalModelsFromAdapter(recordsToSet); }; InternalModel.prototype._preloadBelongsTo = function _preloadBelongsTo(key, preloadValue, modelClass) { var internalModelToSet = this._convertStringOrNumberIntoInternalModel(preloadValue, modelClass); //We use the pathway of setting the hasMany as if it came from the adapter //because the user told us that they know this relationships exists already this._relationships.get(key).setInternalModel(internalModelToSet); }; InternalModel.prototype._convertStringOrNumberIntoInternalModel = function _convertStringOrNumberIntoInternalModel(value, modelClass) { if (typeof value === 'string' || typeof value === 'number') { return this.store._internalModelForId(modelClass, value); } if (value._internalModel) { return value._internalModel; } return value; }; InternalModel.prototype.updateRecordArrays = function updateRecordArrays() { this.store.recordArrayManager.recordDidChange(this); }; InternalModel.prototype.setId = function setId(id) { (false && _ember.default.assert('A record\'s id cannot be changed once it is in the loaded state', this.id === null || this.id === id || this.isNew())); this.id = id; if (this._record.get('id') !== id) { this._record.set('id', id); } }; InternalModel.prototype.didError = function didError(error) { this.error = error; this.isError = true; if (this.hasRecord) { this._record.setProperties({ isError: true, adapterError: error }); } }; InternalModel.prototype.didCleanError = function didCleanError() { this.error = null; this.isError = false; if (this.hasRecord) { this._record.setProperties({ isError: false, adapterError: null }); } }; InternalModel.prototype.adapterDidCommit = function adapterDidCommit(data) { if (data) { this.store._internalModelDidReceiveRelationshipData(this.modelName, this.id, data.relationships); data = data.attributes; } this.didCleanError(); var changedKeys = this._changedKeys(data); assign(this._data, this._inFlightAttributes); if (data) { assign(this._data, data); } this._inFlightAttributes = null; this.send('didCommit'); this.updateRecordArrays(); if (!data) { return; } this._record._notifyProperties(changedKeys); }; InternalModel.prototype.addErrorMessageToAttribute = function addErrorMessageToAttribute(attribute, message) { get(this.getRecord(), 'errors')._add(attribute, message); }; InternalModel.prototype.removeErrorMessageFromAttribute = function removeErrorMessageFromAttribute(attribute) { get(this.getRecord(), 'errors')._remove(attribute); }; InternalModel.prototype.clearErrorMessages = function clearErrorMessages() { get(this.getRecord(), 'errors')._clear(); }; InternalModel.prototype.hasErrors = function hasErrors() { var errors = get(this.getRecord(), 'errors'); return !isEmpty(errors); }; InternalModel.prototype.adapterDidInvalidate = function adapterDidInvalidate(errors) { var attribute = void 0; for (attribute in errors) { if (errors.hasOwnProperty(attribute)) { this.addErrorMessageToAttribute(attribute, errors[attribute]); } } this.send('becameInvalid'); this._saveWasRejected(); }; InternalModel.prototype.adapterDidError = function adapterDidError(error) { this.send('becameError'); this.didError(error); this._saveWasRejected(); }; InternalModel.prototype._saveWasRejected = function _saveWasRejected() { var keys = Object.keys(this._inFlightAttributes); if (keys.length > 0) { var attrs = this._attributes; for (var i = 0; i < keys.length; i++) { if (attrs[keys[i]] === undefined) { attrs[keys[i]] = this._inFlightAttributes[keys[i]]; } } } this._inFlightAttributes = null; }; InternalModel.prototype._changedKeys = function _changedKeys(updates) { var changedKeys = []; if (updates) { var original = void 0, i = void 0, value = void 0, key = void 0; var keys = Object.keys(updates); var length = keys.length; var hasAttrs = this.hasChangedAttributes(); var attrs = void 0; if (hasAttrs) { attrs = this._attributes; } original = assign(Object.create(null), this._data); original = assign(original, this._inFlightAttributes); for (i = 0; i < length; i++) { key = keys[i]; value = updates[key]; // A value in _attributes means the user has a local change to // this attributes. We never override this value when merging // updates from the backend so we should not sent a change // notification if the server value differs from the original. if (hasAttrs === true && attrs[key] !== undefined) { continue; } if (!isEqual(original[key], value)) { changedKeys.push(key); } } } return changedKeys; }; InternalModel.prototype.toString = function toString() { return '<' + this.modelName + ':' + this.id + '>'; }; InternalModel.prototype.referenceFor = function referenceFor(kind, name) { var reference = this.references[name]; if (!reference) { var relationship = this._relationships.get(name); if (false) { var modelName = this.modelName; (false && _ember.default.assert('There is no ' + kind + ' relationship named \'' + name + '\' on a model of modelClass \'' + modelName + '\'', relationship)); var actualRelationshipKind = relationship.relationshipMeta.kind; (false && _ember.default.assert('You tried to get the \'' + name + '\' relationship on a \'' + modelName + '\' via record.' + kind + '(\'' + name + '\'), but the relationship is of kind \'' + actualRelationshipKind + '\'. Use record.' + actualRelationshipKind + '(\'' + name + '\') instead.', actualRelationshipKind === kind)); } if (kind === "belongsTo") { reference = new _references.BelongsToReference(this.store, this, relationship); } else if (kind === "hasMany") { reference = new _references.HasManyReference(this.store, this, relationship); } this.references[name] = reference; } return reference; }; _createClass(InternalModel, [{ key: 'modelClass', get: function () { return this._modelClass || (this._modelClass = this.store._modelFor(this.modelName)); } }, { key: 'type', get: function () { return this.modelClass; } }, { key: 'recordReference', get: function () { if (this._recordReference === null) { this._recordReference = new _references.RecordReference(this.store, this); } return this._recordReference; } }, { key: '_recordArrays', get: function () { if (this.__recordArrays === null) { this.__recordArrays = _orderedSet.default.create(); } return this.__recordArrays; } }, { key: 'references', get: function () { if (this._references === null) { this._references = Object.create(null); } return this._references; } }, { key: '_deferredTriggers', get: function () { if (this.__deferredTriggers === null) { this.__deferredTriggers = []; } return this.__deferredTriggers; } }, { key: '_attributes', get: function () { if (this.__attributes === null) { this.__attributes = Object.create(null); } return this.__attributes; }, set: function (v) { this.__attributes = v; } }, { key: '_relationships', get: function () { if (this.__relationships === null) { this.__relationships = new _create.default(this); } return this.__relationships; } }, { key: '_inFlightAttributes', get: function () { if (this.__inFlightAttributes === null) { this.__inFlightAttributes = Object.create(null); } return this.__inFlightAttributes; }, set: function (v) { this.__inFlightAttributes = v; } }, { key: '_data', get: function () { if (this.__data === null) { this.__data = Object.create(null); } return this.__data; }, set: function (v) { this.__data = v; } }, { key: '_implicitRelationships', get: function () { if (this.__implicitRelationships === null) { this.__implicitRelationships = Object.create(null); } return this.__implicitRelationships; } }, { key: 'isDestroyed', get: function () { return this._isDestroyed; } }, { key: 'hasRecord', get: function () { return !!this._record; } }]); return InternalModel; }(); exports.default = InternalModel; if ((0, _features.default)('ds-rollback-attribute')) { /* Returns the latest truth for an attribute - the canonical value, or the in-flight value. @method lastAcknowledgedValue @private */ InternalModel.prototype.lastAcknowledgedValue = function lastAcknowledgedValue(key) { if (key in this._inFlightAttributes) { return this._inFlightAttributes[key]; } else { return this._data[key]; } }; } }); define('ember-data/-private/system/model/model', ['exports', 'ember', 'ember-data/-private/system/promise-proxies', 'ember-data/-private/system/model/errors', 'ember-data/-private/features', 'ember-data/-private/system/model/states', 'ember-data/-private/system/relationships/ext'], function (exports, _ember, _promiseProxies, _errors, _features, _states, _ext) { 'use strict'; exports.__esModule = true; var get = _ember.default.get, computed = _ember.default.computed, Map = _ember.default.Map; /** @module ember-data */ function findPossibleInverses(type, inverseType, name, relationshipsSoFar) { var possibleRelationships = relationshipsSoFar || []; var relationshipMap = get(inverseType, 'relationships'); if (!relationshipMap) { return possibleRelationships; } var relationships = relationshipMap.get(type.modelName).filter(function (relationship) { var optionsForRelationship = inverseType.metaForProperty(relationship.name).options; if (!optionsForRelationship.inverse) { return true; } return name === optionsForRelationship.inverse; }); if (relationships) { possibleRelationships.push.apply(possibleRelationships, relationships); } //Recurse to support polymorphism if (type.superclass) { findPossibleInverses(type.superclass, inverseType, name, possibleRelationships); } return possibleRelationships; } function intersection(array1, array2) { var result = []; array1.forEach(function (element) { if (array2.indexOf(element) >= 0) { result.push(element); } }); return result; } var RESERVED_MODEL_PROPS = ['currentState', 'data', 'store']; var retrieveFromCurrentState = computed('currentState', function (key) { return get(this._internalModel.currentState, key); }).readOnly(); /** The model class that all Ember Data records descend from. This is the public API of Ember Data models. If you are using Ember Data in your application, this is the class you should use. If you are working on Ember Data internals, you most likely want to be dealing with `InternalModel` @class Model @namespace DS @extends Ember.Object @uses Ember.Evented */ var Model = _ember.default.Object.extend(_ember.default.Evented, { _internalModel: null, store: null, __defineNonEnumerable: function (property) { this[property.name] = property.descriptor.value; }, /** If this property is `true` the record is in the `empty` state. Empty is the first state all records enter after they have been created. Most records created by the store will quickly transition to the `loading` state if data needs to be fetched from the server or the `created` state if the record is created on the client. A record can also enter the empty state if the adapter is unable to locate the record. @property isEmpty @type {Boolean} @readOnly */ isEmpty: retrieveFromCurrentState, /** If this property is `true` the record is in the `loading` state. A record enters this state when the store asks the adapter for its data. It remains in this state until the adapter provides the requested data. @property isLoading @type {Boolean} @readOnly */ isLoading: retrieveFromCurrentState, /** If this property is `true` the record is in the `loaded` state. A record enters this state when its data is populated. Most of a record's lifecycle is spent inside substates of the `loaded` state. Example ```javascript let record = store.createRecord('model'); record.get('isLoaded'); // true store.findRecord('model', 1).then(function(model) { model.get('isLoaded'); // true }); ``` @property isLoaded @type {Boolean} @readOnly */ isLoaded: retrieveFromCurrentState, /** If this property is `true` the record is in the `dirty` state. The record has local changes that have not yet been saved by the adapter. This includes records that have been created (but not yet saved) or deleted. Example ```javascript let record = store.createRecord('model'); record.get('hasDirtyAttributes'); // true store.findRecord('model', 1).then(function(model) { model.get('hasDirtyAttributes'); // false model.set('foo', 'some value'); model.get('hasDirtyAttributes'); // true }); ``` @since 1.13.0 @property hasDirtyAttributes @type {Boolean} @readOnly */ hasDirtyAttributes: computed('currentState.isDirty', function () { return this.get('currentState.isDirty'); }), /** If this property is `true` the record is in the `saving` state. A record enters the saving state when `save` is called, but the adapter has not yet acknowledged that the changes have been persisted to the backend. Example ```javascript let record = store.createRecord('model'); record.get('isSaving'); // false let promise = record.save(); record.get('isSaving'); // true promise.then(function() { record.get('isSaving'); // false }); ``` @property isSaving @type {Boolean} @readOnly */ isSaving: retrieveFromCurrentState, /** If this property is `true` the record is in the `deleted` state and has been marked for deletion. When `isDeleted` is true and `hasDirtyAttributes` is true, the record is deleted locally but the deletion was not yet persisted. When `isSaving` is true, the change is in-flight. When both `hasDirtyAttributes` and `isSaving` are false, the change has persisted. Example ```javascript let record = store.createRecord('model'); record.get('isDeleted'); // false record.deleteRecord(); // Locally deleted record.get('isDeleted'); // true record.get('hasDirtyAttributes'); // true record.get('isSaving'); // false // Persisting the deletion let promise = record.save(); record.get('isDeleted'); // true record.get('isSaving'); // true // Deletion Persisted promise.then(function() { record.get('isDeleted'); // true record.get('isSaving'); // false record.get('hasDirtyAttributes'); // false }); ``` @property isDeleted @type {Boolean} @readOnly */ isDeleted: retrieveFromCurrentState, /** If this property is `true` the record is in the `new` state. A record will be in the `new` state when it has been created on the client and the adapter has not yet report that it was successfully saved. Example ```javascript let record = store.createRecord('model'); record.get('isNew'); // true record.save().then(function(model) { model.get('isNew'); // false }); ``` @property isNew @type {Boolean} @readOnly */ isNew: retrieveFromCurrentState, /** If this property is `true` the record is in the `valid` state. A record will be in the `valid` state when the adapter did not report any server-side validation failures. @property isValid @type {Boolean} @readOnly */ isValid: retrieveFromCurrentState, /** If the record is in the dirty state this property will report what kind of change has caused it to move into the dirty state. Possible values are: - `created` The record has been created by the client and not yet saved to the adapter. - `updated` The record has been updated by the client and not yet saved to the adapter. - `deleted` The record has been deleted by the client and not yet saved to the adapter. Example ```javascript let record = store.createRecord('model'); record.get('dirtyType'); // 'created' ``` @property dirtyType @type {String} @readOnly */ dirtyType: retrieveFromCurrentState, /** If `true` the adapter reported that it was unable to save local changes to the backend for any reason other than a server-side validation error. Example ```javascript record.get('isError'); // false record.set('foo', 'valid value'); record.save().then(null, function() { record.get('isError'); // true }); ``` @property isError @type {Boolean} @readOnly */ isError: false, /** If `true` the store is attempting to reload the record from the adapter. Example ```javascript record.get('isReloading'); // false record.reload(); record.get('isReloading'); // true ``` @property isReloading @type {Boolean} @readOnly */ isReloading: false, /** All ember models have an id property. This is an identifier managed by an external source. These are always coerced to be strings before being used internally. Note when declaring the attributes for a model it is an error to declare an id attribute. ```javascript let record = store.createRecord('model'); record.get('id'); // null store.findRecord('model', 1).then(function(model) { model.get('id'); // '1' }); ``` @property id @type {String} */ id: null, /** @property currentState @private @type {Object} */ currentState: _states.default.empty, /** When the record is in the `invalid` state this object will contain any errors returned by the adapter. When present the errors hash contains keys corresponding to the invalid property names and values which are arrays of Javascript objects with two keys: - `message` A string containing the error message from the backend - `attribute` The name of the property associated with this error message ```javascript record.get('errors.length'); // 0 record.set('foo', 'invalid value'); record.save().catch(function() { record.get('errors').get('foo'); // [{message: 'foo should be a number.', attribute: 'foo'}] }); ``` The `errors` property us useful for displaying error messages to the user. ```handlebars <label>Username: {{input value=username}} </label> {{#each model.errors.username as |error|}} <div class="error"> {{error.message}} </div> {{/each}} <label>Email: {{input value=email}} </label> {{#each model.errors.email as |error|}} <div class="error"> {{error.message}} </div> {{/each}} ``` You can also access the special `messages` property on the error object to get an array of all the error strings. ```handlebars {{#each model.errors.messages as |message|}} <div class="error"> {{message}} </div> {{/each}} ``` @property errors @type {DS.Errors} */ errors: computed(function () { var errors = _errors.default.create(); errors._registerHandlers(this._internalModel, function () { this.send('becameInvalid'); }, function () { this.send('becameValid'); }); return errors; }).readOnly(), /** This property holds the `DS.AdapterError` object with which last adapter operation was rejected. @property adapterError @type {DS.AdapterError} */ adapterError: null, serialize: function (options) { return this._internalModel.createSnapshot().serialize(options); }, toJSON: function (options) { // container is for lazy transform lookups var serializer = this.store.serializerFor('-default'); var snapshot = this._internalModel.createSnapshot(); return serializer.serialize(snapshot, options); }, /** Fired when the record is ready to be interacted with, that is either loaded from the server or created locally. @event ready */ ready: null, /** Fired when the record is loaded from the server. @event didLoad */ didLoad: null, /** Fired when the record is updated. @event didUpdate */ didUpdate: null, /** Fired when a new record is commited to the server. @event didCreate */ didCreate: null, /** Fired when the record is deleted. @event didDelete */ didDelete: null, /** Fired when the record becomes invalid. @event becameInvalid */ becameInvalid: null, /** Fired when the record enters the error state. @event becameError */ becameError: null, /** Fired when the record is rolled back. @event rolledBack */ rolledBack: null, send: function (name, context) { return this._internalModel.send(name, context); }, transitionTo: function (name) { return this._internalModel.transitionTo(name); }, deleteRecord: function () { this._internalModel.deleteRecord(); }, destroyRecord: function (options) { this.deleteRecord(); return this.save(options); }, unloadRecord: function () { if (this.isDestroyed) { return; } this._internalModel.unloadRecord(); }, _notifyProperties: function (keys) { _ember.default.beginPropertyChanges(); var key = void 0; for (var i = 0, length = keys.length; i < length; i++) { key = keys[i]; this.notifyPropertyChange(key); } _ember.default.endPropertyChanges(); }, changedAttributes: function () { return this._internalModel.changedAttributes(); }, rollbackAttributes: function () { this._internalModel.rollbackAttributes(); }, _createSnapshot: function () { return this._internalModel.createSnapshot(); }, toStringExtension: function () { return get(this, 'id'); }, save: function (options) { var _this = this; return _promiseProxies.PromiseObject.create({ promise: this._internalModel.save(options).then(function () { return _this; }) }); }, reload: function () { var _this2 = this; return _promiseProxies.PromiseObject.create({ promise: this._internalModel.reload().then(function () { return _this2; }) }); }, trigger: function (name) { var fn = this[name]; if (typeof fn === 'function') { var length = arguments.length; var args = new Array(length - 1); for (var i = 1; i < length; i++) { args[i - 1] = arguments[i]; } fn.apply(this, args); } this._super.apply(this, arguments); }, attr: function () { (false && _ember.default.assert("The `attr` method is not available on DS.Model, a DS.Snapshot was probably expected. Are you passing a DS.Model instead of a DS.Snapshot to your serializer?", false)); }, belongsTo: function (name) { return this._internalModel.referenceFor('belongsTo', name); }, hasMany: function (name) { return this._internalModel.referenceFor('hasMany', name); }, setId: _ember.default.observer('id', function () { this._internalModel.setId(this.get('id')); }), _debugInfo: function () { var attributes = ['id']; var relationships = {}; var expensiveProperties = []; this.eachAttribute(function (name, meta) { return attributes.push(name); }); var groups = [{ name: 'Attributes', properties: attributes, expand: true }]; this.eachRelationship(function (name, relationship) { var properties = relationships[relationship.kind]; if (properties === undefined) { properties = relationships[relationship.kind] = []; groups.push({ name: relationship.name, properties: properties, expand: true }); } properties.push(name); expensiveProperties.push(name); }); groups.push({ name: 'Flags', properties: ['isLoaded', 'hasDirtyAttributes', 'isSaving', 'isDeleted', 'isError', 'isNew', 'isValid'] }); return { propertyInfo: { // include all other mixins / properties (not just the grouped ones) includeOtherProperties: true, groups: groups, // don't pre-calculate unless cached expensiveProperties: expensiveProperties } }; }, notifyBelongsToChanged: function (key) { this.notifyPropertyChange(key); }, eachRelationship: function (callback, binding) { this.constructor.eachRelationship(callback, binding); }, relationshipFor: function (name) { return get(this.constructor, 'relationshipsByName').get(name); }, inverseFor: function (key) { return this.constructor.inverseFor(key, this.store); }, notifyHasManyAdded: function (key) { //We need to notifyPropertyChange in the adding case because we need to make sure //we fetch the newly added record in case it is unloaded //TODO(Igor): Consider whether we could do this only if the record state is unloaded //Goes away once hasMany is double promisified this.notifyPropertyChange(key); }, eachAttribute: function (callback, binding) { this.constructor.eachAttribute(callback, binding); } }); /** @property data @private @type {Object} */ Object.defineProperty(Model.prototype, 'data', { get: function () { return this._internalModel._data; } }); if (false) { Model.reopen({ init: function () { this._super.apply(this, arguments); if (!this._internalModel) { throw new _ember.default.Error('You should not call `create` on a model. Instead, call `store.createRecord` with the attributes you would like to set.'); } } }); } Model.reopenClass({ isModel: true, /** Override the class' `create()` method to raise an error. This prevents end users from inadvertently calling `create()` instead of `createRecord()`. The store is still able to create instances by calling the `_create()` method. To create an instance of a `DS.Model` use [store.createRecord](DS.Store.html#method_createRecord). @method create @private @static */ /** Represents the model's class name as a string. This can be used to look up the model's class name through `DS.Store`'s modelFor method. `modelName` is generated for you by Ember Data. It will be a lowercased, dasherized string. For example: ```javascript store.modelFor('post').modelName; // 'post' store.modelFor('blog-post').modelName; // 'blog-post' ``` The most common place you'll want to access `modelName` is in your serializer's `payloadKeyFromModelName` method. For example, to change payload keys to underscore (instead of dasherized), you might use the following code: ```javascript export default const PostSerializer = DS.RESTSerializer.extend({ payloadKeyFromModelName: function(modelName) { return Ember.String.underscore(modelName); } }); ``` @property modelName @type String @readonly @static */ modelName: null, typeForRelationship: function (name, store) { var relationship = get(this, 'relationshipsByName').get(name); return relationship && store.modelFor(relationship.type); }, inverseMap: _ember.default.computed(function () { return Object.create(null); }), inverseFor: function (name, store) { var inverseMap = get(this, 'inverseMap'); if (inverseMap[name] !== undefined) { return inverseMap[name]; } else { var relationship = get(this, 'relationshipsByName').get(name); if (!relationship) { inverseMap[name] = null; return null; } var options = relationship.options; if (options && options.inverse === null) { // populate the cache with a miss entry so we can skip getting and going // through `relationshipsByName` inverseMap[name] = null; return null; } return inverseMap[name] = this._findInverseFor(name, store); } }, _findInverseFor: function (name, store) { var inverseType = this.typeForRelationship(name, store); if (!inverseType) { return null; } var propertyMeta = this.metaForProperty(name); //If inverse is manually specified to be null, like `comments: DS.hasMany('message', { inverse: null })` var options = propertyMeta.options; if (options.inverse === null) { return null; } var inverseName = void 0, inverseKind = void 0, inverse = void 0; //If inverse is specified manually, return the inverse if (options.inverse) { inverseName = options.inverse; inverse = _ember.default.get(inverseType, 'relationshipsByName').get(inverseName); (false && _ember.default.assert("We found no inverse relationships by the name of '" + inverseName + "' on the '" + inverseType.modelName + "' model. This is most likely due to a missing attribute on your model definition.", !_ember.default.isNone(inverse))); inverseKind = inverse.kind; } else { //No inverse was specified manually, we need to use a heuristic to guess one if (propertyMeta.parentType && propertyMeta.type === propertyMeta.parentType.modelName) { (false && _ember.default.warn('Detected a reflexive relationship by the name of \'' + name + '\' without an inverse option. Look at https://emberjs.com/guides/models/defining-models/#toc_reflexive-relation for how to explicitly specify inverses.', false, { id: 'ds.model.reflexive-relationship-without-inverse' })); } var possibleRelationships = findPossibleInverses(this, inverseType, name); if (possibleRelationships.length === 0) { return null; } var filteredRelationships = possibleRelationships.filter(function (possibleRelationship) { var optionsForRelationship = inverseType.metaForProperty(possibleRelationship.name).options; return name === optionsForRelationship.inverse; }); (false && _ember.default.assert("You defined the '" + name + "' relationship on " + this + ", but you defined the inverse relationships of type " + inverseType.toString() + " multiple times. Look at https://emberjs.com/guides/models/defining-models/#toc_explicit-inverses for how to explicitly specify inverses", filteredRelationships.length < 2)); if (filteredRelationships.length === 1) { possibleRelationships = filteredRelationships; } (false && _ember.default.assert("You defined the '" + name + "' relationship on " + this + ", but multiple possible inverse relationships of type " + this + " were found on " + inverseType + ". Look at https://emberjs.com/guides/models/defining-models/#toc_explicit-inverses for how to explicitly specify inverses", possibleRelationships.length === 1)); inverseName = possibleRelationships[0].name; inverseKind = possibleRelationships[0].kind; } return { type: inverseType, name: inverseName, kind: inverseKind }; }, /** The model's relationships as a map, keyed on the type of the relationship. The value of each entry is an array containing a descriptor for each relationship with that type, describing the name of the relationship as well as the type. For example, given the following model definition: ```app/models/blog.js import DS from 'ember-data'; export default DS.Model.extend({ users: DS.hasMany('user'), owner: DS.belongsTo('user'), posts: DS.hasMany('post') }); ``` This computed property would return a map describing these relationships, like this: ```javascript import Ember from 'ember'; import Blog from 'app/models/blog'; import User from 'app/models/user'; import Post from 'app/models/post'; let relationships = Ember.get(Blog, 'relationships'); relationships.get(User); //=> [ { name: 'users', kind: 'hasMany' }, // { name: 'owner', kind: 'belongsTo' } ] relationships.get(Post); //=> [ { name: 'posts', kind: 'hasMany' } ] ``` @property relationships @static @type Ember.Map @readOnly */ relationships: _ext.relationshipsDescriptor, /** A hash containing lists of the model's relationships, grouped by the relationship kind. For example, given a model with this definition: ```app/models/blog.js import DS from 'ember-data'; export default DS.Model.extend({ users: DS.hasMany('user'), owner: DS.belongsTo('user'), posts: DS.hasMany('post') }); ``` This property would contain the following: ```javascript import Ember from 'ember'; import Blog from 'app/models/blog'; let relationshipNames = Ember.get(Blog, 'relationshipNames'); relationshipNames.hasMany; //=> ['users', 'posts'] relationshipNames.belongsTo; //=> ['owner'] ``` @property relationshipNames @static @type Object @readOnly */ relationshipNames: _ember.default.computed(function () { var names = { hasMany: [], belongsTo: [] }; this.eachComputedProperty(function (name, meta) { if (meta.isRelationship) { names[meta.kind].push(name); } }); return names; }), /** An array of types directly related to a model. Each type will be included once, regardless of the number of relationships it has with the model. For example, given a model with this definition: ```app/models/blog.js import DS from 'ember-data'; export default DS.Model.extend({ users: DS.hasMany('user'), owner: DS.belongsTo('user'), posts: DS.hasMany('post') }); ``` This property would contain the following: ```javascript import Ember from 'ember'; import Blog from 'app/models/blog'; let relatedTypes = Ember.get(Blog, 'relatedTypes'); //=> [ User, Post ] ``` @property relatedTypes @static @type Ember.Array @readOnly */ relatedTypes: _ext.relatedTypesDescriptor, /** A map whose keys are the relationships of a model and whose values are relationship descriptors. For example, given a model with this definition: ```app/models/blog.js import DS from 'ember-data'; export default DS.Model.extend({ users: DS.hasMany('user'), owner: DS.belongsTo('user'), posts: DS.hasMany('post') }); ``` This property would contain the following: ```javascript import Ember from 'ember'; import Blog from 'app/models/blog'; let relationshipsByName = Ember.get(Blog, 'relationshipsByName'); relationshipsByName.get('users'); //=> { key: 'users', kind: 'hasMany', type: 'user', options: Object, isRelationship: true } relationshipsByName.get('owner'); //=> { key: 'owner', kind: 'belongsTo', type: 'user', options: Object, isRelationship: true } ``` @property relationshipsByName @static @type Ember.Map @readOnly */ relationshipsByName: _ext.relationshipsByNameDescriptor, /** A map whose keys are the fields of the model and whose values are strings describing the kind of the field. A model's fields are the union of all of its attributes and relationships. For example: ```app/models/blog.js import DS from 'ember-data'; export default DS.Model.extend({ users: DS.hasMany('user'), owner: DS.belongsTo('user'), posts: DS.hasMany('post'), title: DS.attr('string') }); ``` ```js import Ember from 'ember'; import Blog from 'app/models/blog'; let fields = Ember.get(Blog, 'fields'); fields.forEach(function(kind, field) { console.log(field, kind); }); // prints: // users, hasMany // owner, belongsTo // posts, hasMany // title, attribute ``` @property fields @static @type Ember.Map @readOnly */ fields: _ember.default.computed(function () { var map = Map.create(); this.eachComputedProperty(function (name, meta) { if (meta.isRelationship) { map.set(name, meta.kind); } else if (meta.isAttribute) { map.set(name, 'attribute'); } }); return map; }).readOnly(), eachRelationship: function (callback, binding) { get(this, 'relationshipsByName').forEach(function (relationship, name) { callback.call(binding, name, relationship); }); }, eachRelatedType: function (callback, binding) { var relationshipTypes = get(this, 'relatedTypes'); for (var i = 0; i < relationshipTypes.length; i++) { var type = relationshipTypes[i]; callback.call(binding, type); } }, determineRelationshipType: function (knownSide, store) { var knownKey = knownSide.key; var knownKind = knownSide.kind; var inverse = this.inverseFor(knownKey, store); // let key; var otherKind = void 0; if (!inverse) { return knownKind === 'belongsTo' ? 'oneToNone' : 'manyToNone'; } // key = inverse.name; otherKind = inverse.kind; if (otherKind === 'belongsTo') { return knownKind === 'belongsTo' ? 'oneToOne' : 'manyToOne'; } else { return knownKind === 'belongsTo' ? 'oneToMany' : 'manyToMany'; } }, /** A map whose keys are the attributes of the model (properties described by DS.attr) and whose values are the meta object for the property. Example ```app/models/person.js import DS from 'ember-data'; export default DS.Model.extend({ firstName: DS.attr('string'), lastName: DS.attr('string'), birthday: DS.attr('date') }); ``` ```javascript import Ember from 'ember'; import Person from 'app/models/person'; let attributes = Ember.get(Person, 'attributes') attributes.forEach(function(meta, name) { console.log(name, meta); }); // prints: // firstName {type: "string", isAttribute: true, options: Object, parentType: function, name: "firstName"} // lastName {type: "string", isAttribute: true, options: Object, parentType: function, name: "lastName"} // birthday {type: "date", isAttribute: true, options: Object, parentType: function, name: "birthday"} ``` @property attributes @static @type {Ember.Map} @readOnly */ attributes: _ember.default.computed(function () { var _this3 = this; var map = Map.create(); this.eachComputedProperty(function (name, meta) { if (meta.isAttribute) { (false && _ember.default.assert("You may not set `id` as an attribute on your model. Please remove any lines that look like: `id: DS.attr('<type>')` from " + _this3.toString(), name !== 'id')); meta.name = name; map.set(name, meta); } }); return map; }).readOnly(), /** A map whose keys are the attributes of the model (properties described by DS.attr) and whose values are type of transformation applied to each attribute. This map does not include any attributes that do not have an transformation type. Example ```app/models/person.js import DS from 'ember-data'; export default DS.Model.extend({ firstName: DS.attr(), lastName: DS.attr('string'), birthday: DS.attr('date') }); ``` ```javascript import Ember from 'ember'; import Person from 'app/models/person'; let transformedAttributes = Ember.get(Person, 'transformedAttributes') transformedAttributes.forEach(function(field, type) { console.log(field, type); }); // prints: // lastName string // birthday date ``` @property transformedAttributes @static @type {Ember.Map} @readOnly */ transformedAttributes: _ember.default.computed(function () { var map = Map.create(); this.eachAttribute(function (key, meta) { if (meta.type) { map.set(key, meta.type); } }); return map; }).readOnly(), eachAttribute: function (callback, binding) { get(this, 'attributes').forEach(function (meta, name) { callback.call(binding, name, meta); }); }, eachTransformedAttribute: function (callback, binding) { get(this, 'transformedAttributes').forEach(function (type, name) { callback.call(binding, name, type); }); } }); // if `Ember.setOwner` is defined, accessing `this.container` is // deprecated (but functional). In "standard" Ember usage, this // deprecation is actually created via an `.extend` of the factory // inside the container itself, but that only happens on models // with MODEL_FACTORY_INJECTIONS enabled :( if (_ember.default.setOwner) { Object.defineProperty(Model.prototype, 'container', { configurable: true, enumerable: false, get: function () { (false && !(false) && _ember.default.deprecate('Using the injected `container` is deprecated. Please use the `getOwner` helper instead to access the owner of this object.', false, { id: 'ember-application.injected-container', until: '3.0.0' })); return this.store.container; } }); } if ((0, _features.default)('ds-rollback-attribute')) { Model.reopen({ rollbackAttribute: function (attributeName) { if (attributeName in this._internalModel._attributes) { this.set(attributeName, this._internalModel.lastAcknowledgedValue(attributeName)); } } }); } if (false) { Model.reopen({ willMergeMixin: function (props) { var constructor = this.constructor; (false && _ember.default.assert('`' + intersection(Object.keys(props), RESERVED_MODEL_PROPS)[0] + '` is a reserved property name on DS.Model objects. Please choose a different property name for ' + constructor.toString(), !intersection(Object.keys(props), RESERVED_MODEL_PROPS)[0])); (false && _ember.default.assert("You may not set `id` as an attribute on your model. Please remove any lines that look like: `id: DS.attr('<type>')` from " + constructor.toString(), Object.keys(props).indexOf('id') === -1)); }, didDefineProperty: function (proto, key, value) { // Check if the value being set is a computed property. if (value instanceof _ember.default.ComputedProperty) { // If it is, get the metadata for the relationship. This is // populated by the `DS.belongsTo` helper when it is creating // the computed property. var meta = value.meta(); meta.parentType = proto.constructor; } } }); } exports.default = Model; }); define('ember-data/-private/system/model/states', ['exports'], function (exports) { 'use strict'; exports.__esModule = true; /* This file encapsulates the various states that a record can transition through during its lifecycle. */ /** ### State Each record has a `currentState` property that explicitly tracks what state a record is in at any given time. For instance, if a record is newly created and has not yet been sent to the adapter to be saved, it would be in the `root.loaded.created.uncommitted` state. If a record has had local modifications made to it that are in the process of being saved, the record would be in the `root.loaded.updated.inFlight` state. (This state paths will be explained in more detail below.) Events are sent by the record or its store to the record's `currentState` property. How the state reacts to these events is dependent on which state it is in. In some states, certain events will be invalid and will cause an exception to be raised. States are hierarchical and every state is a substate of the `RootState`. For example, a record can be in the `root.deleted.uncommitted` state, then transition into the `root.deleted.inFlight` state. If a child state does not implement an event handler, the state manager will attempt to invoke the event on all parent states until the root state is reached. The state hierarchy of a record is described in terms of a path string. You can determine a record's current state by getting the state's `stateName` property: ```javascript record.get('currentState.stateName'); //=> "root.created.uncommitted" ``` The hierarchy of valid states that ship with ember data looks like this: ```text * root * deleted * saved * uncommitted * inFlight * empty * loaded * created * uncommitted * inFlight * saved * updated * uncommitted * inFlight * loading ``` The `DS.Model` states are themselves stateless. What that means is that, the hierarchical states that each of *those* points to is a shared data structure. For performance reasons, instead of each record getting its own copy of the hierarchy of states, each record points to this global, immutable shared instance. How does a state know which record it should be acting on? We pass the record instance into the state's event handlers as the first argument. The record passed as the first parameter is where you should stash state about the record if needed; you should never store data on the state object itself. ### Events and Flags A state may implement zero or more events and flags. #### Events Events are named functions that are invoked when sent to a record. The record will first look for a method with the given name on the current state. If no method is found, it will search the current state's parent, and then its grandparent, and so on until reaching the top of the hierarchy. If the root is reached without an event handler being found, an exception will be raised. This can be very helpful when debugging new features. Here's an example implementation of a state with a `myEvent` event handler: ```javascript aState: DS.State.create({ myEvent: function(manager, param) { console.log("Received myEvent with", param); } }) ``` To trigger this event: ```javascript record.send('myEvent', 'foo'); //=> "Received myEvent with foo" ``` Note that an optional parameter can be sent to a record's `send()` method, which will be passed as the second parameter to the event handler. Events should transition to a different state if appropriate. This can be done by calling the record's `transitionTo()` method with a path to the desired state. The state manager will attempt to resolve the state path relative to the current state. If no state is found at that path, it will attempt to resolve it relative to the current state's parent, and then its parent, and so on until the root is reached. For example, imagine a hierarchy like this: * created * uncommitted <-- currentState * inFlight * updated * inFlight If we are currently in the `uncommitted` state, calling `transitionTo('inFlight')` would transition to the `created.inFlight` state, while calling `transitionTo('updated.inFlight')` would transition to the `updated.inFlight` state. Remember that *only events* should ever cause a state transition. You should never call `transitionTo()` from outside a state's event handler. If you are tempted to do so, create a new event and send that to the state manager. #### Flags Flags are Boolean values that can be used to introspect a record's current state in a more user-friendly way than examining its state path. For example, instead of doing this: ```javascript var statePath = record.get('stateManager.currentPath'); if (statePath === 'created.inFlight') { doSomething(); } ``` You can say: ```javascript if (record.get('isNew') && record.get('isSaving')) { doSomething(); } ``` If your state does not set a value for a given flag, the value will be inherited from its parent (or the first place in the state hierarchy where it is defined). The current set of flags are defined below. If you want to add a new flag, in addition to the area below, you will also need to declare it in the `DS.Model` class. * [isEmpty](DS.Model.html#property_isEmpty) * [isLoading](DS.Model.html#property_isLoading) * [isLoaded](DS.Model.html#property_isLoaded) * [hasDirtyAttributes](DS.Model.html#property_hasDirtyAttributes) * [isSaving](DS.Model.html#property_isSaving) * [isDeleted](DS.Model.html#property_isDeleted) * [isNew](DS.Model.html#property_isNew) * [isValid](DS.Model.html#property_isValid) @namespace DS @class RootState */ function didSetProperty(internalModel, context) { if (context.value === context.originalValue) { delete internalModel._attributes[context.name]; internalModel.send('propertyWasReset', context.name); } else if (context.value !== context.oldValue) { internalModel.send('becomeDirty'); } internalModel.updateRecordArrays(); } // Implementation notes: // // Each state has a boolean value for all of the following flags: // // * isLoaded: The record has a populated `data` property. When a // record is loaded via `store.find`, `isLoaded` is false // until the adapter sets it. When a record is created locally, // its `isLoaded` property is always true. // * isDirty: The record has local changes that have not yet been // saved by the adapter. This includes records that have been // created (but not yet saved) or deleted. // * isSaving: The record has been committed, but // the adapter has not yet acknowledged that the changes have // been persisted to the backend. // * isDeleted: The record was marked for deletion. When `isDeleted` // is true and `isDirty` is true, the record is deleted locally // but the deletion was not yet persisted. When `isSaving` is // true, the change is in-flight. When both `isDirty` and // `isSaving` are false, the change has persisted. // * isNew: The record was created on the client and the adapter // did not yet report that it was successfully saved. // * isValid: The adapter did not report any server-side validation // failures. // The dirty state is a abstract state whose functionality is // shared between the `created` and `updated` states. // // The deleted state shares the `isDirty` flag with the // subclasses of `DirtyState`, but with a very different // implementation. // // Dirty states have three child states: // // `uncommitted`: the store has not yet handed off the record // to be saved. // `inFlight`: the store has handed off the record to be saved, // but the adapter has not yet acknowledged success. // `invalid`: the record has invalid information and cannot be // sent to the adapter yet. /** @module ember-data */ var DirtyState = { initialState: 'uncommitted', // FLAGS isDirty: true, // SUBSTATES // When a record first becomes dirty, it is `uncommitted`. // This means that there are local pending changes, but they // have not yet begun to be saved, and are not invalid. uncommitted: { // EVENTS didSetProperty: didSetProperty, loadingData: function () {}, propertyWasReset: function (internalModel, name) { if (!internalModel.hasChangedAttributes()) { internalModel.send('rolledBack'); } }, pushedData: function (internalModel) { internalModel.updateChangedAttributes(); if (!internalModel.hasChangedAttributes()) { internalModel.transitionTo('loaded.saved'); } }, becomeDirty: function () {}, willCommit: function (internalModel) { internalModel.transitionTo('inFlight'); }, reloadRecord: function (internalModel, resolve) { resolve(internalModel.store._reloadRecord(internalModel)); }, rolledBack: function (internalModel) { internalModel.transitionTo('loaded.saved'); }, becameInvalid: function (internalModel) { internalModel.transitionTo('invalid'); }, rollback: function (internalModel) { internalModel.rollbackAttributes(); internalModel.triggerLater('ready'); } }, // Once a record has been handed off to the adapter to be // saved, it is in the 'in flight' state. Changes to the // record cannot be made during this window. inFlight: { // FLAGS isSaving: true, // EVENTS didSetProperty: didSetProperty, becomeDirty: function () {}, pushedData: function () {}, unloadRecord: assertAgainstUnloadRecord, willCommit: function () {}, didCommit: function (internalModel) { internalModel.transitionTo('saved'); internalModel.send('invokeLifecycleCallbacks', this.dirtyType); }, becameInvalid: function (internalModel) { internalModel.transitionTo('invalid'); internalModel.send('invokeLifecycleCallbacks'); }, becameError: function (internalModel) { internalModel.transitionTo('uncommitted'); internalModel.triggerLater('becameError', internalModel); } }, // A record is in the `invalid` if the adapter has indicated // the the record failed server-side invalidations. invalid: { // FLAGS isValid: false, deleteRecord: function (internalModel) { internalModel.transitionTo('deleted.uncommitted'); }, didSetProperty: function (internalModel, context) { internalModel.removeErrorMessageFromAttribute(context.name); didSetProperty(internalModel, context); if (!internalModel.hasErrors()) { this.becameValid(internalModel); } }, becameInvalid: function () {}, becomeDirty: function () {}, pushedData: function () {}, willCommit: function (internalModel) { internalModel.clearErrorMessages(); internalModel.transitionTo('inFlight'); }, rolledBack: function (internalModel) { internalModel.clearErrorMessages(); internalModel.transitionTo('loaded.saved'); internalModel.triggerLater('ready'); }, becameValid: function (internalModel) { internalModel.transitionTo('uncommitted'); }, invokeLifecycleCallbacks: function (internalModel) { internalModel.triggerLater('becameInvalid', internalModel); } } }; // The created and updated states are created outside the state // chart so we can reopen their substates and add mixins as // necessary. function deepClone(object) { var clone = {}; var value = void 0; for (var prop in object) { value = object[prop]; if (value && typeof value === 'object') { clone[prop] = deepClone(value); } else { clone[prop] = value; } } return clone; } function mixin(original, hash) { for (var prop in hash) { original[prop] = hash[prop]; } return original; } function dirtyState(options) { var newState = deepClone(DirtyState); return mixin(newState, options); } var createdState = dirtyState({ dirtyType: 'created', // FLAGS isNew: true }); createdState.invalid.rolledBack = function (internalModel) { internalModel.transitionTo('deleted.saved'); }; createdState.uncommitted.rolledBack = function (internalModel) { internalModel.transitionTo('deleted.saved'); }; var updatedState = dirtyState({ dirtyType: 'updated' }); function createdStateDeleteRecord(internalModel) { internalModel.transitionTo('deleted.saved'); internalModel.send('invokeLifecycleCallbacks'); } createdState.uncommitted.deleteRecord = createdStateDeleteRecord; createdState.invalid.deleteRecord = createdStateDeleteRecord; createdState.uncommitted.rollback = function (internalModel) { DirtyState.uncommitted.rollback.apply(this, arguments); internalModel.transitionTo('deleted.saved'); }; createdState.uncommitted.pushedData = function (internalModel) { internalModel.transitionTo('loaded.updated.uncommitted'); internalModel.triggerLater('didLoad'); }; createdState.uncommitted.propertyWasReset = function () {}; function assertAgainstUnloadRecord(internalModel) { (false && Ember.assert("You can only unload a record which is not inFlight. `" + internalModel + "`", false)); } updatedState.inFlight.unloadRecord = assertAgainstUnloadRecord; updatedState.uncommitted.deleteRecord = function (internalModel) { internalModel.transitionTo('deleted.uncommitted'); }; var RootState = { // FLAGS isEmpty: false, isLoading: false, isLoaded: false, isDirty: false, isSaving: false, isDeleted: false, isNew: false, isValid: true, rolledBack: function () {}, unloadRecord: function (internalModel) {}, propertyWasReset: function () {}, // SUBSTATES // A record begins its lifecycle in the `empty` state. // If its data will come from the adapter, it will // transition into the `loading` state. Otherwise, if // the record is being created on the client, it will // transition into the `created` state. empty: { isEmpty: true, loadingData: function (internalModel, promise) { internalModel._loadingPromise = promise; internalModel.transitionTo('loading'); }, loadedData: function (internalModel) { internalModel.transitionTo('loaded.created.uncommitted'); internalModel.triggerLater('ready'); }, pushedData: function (internalModel) { internalModel.transitionTo('loaded.saved'); internalModel.triggerLater('didLoad'); internalModel.triggerLater('ready'); } }, // A record enters this state when the store asks // the adapter for its data. It remains in this state // until the adapter provides the requested data. // // Usually, this process is asynchronous, using an // XHR to retrieve the data. loading: { // FLAGS isLoading: true, exit: function (internalModel) { internalModel._loadingPromise = null; }, pushedData: function (internalModel) { internalModel.transitionTo('loaded.saved'); internalModel.triggerLater('didLoad'); internalModel.triggerLater('ready'); //TODO this seems out of place here internalModel.didCleanError(); }, becameError: function (internalModel) { internalModel.triggerLater('becameError', internalModel); }, notFound: function (internalModel) { internalModel.transitionTo('empty'); } }, // A record enters this state when its data is populated. // Most of a record's lifecycle is spent inside substates // of the `loaded` state. loaded: { initialState: 'saved', // FLAGS isLoaded: true, loadingData: function () {}, // SUBSTATES // If there are no local changes to a record, it remains // in the `saved` state. saved: { setup: function (internalModel) { if (internalModel.hasChangedAttributes()) { internalModel.adapterDidDirty(); } }, // EVENTS didSetProperty: didSetProperty, pushedData: function () {}, becomeDirty: function (internalModel) { internalModel.transitionTo('updated.uncommitted'); }, willCommit: function (internalModel) { internalModel.transitionTo('updated.inFlight'); }, reloadRecord: function (internalModel, resolve) { resolve(internalModel.store._reloadRecord(internalModel)); }, deleteRecord: function (internalModel) { internalModel.transitionTo('deleted.uncommitted'); }, unloadRecord: function (internalModel) {}, didCommit: function () {}, notFound: function () {} }, // A record is in this state after it has been locally // created but before the adapter has indicated that // it has been saved. created: createdState, // A record is in this state if it has already been // saved to the server, but there are new local changes // that have not yet been saved. updated: updatedState }, // A record is in this state if it was deleted from the store. deleted: { initialState: 'uncommitted', dirtyType: 'deleted', // FLAGS isDeleted: true, isLoaded: true, isDirty: true, setup: function (internalModel) { internalModel.updateRecordArrays(); }, // SUBSTATES // When a record is deleted, it enters the `start` // state. It will exit this state when the record // starts to commit. uncommitted: { willCommit: function (internalModel) { internalModel.transitionTo('inFlight'); }, rollback: function (internalModel) { internalModel.rollbackAttributes(); internalModel.triggerLater('ready'); }, pushedData: function () {}, becomeDirty: function () {}, deleteRecord: function () {}, rolledBack: function (internalModel) { internalModel.transitionTo('loaded.saved'); internalModel.triggerLater('ready'); } }, // After a record starts committing, but // before the adapter indicates that the deletion // has saved to the server, a record is in the // `inFlight` substate of `deleted`. inFlight: { // FLAGS isSaving: true, // EVENTS unloadRecord: assertAgainstUnloadRecord, willCommit: function () {}, didCommit: function (internalModel) { internalModel.transitionTo('saved'); internalModel.send('invokeLifecycleCallbacks'); }, becameError: function (internalModel) { internalModel.transitionTo('uncommitted'); internalModel.triggerLater('becameError', internalModel); }, becameInvalid: function (internalModel) { internalModel.transitionTo('invalid'); internalModel.triggerLater('becameInvalid', internalModel); } }, // Once the adapter indicates that the deletion has // been saved, the record enters the `saved` substate // of `deleted`. saved: { // FLAGS isDirty: false, setup: function (internalModel) { internalModel.removeFromInverseRelationships(); }, invokeLifecycleCallbacks: function (internalModel) { internalModel.triggerLater('didDelete', internalModel); internalModel.triggerLater('didCommit', internalModel); }, willCommit: function () {}, didCommit: function () {} }, invalid: { isValid: false, didSetProperty: function (internalModel, context) { internalModel.removeErrorMessageFromAttribute(context.name); didSetProperty(internalModel, context); if (!internalModel.hasErrors()) { this.becameValid(internalModel); } }, becameInvalid: function () {}, becomeDirty: function () {}, deleteRecord: function () {}, willCommit: function () {}, rolledBack: function (internalModel) { internalModel.clearErrorMessages(); internalModel.transitionTo('loaded.saved'); internalModel.triggerLater('ready'); }, becameValid: function (internalModel) { internalModel.transitionTo('uncommitted'); } } }, invokeLifecycleCallbacks: function (internalModel, dirtyType) { if (dirtyType === 'created') { internalModel.triggerLater('didCreate', internalModel); } else { internalModel.triggerLater('didUpdate', internalModel); } internalModel.triggerLater('didCommit', internalModel); } }; function wireState(object, parent, name) { // TODO: Use Object.create and copy instead object = mixin(parent ? Object.create(parent) : {}, object); object.parentState = parent; object.stateName = name; for (var prop in object) { if (!object.hasOwnProperty(prop) || prop === 'parentState' || prop === 'stateName') { continue; } if (typeof object[prop] === 'object') { object[prop] = wireState(object[prop], object, name + '.' + prop); } } return object; } exports.default = wireState(RootState, null, 'root'); }); define('ember-data/-private/system/normalize-link', ['exports'], function (exports) { 'use strict'; exports.__esModule = true; exports.default = _normalizeLink; /* This method normalizes a link to an "links object". If the passed link is already an object it's returned without any modifications. See http://jsonapi.org/format/#document-links for more information. @method _normalizeLink @private @param {String} link @return {Object|null} @for DS */ function _normalizeLink(link) { switch (typeof link) { case 'object': return link; case 'string': return { href: link }; } return null; } }); define('ember-data/-private/system/normalize-model-name', ['exports', 'ember'], function (exports, _ember) { 'use strict'; exports.__esModule = true; exports.default = normalizeModelName; // All modelNames are dasherized internally. Changing this function may // require changes to other normalization hooks (such as typeForRoot). /** This method normalizes a modelName into the format Ember Data uses internally. @method normalizeModelName @public @param {String} modelName @return {String} normalizedModelName @for DS */ function normalizeModelName(modelName) { return _ember.default.String.dasherize(modelName); } }); define('ember-data/-private/system/ordered-set', ['exports', 'ember'], function (exports, _ember) { 'use strict'; exports.__esModule = true; exports.default = OrderedSet; var EmberOrderedSet = _ember.default.OrderedSet; var guidFor = _ember.default.guidFor; function OrderedSet() { this._super$constructor(); } OrderedSet.create = function () { var Constructor = this; return new Constructor(); }; OrderedSet.prototype = Object.create(EmberOrderedSet.prototype); OrderedSet.prototype.constructor = OrderedSet; OrderedSet.prototype._super$constructor = EmberOrderedSet; OrderedSet.prototype.addWithIndex = function (obj, idx) { var guid = guidFor(obj); var presenceSet = this.presenceSet; var list = this.list; if (presenceSet[guid] === true) { return; } presenceSet[guid] = true; if (idx === undefined || idx === null) { list.push(obj); } else { list.splice(idx, 0, obj); } this.size += 1; return this; }; }); define('ember-data/-private/system/promise-proxies', ['exports', 'ember'], function (exports, _ember) { 'use strict'; exports.__esModule = true; exports.PromiseManyArray = exports.PromiseObject = exports.PromiseArray = undefined; exports.promiseObject = promiseObject; exports.promiseArray = promiseArray; exports.proxyToContent = proxyToContent; exports.promiseManyArray = promiseManyArray; var get = _ember.default.get, Promise = _ember.default.RSVP.Promise; /** A `PromiseArray` is an object that acts like both an `Ember.Array` and a promise. When the promise is resolved the resulting value will be set to the `PromiseArray`'s `content` property. This makes it easy to create data bindings with the `PromiseArray` that will be updated when the promise resolves. For more information see the [Ember.PromiseProxyMixin documentation](/api/classes/Ember.PromiseProxyMixin.html). Example ```javascript let promiseArray = DS.PromiseArray.create({ promise: $.getJSON('/some/remote/data.json') }); promiseArray.get('length'); // 0 promiseArray.then(function() { promiseArray.get('length'); // 100 }); ``` @class PromiseArray @namespace DS @extends Ember.ArrayProxy @uses Ember.PromiseProxyMixin */ var PromiseArray = exports.PromiseArray = _ember.default.ArrayProxy.extend(_ember.default.PromiseProxyMixin); /** A `PromiseObject` is an object that acts like both an `Ember.Object` and a promise. When the promise is resolved, then the resulting value will be set to the `PromiseObject`'s `content` property. This makes it easy to create data bindings with the `PromiseObject` that will be updated when the promise resolves. For more information see the [Ember.PromiseProxyMixin documentation](/api/classes/Ember.PromiseProxyMixin.html). Example ```javascript let promiseObject = DS.PromiseObject.create({ promise: $.getJSON('/some/remote/data.json') }); promiseObject.get('name'); // null promiseObject.then(function() { promiseObject.get('name'); // 'Tomster' }); ``` @class PromiseObject @namespace DS @extends Ember.ObjectProxy @uses Ember.PromiseProxyMixin */ var PromiseObject = exports.PromiseObject = _ember.default.ObjectProxy.extend(_ember.default.PromiseProxyMixin); function promiseObject(promise, label) { return PromiseObject.create({ promise: Promise.resolve(promise, label) }); } function promiseArray(promise, label) { return PromiseArray.create({ promise: Promise.resolve(promise, label) }); } /** A PromiseManyArray is a PromiseArray that also proxies certain method calls to the underlying manyArray. Right now we proxy: * `reload()` * `createRecord()` * `on()` * `one()` * `trigger()` * `off()` * `has()` @class PromiseManyArray @namespace DS @extends Ember.ArrayProxy */ function proxyToContent(method) { return function () { var _get; return (_get = get(this, 'content'))[method].apply(_get, arguments); }; } var PromiseManyArray = exports.PromiseManyArray = PromiseArray.extend({ reload: function () { (false && _ember.default.assert('You are trying to reload an async manyArray before it has been created', get(this, 'content'))); this.set('promise', this.get('content').reload()); return this; }, createRecord: proxyToContent('createRecord'), on: proxyToContent('on'), one: proxyToContent('one'), trigger: proxyToContent('trigger'), off: proxyToContent('off'), has: proxyToContent('has') }); function promiseManyArray(promise, label) { return PromiseManyArray.create({ promise: Promise.resolve(promise, label) }); } }); define("ember-data/-private/system/record-array-manager", ["exports", "ember", "ember-data/-private/system/record-arrays", "ember-data/-private/system/clone-null"], function (exports, _ember, _recordArrays, _cloneNull) { "use strict"; exports.__esModule = true; exports.associateWithRecordArray = associateWithRecordArray; function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } } var get = _ember.default.get, set = _ember.default.set, emberRun = _ember.default.run; var RecordArrayManager = function () { function RecordArrayManager(options) { this.store = options.store; this.isDestroying = false; this.isDestroyed = false; this._filteredRecordArrays = Object.create(null); this._liveRecordArrays = Object.create(null); this._pending = Object.create(null); this._adapterPopulatedRecordArrays = []; } RecordArrayManager.prototype.recordDidChange = function recordDidChange(internalModel) { // TODO: change name // TODO: track that it was also a change this.internalModelDidChange(internalModel); }; RecordArrayManager.prototype.recordWasLoaded = function recordWasLoaded(internalModel) { // TODO: change name // TODO: track that it was also that it was first loaded this.internalModelDidChange(internalModel); }; RecordArrayManager.prototype.internalModelDidChange = function internalModelDidChange(internalModel) { var modelName = internalModel.modelName; if (internalModel._pendingRecordArrayManagerFlush) { return; } internalModel._pendingRecordArrayManagerFlush = true; var pending = this._pending; var models = pending[modelName] = pending[modelName] || []; if (models.push(internalModel) !== 1) { return; } emberRun.schedule('actions', this, this._flush); }; RecordArrayManager.prototype._flush = function _flush() { var pending = this._pending; this._pending = Object.create(null); var modelsToRemove = []; for (var modelName in pending) { var internalModels = pending[modelName]; for (var j = 0; j < internalModels.length; j++) { var internalModel = internalModels[j]; // mark internalModels, so they can once again be processed by the // recordArrayManager internalModel._pendingRecordArrayManagerFlush = false; // build up a set of models to ensure we have purged correctly; if (internalModel.isHiddenFromRecordArrays()) { modelsToRemove.push(internalModel); } } // process filteredRecordArrays if (this._filteredRecordArrays[modelName]) { var recordArrays = this.filteredRecordArraysFor(modelName); for (var i = 0; i < recordArrays.length; i++) { this.updateFilterRecordArray(recordArrays[i], modelName, internalModels); } } var array = this._liveRecordArrays[modelName]; if (array) { // TODO: skip if it only changed // process liveRecordArrays this.updateLiveRecordArray(array, internalModels); } // process adapterPopulatedRecordArrays if (modelsToRemove.length > 0) { removeFromAdapterPopulatedRecordArrays(modelsToRemove); } } }; RecordArrayManager.prototype.updateLiveRecordArray = function updateLiveRecordArray(array, internalModels) { return _updateLiveRecordArray(array, internalModels); }; RecordArrayManager.prototype.updateFilterRecordArray = function updateFilterRecordArray(array, modelName, internalModels) { var filter = get(array, 'filterFunction'); var shouldBeInAdded = []; var shouldBeRemoved = []; for (var i = 0; i < internalModels.length; i++) { var internalModel = internalModels[i]; if (internalModel.isHiddenFromRecordArrays() === false && filter(internalModel.getRecord())) { if (internalModel._recordArrays.has(array)) { continue; } shouldBeInAdded.push(internalModel); internalModel._recordArrays.add(array); } else { if (internalModel._recordArrays.delete(array)) { shouldBeRemoved.push(internalModel); } } } if (shouldBeInAdded.length > 0) { array._pushInternalModels(shouldBeInAdded); } if (shouldBeRemoved.length > 0) { array._removeInternalModels(shouldBeRemoved); } }; RecordArrayManager.prototype._syncLiveRecordArray = function _syncLiveRecordArray(array, modelName) { (false && _ember.default.assert("recordArrayManger.syncLiveRecordArray expects modelName not modelClass as the second param", typeof modelName === 'string')); var hasNoPotentialDeletions = Object.keys(this._pending).length === 0; var map = this.store._internalModelsFor(modelName); var hasNoInsertionsOrRemovals = get(map, 'length') === get(array, 'length'); /* Ideally the recordArrayManager has knowledge of the changes to be applied to liveRecordArrays, and is capable of strategically flushing those changes and applying small diffs if desired. However, until we've refactored recordArrayManager, this dirty check prevents us from unnecessarily wiping out live record arrays returned by peekAll. */ if (hasNoPotentialDeletions && hasNoInsertionsOrRemovals) { return; } var internalModels = this._visibleInternalModelsByType(modelName); var modelsToAdd = []; for (var i = 0; i < internalModels.length; i++) { var internalModel = internalModels[i]; var recordArrays = internalModel._recordArrays; if (recordArrays.has(array) === false) { recordArrays.add(array); modelsToAdd.push(internalModel); } } array._pushInternalModels(modelsToAdd); }; RecordArrayManager.prototype.updateFilter = function updateFilter(array, modelName, filter) { (false && _ember.default.assert("recordArrayManger.updateFilter expects modelName not modelClass as the second param, received " + modelName, typeof modelName === 'string')); var modelMap = this.store._internalModelsFor(modelName); var internalModels = modelMap.models; this.updateFilterRecordArray(array, filter, internalModels); }; RecordArrayManager.prototype._didUpdateAll = function _didUpdateAll(modelName) { var recordArray = this._liveRecordArrays[modelName]; if (recordArray) { set(recordArray, 'isUpdating', false); } }; RecordArrayManager.prototype.liveRecordArrayFor = function liveRecordArrayFor(modelName) { (false && _ember.default.assert("recordArrayManger.liveRecordArrayFor expects modelName not modelClass as the param", typeof modelName === 'string')); var array = this._liveRecordArrays[modelName]; if (array) { // if the array already exists, synchronize this._syncLiveRecordArray(array, modelName); } else { // if the array is being newly created merely create it with its initial // content already set. This prevents unneeded change events. var internalModels = this._visibleInternalModelsByType(modelName); array = this.createRecordArray(modelName, internalModels); this._liveRecordArrays[modelName] = array; } return array; }; RecordArrayManager.prototype._visibleInternalModelsByType = function _visibleInternalModelsByType(modelName) { var all = this.store._internalModelsFor(modelName)._models; var visible = []; for (var i = 0; i < all.length; i++) { var model = all[i]; if (model.isHiddenFromRecordArrays() === false) { visible.push(model); } } return visible; }; RecordArrayManager.prototype.filteredRecordArraysFor = function filteredRecordArraysFor(modelName) { (false && _ember.default.assert("recordArrayManger.filteredRecordArraysFor expects modelName not modelClass as the param", typeof modelName === 'string')); return this._filteredRecordArrays[modelName] || (this._filteredRecordArrays[modelName] = []); }; RecordArrayManager.prototype.createRecordArray = function createRecordArray(modelName, content) { (false && _ember.default.assert("recordArrayManger.createRecordArray expects modelName not modelClass as the param", typeof modelName === 'string')); var array = _recordArrays.RecordArray.create({ modelName: modelName, content: _ember.default.A(content || []), store: this.store, isLoaded: true, manager: this }); if (Array.isArray(content)) { associateWithRecordArray(content, array); } return array; }; RecordArrayManager.prototype.createFilteredRecordArray = function createFilteredRecordArray(modelName, filter, query) { (false && _ember.default.assert("recordArrayManger.createFilteredRecordArray expects modelName not modelClass as the first param, received " + modelName, typeof modelName === 'string')); var array = _recordArrays.FilteredRecordArray.create({ query: query, modelName: modelName, content: _ember.default.A(), store: this.store, manager: this, filterFunction: filter }); this.registerFilteredRecordArray(array, modelName, filter); return array; }; RecordArrayManager.prototype.createAdapterPopulatedRecordArray = function createAdapterPopulatedRecordArray(modelName, query, internalModels, payload) { (false && _ember.default.assert("recordArrayManger.createAdapterPopulatedRecordArray expects modelName not modelClass as the first param, received " + modelName, typeof modelName === 'string')); var array = void 0; if (Array.isArray(internalModels)) { array = _recordArrays.AdapterPopulatedRecordArray.create({ modelName: modelName, query: query, content: _ember.default.A(internalModels), store: this.store, manager: this, isLoaded: true, isUpdating: false, meta: (0, _cloneNull.default)(payload.meta), links: (0, _cloneNull.default)(payload.links) }); associateWithRecordArray(internalModels, array); } else { array = _recordArrays.AdapterPopulatedRecordArray.create({ modelName: modelName, query: query, content: _ember.default.A(), store: this.store, manager: this }); } this._adapterPopulatedRecordArrays.push(array); return array; }; RecordArrayManager.prototype.registerFilteredRecordArray = function registerFilteredRecordArray(array, modelName, filter) { (false && _ember.default.assert("recordArrayManger.registerFilteredRecordArray expects modelName not modelClass as the second param, received " + modelName, typeof modelName === 'string')); this.filteredRecordArraysFor(modelName).push(array); this.updateFilter(array, modelName, filter); }; RecordArrayManager.prototype.unregisterRecordArray = function unregisterRecordArray(array) { var modelName = array.modelName; // unregister filtered record array var recordArrays = this.filteredRecordArraysFor(modelName); var removedFromFiltered = remove(recordArrays, array); // remove from adapter populated record array var removedFromAdapterPopulated = remove(this._adapterPopulatedRecordArrays, array); if (!removedFromFiltered && !removedFromAdapterPopulated) { var liveRecordArrayForType = this._liveRecordArrays[modelName]; // unregister live record array if (liveRecordArrayForType) { if (array === liveRecordArrayForType) { delete this._liveRecordArrays[modelName]; } } } }; RecordArrayManager.prototype.willDestroy = function willDestroy() { var _this = this; Object.keys(this._filteredRecordArrays).forEach(function (modelName) { return flatten(_this._filteredRecordArrays[modelName]).forEach(destroy); }); Object.keys(this._liveRecordArrays).forEach(function (modelName) { return _this._liveRecordArrays[modelName].destroy(); }); this._adapterPopulatedRecordArrays.forEach(destroy); this.isDestroyed = true; }; RecordArrayManager.prototype.destroy = function destroy() { this.isDestroying = true; emberRun.schedule('actions', this, this.willDestroy); }; return RecordArrayManager; }(); exports.default = RecordArrayManager; function destroy(entry) { entry.destroy(); } function flatten(list) { var length = list.length; var result = []; for (var i = 0; i < length; i++) { result = result.concat(list[i]); } return result; } function remove(array, item) { var index = array.indexOf(item); if (index !== -1) { array.splice(index, 1); return true; } return false; } function _updateLiveRecordArray(array, internalModels) { var modelsToAdd = []; var modelsToRemove = []; for (var i = 0; i < internalModels.length; i++) { var internalModel = internalModels[i]; var isDeleted = internalModel.isHiddenFromRecordArrays(); var recordArrays = internalModel._recordArrays; if (!isDeleted && !internalModel.isEmpty()) { if (!recordArrays.has(array)) { modelsToAdd.push(internalModel); recordArrays.add(array); } } if (isDeleted) { modelsToRemove.push(internalModel); recordArrays.delete(array); } } if (modelsToAdd.length > 0) { array._pushInternalModels(modelsToAdd); } if (modelsToRemove.length > 0) { array._removeInternalModels(modelsToRemove); } } function removeFromAdapterPopulatedRecordArrays(internalModels) { for (var i = 0; i < internalModels.length; i++) { var internalModel = internalModels[i]; var list = internalModel._recordArrays.list; for (var j = 0; j < list.length; j++) { // TODO: group by arrays, so we can batch remove list[j]._removeInternalModels([internalModel]); } internalModel._recordArrays.clear(); } } function associateWithRecordArray(internalModels, array) { for (var i = 0, l = internalModels.length; i < l; i++) { var internalModel = internalModels[i]; internalModel._recordArrays.add(array); } } }); define("ember-data/-private/system/record-arrays", ["exports", "ember-data/-private/system/record-arrays/record-array", "ember-data/-private/system/record-arrays/filtered-record-array", "ember-data/-private/system/record-arrays/adapter-populated-record-array"], function (exports, _recordArray, _filteredRecordArray, _adapterPopulatedRecordArray) { "use strict"; exports.__esModule = true; exports.AdapterPopulatedRecordArray = exports.FilteredRecordArray = exports.RecordArray = undefined; exports.RecordArray = _recordArray.default; exports.FilteredRecordArray = _filteredRecordArray.default; exports.AdapterPopulatedRecordArray = _adapterPopulatedRecordArray.default; }); define("ember-data/-private/system/record-arrays/adapter-populated-record-array", ["exports", "ember", "ember-data/-private/system/record-arrays/record-array", "ember-data/-private/system/clone-null", "ember-data/-private/system/record-array-manager"], function (exports, _ember, _recordArray, _cloneNull, _recordArrayManager) { "use strict"; exports.__esModule = true; var get = _ember.default.get; exports.default = _recordArray.default.extend({ init: function () { // yes we are touching `this` before super, but ArrayProxy has a bug that requires this. this.set('content', this.get('content') || _ember.default.A()); this._super.apply(this, arguments); this.query = this.query || null; this.links = null; }, replace: function () { throw new Error("The result of a server query (on " + this.modelName + ") is immutable."); }, _update: function () { var store = get(this, 'store'); var query = get(this, 'query'); return store._query(this.modelName, query, this); }, /** @method _setInternalModels @param {Array} internalModels @param {Object} payload normalized payload @private */ _setInternalModels: function (internalModels, payload) { // TODO: initial load should not cause change events at all, only // subsequent. This requires changing the public api of adapter.query, but // hopefully we can do that soon. this.get('content').setObjects(internalModels); this.setProperties({ isLoaded: true, isUpdating: false, meta: (0, _cloneNull.default)(payload.meta), links: (0, _cloneNull.default)(payload.links) }); (0, _recordArrayManager.associateWithRecordArray)(internalModels, this); // TODO: should triggering didLoad event be the last action of the runLoop? _ember.default.run.once(this, 'trigger', 'didLoad'); } }); }); define('ember-data/-private/system/record-arrays/filtered-record-array', ['exports', 'ember', 'ember-data/-private/system/record-arrays/record-array'], function (exports, _ember, _recordArray) { 'use strict'; exports.__esModule = true; var get = _ember.default.get; exports.default = _recordArray.default.extend({ init: function () { this._super.apply(this, arguments); this.set('filterFunction', this.get('filterFunction') || null); this.isLoaded = true; }, /** The filterFunction is a function used to test records from the store to determine if they should be part of the record array. Example ```javascript var allPeople = store.peekAll('person'); allPeople.mapBy('name'); // ["Tom Dale", "Yehuda Katz", "Trek Glowacki"] var people = store.filter('person', function(person) { if (person.get('name').match(/Katz$/)) { return true; } }); people.mapBy('name'); // ["Yehuda Katz"] var notKatzFilter = function(person) { return !person.get('name').match(/Katz$/); }; people.set('filterFunction', notKatzFilter); people.mapBy('name'); // ["Tom Dale", "Trek Glowacki"] ``` @method filterFunction @param {DS.Model} record @return {Boolean} `true` if the record should be in the array */ replace: function () { throw new Error('The result of a client-side filter (on ' + this.modelName + ') is immutable.'); }, /** @method updateFilter @private */ _updateFilter: function () { if (get(this, 'isDestroying') || get(this, 'isDestroyed')) { return; } get(this, 'manager').updateFilter(this, this.modelName, get(this, 'filterFunction')); }, updateFilter: _ember.default.observer('filterFunction', function () { _ember.default.run.once(this, this._updateFilter); }) }); }); define("ember-data/-private/system/record-arrays/record-array", ["exports", "ember", "ember-data/-private/system/promise-proxies", "ember-data/-private/system/snapshot-record-array"], function (exports, _ember, _promiseProxies, _snapshotRecordArray) { "use strict"; exports.__esModule = true; var computed = _ember.default.computed, get = _ember.default.get, set = _ember.default.set, Promise = _ember.default.RSVP.Promise; exports.default = _ember.default.ArrayProxy.extend(_ember.default.Evented, { init: function () { this._super.apply(this, arguments); /** The array of client ids backing the record array. When a record is requested from the record array, the record for the client id at the same index is materialized, if necessary, by the store. @property content @private @type Ember.Array */ this.set('content', this.content || null); /** The flag to signal a `RecordArray` is finished loading data. Example ```javascript var people = store.peekAll('person'); people.get('isLoaded'); // true ``` @property isLoaded @type Boolean */ this.isLoaded = this.isLoaded || false; /** The flag to signal a `RecordArray` is currently loading data. Example ```javascript var people = store.peekAll('person'); people.get('isUpdating'); // false people.update(); people.get('isUpdating'); // true ``` @property isUpdating @type Boolean */ this.isUpdating = false; /** The store that created this record array. @property store @private @type DS.Store */ this.store = this.store || null; this._updatingPromise = null; }, replace: function () { throw new Error("The result of a server query (for all " + this.modelName + " types) is immutable. To modify contents, use toArray()"); }, /** The modelClass represented by this record array. @property type @type DS.Model */ type: computed('modelName', function () { if (!this.modelName) { return null; } return this.store._modelFor(this.modelName); }).readOnly(), /** Retrieves an object from the content by index. @method objectAtContent @private @param {Number} index @return {DS.Model} record */ objectAtContent: function (index) { var internalModel = get(this, 'content').objectAt(index); return internalModel && internalModel.getRecord(); }, /** Used to get the latest version of all of the records in this array from the adapter. Example ```javascript var people = store.peekAll('person'); people.get('isUpdating'); // false people.update().then(function() { people.get('isUpdating'); // false }); people.get('isUpdating'); // true ``` @method update */ update: function () { var _this = this; if (get(this, 'isUpdating')) { return this._updatingPromise; } this.set('isUpdating', true); var updatingPromise = this._update().finally(function () { _this._updatingPromise = null; if (_this.get('isDestroying') || _this.get('isDestroyed')) { return; } _this.set('isUpdating', false); }); this._updatingPromise = updatingPromise; return updatingPromise; }, /* Update this RecordArray and return a promise which resolves once the update is finished. */ _update: function () { return this.store.findAll(this.modelName, { reload: true }); }, /** Adds an internal model to the `RecordArray` without duplicates @method _pushInternalModels @private @param {InternalModel} internalModel */ _pushInternalModels: function (internalModels) { // pushObjects because the internalModels._recordArrays set was already // consulted for inclusion, so addObject and its on .contains call is not // required. get(this, 'content').pushObjects(internalModels); }, /** Removes an internalModel to the `RecordArray`. @method removeInternalModel @private @param {InternalModel} internalModel */ _removeInternalModels: function (internalModels) { get(this, 'content').removeObjects(internalModels); }, /** Saves all of the records in the `RecordArray`. Example ```javascript var messages = store.peekAll('message'); messages.forEach(function(message) { message.set('hasBeenSeen', true); }); messages.save(); ``` @method save @return {DS.PromiseArray} promise */ save: function () { var _this2 = this; var promiseLabel = "DS: RecordArray#save " + this.modelName; var promise = Promise.all(this.invoke('save'), promiseLabel).then(function () { return _this2; }, null, 'DS: RecordArray#save return RecordArray'); return _promiseProxies.PromiseArray.create({ promise: promise }); }, _dissociateFromOwnRecords: function () { var _this3 = this; this.get('content').forEach(function (internalModel) { var recordArrays = internalModel.__recordArrays; if (recordArrays) { recordArrays.delete(_this3); } }); }, /** @method _unregisterFromManager @private */ _unregisterFromManager: function () { this.manager.unregisterRecordArray(this); }, willDestroy: function () { this._unregisterFromManager(); this._dissociateFromOwnRecords(); // TODO: we should not do work during destroy: // * when objects are destroyed, they should simply be left to do // * if logic errors do to this, that logic needs to be more careful during // teardown (ember provides isDestroying/isDestroyed) for this reason // * the exception being: if an dominator has a reference to this object, // and must be informed to release e.g. e.g. removing itself from th // recordArrayMananger set(this, 'content', null); set(this, 'length', 0); this._super.apply(this, arguments); }, /* @method _createSnapshot @private */ _createSnapshot: function (options) { // this is private for users, but public for ember-data internals return new _snapshotRecordArray.default(this, this.get('meta'), options); }, /* @method _takeSnapshot @private */ _takeSnapshot: function () { return get(this, 'content').map(function (internalModel) { return internalModel.createSnapshot(); }); } }); }); define('ember-data/-private/system/references', ['exports', 'ember-data/-private/system/references/record', 'ember-data/-private/system/references/belongs-to', 'ember-data/-private/system/references/has-many'], function (exports, _record, _belongsTo, _hasMany) { 'use strict'; exports.__esModule = true; exports.HasManyReference = exports.BelongsToReference = exports.RecordReference = undefined; exports.RecordReference = _record.default; exports.BelongsToReference = _belongsTo.default; exports.HasManyReference = _hasMany.default; }); define('ember-data/-private/system/references/belongs-to', ['exports', 'ember-data/-private/system/model/model', 'ember', 'ember-data/-private/system/references/reference', 'ember-data/-private/features'], function (exports, _model, _ember, _reference, _features) { 'use strict'; exports.__esModule = true; /** A BelongsToReference is a low level API that allows users and addon author to perform meta-operations on a belongs-to relationship. @class BelongsToReference @namespace DS @extends DS.Reference */ var BelongsToReference = function (store, parentInternalModel, belongsToRelationship) { this._super$constructor(store, parentInternalModel); this.belongsToRelationship = belongsToRelationship; this.type = belongsToRelationship.relationshipMeta.type; this.parent = parentInternalModel.recordReference; // TODO inverse }; BelongsToReference.prototype = Object.create(_reference.default.prototype); BelongsToReference.prototype.constructor = BelongsToReference; BelongsToReference.prototype._super$constructor = _reference.default; /** This returns a string that represents how the reference will be looked up when it is loaded. If the relationship has a link it will use the "link" otherwise it defaults to "id". Example ```javascript // models/blog.js export default DS.Model.extend({ user: DS.belongsTo({ async: true }) }); let blog = store.push({ type: 'blog', id: 1, relationships: { user: { data: { type: 'user', id: 1 } } } }); let userRef = blog.belongsTo('user'); // get the identifier of the reference if (userRef.remoteType() === "id") { let id = userRef.id(); } else if (userRef.remoteType() === "link") { let link = userRef.link(); } ``` @method remoteType @return {String} The name of the remote type. This should either be "link" or "id" */ BelongsToReference.prototype.remoteType = function () { if (this.belongsToRelationship.link) { return "link"; } return "id"; }; /** The `id` of the record that this reference refers to. Together, the `type()` and `id()` methods form a composite key for the identity map. This can be used to access the id of an async relationship without triggering a fetch that would normally happen if you attempted to use `record.get('relationship.id')`. Example ```javascript // models/blog.js export default DS.Model.extend({ user: DS.belongsTo({ async: true }) }); let blog = store.push({ data: { type: 'blog', id: 1, relationships: { user: { data: { type: 'user', id: 1 } } } } }); let userRef = blog.belongsTo('user'); // get the identifier of the reference if (userRef.remoteType() === "id") { let id = userRef.id(); } ``` @method id @return {String} The id of the record in this belongsTo relationship. */ BelongsToReference.prototype.id = function () { var inverseInternalModel = this.belongsToRelationship.inverseInternalModel; return inverseInternalModel && inverseInternalModel.id; }; /** The link Ember Data will use to fetch or reload this belongs-to relationship. Example ```javascript // models/blog.js export default DS.Model.extend({ user: DS.belongsTo({ async: true }) }); let blog = store.push({ data: { type: 'blog', id: 1, relationships: { user: { links: { related: '/articles/1/author' } } } } }); let userRef = blog.belongsTo('user'); // get the identifier of the reference if (userRef.remoteType() === "link") { let link = userRef.link(); } ``` @method link @return {String} The link Ember Data will use to fetch or reload this belongs-to relationship. */ BelongsToReference.prototype.link = function () { return this.belongsToRelationship.link; }; /** The meta data for the belongs-to relationship. Example ```javascript // models/blog.js export default DS.Model.extend({ user: DS.belongsTo({ async: true }) }); let blog = store.push({ data: { type: 'blog', id: 1, relationships: { user: { links: { related: { href: '/articles/1/author', meta: { lastUpdated: 1458014400000 } } } } } } }); let userRef = blog.belongsTo('user'); userRef.meta() // { lastUpdated: 1458014400000 } ``` @method meta @return {Object} The meta information for the belongs-to relationship. */ BelongsToReference.prototype.meta = function () { return this.belongsToRelationship.meta; }; /** `push` can be used to update the data in the relationship and Ember Data will treat the new data as the conanical value of this relationship on the backend. Example ```javascript // models/blog.js export default DS.Model.extend({ user: DS.belongsTo({ async: true }) }); let blog = store.push({ data: { type: 'blog', id: 1, relationships: { user: { data: { type: 'user', id: 1 } } } } }); let userRef = blog.belongsTo('user'); // provide data for reference userRef.push({ data: { type: 'user', id: 1, attributes: { username: "@user" } } }).then(function(user) { userRef.value() === user; }); ``` @method push @param {Object|Promise} objectOrPromise a promise that resolves to a JSONAPI document object describing the new value of this relationship. @return {Promise<record>} A promise that resolves with the new value in this belongs-to relationship. */ BelongsToReference.prototype.push = function (objectOrPromise) { var _this = this; return _ember.default.RSVP.resolve(objectOrPromise).then(function (data) { var record = void 0; if (data instanceof _model.default) { if ((0, _features.default)('ds-overhaul-references')) { (false && !(false) && _ember.default.deprecate("BelongsToReference#push(DS.Model) is deprecated. Update relationship via `model.set('relationshipName', value)` instead.", false, { id: 'ds.references.belongs-to.push-record', until: '3.0' })); } record = data; } else { record = _this.store.push(data); } _this.belongsToRelationship.setCanonicalInternalModel(record._internalModel); return record; }); }; /** `value()` synchronously returns the current value of the belongs-to relationship. Unlike `record.get('relationshipName')`, calling `value()` on a reference does not trigger a fetch if the async relationship is not yet loaded. If the relationship is not loaded it will always return `null`. Example ```javascript // models/blog.js export default DS.Model.extend({ user: DS.belongsTo({ async: true }) }); let blog = store.push({ data: { type: 'blog', id: 1, relationships: { user: { data: { type: 'user', id: 1 } } } } }); let userRef = blog.belongsTo('user'); userRef.value(); // null // provide data for reference userRef.push({ data: { type: 'user', id: 1, attributes: { username: "@user" } } }).then(function(user) { userRef.value(); // user }); ``` @method value @return {DS.Model} the record in this relationship */ BelongsToReference.prototype.value = function () { var inverseInternalModel = this.belongsToRelationship.inverseInternalModel; if (inverseInternalModel && inverseInternalModel.isLoaded()) { return inverseInternalModel.getRecord(); } return null; }; /** Loads a record in a belongs to relationship if it is not already loaded. If the relationship is already loaded this method does not trigger a new load. Example ```javascript // models/blog.js export default DS.Model.extend({ user: DS.belongsTo({ async: true }) }); let blog = store.push({ data: { type: 'blog', id: 1, relationships: { user: { data: { type: 'user', id: 1 } } } } }); let userRef = blog.belongsTo('user'); userRef.value(); // null userRef.load().then(function(user) { userRef.value() === user }); ``` @method load @return {Promise} a promise that resolves with the record in this belongs-to relationship. */ BelongsToReference.prototype.load = function () { var _this2 = this; if (this.remoteType() === "id") { return this.belongsToRelationship.getRecord(); } if (this.remoteType() === "link") { return this.belongsToRelationship.findLink().then(function (internalModel) { return _this2.value(); }); } }; /** Triggers a reload of the value in this relationship. If the remoteType is `"link"` Ember Data will use the relationship link to reload the relationship. Otherwise it will reload the record by its id. Example ```javascript // models/blog.js export default DS.Model.extend({ user: DS.belongsTo({ async: true }) }); let blog = store.push({ data: { type: 'blog', id: 1, relationships: { user: { data: { type: 'user', id: 1 } } } } }); let userRef = blog.belongsTo('user'); userRef.reload().then(function(user) { userRef.value() === user }); ``` @method reload @return {Promise} a promise that resolves with the record in this belongs-to relationship after the reload has completed. */ BelongsToReference.prototype.reload = function () { var _this3 = this; return this.belongsToRelationship.reload().then(function (internalModel) { return _this3.value(); }); }; exports.default = BelongsToReference; }); define('ember-data/-private/system/references/has-many', ['exports', 'ember', 'ember-data/-private/system/references/reference', 'ember-data/-private/features'], function (exports, _ember, _reference, _features) { 'use strict'; exports.__esModule = true; var resolve = _ember.default.RSVP.resolve, get = _ember.default.get; /** A HasManyReference is a low level API that allows users and addon author to perform meta-operations on a has-many relationship. @class HasManyReference @namespace DS */ var HasManyReference = function (store, parentInternalModel, hasManyRelationship) { this._super$constructor(store, parentInternalModel); this.hasManyRelationship = hasManyRelationship; this.type = hasManyRelationship.relationshipMeta.type; this.parent = parentInternalModel.recordReference; // TODO inverse }; HasManyReference.prototype = Object.create(_reference.default.prototype); HasManyReference.prototype.constructor = HasManyReference; HasManyReference.prototype._super$constructor = _reference.default; /** This returns a string that represents how the reference will be looked up when it is loaded. If the relationship has a link it will use the "link" otherwise it defaults to "id". Example ```app/models/post.js export default DS.Model.extend({ comments: DS.hasMany({ async: true }) }); ``` ```javascript let post = store.push({ data: { type: 'post', id: 1, relationships: { comments: { data: [{ type: 'comment', id: 1 }] } } } }); let commentsRef = post.hasMany('comments'); // get the identifier of the reference if (commentsRef.remoteType() === "ids") { let ids = commentsRef.ids(); } else if (commentsRef.remoteType() === "link") { let link = commentsRef.link(); } ``` @method remoteType @return {String} The name of the remote type. This should either be "link" or "ids" */ HasManyReference.prototype.remoteType = function () { if (this.hasManyRelationship.link) { return "link"; } return "ids"; }; /** The link Ember Data will use to fetch or reload this has-many relationship. Example ```app/models/post.js export default DS.Model.extend({ comments: DS.hasMany({ async: true }) }); ``` ```javascript let post = store.push({ data: { type: 'post', id: 1, relationships: { comments: { links: { related: '/posts/1/comments' } } } } }); let commentsRef = post.hasMany('comments'); commentsRef.link(); // '/posts/1/comments' ``` @method link @return {String} The link Ember Data will use to fetch or reload this has-many relationship. */ HasManyReference.prototype.link = function () { return this.hasManyRelationship.link; }; /** `ids()` returns an array of the record ids in this relationship. Example ```app/models/post.js export default DS.Model.extend({ comments: DS.hasMany({ async: true }) }); ``` ```javascript let post = store.push({ data: { type: 'post', id: 1, relationships: { comments: { data: [{ type: 'comment', id: 1 }] } } } }); let commentsRef = post.hasMany('comments'); commentsRef.ids(); // ['1'] ``` @method ids @return {Array} The ids in this has-many relationship */ HasManyReference.prototype.ids = function () { var members = this.hasManyRelationship.members.toArray(); return members.map(function (internalModel) { return internalModel.id; }); }; /** The meta data for the has-many relationship. Example ```app/models/post.js export default DS.Model.extend({ comments: DS.hasMany({ async: true }) }); ``` ```javascript let post = store.push({ data: { type: 'post', id: 1, relationships: { comments: { links: { related: { href: '/posts/1/comments', meta: { count: 10 } } } } } } }); let commentsRef = post.hasMany('comments'); commentsRef.meta(); // { count: 10 } ``` @method meta @return {Object} The meta information for the has-many relationship. */ HasManyReference.prototype.meta = function () { return this.hasManyRelationship.meta; }; /** `push` can be used to update the data in the relationship and Ember Data will treat the new data as the canonical value of this relationship on the backend. Example ```app/models/post.js export default DS.Model.extend({ comments: DS.hasMany({ async: true }) }); ``` ``` let post = store.push({ data: { type: 'post', id: 1, relationships: { comments: { data: [{ type: 'comment', id: 1 }] } } } }); let commentsRef = post.hasMany('comments'); commentsRef.ids(); // ['1'] commentsRef.push([ [{ type: 'comment', id: 2 }], [{ type: 'comment', id: 3 }], ]) commentsRef.ids(); // ['2', '3'] ``` @method push @param {Array|Promise} objectOrPromise a promise that resolves to a JSONAPI document object describing the new value of this relationship. @return {DS.ManyArray} */ HasManyReference.prototype.push = function (objectOrPromise) { var _this = this; return resolve(objectOrPromise).then(function (payload) { var array = payload; if ((0, _features.default)("ds-overhaul-references")) { (false && !(!Array.isArray(payload)) && _ember.default.deprecate("HasManyReference#push(array) is deprecated. Push a JSON-API document instead.", !Array.isArray(payload), { id: 'ds.references.has-many.push-array', until: '3.0' })); } var useLegacyArrayPush = true; if (typeof payload === "object" && payload.data) { array = payload.data; useLegacyArrayPush = array.length && array[0].data; if ((0, _features.default)('ds-overhaul-references')) { (false && !(!useLegacyArrayPush) && _ember.default.deprecate("HasManyReference#push() expects a valid JSON-API document.", !useLegacyArrayPush, { id: 'ds.references.has-many.push-invalid-json-api', until: '3.0' })); } } if (!(0, _features.default)('ds-overhaul-references')) { useLegacyArrayPush = true; } var internalModels = void 0; if (useLegacyArrayPush) { internalModels = array.map(function (obj) { var record = _this.store.push(obj); if (false) { var relationshipMeta = _this.hasManyRelationship.relationshipMeta; } return record._internalModel; }); } else { var records = _this.store.push(payload); internalModels = _ember.default.A(records).mapBy('_internalModel'); if (false) { internalModels.forEach(function (internalModel) { var relationshipMeta = _this.hasManyRelationship.relationshipMeta; }); } } _this.hasManyRelationship.computeChanges(internalModels); return _this.hasManyRelationship.manyArray; }); }; HasManyReference.prototype._isLoaded = function () { var hasData = get(this.hasManyRelationship, 'hasData'); if (!hasData) { return false; } var members = this.hasManyRelationship.members.toArray(); return members.every(function (internalModel) { return internalModel.isLoaded() === true; }); }; /** `value()` synchronously returns the current value of the has-many relationship. Unlike `record.get('relationshipName')`, calling `value()` on a reference does not trigger a fetch if the async relationship is not yet loaded. If the relationship is not loaded it will always return `null`. Example ```app/models/post.js export default DS.Model.extend({ comments: DS.hasMany({ async: true }) }); ``` ```javascript let post = store.push({ data: { type: 'post', id: 1, relationships: { comments: { data: [{ type: 'comment', id: 1 }] } } } }); let commentsRef = post.hasMany('comments'); post.get('comments').then(function(comments) { commentsRef.value() === comments }) ``` @method value @return {DS.ManyArray} */ HasManyReference.prototype.value = function () { if (this._isLoaded()) { return this.hasManyRelationship.manyArray; } return null; }; /** Loads the relationship if it is not already loaded. If the relationship is already loaded this method does not trigger a new load. Example ```app/models/post.js export default DS.Model.extend({ comments: DS.hasMany({ async: true }) }); ``` ```javascript let post = store.push({ data: { type: 'post', id: 1, relationships: { comments: { data: [{ type: 'comment', id: 1 }] } } } }); let commentsRef = post.hasMany('comments'); commentsRef.load().then(function(comments) { //... }); ``` @method load @return {Promise} a promise that resolves with the ManyArray in this has-many relationship. */ HasManyReference.prototype.load = function () { if (!this._isLoaded()) { return this.hasManyRelationship.getRecords(); } return resolve(this.hasManyRelationship.manyArray); }; /** Reloads this has-many relationship. Example ```app/models/post.js export default DS.Model.extend({ comments: DS.hasMany({ async: true }) }); ``` ```javascript let post = store.push({ data: { type: 'post', id: 1, relationships: { comments: { data: [{ type: 'comment', id: 1 }] } } } }); let commentsRef = post.hasMany('comments'); commentsRef.reload().then(function(comments) { //... }); ``` @method reload @return {Promise} a promise that resolves with the ManyArray in this has-many relationship. */ HasManyReference.prototype.reload = function () { return this.hasManyRelationship.reload(); }; exports.default = HasManyReference; }); define('ember-data/-private/system/references/record', ['exports', 'ember', 'ember-data/-private/system/references/reference'], function (exports, _ember, _reference) { 'use strict'; exports.__esModule = true; /** An RecordReference is a low level API that allows users and addon author to perform meta-operations on a record. @class RecordReference @namespace DS */ var RecordReference = function (store, internalModel) { this._super$constructor(store, internalModel); this.type = internalModel.modelName; this._id = internalModel.id; }; RecordReference.prototype = Object.create(_reference.default.prototype); RecordReference.prototype.constructor = RecordReference; RecordReference.prototype._super$constructor = _reference.default; /** The `id` of the record that this reference refers to. Together, the `type` and `id` properties form a composite key for the identity map. Example ```javascript let userRef = store.getReference('user', 1); userRef.id(); // '1' ``` @method id @return {String} The id of the record. */ RecordReference.prototype.id = function () { return this._id; }; /** How the reference will be looked up when it is loaded: Currently this always return `identity` to signifying that a record will be loaded by the `type` and `id`. Example ```javascript const userRef = store.getReference('user', 1); userRef.remoteType(); // 'identity' ``` @method remoteType @return {String} 'identity' */ RecordReference.prototype.remoteType = function () { return 'identity'; }; /** This API allows you to provide a reference with new data. The simplest usage of this API is similar to `store.push`: you provide a normalized hash of data and the object represented by the reference will update. If you pass a promise to `push`, Ember Data will not ask the adapter for the data if another attempt to fetch it is made in the interim. When the promise resolves, the underlying object is updated with the new data, and the promise returned by *this function* is resolved with that object. For example, `recordReference.push(promise)` will be resolved with a record. Example ```javascript let userRef = store.getReference('user', 1); // provide data for reference userRef.push({ data: { id: 1, username: "@user" }}).then(function(user) { userRef.value() === user; }); ``` @method push @param {Promise|Object} @return Promise<record> a promise for the value (record or relationship) */ RecordReference.prototype.push = function (objectOrPromise) { var _this = this; return _ember.default.RSVP.resolve(objectOrPromise).then(function (data) { return _this.store.push(data); }); }; /** If the entity referred to by the reference is already loaded, it is present as `reference.value`. Otherwise the value returned by this function is `null`. Example ```javascript let userRef = store.getReference('user', 1); userRef.value(); // user ``` @method value @return {DS.Model} the record for this RecordReference */ RecordReference.prototype.value = function () { if (this.internalModel.hasRecord) { return this.internalModel.getRecord(); } }; /** Triggers a fetch for the backing entity based on its `remoteType` (see `remoteType` definitions per reference type). Example ```javascript let userRef = store.getReference('user', 1); // load user (via store.find) userRef.load().then(...) ``` @method load @return {Promise<record>} the record for this RecordReference */ RecordReference.prototype.load = function () { return this.store.findRecord(this.type, this._id); }; /** Reloads the record if it is already loaded. If the record is not loaded it will load the record via `store.findRecord` Example ```javascript let userRef = store.getReference('user', 1); // or trigger a reload userRef.reload().then(...) ``` @method reload @return {Promise<record>} the record for this RecordReference */ RecordReference.prototype.reload = function () { var record = this.value(); if (record) { return record.reload(); } return this.load(); }; exports.default = RecordReference; }); define("ember-data/-private/system/references/reference", ["exports"], function (exports) { "use strict"; exports.__esModule = true; var Reference = function (store, internalModel) { this.store = store; this.internalModel = internalModel; }; Reference.prototype = { constructor: Reference }; exports.default = Reference; }); define('ember-data/-private/system/relationship-meta', ['exports', 'ember-inflector', 'ember-data/-private/system/normalize-model-name'], function (exports, _emberInflector, _normalizeModelName) { 'use strict'; exports.__esModule = true; exports.typeForRelationshipMeta = typeForRelationshipMeta; exports.relationshipFromMeta = relationshipFromMeta; function typeForRelationshipMeta(meta) { var modelName = void 0; modelName = meta.type || meta.key; if (meta.kind === 'hasMany') { modelName = (0, _emberInflector.singularize)((0, _normalizeModelName.default)(modelName)); } return modelName; } function relationshipFromMeta(meta) { var result = { key: meta.key, kind: meta.kind, type: typeForRelationshipMeta(meta), options: meta.options, name: meta.name, parentType: meta.parentType, isRelationship: true }; if (false) { result.parentType = meta.parentType; } return result; } }); define('ember-data/-private/system/relationships/belongs-to', ['exports', 'ember', 'ember-data/-private/system/normalize-model-name'], function (exports, _ember, _normalizeModelName) { 'use strict'; exports.__esModule = true; exports.default = belongsTo; /** `DS.belongsTo` is used to define One-To-One and One-To-Many relationships on a [DS.Model](/api/data/classes/DS.Model.html). `DS.belongsTo` takes an optional hash as a second parameter, currently supported options are: - `async`: A boolean value used to explicitly declare this to be an async relationship. - `inverse`: A string used to identify the inverse property on a related model in a One-To-Many relationship. See [Explicit Inverses](#toc_explicit-inverses) #### One-To-One To declare a one-to-one relationship between two models, use `DS.belongsTo`: ```app/models/user.js import DS from 'ember-data'; export default DS.Model.extend({ profile: DS.belongsTo('profile') }); ``` ```app/models/profile.js import DS from 'ember-data'; export default DS.Model.extend({ user: DS.belongsTo('user') }); ``` #### One-To-Many To declare a one-to-many relationship between two models, use `DS.belongsTo` in combination with `DS.hasMany`, like this: ```app/models/post.js import DS from 'ember-data'; export default DS.Model.extend({ comments: DS.hasMany('comment') }); ``` ```app/models/comment.js import DS from 'ember-data'; export default DS.Model.extend({ post: DS.belongsTo('post') }); ``` You can avoid passing a string as the first parameter. In that case Ember Data will infer the type from the key name. ```app/models/comment.js import DS from 'ember-data'; export default DS.Model.extend({ post: DS.belongsTo() }); ``` will lookup for a Post type. @namespace @method belongsTo @for DS @param {String} modelName (optional) type of the relationship @param {Object} options (optional) a hash of options @return {Ember.computed} relationship */ function belongsTo(modelName, options) { var opts = void 0, userEnteredModelName = void 0; if (typeof modelName === 'object') { opts = modelName; userEnteredModelName = undefined; } else { opts = options; userEnteredModelName = modelName; } if (typeof userEnteredModelName === 'string') { userEnteredModelName = (0, _normalizeModelName.default)(userEnteredModelName); } (false && _ember.default.assert("The first argument to DS.belongsTo must be a string representing a model type key, not an instance of " + _ember.default.inspect(userEnteredModelName) + ". E.g., to define a relation to the Person model, use DS.belongsTo('person')", typeof userEnteredModelName === 'string' || typeof userEnteredModelName === 'undefined')); opts = opts || {}; var meta = { type: userEnteredModelName, isRelationship: true, options: opts, kind: 'belongsTo', name: 'Belongs To', key: null }; return _ember.default.computed({ get: function (key) { if (opts.hasOwnProperty('serialize')) { (false && _ember.default.warn('You provided a serialize option on the "' + key + '" property in the "' + this._internalModel.modelName + '" class, this belongs in the serializer. See DS.Serializer and it\'s implementations https://emberjs.com/api/data/classes/DS.Serializer.html', false, { id: 'ds.model.serialize-option-in-belongs-to' })); } if (opts.hasOwnProperty('embedded')) { (false && _ember.default.warn('You provided an embedded option on the "' + key + '" property in the "' + this._internalModel.modelName + '" class, this belongs in the serializer. See DS.EmbeddedRecordsMixin https://emberjs.com/api/data/classes/DS.EmbeddedRecordsMixin.html', false, { id: 'ds.model.embedded-option-in-belongs-to' })); } return this._internalModel._relationships.get(key).getRecord(); }, set: function (key, value) { if (value === undefined) { value = null; } if (value && value.then) { this._internalModel._relationships.get(key).setRecordPromise(value); } else if (value) { this._internalModel._relationships.get(key).setInternalModel(value._internalModel); } else { this._internalModel._relationships.get(key).setInternalModel(value); } return this._internalModel._relationships.get(key).getRecord(); } }).meta(meta); } }); define('ember-data/-private/system/relationships/ext', ['exports', 'ember', 'ember-data/-private/system/relationship-meta'], function (exports, _ember, _relationshipMeta) { 'use strict'; exports.__esModule = true; exports.relationshipsByNameDescriptor = exports.relatedTypesDescriptor = exports.relationshipsDescriptor = undefined; var Map = _ember.default.Map; var MapWithDefault = _ember.default.MapWithDefault; var relationshipsDescriptor = exports.relationshipsDescriptor = _ember.default.computed(function () { if (_ember.default.testing === true && relationshipsDescriptor._cacheable === true) { relationshipsDescriptor._cacheable = false; } var map = new MapWithDefault({ defaultValue: function () { return []; } }); // Loop through each computed property on the class this.eachComputedProperty(function (name, meta) { // If the computed property is a relationship, add // it to the map. if (meta.isRelationship) { meta.key = name; var relationshipsForType = map.get((0, _relationshipMeta.typeForRelationshipMeta)(meta)); relationshipsForType.push({ name: name, kind: meta.kind }); } }); return map; }).readOnly(); var relatedTypesDescriptor = exports.relatedTypesDescriptor = _ember.default.computed(function () { var _this = this; if (_ember.default.testing === true && relatedTypesDescriptor._cacheable === true) { relatedTypesDescriptor._cacheable = false; } var modelName = void 0; var types = _ember.default.A(); // Loop through each computed property on the class, // and create an array of the unique types involved // in relationships this.eachComputedProperty(function (name, meta) { if (meta.isRelationship) { meta.key = name; modelName = (0, _relationshipMeta.typeForRelationshipMeta)(meta); (false && _ember.default.assert('You specified a hasMany (' + meta.type + ') on ' + meta.parentType + ' but ' + meta.type + ' was not found.', modelName)); if (!types.includes(modelName)) { (false && _ember.default.assert('Trying to sideload ' + name + ' on ' + _this.toString() + ' but the type doesn\'t exist.', !!modelName)); types.push(modelName); } } }); return types; }).readOnly(); var relationshipsByNameDescriptor = exports.relationshipsByNameDescriptor = _ember.default.computed(function () { var map = Map.create(); this.eachComputedProperty(function (name, meta) { if (meta.isRelationship) { meta.key = name; var relationship = (0, _relationshipMeta.relationshipFromMeta)(meta); relationship.type = (0, _relationshipMeta.typeForRelationshipMeta)(meta); map.set(name, relationship); } }); return map; }).readOnly(); }); define('ember-data/-private/system/relationships/has-many', ['exports', 'ember', 'ember-data/-private/system/normalize-model-name', 'ember-data/-private/system/is-array-like'], function (exports, _ember, _normalizeModelName, _isArrayLike) { 'use strict'; exports.__esModule = true; exports.default = hasMany; var get = _ember.default.get; /** `DS.hasMany` is used to define One-To-Many and Many-To-Many relationships on a [DS.Model](/api/data/classes/DS.Model.html). `DS.hasMany` takes an optional hash as a second parameter, currently supported options are: - `async`: A boolean value used to explicitly declare this to be an async relationship. - `inverse`: A string used to identify the inverse property on a related model. #### One-To-Many To declare a one-to-many relationship between two models, use `DS.belongsTo` in combination with `DS.hasMany`, like this: ```app/models/post.js import DS from 'ember-data'; export default DS.Model.extend({ comments: DS.hasMany('comment') }); ``` ```app/models/comment.js import DS from 'ember-data'; export default DS.Model.extend({ post: DS.belongsTo('post') }); ``` #### Many-To-Many To declare a many-to-many relationship between two models, use `DS.hasMany`: ```app/models/post.js import DS from 'ember-data'; export default DS.Model.extend({ tags: DS.hasMany('tag') }); ``` ```app/models/tag.js import DS from 'ember-data'; export default DS.Model.extend({ posts: DS.hasMany('post') }); ``` You can avoid passing a string as the first parameter. In that case Ember Data will infer the type from the singularized key name. ```app/models/post.js import DS from 'ember-data'; export default DS.Model.extend({ tags: DS.hasMany() }); ``` will lookup for a Tag type. #### Explicit Inverses Ember Data will do its best to discover which relationships map to one another. In the one-to-many code above, for example, Ember Data can figure out that changing the `comments` relationship should update the `post` relationship on the inverse because post is the only relationship to that model. However, sometimes you may have multiple `belongsTo`/`hasMany` for the same type. You can specify which property on the related model is the inverse using `DS.hasMany`'s `inverse` option: ```app/models/comment.js import DS from 'ember-data'; export default DS.Model.extend({ onePost: DS.belongsTo('post'), twoPost: DS.belongsTo('post'), redPost: DS.belongsTo('post'), bluePost: DS.belongsTo('post') }); ``` ```app/models/post.js import DS from 'ember-data'; export default DS.Model.extend({ comments: DS.hasMany('comment', { inverse: 'redPost' }) }); ``` You can also specify an inverse on a `belongsTo`, which works how you'd expect. @namespace @method hasMany @for DS @param {String} type (optional) type of the relationship @param {Object} options (optional) a hash of options @return {Ember.computed} relationship */ function hasMany(type, options) { if (typeof type === 'object') { options = type; type = undefined; } (false && _ember.default.assert('The first argument to DS.hasMany must be a string representing a model type key, not an instance of ' + _ember.default.inspect(type) + '. E.g., to define a relation to the Comment model, use DS.hasMany(\'comment\')', typeof type === 'string' || typeof type === 'undefined')); options = options || {}; if (typeof type === 'string') { type = (0, _normalizeModelName.default)(type); } // Metadata about relationships is stored on the meta of // the relationship. This is used for introspection and // serialization. Note that `key` is populated lazily // the first time the CP is called. var meta = { type: type, options: options, isRelationship: true, kind: 'hasMany', name: 'Has Many', key: null }; return _ember.default.computed({ get: function (key) { return this._internalModel._relationships.get(key).getRecords(); }, set: function (key, records) { (false && _ember.default.assert('You must pass an array of records to set a hasMany relationship', (0, _isArrayLike.default)(records))); (false && _ember.default.assert('All elements of a hasMany relationship must be instances of DS.Model, you passed ' + _ember.default.inspect(records), function () { return _ember.default.A(records).every(function (record) { return record.hasOwnProperty('_internalModel') === true; }); }())); var relationship = this._internalModel._relationships.get(key); relationship.clear(); relationship.addInternalModels(records.map(function (record) { return get(record, '_internalModel'); })); return relationship.getRecords(); } }).meta(meta); } }); define('ember-data/-private/system/relationships/relationship-payloads-manager', ['exports', 'ember', 'ember-data/-private/system/relationships/relationship-payloads'], function (exports, _ember, _relationshipPayloads) { 'use strict'; exports.__esModule = true; function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } } var _get = _ember.default.get; /** Manages relationship payloads for a given store, for uninitialized relationships. Acts as a single source of truth (of payloads) for both sides of an uninitialized relationship so they can agree on the most up-to-date payload received without needing too much eager processing when those payloads are pushed into the store. This minimizes the work spent on relationships that are never initialized. Once relationships are initialized, their state is managed in a relationship state object (eg BelongsToRelationship or ManyRelationship). @example let relationshipPayloadsManager = new RelationshipPayloadsManager(store); const User = DS.Model.extend({ hobbies: DS.hasMany('hobby') }); const Hobby = DS.Model.extend({ user: DS.belongsTo('user') }); let userPayload = { data: { id: 1, type: 'user', relationships: { hobbies: { data: [{ id: 2, type: 'hobby' }] } } }, }; relationshipPayloadsManager.push('user', 1, userPayload.data.relationships); relationshipPayloadsManager.get('hobby', 2, 'user') === { { data: { id: 1, type: 'user' } } } @private @class RelationshipPayloadsManager */ var RelationshipPayloadsManager = function () { function RelationshipPayloadsManager(store) { this._store = store; // cache of `RelationshipPayload`s this._cache = Object.create(null); } /** Find the payload for the given relationship of the given model. Returns the payload for the given relationship, whether raw or computed from the payload of the inverse relationship. @example relationshipPayloadsManager.get('hobby', 2, 'user') === { { data: { id: 1, type: 'user' } } } @method */ RelationshipPayloadsManager.prototype.get = function get(modelName, id, relationshipName) { var modelClass = this._store._modelFor(modelName); var relationshipsByName = _get(modelClass, 'relationshipsByName'); var relationshipPayloads = this._getRelationshipPayloads(modelName, relationshipName, modelClass, relationshipsByName, false); return relationshipPayloads && relationshipPayloads.get(modelName, id, relationshipName); }; RelationshipPayloadsManager.prototype.push = function push(modelName, id, relationshipsData) { var _this = this; if (!relationshipsData) { return; } var modelClass = this._store._modelFor(modelName); var relationshipsByName = _get(modelClass, 'relationshipsByName'); Object.keys(relationshipsData).forEach(function (key) { var relationshipPayloads = _this._getRelationshipPayloads(modelName, key, modelClass, relationshipsByName, true); if (relationshipPayloads) { relationshipPayloads.push(modelName, id, key, relationshipsData[key]); } }); }; RelationshipPayloadsManager.prototype.unload = function unload(modelName, id) { var _this2 = this; var modelClass = this._store._modelFor(modelName); var relationshipsByName = _get(modelClass, 'relationshipsByName'); relationshipsByName.forEach(function (_, relationshipName) { var relationshipPayloads = _this2._getRelationshipPayloads(modelName, relationshipName, modelClass, relationshipsByName, false); if (relationshipPayloads) { relationshipPayloads.unload(modelName, id, relationshipName); } }); }; RelationshipPayloadsManager.prototype._getRelationshipPayloads = function _getRelationshipPayloads(modelName, relationshipName, modelClass, relationshipsByName, init) { if (!relationshipsByName.has(relationshipName)) { return; } var key = modelName + ':' + relationshipName; if (!this._cache[key] && init) { return this._initializeRelationshipPayloads(modelName, relationshipName, modelClass, relationshipsByName); } return this._cache[key]; }; RelationshipPayloadsManager.prototype._initializeRelationshipPayloads = function _initializeRelationshipPayloads(modelName, relationshipName, modelClass, relationshipsByName) { var relationshipMeta = relationshipsByName.get(relationshipName); var inverseMeta = modelClass.inverseFor(relationshipName, this._store); var inverseModelName = void 0; var inverseRelationshipName = void 0; var inverseRelationshipMeta = void 0; // figure out the inverse relationship; we need two things // a) the inverse model name //- b) the name of the inverse relationship if (inverseMeta) { inverseRelationshipName = inverseMeta.name; inverseModelName = relationshipMeta.type; inverseRelationshipMeta = _get(inverseMeta.type, 'relationshipsByName').get(inverseRelationshipName); } else { // relationship has no inverse inverseModelName = inverseRelationshipName = ''; inverseRelationshipMeta = null; } var lhsKey = modelName + ':' + relationshipName; var rhsKey = inverseModelName + ':' + inverseRelationshipName; // populate the cache for both sides of the relationship, as they both use // the same `RelationshipPayloads`. // // This works out better than creating a single common key, because to // compute that key we would need to do work to look up the inverse // return this._cache[lhsKey] = this._cache[rhsKey] = new _relationshipPayloads.default(this._store, modelName, relationshipName, relationshipMeta, inverseModelName, inverseRelationshipName, inverseRelationshipMeta); }; return RelationshipPayloadsManager; }(); exports.default = RelationshipPayloadsManager; }); define('ember-data/-private/system/relationships/relationship-payloads', ['exports'], function (exports) { 'use strict'; exports.__esModule = true; function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } } var _createClass = function () { function defineProperties(target, props) { for (var i = 0; i < props.length; i++) { var descriptor = props[i]; descriptor.enumerable = descriptor.enumerable || false; descriptor.configurable = true; if ("value" in descriptor) descriptor.writable = true; Object.defineProperty(target, descriptor.key, descriptor); } } return function (Constructor, protoProps, staticProps) { if (protoProps) defineProperties(Constructor.prototype, protoProps); if (staticProps) defineProperties(Constructor, staticProps); return Constructor; }; }(); var RelationshipPayloads = function () { function RelationshipPayloads(store, modelName, relationshipName, relationshipMeta, inverseModelName, inverseRelationshipName, inverseRelationshipMeta) { this._store = store; this._lhsModelName = modelName; this._lhsRelationshipName = relationshipName; this._lhsRelationshipMeta = relationshipMeta; this._rhsModelName = inverseModelName; this._rhsRelationshipName = inverseRelationshipName; this._rhsRelationshipMeta = inverseRelationshipMeta; // a map of id -> payloads for the left hand side of the relationship. this._lhsPayloads = Object.create(null); if (modelName !== inverseModelName || relationshipName !== inverseRelationshipName) { // The common case of a non-reflexive relationship, or a reflexive // relationship whose inverse is not itself this._rhsPayloads = Object.create(null); this._isReflexive = false; } else { // Edge case when we have a reflexive relationship to itself // eg user hasMany friends inverse friends // // In this case there aren't really two sides to the relationship, but // we set `_rhsPayloads = _lhsPayloads` to make things easier to reason // about this._rhsPayloads = this._lhsPayloads; this._isReflexive = true; } // When we push relationship payloads, just stash them in a queue until // somebody actually asks for one of them. // // This is a queue of the relationship payloads that have been pushed for // either side of this relationship this._pendingPayloads = []; } /** Get the payload for the relationship of an individual record. This might return the raw payload as pushed into the store, or one computed from the payload of the inverse relationship. @method */ RelationshipPayloads.prototype.get = function get(modelName, id, relationshipName) { this._flushPending(); if (this._isLHS(modelName, relationshipName)) { return this._lhsPayloads[id]; } else { (false && Ember.assert(modelName + ':' + relationshipName + ' is not either side of this relationship, ' + this._lhsModelName + ':' + this._lhsRelationshipName + '<->' + this._rhsModelName + ':' + this._rhsRelationshipName, this._isRHS(modelName, relationshipName))); return this._rhsPayloads[id]; } }; RelationshipPayloads.prototype.push = function push(modelName, id, relationshipName, relationshipData) { this._pendingPayloads.push([modelName, id, relationshipName, relationshipData]); }; RelationshipPayloads.prototype.unload = function unload(modelName, id, relationshipName) { this._flushPending(); if (this._isLHS(modelName, relationshipName)) { delete this._lhsPayloads[id]; } else { (false && Ember.assert(modelName + ':' + relationshipName + ' is not either side of this relationship, ' + this._lhsModelName + ':' + this._lhsRelationshipName + '<->' + this._rhsModelName + ':' + this._rhsRelationshipName, this._isRHS(modelName, relationshipName))); delete this._rhsPayloads[id]; } }; RelationshipPayloads.prototype._isLHS = function _isLHS(modelName, relationshipName) { return modelName === this._lhsModelName && relationshipName === this._lhsRelationshipName; }; RelationshipPayloads.prototype._isRHS = function _isRHS(modelName, relationshipName) { return modelName === this._rhsModelName && relationshipName === this._rhsRelationshipName; }; RelationshipPayloads.prototype._flushPending = function _flushPending() { if (this._pendingPayloads.length === 0) { return; } var payloadsToBeProcessed = this._pendingPayloads.splice(0, this._pendingPayloads.length); for (var i = 0; i < payloadsToBeProcessed.length; ++i) { var modelName = payloadsToBeProcessed[i][0]; var id = payloadsToBeProcessed[i][1]; var relationshipName = payloadsToBeProcessed[i][2]; var relationshipData = payloadsToBeProcessed[i][3]; // TODO: maybe delay this allocation slightly? var inverseRelationshipData = { data: { id: id, type: modelName } // start flushing this individual payload. The logic is the same whether // it's for the left hand side of the relationship or the right hand side, // except the role of primary and inverse idToPayloads is reversed // };var previousPayload = void 0; var idToPayloads = void 0; var inverseIdToPayloads = void 0; var inverseIsMany = void 0; if (this._isLHS(modelName, relationshipName)) { previousPayload = this._lhsPayloads[id]; idToPayloads = this._lhsPayloads; inverseIdToPayloads = this._rhsPayloads; inverseIsMany = this._rhsRelationshipIsMany; } else { (false && Ember.assert(modelName + ':' + relationshipName + ' is not either side of this relationship, ' + this._lhsModelName + ':' + this._lhsRelationshipName + '<->' + this._rhsModelName + ':' + this._rhsRelationshipName, this._isRHS(modelName, relationshipName))); previousPayload = this._rhsPayloads[id]; idToPayloads = this._rhsPayloads; inverseIdToPayloads = this._lhsPayloads; inverseIsMany = this._lhsRelationshipIsMany; } // actually flush this individual payload // // We remove the previous inverse before populating our current one // because we may have multiple payloads for the same relationship, in // which case the last one wins. // // eg if user hasMany helicopters, and helicopter belongsTo user and we see // // [{ // data: { // id: 1, // type: 'helicopter', // relationships: { // user: { // id: 2, // type: 'user' // } // } // } // }, { // data: { // id: 1, // type: 'helicopter', // relationships: { // user: { // id: 4, // type: 'user' // } // } // } // }] // // Then we will initially have set user:2 as having helicopter:1, which we // need to remove before adding helicopter:1 to user:4 // // only remove relationship information before adding if there is relationshipData.data // * null is considered new information "empty", and it should win // * undefined is NOT considered new information, we should keep original state // * anything else is considered new information, and it should win if (relationshipData.data !== undefined) { this._removeInverse(id, previousPayload, inverseIdToPayloads); } idToPayloads[id] = relationshipData; this._populateInverse(relationshipData, inverseRelationshipData, inverseIdToPayloads, inverseIsMany); } }; RelationshipPayloads.prototype._populateInverse = function _populateInverse(relationshipData, inversePayload, inverseIdToPayloads, inverseIsMany) { if (!relationshipData.data) { // This id doesn't have an inverse, eg a belongsTo with a payload // { data: null }, so there's nothing to populate return; } if (Array.isArray(relationshipData.data)) { for (var i = 0; i < relationshipData.data.length; ++i) { var inverseId = relationshipData.data[i].id; this._addToInverse(inversePayload, inverseId, inverseIdToPayloads, inverseIsMany); } } else { var _inverseId = relationshipData.data.id; this._addToInverse(inversePayload, _inverseId, inverseIdToPayloads, inverseIsMany); } }; RelationshipPayloads.prototype._addToInverse = function _addToInverse(inversePayload, inverseId, inverseIdToPayloads, inverseIsMany) { if (this._isReflexive && inversePayload.data.id === inverseId) { // eg <user:1>.friends = [{ id: 1, type: 'user' }] return; } var existingPayload = inverseIdToPayloads[inverseId]; var existingData = existingPayload && existingPayload.data; if (existingData) { // There already is an inverse, either add or overwrite depehnding on // whether the inverse is a many relationship or not // if (Array.isArray(existingData)) { existingData.push(inversePayload.data); } else { inverseIdToPayloads[inverseId] = inversePayload; } } else { // first time we're populating the inverse side // if (inverseIsMany) { inverseIdToPayloads[inverseId] = { data: [inversePayload.data] }; } else { inverseIdToPayloads[inverseId] = inversePayload; } } }; RelationshipPayloads.prototype._removeInverse = function _removeInverse(id, previousPayload, inverseIdToPayloads) { var data = previousPayload && previousPayload.data; if (!data) { // either this is the first time we've seen a payload for this id, or its // previous payload indicated that it had no inverse, eg a belongsTo // relationship with payload { data: null } // // In either case there's nothing that needs to be removed from the // inverse map of payloads return; } if (Array.isArray(data)) { // TODO: diff rather than removeall addall? for (var i = 0; i < data.length; ++i) { this._removeFromInverse(id, data[i].id, inverseIdToPayloads); } } else { this._removeFromInverse(id, data.id, inverseIdToPayloads); } }; RelationshipPayloads.prototype._removeFromInverse = function _removeFromInverse(id, inverseId, inversePayloads) { var inversePayload = inversePayloads[inverseId]; var data = inversePayload && inversePayload.data; if (!data) { return; } if (Array.isArray(data)) { inversePayload.data = data.filter(function (x) { return x.id !== id; }); } else { inversePayloads[inverseId] = { data: null }; } }; _createClass(RelationshipPayloads, [{ key: '_lhsRelationshipIsMany', get: function () { return this._lhsRelationshipMeta && this._lhsRelationshipMeta.kind === 'hasMany'; } }, { key: '_rhsRelationshipIsMany', get: function () { return this._rhsRelationshipMeta && this._rhsRelationshipMeta.kind === 'hasMany'; } }]); return RelationshipPayloads; }(); exports.default = RelationshipPayloads; }); define('ember-data/-private/system/relationships/state/belongs-to', ['exports', 'ember', 'ember-data/-private/system/promise-proxies', 'ember-data/-private/system/relationships/state/relationship'], function (exports, _ember, _promiseProxies, _relationship) { 'use strict'; exports.__esModule = true; function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } } function _possibleConstructorReturn(self, call) { if (!self) { throw new ReferenceError("this hasn't been initialised - super() hasn't been called"); } return call && (typeof call === "object" || typeof call === "function") ? call : self; } function _inherits(subClass, superClass) { if (typeof superClass !== "function" && superClass !== null) { throw new TypeError("Super expression must either be null or a function, not " + typeof superClass); } subClass.prototype = Object.create(superClass && superClass.prototype, { constructor: { value: subClass, enumerable: false, writable: true, configurable: true } }); if (superClass) Object.setPrototypeOf ? Object.setPrototypeOf(subClass, superClass) : subClass.__proto__ = superClass; } var BelongsToRelationship = function (_Relationship) { _inherits(BelongsToRelationship, _Relationship); function BelongsToRelationship(store, internalModel, inverseKey, relationshipMeta) { var _this = _possibleConstructorReturn(this, _Relationship.call(this, store, internalModel, inverseKey, relationshipMeta)); _this.internalModel = internalModel; _this.key = relationshipMeta.key; _this.inverseInternalModel = null; _this.canonicalState = null; return _this; } BelongsToRelationship.prototype.setInternalModel = function setInternalModel(internalModel) { if (internalModel) { this.addInternalModel(internalModel); } else if (this.inverseInternalModel) { this.removeInternalModel(this.inverseInternalModel); } this.setHasData(true); this.setHasLoaded(true); }; BelongsToRelationship.prototype.setCanonicalInternalModel = function setCanonicalInternalModel(internalModel) { if (internalModel) { this.addCanonicalInternalModel(internalModel); } else if (this.canonicalState) { this.removeCanonicalInternalModel(this.canonicalState); } this.flushCanonicalLater(); }; BelongsToRelationship.prototype.setInitialCanonicalInternalModel = function setInitialCanonicalInternalModel(internalModel) { if (!internalModel) { return; } // When we initialize a belongsTo relationship, we want to avoid work like // notifying our internalModel that we've "changed" and excessive thrash on // setting up inverse relationships this.canonicalMembers.add(internalModel); this.members.add(internalModel); this.inverseInternalModel = this.canonicalState = internalModel; this.setupInverseRelationship(internalModel); }; BelongsToRelationship.prototype.addCanonicalInternalModel = function addCanonicalInternalModel(internalModel) { if (this.canonicalMembers.has(internalModel)) { return; } if (this.canonicalState) { this.removeCanonicalInternalModel(this.canonicalState); } this.canonicalState = internalModel; _Relationship.prototype.addCanonicalInternalModel.call(this, internalModel); }; BelongsToRelationship.prototype.inverseDidDematerialize = function inverseDidDematerialize() { this.notifyBelongsToChanged(); }; BelongsToRelationship.prototype.removeCompletelyFromOwn = function removeCompletelyFromOwn(internalModel) { _Relationship.prototype.removeCompletelyFromOwn.call(this, internalModel); if (this.canonicalState === internalModel) { this.canonicalState = null; } if (this.inverseInternalModel === internalModel) { this.inverseInternalModel = null; this.notifyBelongsToChanged(); } }; BelongsToRelationship.prototype.flushCanonical = function flushCanonical() { //temporary fix to not remove newly created records if server returned null. //TODO remove once we have proper diffing if (this.inverseInternalModel && this.inverseInternalModel.isNew() && !this.canonicalState) { return; } if (this.inverseInternalModel !== this.canonicalState) { this.inverseInternalModel = this.canonicalState; this.notifyBelongsToChanged(); } _Relationship.prototype.flushCanonical.call(this); }; BelongsToRelationship.prototype.addInternalModel = function addInternalModel(internalModel) { if (this.members.has(internalModel)) { return; } if (this.inverseInternalModel) { this.removeInternalModel(this.inverseInternalModel); } this.inverseInternalModel = internalModel; _Relationship.prototype.addInternalModel.call(this, internalModel); this.notifyBelongsToChanged(); }; BelongsToRelationship.prototype.setRecordPromise = function setRecordPromise(newPromise) { var content = newPromise.get && newPromise.get('content'); (false && _ember.default.assert("You passed in a promise that did not originate from an EmberData relationship. You can only pass promises that come from a belongsTo or hasMany relationship to the get call.", content !== undefined)); this.setInternalModel(content ? content._internalModel : content); }; BelongsToRelationship.prototype.removeInternalModelFromOwn = function removeInternalModelFromOwn(internalModel) { if (!this.members.has(internalModel)) { return; } this.inverseInternalModel = null; _Relationship.prototype.removeInternalModelFromOwn.call(this, internalModel); this.notifyBelongsToChanged(); }; BelongsToRelationship.prototype.notifyBelongsToChanged = function notifyBelongsToChanged() { this.internalModel.notifyBelongsToChanged(this.key); }; BelongsToRelationship.prototype.removeCanonicalInternalModelFromOwn = function removeCanonicalInternalModelFromOwn(internalModel) { if (!this.canonicalMembers.has(internalModel)) { return; } this.canonicalState = null; _Relationship.prototype.removeCanonicalInternalModelFromOwn.call(this, internalModel); }; BelongsToRelationship.prototype.findRecord = function findRecord() { if (this.inverseInternalModel) { return this.store._findByInternalModel(this.inverseInternalModel); } else { return _ember.default.RSVP.Promise.resolve(null); } }; BelongsToRelationship.prototype.fetchLink = function fetchLink() { var _this2 = this; return this.store.findBelongsTo(this.internalModel, this.link, this.relationshipMeta).then(function (internalModel) { if (internalModel) { _this2.addInternalModel(internalModel); } return internalModel; }); }; BelongsToRelationship.prototype.getRecord = function getRecord() { var _this3 = this; //TODO(Igor) flushCanonical here once our syncing is not stupid if (this.isAsync) { var promise = void 0; if (this.link) { if (this.hasLoaded) { promise = this.findRecord(); } else { promise = this.findLink().then(function () { return _this3.findRecord(); }); } } else { promise = this.findRecord(); } return _promiseProxies.PromiseObject.create({ promise: promise, content: this.inverseInternalModel ? this.inverseInternalModel.getRecord() : null }); } else { if (this.inverseInternalModel === null) { return null; } var toReturn = this.inverseInternalModel.getRecord(); (false && _ember.default.assert("You looked up the '" + this.key + "' relationship on a '" + this.internalModel.modelName + "' with id " + this.internalModel.id + " but some of the associated records were not loaded. Either make sure they are all loaded together with the parent record, or specify that the relationship is async (`DS.belongsTo({ async: true })`)", toReturn === null || !toReturn.get('isEmpty'))); return toReturn; } }; BelongsToRelationship.prototype.reload = function reload() { // TODO handle case when reload() is triggered multiple times if (this.link) { return this.fetchLink(); } // reload record, if it is already loaded if (this.inverseInternalModel && this.inverseInternalModel.hasRecord) { return this.inverseInternalModel.getRecord().reload(); } return this.findRecord(); }; BelongsToRelationship.prototype.updateData = function updateData(data, initial) { (false && _ember.default.assert('Ember Data expected the data for the ' + this.key + ' relationship on a ' + this.internalModel.toString() + ' to be in a JSON API format and include an `id` and `type` property but it found ' + _ember.default.inspect(data) + '. Please check your serializer and make sure it is serializing the relationship payload into a JSON API format.', data === null || data.id !== undefined && data.type !== undefined)); var internalModel = this.store._pushResourceIdentifier(this, data); if (initial) { this.setInitialCanonicalInternalModel(internalModel); } else { this.setCanonicalInternalModel(internalModel); } }; return BelongsToRelationship; }(_relationship.default); exports.default = BelongsToRelationship; }); define("ember-data/-private/system/relationships/state/create", ["exports", "ember", "ember-data/-private/system/relationships/state/has-many", "ember-data/-private/system/relationships/state/belongs-to"], function (exports, _ember, _hasMany, _belongsTo) { "use strict"; exports.__esModule = true; function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } } var _createClass = function () { function defineProperties(target, props) { for (var i = 0; i < props.length; i++) { var descriptor = props[i]; descriptor.enumerable = descriptor.enumerable || false; descriptor.configurable = true; if ("value" in descriptor) descriptor.writable = true; Object.defineProperty(target, descriptor.key, descriptor); } } return function (Constructor, protoProps, staticProps) { if (protoProps) defineProperties(Constructor.prototype, protoProps); if (staticProps) defineProperties(Constructor, staticProps); return Constructor; }; }(); var _get = _ember.default.get; function shouldFindInverse(relationshipMeta) { var options = relationshipMeta.options; return !(options && options.inverse === null); } function createRelationshipFor(internalModel, relationshipMeta, store) { var inverseKey = void 0; var inverse = null; if (shouldFindInverse(relationshipMeta)) { inverse = internalModel.type.inverseFor(relationshipMeta.key, store); } else if (false) { internalModel.type.typeForRelationship(relationshipMeta.key, store); } if (inverse) { inverseKey = inverse.name; } if (relationshipMeta.kind === 'hasMany') { return new _hasMany.default(store, internalModel, inverseKey, relationshipMeta); } else { return new _belongsTo.default(store, internalModel, inverseKey, relationshipMeta); } } var Relationships = function () { function Relationships(internalModel) { this.internalModel = internalModel; this.initializedRelationships = Object.create(null); } // TODO @runspired deprecate this as it was never truly a record instance Relationships.prototype.has = function has(key) { return !!this.initializedRelationships[key]; }; Relationships.prototype.forEach = function forEach(cb) { var rels = this.initializedRelationships; Object.keys(rels).forEach(function (name) { cb(name, rels[name]); }); }; Relationships.prototype.get = function get(key) { var relationships = this.initializedRelationships; var relationship = relationships[key]; var internalModel = this.internalModel; if (!relationship) { var relationshipsByName = _get(internalModel.type, 'relationshipsByName'); var rel = relationshipsByName.get(key); if (!rel) { return undefined; } var relationshipPayload = internalModel.store._relationshipsPayloads.get(internalModel.modelName, internalModel.id, key); relationship = relationships[key] = createRelationshipFor(internalModel, rel, internalModel.store); if (relationshipPayload) { relationship.push(relationshipPayload, true); } } return relationship; }; _createClass(Relationships, [{ key: "record", get: function () { return this.internalModel; } }]); return Relationships; }(); exports.default = Relationships; }); define('ember-data/-private/system/relationships/state/has-many', ['exports', 'ember-data/-private/system/promise-proxies', 'ember-data/-private/system/relationships/state/relationship', 'ember-data/-private/system/ordered-set', 'ember-data/-private/system/many-array'], function (exports, _promiseProxies, _relationship, _orderedSet, _manyArray) { 'use strict'; exports.__esModule = true; function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } } var _createClass = function () { function defineProperties(target, props) { for (var i = 0; i < props.length; i++) { var descriptor = props[i]; descriptor.enumerable = descriptor.enumerable || false; descriptor.configurable = true; if ("value" in descriptor) descriptor.writable = true; Object.defineProperty(target, descriptor.key, descriptor); } } return function (Constructor, protoProps, staticProps) { if (protoProps) defineProperties(Constructor.prototype, protoProps); if (staticProps) defineProperties(Constructor, staticProps); return Constructor; }; }(); function _possibleConstructorReturn(self, call) { if (!self) { throw new ReferenceError("this hasn't been initialised - super() hasn't been called"); } return call && (typeof call === "object" || typeof call === "function") ? call : self; } function _inherits(subClass, superClass) { if (typeof superClass !== "function" && superClass !== null) { throw new TypeError("Super expression must either be null or a function, not " + typeof superClass); } subClass.prototype = Object.create(superClass && superClass.prototype, { constructor: { value: subClass, enumerable: false, writable: true, configurable: true } }); if (superClass) Object.setPrototypeOf ? Object.setPrototypeOf(subClass, superClass) : subClass.__proto__ = superClass; } var ManyRelationship = function (_Relationship) { _inherits(ManyRelationship, _Relationship); function ManyRelationship(store, internalModel, inverseKey, relationshipMeta) { var _this = _possibleConstructorReturn(this, _Relationship.call(this, store, internalModel, inverseKey, relationshipMeta)); _this.belongsToType = relationshipMeta.type; _this.canonicalState = []; _this.isPolymorphic = relationshipMeta.options.polymorphic; _this._manyArray = null; _this.__loadingPromise = null; return _this; } ManyRelationship.prototype._updateLoadingPromise = function _updateLoadingPromise(promise, content) { if (this.__loadingPromise) { if (content) { this.__loadingPromise.set('content', content); } this.__loadingPromise.set('promise', promise); } else { this.__loadingPromise = _promiseProxies.PromiseManyArray.create({ promise: promise, content: content }); } return this.__loadingPromise; }; ManyRelationship.prototype.removeInverseRelationships = function removeInverseRelationships() { _Relationship.prototype.removeInverseRelationships.call(this); if (this._manyArray) { this._manyArray.destroy(); this._manyArray = null; } if (this._loadingPromise) { this._loadingPromise.destroy(); } }; ManyRelationship.prototype.updateMeta = function updateMeta(meta) { _Relationship.prototype.updateMeta.call(this, meta); if (this._manyArray) { this._manyArray.set('meta', meta); } }; ManyRelationship.prototype.addCanonicalInternalModel = function addCanonicalInternalModel(internalModel, idx) { if (this.canonicalMembers.has(internalModel)) { return; } if (idx !== undefined) { this.canonicalState.splice(idx, 0, internalModel); } else { this.canonicalState.push(internalModel); } _Relationship.prototype.addCanonicalInternalModel.call(this, internalModel, idx); }; ManyRelationship.prototype.inverseDidDematerialize = function inverseDidDematerialize() { if (this._manyArray) { this._manyArray.destroy(); this._manyArray = null; } this.notifyHasManyChanged(); }; ManyRelationship.prototype.addInternalModel = function addInternalModel(internalModel, idx) { if (this.members.has(internalModel)) { return; } _Relationship.prototype.addInternalModel.call(this, internalModel, idx); // make lazy later this.manyArray._addInternalModels([internalModel], idx); }; ManyRelationship.prototype.removeCanonicalInternalModelFromOwn = function removeCanonicalInternalModelFromOwn(internalModel, idx) { var i = idx; if (!this.canonicalMembers.has(internalModel)) { return; } if (i === undefined) { i = this.canonicalState.indexOf(internalModel); } if (i > -1) { this.canonicalState.splice(i, 1); } _Relationship.prototype.removeCanonicalInternalModelFromOwn.call(this, internalModel, idx); }; ManyRelationship.prototype.removeCompletelyFromOwn = function removeCompletelyFromOwn(internalModel) { _Relationship.prototype.removeCompletelyFromOwn.call(this, internalModel); var canonicalIndex = this.canonicalState.indexOf(internalModel); if (canonicalIndex !== -1) { this.canonicalState.splice(canonicalIndex, 1); } var manyArray = this._manyArray; if (manyArray) { var idx = manyArray.currentState.indexOf(internalModel); if (idx !== -1) { manyArray.internalReplace(idx, 1); } } }; ManyRelationship.prototype.flushCanonical = function flushCanonical() { if (this._manyArray) { this._manyArray.flushCanonical(); } _Relationship.prototype.flushCanonical.call(this); }; ManyRelationship.prototype.removeInternalModelFromOwn = function removeInternalModelFromOwn(internalModel, idx) { if (!this.members.has(internalModel)) { return; } _Relationship.prototype.removeInternalModelFromOwn.call(this, internalModel, idx); var manyArray = this.manyArray; if (idx !== undefined) { //TODO(Igor) not used currently, fix manyArray.currentState.removeAt(idx); } else { manyArray._removeInternalModels([internalModel]); } }; ManyRelationship.prototype.notifyRecordRelationshipAdded = function notifyRecordRelationshipAdded(internalModel, idx) { this.internalModel.notifyHasManyAdded(this.key, internalModel, idx); }; ManyRelationship.prototype.reload = function reload() { var manyArray = this.manyArray; var manyArrayLoadedState = manyArray.get('isLoaded'); if (this._loadingPromise) { if (this._loadingPromise.get('isPending')) { return this._loadingPromise; } if (this._loadingPromise.get('isRejected')) { manyArray.set('isLoaded', manyArrayLoadedState); } } var promise = void 0; if (this.link) { promise = this.fetchLink(); } else { promise = this.store._scheduleFetchMany(manyArray.currentState).then(function () { return manyArray; }); } this._updateLoadingPromise(promise); return this._loadingPromise; }; ManyRelationship.prototype.computeChanges = function computeChanges() { var internalModels = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : []; var members = this.canonicalMembers; var internalModelsToRemove = []; var internalModelSet = setForArray(internalModels); members.forEach(function (member) { if (internalModelSet.has(member)) { return; } internalModelsToRemove.push(member); }); this.removeCanonicalInternalModels(internalModelsToRemove); for (var i = 0, l = internalModels.length; i < l; i++) { var internalModel = internalModels[i]; this.removeCanonicalInternalModel(internalModel); this.addCanonicalInternalModel(internalModel, i); } }; ManyRelationship.prototype.setInitialInternalModels = function setInitialInternalModels(internalModels) { if (Array.isArray(internalModels) === false || internalModels.length === 0) { return; } for (var i = 0; i < internalModels.length; i++) { var internalModel = internalModels[i]; if (this.canonicalMembers.has(internalModel)) { continue; } this.canonicalMembers.add(internalModel); this.members.add(internalModel); this.setupInverseRelationship(internalModel); } this.canonicalState = this.canonicalMembers.toArray(); }; ManyRelationship.prototype.fetchLink = function fetchLink() { var _this2 = this; return this.store.findHasMany(this.internalModel, this.link, this.relationshipMeta).then(function (records) { if (records.hasOwnProperty('meta')) { _this2.updateMeta(records.meta); } _this2.store._backburner.join(function () { _this2.updateInternalModelsFromAdapter(records); _this2.manyArray.set('isLoaded', true); _this2.setHasData(true); }); return _this2.manyArray; }); }; ManyRelationship.prototype.findRecords = function findRecords() { var manyArray = this.manyArray; var internalModels = manyArray.currentState; //TODO CLEANUP return this.store.findMany(internalModels).then(function () { if (!manyArray.get('isDestroyed')) { //Goes away after the manyArray refactor manyArray.set('isLoaded', true); } return manyArray; }); }; ManyRelationship.prototype.notifyHasManyChanged = function notifyHasManyChanged() { this.internalModel.notifyHasManyAdded(this.key); }; ManyRelationship.prototype.getRecords = function getRecords() { var _this3 = this; //TODO(Igor) sync server here, once our syncing is not stupid var manyArray = this.manyArray; if (this.isAsync) { var promise = void 0; if (this.link) { if (this.hasLoaded) { promise = this.findRecords(); } else { promise = this.findLink().then(function () { return _this3.findRecords(); }); } } else { promise = this.findRecords(); } return this._updateLoadingPromise(promise, manyArray); } else { (false && Ember.assert('You looked up the \'' + this.key + '\' relationship on a \'' + this.internalModel.type.modelName + '\' with id ' + this.internalModel.id + ' but some of the associated records were not loaded. Either make sure they are all loaded together with the parent record, or specify that the relationship is async (\'DS.hasMany({ async: true })\')', manyArray.isEvery('isEmpty', false))); //TODO(Igor) WTF DO I DO HERE? // TODO @runspired equal WTFs to Igor if (!manyArray.get('isDestroyed')) { manyArray.set('isLoaded', true); } return manyArray; } }; ManyRelationship.prototype.updateData = function updateData(data, initial) { var internalModels = this.store._pushResourceIdentifiers(this, data); if (initial) { this.setInitialInternalModels(internalModels); } else { this.updateInternalModelsFromAdapter(internalModels); } }; ManyRelationship.prototype.destroy = function destroy() { _Relationship.prototype.destroy.call(this); var manyArray = this._manyArray; if (manyArray) { manyArray.destroy(); } var proxy = this.__loadingPromise; if (proxy) { proxy.destroy(); } }; _createClass(ManyRelationship, [{ key: '_loadingPromise', get: function () { return this.__loadingPromise; } }, { key: 'manyArray', get: function () { if (!this._manyArray) { this._manyArray = _manyArray.default.create({ canonicalState: this.canonicalState, store: this.store, relationship: this, type: this.store.modelFor(this.belongsToType), record: this.internalModel, meta: this.meta, isPolymorphic: this.isPolymorphic }); } return this._manyArray; } }]); return ManyRelationship; }(_relationship.default); exports.default = ManyRelationship; function setForArray(array) { var set = new _orderedSet.default(); if (array) { for (var i = 0, l = array.length; i < l; i++) { set.add(array[i]); } } return set; } }); define('ember-data/-private/system/relationships/state/relationship', ['exports', 'ember-data/-private/system/ordered-set', 'ember-data/-private/system/normalize-link', 'ember'], function (exports, _orderedSet, _normalizeLink2, _ember) { 'use strict'; exports.__esModule = true; function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } } var _createClass = function () { function defineProperties(target, props) { for (var i = 0; i < props.length; i++) { var descriptor = props[i]; descriptor.enumerable = descriptor.enumerable || false; descriptor.configurable = true; if ("value" in descriptor) descriptor.writable = true; Object.defineProperty(target, descriptor.key, descriptor); } } return function (Constructor, protoProps, staticProps) { if (protoProps) defineProperties(Constructor.prototype, protoProps); if (staticProps) defineProperties(Constructor, staticProps); return Constructor; }; }(); var guidFor = _ember.default.guidFor; var Relationship = function () { function Relationship(store, internalModel, inverseKey, relationshipMeta) { var async = relationshipMeta.options.async; var polymorphic = relationshipMeta.options.polymorphic; this.members = new _orderedSet.default(); this.canonicalMembers = new _orderedSet.default(); this.store = store; this.key = relationshipMeta.key; this.inverseKey = inverseKey; this.internalModel = internalModel; this.isAsync = typeof async === 'undefined' ? true : async; this.isPolymorphic = typeof polymorphic === 'undefined' ? true : polymorphic; this.relationshipMeta = relationshipMeta; //This probably breaks for polymorphic relationship in complex scenarios, due to //multiple possible modelNames this.inverseKeyForImplicit = this.internalModel.modelName + this.key; this.linkPromise = null; this.meta = null; this.hasData = false; this.hasLoaded = false; } Relationship.prototype._inverseIsAsync = function _inverseIsAsync() { if (!this.inverseKey || !this.inverseInternalModel) { return false; } return this.inverseInternalModel._relationships.get(this.inverseKey).isAsync; }; Relationship.prototype.removeInverseRelationships = function removeInverseRelationships() { if (!this.inverseKey) { return; } var allMembers = // we actually want a union of members and canonicalMembers // they should be disjoint but currently are not due to a bug this.members.list.concat(this.canonicalMembers.list); for (var i = 0; i < allMembers.length; i++) { var inverseInternalModel = allMembers[i]; var relationship = inverseInternalModel._relationships.get(this.inverseKey); relationship.inverseDidDematerialize(); } }; Relationship.prototype.inverseDidDematerialize = function inverseDidDematerialize() {}; Relationship.prototype.updateMeta = function updateMeta(meta) { this.meta = meta; }; Relationship.prototype.clear = function clear() { var members = this.members.list; while (members.length > 0) { var member = members[0]; this.removeInternalModel(member); } var canonicalMembers = this.canonicalMembers.list; while (canonicalMembers.length > 0) { var _member = canonicalMembers[0]; this.removeCanonicalInternalModel(_member); } }; Relationship.prototype.removeInternalModels = function removeInternalModels(internalModels) { var _this = this; internalModels.forEach(function (internalModel) { return _this.removeInternalModel(internalModel); }); }; Relationship.prototype.addInternalModels = function addInternalModels(internalModels, idx) { var _this2 = this; internalModels.forEach(function (internalModel) { _this2.addInternalModel(internalModel, idx); if (idx !== undefined) { idx++; } }); }; Relationship.prototype.addCanonicalInternalModels = function addCanonicalInternalModels(internalModels, idx) { for (var i = 0; i < internalModels.length; i++) { if (idx !== undefined) { this.addCanonicalInternalModel(internalModels[i], i + idx); } else { this.addCanonicalInternalModel(internalModels[i]); } } }; Relationship.prototype.addCanonicalInternalModel = function addCanonicalInternalModel(internalModel, idx) { if (!this.canonicalMembers.has(internalModel)) { this.canonicalMembers.add(internalModel); this.setupInverseRelationship(internalModel); } this.flushCanonicalLater(); this.setHasData(true); }; Relationship.prototype.setupInverseRelationship = function setupInverseRelationship(internalModel) { if (this.inverseKey) { var relationships = internalModel._relationships; var relationshipExisted = relationships.has(this.inverseKey); var relationship = relationships.get(this.inverseKey); if (relationshipExisted || this.isPolymorphic) { // if we have only just initialized the inverse relationship, then it // already has this.internalModel in its canonicalMembers, so skip the // unnecessary work. The exception to this is polymorphic // relationships whose members are determined by their inverse, as those // relationships cannot efficiently find their inverse payloads. relationship.addCanonicalInternalModel(this.internalModel); } } else { var _relationships = internalModel._implicitRelationships; var _relationship = _relationships[this.inverseKeyForImplicit]; if (!_relationship) { _relationship = _relationships[this.inverseKeyForImplicit] = new Relationship(this.store, internalModel, this.key, { options: { async: this.isAsync } }); } _relationship.addCanonicalInternalModel(this.internalModel); } }; Relationship.prototype.removeCanonicalInternalModels = function removeCanonicalInternalModels(internalModels, idx) { for (var i = 0; i < internalModels.length; i++) { if (idx !== undefined) { this.removeCanonicalInternalModel(internalModels[i], i + idx); } else { this.removeCanonicalInternalModel(internalModels[i]); } } }; Relationship.prototype.removeCanonicalInternalModel = function removeCanonicalInternalModel(internalModel, idx) { if (this.canonicalMembers.has(internalModel)) { this.removeCanonicalInternalModelFromOwn(internalModel); if (this.inverseKey) { this.removeCanonicalInternalModelFromInverse(internalModel); } else { if (internalModel._implicitRelationships[this.inverseKeyForImplicit]) { internalModel._implicitRelationships[this.inverseKeyForImplicit].removeCanonicalInternalModel(this.internalModel); } } } this.flushCanonicalLater(); }; Relationship.prototype.addInternalModel = function addInternalModel(internalModel, idx) { if (!this.members.has(internalModel)) { this.members.addWithIndex(internalModel, idx); this.notifyRecordRelationshipAdded(internalModel, idx); if (this.inverseKey) { internalModel._relationships.get(this.inverseKey).addInternalModel(this.internalModel); } else { if (!internalModel._implicitRelationships[this.inverseKeyForImplicit]) { internalModel._implicitRelationships[this.inverseKeyForImplicit] = new Relationship(this.store, internalModel, this.key, { options: { async: this.isAsync } }); } internalModel._implicitRelationships[this.inverseKeyForImplicit].addInternalModel(this.internalModel); } this.internalModel.updateRecordArrays(); } this.setHasData(true); }; Relationship.prototype.removeInternalModel = function removeInternalModel(internalModel) { if (this.members.has(internalModel)) { this.removeInternalModelFromOwn(internalModel); if (this.inverseKey) { this.removeInternalModelFromInverse(internalModel); } else { if (internalModel._implicitRelationships[this.inverseKeyForImplicit]) { internalModel._implicitRelationships[this.inverseKeyForImplicit].removeInternalModel(this.internalModel); } } } }; Relationship.prototype.removeInternalModelFromInverse = function removeInternalModelFromInverse(internalModel) { var inverseRelationship = internalModel._relationships.get(this.inverseKey); //Need to check for existence, as the record might unloading at the moment if (inverseRelationship) { inverseRelationship.removeInternalModelFromOwn(this.internalModel); } }; Relationship.prototype.removeInternalModelFromOwn = function removeInternalModelFromOwn(internalModel) { this.members.delete(internalModel); this.internalModel.updateRecordArrays(); }; Relationship.prototype.removeCanonicalInternalModelFromInverse = function removeCanonicalInternalModelFromInverse(internalModel) { var inverseRelationship = internalModel._relationships.get(this.inverseKey); //Need to check for existence, as the record might unloading at the moment if (inverseRelationship) { inverseRelationship.removeCanonicalInternalModelFromOwn(this.internalModel); } }; Relationship.prototype.removeCanonicalInternalModelFromOwn = function removeCanonicalInternalModelFromOwn(internalModel) { this.canonicalMembers.delete(internalModel); this.flushCanonicalLater(); }; Relationship.prototype.removeCompletelyFromInverse = function removeCompletelyFromInverse() { var _this3 = this; if (!this.inverseKey) { return; } // we actually want a union of members and canonicalMembers // they should be disjoint but currently are not due to a bug var seen = Object.create(null); var internalModel = this.internalModel; var unload = function (inverseInternalModel) { var id = guidFor(inverseInternalModel); if (seen[id] === undefined) { var relationship = inverseInternalModel._relationships.get(_this3.inverseKey); relationship.removeCompletelyFromOwn(internalModel); seen[id] = true; } }; this.members.forEach(unload); this.canonicalMembers.forEach(unload); }; Relationship.prototype.removeCompletelyFromOwn = function removeCompletelyFromOwn(internalModel) { this.canonicalMembers.delete(internalModel); this.members.delete(internalModel); this.internalModel.updateRecordArrays(); }; Relationship.prototype.flushCanonical = function flushCanonical() { var list = this.members.list; this.willSync = false; //a hack for not removing new internalModels //TODO remove once we have proper diffing var newInternalModels = []; for (var i = 0; i < list.length; i++) { if (list[i].isNew()) { newInternalModels.push(list[i]); } } //TODO(Igor) make this less abysmally slow this.members = this.canonicalMembers.copy(); for (var _i = 0; _i < newInternalModels.length; _i++) { this.members.add(newInternalModels[_i]); } }; Relationship.prototype.flushCanonicalLater = function flushCanonicalLater() { if (this.willSync) { return; } this.willSync = true; this.store._updateRelationshipState(this); }; Relationship.prototype.updateLink = function updateLink(link, initial) { (false && _ember.default.warn('You pushed a record of type \'' + this.internalModel.modelName + '\' with a relationship \'' + this.key + '\' configured as \'async: false\'. You\'ve included a link but no primary data, this may be an error in your payload.', this.isAsync || this.hasData, { id: 'ds.store.push-link-for-sync-relationship' })); (false && _ember.default.assert('You have pushed a record of type \'' + this.internalModel.modelName + '\' with \'' + this.key + '\' as a link, but the value of that link is not a string.', typeof link === 'string' || link === null)); this.link = link; this.linkPromise = null; if (!initial) { this.internalModel.notifyPropertyChange(this.key); } }; Relationship.prototype.findLink = function findLink() { if (this.linkPromise) { return this.linkPromise; } else { var promise = this.fetchLink(); this.linkPromise = promise; return promise.then(function (result) { return result; }); } }; Relationship.prototype.updateInternalModelsFromAdapter = function updateInternalModelsFromAdapter(internalModels) { this.setHasData(true); //TODO(Igor) move this to a proper place //TODO Once we have adapter support, we need to handle updated and canonical changes this.computeChanges(internalModels); }; Relationship.prototype.notifyRecordRelationshipAdded = function notifyRecordRelationshipAdded() {}; Relationship.prototype.setHasData = function setHasData(value) { this.hasData = value; }; Relationship.prototype.setHasLoaded = function setHasLoaded(value) { this.hasLoaded = value; }; Relationship.prototype.push = function push(payload, initial) { var hasData = false; var hasLink = false; if (payload.meta) { this.updateMeta(payload.meta); } if (payload.data !== undefined) { hasData = true; this.updateData(payload.data, initial); } if (payload.links && payload.links.related) { var relatedLink = (0, _normalizeLink2.default)(payload.links.related); if (relatedLink && relatedLink.href && relatedLink.href !== this.link) { hasLink = true; this.updateLink(relatedLink.href, initial); } } /* Data being pushed into the relationship might contain only data or links, or a combination of both. If we got data we want to set both hasData and hasLoaded to true since this would indicate that we should prefer the local state instead of trying to fetch the link or call findRecord(). If we have no data but a link is present we want to set hasLoaded to false without modifying the hasData flag. This will ensure we fetch the updated link next time the relationship is accessed. */ if (hasData) { this.setHasData(true); this.setHasLoaded(true); } else if (hasLink) { this.setHasLoaded(false); } }; Relationship.prototype.updateData = function updateData() {}; Relationship.prototype.destroy = function destroy() {}; _createClass(Relationship, [{ key: 'parentType', get: function () { return this.internalModel.modelName; } }]); return Relationship; }(); exports.default = Relationship; }); define('ember-data/-private/system/snapshot-record-array', ['exports'], function (exports) { 'use strict'; exports.__esModule = true; function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } } var _createClass = function () { function defineProperties(target, props) { for (var i = 0; i < props.length; i++) { var descriptor = props[i]; descriptor.enumerable = descriptor.enumerable || false; descriptor.configurable = true; if ("value" in descriptor) descriptor.writable = true; Object.defineProperty(target, descriptor.key, descriptor); } } return function (Constructor, protoProps, staticProps) { if (protoProps) defineProperties(Constructor.prototype, protoProps); if (staticProps) defineProperties(Constructor, staticProps); return Constructor; }; }(); var SnapshotRecordArray = function () { function SnapshotRecordArray(recordArray, meta) { var options = arguments.length > 2 && arguments[2] !== undefined ? arguments[2] : {}; /** An array of snapshots @private @property _snapshots @type {Array} */ this._snapshots = null; /** An array of records @private @property _recordArray @type {Array} */ this._recordArray = recordArray; /** Number of records in the array Example ```app/adapters/post.js import DS from 'ember-data' export default DS.JSONAPIAdapter.extend({ shouldReloadAll(store, snapshotRecordArray) { return !snapshotRecordArray.length; }, }); ``` @property length @type {Number} */ this.length = recordArray.get('length'); this._type = null; /** Meta objects for the record array. Example ```app/adapters/post.js import DS from 'ember-data' export default DS.JSONAPIAdapter.extend({ shouldReloadAll(store, snapshotRecordArray) { var lastRequestTime = snapshotRecordArray.meta.lastRequestTime; var twentyMinutes = 20 * 60 * 1000; return Date.now() > lastRequestTime + twentyMinutes; }, }); ``` @property meta @type {Object} */ this.meta = meta; /** A hash of adapter options passed into the store method for this request. Example ```app/adapters/post.js import MyCustomAdapter from './custom-adapter'; export default MyCustomAdapter.extend({ findAll(store, type, sinceToken, snapshotRecordArray) { if (snapshotRecordArray.adapterOptions.subscribe) { // ... } // ... } }); ``` @property adapterOptions @type {Object} */ this.adapterOptions = options.adapterOptions; /** The relationships to include for this request. Example ```app/adapters/application.js import DS from 'ember-data'; export default DS.Adapter.extend({ findAll(store, type, snapshotRecordArray) { var url = `/${type.modelName}?include=${encodeURIComponent(snapshotRecordArray.include)}`; return fetch(url).then((response) => response.json()) } }); @property include @type {String|Array} */ this.include = options.include; } /** The type of the underlying records for the snapshots in the array, as a DS.Model @property type @type {DS.Model} */ SnapshotRecordArray.prototype.snapshots = function snapshots() { if (this._snapshots !== null) { return this._snapshots; } this._snapshots = this._recordArray._takeSnapshot(); return this._snapshots; }; _createClass(SnapshotRecordArray, [{ key: 'type', get: function () { return this._type || (this._type = this._recordArray.get('type')); } }]); return SnapshotRecordArray; }(); exports.default = SnapshotRecordArray; }); define("ember-data/-private/system/snapshot", ["exports", "ember"], function (exports, _ember) { "use strict"; exports.__esModule = true; function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } } var _createClass = function () { function defineProperties(target, props) { for (var i = 0; i < props.length; i++) { var descriptor = props[i]; descriptor.enumerable = descriptor.enumerable || false; descriptor.configurable = true; if ("value" in descriptor) descriptor.writable = true; Object.defineProperty(target, descriptor.key, descriptor); } } return function (Constructor, protoProps, staticProps) { if (protoProps) defineProperties(Constructor.prototype, protoProps); if (staticProps) defineProperties(Constructor, staticProps); return Constructor; }; }(); var get = _ember.default.get; var Snapshot = function () { function Snapshot(internalModel) { var _this = this; var options = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : {}; this._attributes = Object.create(null); this._belongsToRelationships = Object.create(null); this._belongsToIds = Object.create(null); this._hasManyRelationships = Object.create(null); this._hasManyIds = Object.create(null); this._internalModel = internalModel; var record = internalModel.getRecord(); /** The underlying record for this snapshot. Can be used to access methods and properties defined on the record. Example ```javascript let json = snapshot.record.toJSON(); ``` @property record @type {DS.Model} */ this.record = record; record.eachAttribute(function (keyName) { return _this._attributes[keyName] = get(record, keyName); }); /** The id of the snapshot's underlying record Example ```javascript // store.push('post', { id: 1, author: 'Tomster', title: 'Ember.js rocks' }); postSnapshot.id; // => '1' ``` @property id @type {String} */ this.id = internalModel.id; /** A hash of adapter options @property adapterOptions @type {Object} */ this.adapterOptions = options.adapterOptions; this.include = options.include; /** The name of the type of the underlying record for this snapshot, as a string. @property modelName @type {String} */ this.modelName = internalModel.modelName; this._changedAttributes = record.changedAttributes(); } /** The type of the underlying record for this snapshot, as a DS.Model. @property type @type {DS.Model} */ Snapshot.prototype.attr = function attr(keyName) { if (keyName in this._attributes) { return this._attributes[keyName]; } throw new _ember.default.Error("Model '" + _ember.default.inspect(this.record) + "' has no attribute named '" + keyName + "' defined."); }; Snapshot.prototype.attributes = function attributes() { return _ember.default.copy(this._attributes); }; Snapshot.prototype.changedAttributes = function changedAttributes() { var changedAttributes = Object.create(null); var changedAttributeKeys = Object.keys(this._changedAttributes); for (var i = 0, length = changedAttributeKeys.length; i < length; i++) { var key = changedAttributeKeys[i]; changedAttributes[key] = _ember.default.copy(this._changedAttributes[key]); } return changedAttributes; }; Snapshot.prototype.belongsTo = function belongsTo(keyName, options) { var id = options && options.id; var relationship = void 0, inverseInternalModel = void 0, hasData = void 0; var result = void 0; if (id && keyName in this._belongsToIds) { return this._belongsToIds[keyName]; } if (!id && keyName in this._belongsToRelationships) { return this._belongsToRelationships[keyName]; } relationship = this._internalModel._relationships.get(keyName); if (!(relationship && relationship.relationshipMeta.kind === 'belongsTo')) { throw new _ember.default.Error("Model '" + _ember.default.inspect(this.record) + "' has no belongsTo relationship named '" + keyName + "' defined."); } hasData = get(relationship, 'hasData'); inverseInternalModel = get(relationship, 'inverseInternalModel'); if (hasData) { if (inverseInternalModel && !inverseInternalModel.isDeleted()) { if (id) { result = get(inverseInternalModel, 'id'); } else { result = inverseInternalModel.createSnapshot(); } } else { result = null; } } if (id) { this._belongsToIds[keyName] = result; } else { this._belongsToRelationships[keyName] = result; } return result; }; Snapshot.prototype.hasMany = function hasMany(keyName, options) { var ids = options && options.ids; var relationship = void 0, members = void 0, hasData = void 0; var results = void 0; if (ids && keyName in this._hasManyIds) { return this._hasManyIds[keyName]; } if (!ids && keyName in this._hasManyRelationships) { return this._hasManyRelationships[keyName]; } relationship = this._internalModel._relationships.get(keyName); if (!(relationship && relationship.relationshipMeta.kind === 'hasMany')) { throw new _ember.default.Error("Model '" + _ember.default.inspect(this.record) + "' has no hasMany relationship named '" + keyName + "' defined."); } hasData = get(relationship, 'hasData'); members = get(relationship, 'members'); if (hasData) { results = []; members.forEach(function (member) { if (!member.isDeleted()) { if (ids) { results.push(member.id); } else { results.push(member.createSnapshot()); } } }); } if (ids) { this._hasManyIds[keyName] = results; } else { this._hasManyRelationships[keyName] = results; } return results; }; Snapshot.prototype.eachAttribute = function eachAttribute(callback, binding) { this.record.eachAttribute(callback, binding); }; Snapshot.prototype.eachRelationship = function eachRelationship(callback, binding) { this.record.eachRelationship(callback, binding); }; Snapshot.prototype.serialize = function serialize(options) { return this.record.store.serializerFor(this.modelName).serialize(this, options); }; _createClass(Snapshot, [{ key: "type", get: function () { // TODO @runspired we should deprecate this in favor of modelClass but only once // we've cleaned up the internals enough that a public change to follow suite is // uncontroversial. return this._internalModel.modelClass; } }]); return Snapshot; }(); exports.default = Snapshot; }); define('ember-data/-private/system/store', ['exports', 'ember', 'ember-data/-private/adapters/errors', 'ember-data/-private/system/model/model', 'ember-data/-private/system/normalize-model-name', 'ember-data/-private/system/identity-map', 'ember-data/-private/system/promise-proxies', 'ember-data/-private/system/store/common', 'ember-data/-private/system/store/serializer-response', 'ember-data/-private/system/store/serializers', 'ember-data/-private/system/relationships/relationship-payloads-manager', 'ember-data/-private/system/store/finders', 'ember-data/-private/utils', 'ember-data/-private/system/coerce-id', 'ember-data/-private/system/record-array-manager', 'ember-data/-private/system/store/container-instance-cache', 'ember-data/-private/system/model/internal-model', 'ember-data/-private/features'], function (exports, _ember, _errors, _model, _normalizeModelName, _identityMap, _promiseProxies, _common, _serializerResponse, _serializers, _relationshipPayloadsManager, _finders, _utils, _coerceId, _recordArrayManager, _containerInstanceCache, _internalModel5, _features) { 'use strict'; exports.__esModule = true; exports.Store = undefined; var badIdFormatAssertion = '`id` passed to `findRecord()` has to be non-empty string or number'; /** @module ember-data */ var A = _ember.default.A, Backburner = _ember.default._Backburner, computed = _ember.default.computed, copy = _ember.default.copy, ENV = _ember.default.ENV, EmberError = _ember.default.Error, get = _ember.default.get, inspect = _ember.default.inspect, isNone = _ember.default.isNone, isPresent = _ember.default.isPresent, MapWithDefault = _ember.default.MapWithDefault, emberRun = _ember.default.run, set = _ember.default.set, RSVP = _ember.default.RSVP, Service = _ember.default.Service, typeOf = _ember.default.typeOf; var Promise = RSVP.Promise; //Get the materialized model from the internalModel/promise that returns //an internal model and return it in a promiseObject. Useful for returning //from find methods function promiseRecord(internalModelPromise, label) { var toReturn = internalModelPromise.then(function (internalModel) { return internalModel.getRecord(); }); return (0, _promiseProxies.promiseObject)(toReturn, label); } var Store = void 0; // Implementors Note: // // The variables in this file are consistently named according to the following // scheme: // // * +id+ means an identifier managed by an external source, provided inside // the data provided by that source. These are always coerced to be strings // before being used internally. // * +clientId+ means a transient numerical identifier generated at runtime by // the data store. It is important primarily because newly created objects may // not yet have an externally generated id. // * +internalModel+ means a record internalModel object, which holds metadata about a // record, even if it has not yet been fully materialized. // * +type+ means a DS.Model. /** The store contains all of the data for records loaded from the server. It is also responsible for creating instances of `DS.Model` that wrap the individual data for a record, so that they can be bound to in your Handlebars templates. Define your application's store like this: ```app/services/store.js import DS from 'ember-data'; export default DS.Store.extend({ }); ``` Most Ember.js applications will only have a single `DS.Store` that is automatically created by their `Ember.Application`. You can retrieve models from the store in several ways. To retrieve a record for a specific id, use `DS.Store`'s `findRecord()` method: ```javascript store.findRecord('person', 123).then(function (person) { }); ``` By default, the store will talk to your backend using a standard REST mechanism. You can customize how the store talks to your backend by specifying a custom adapter: ```app/adapters/application.js import DS from 'ember-data'; export default DS.Adapter.extend({ }); ``` You can learn more about writing a custom adapter by reading the `DS.Adapter` documentation. ### Store createRecord() vs. push() vs. pushPayload() The store provides multiple ways to create new record objects. They have some subtle differences in their use which are detailed below: [createRecord](#method_createRecord) is used for creating new records on the client side. This will return a new record in the `created.uncommitted` state. In order to persist this record to the backend you will need to call `record.save()`. [push](#method_push) is used to notify Ember Data's store of new or updated records that exist in the backend. This will return a record in the `loaded.saved` state. The primary use-case for `store#push` is to notify Ember Data about record updates (full or partial) that happen outside of the normal adapter methods (for example [SSE](http://dev.w3.org/html5/eventsource/) or [Web Sockets](http://www.w3.org/TR/2009/WD-websockets-20091222/)). [pushPayload](#method_pushPayload) is a convenience wrapper for `store#push` that will deserialize payloads if the Serializer implements a `pushPayload` method. Note: When creating a new record using any of the above methods Ember Data will update `DS.RecordArray`s such as those returned by `store#peekAll()` or `store#findAll()`. This means any data bindings or computed properties that depend on the RecordArray will automatically be synced to include the new or updated record values. @class Store @namespace DS @extends Ember.Service */ exports.Store = Store = Service.extend({ /** @method init @private */ init: function () { this._super.apply(this, arguments); this._backburner = new Backburner(['normalizeRelationships', 'syncRelationships', 'finished']); // internal bookkeeping; not observable this.recordArrayManager = new _recordArrayManager.default({ store: this }); this._identityMap = new _identityMap.default(); this._pendingSave = []; this._instanceCache = new _containerInstanceCache.default((0, _utils.getOwner)(this), this); this._modelFactoryCache = Object.create(null); this._relationshipsPayloads = new _relationshipPayloadsManager.default(this); /* Ember Data uses several specialized micro-queues for organizing and coalescing similar async work. These queues are currently controlled by a flush scheduled into ember-data's custom backburner instance. */ // used for coalescing record save requests this._pendingSave = []; // used for coalescing relationship updates this._updatedRelationships = []; // used for coalescing relationship setup needs this._pushedInternalModels = []; // used for coalescing internal model updates this._updatedInternalModels = []; // used to keep track of all the find requests that need to be coalesced this._pendingFetch = MapWithDefault.create({ defaultValue: function () { return []; } }); this._instanceCache = new _containerInstanceCache.default((0, _utils.getOwner)(this), this); }, /** The default adapter to use to communicate to a backend server or other persistence layer. This will be overridden by an application adapter if present. If you want to specify `app/adapters/custom.js` as a string, do: ```js import DS from 'ember-data'; export default DS.Store.extend({ adapter: 'custom', }); ``` @property adapter @default '-json-api' @type {String} */ adapter: '-json-api', /** Returns a JSON representation of the record using a custom type-specific serializer, if one exists. The available options are: * `includeId`: `true` if the record's ID should be included in the JSON representation @method serialize @private @deprecated @param {DS.Model} record the record to serialize @param {Object} options an options hash */ serialize: function (record, options) { if (true) { (false && !(false) && _ember.default.deprecate('Use of store.serialize is deprecated, use record.serialize instead.', false, { id: 'ds.store.serialize', until: '3.0' })); } var snapshot = record._internalModel.createSnapshot(); return snapshot.serialize(options); }, /** This property returns the adapter, after resolving a possible string key. If the supplied `adapter` was a class, or a String property path resolved to a class, this property will instantiate the class. This property is cacheable, so the same instance of a specified adapter class should be used for the lifetime of the store. @property defaultAdapter @private @return DS.Adapter */ defaultAdapter: computed('adapter', function () { var adapter = get(this, 'adapter'); (false && _ember.default.assert('You tried to set `adapter` property to an instance of `DS.Adapter`, where it should be a name', typeof adapter === 'string')); return this.adapterFor(adapter); }), // ..................... // . CREATE NEW RECORD . // ..................... /** Create a new record in the current store. The properties passed to this method are set on the newly created record. To create a new instance of a `Post`: ```js store.createRecord('post', { title: 'Rails is omakase' }); ``` To create a new instance of a `Post` that has a relationship with a `User` record: ```js let user = this.store.peekRecord('user', 1); store.createRecord('post', { title: 'Rails is omakase', user: user }); ``` @method createRecord @param {String} modelName @param {Object} inputProperties a hash of properties to set on the newly created record. @return {DS.Model} record */ createRecord: function (modelName, inputProperties) { (false && _ember.default.assert('You need to pass a model name to the store\'s createRecord method', isPresent(modelName))); (false && _ember.default.assert('Passing classes to store methods has been removed. Please pass a dasherized string instead of ' + modelName, typeof modelName === 'string')); var normalizedModelName = (0, _normalizeModelName.default)(modelName); var properties = copy(inputProperties) || Object.create(null); // If the passed properties do not include a primary key, // give the adapter an opportunity to generate one. Typically, // client-side ID generators will use something like uuid.js // to avoid conflicts. if (isNone(properties.id)) { properties.id = this._generateId(normalizedModelName, properties); } // Coerce ID to a string properties.id = (0, _coerceId.default)(properties.id); var internalModel = this._buildInternalModel(normalizedModelName, properties.id); internalModel.loadedData(); var record = internalModel.getRecord(properties); // TODO @runspired this should also be coalesced into some form of internalModel.setState() internalModel.eachRelationship(function (key, descriptor) { if (properties[key] !== undefined) { internalModel._relationships.get(key).setHasData(true); } }); return record; }, /** If possible, this method asks the adapter to generate an ID for a newly created record. @method _generateId @private @param {String} modelName @param {Object} properties from the new record @return {String} if the adapter can generate one, an ID */ _generateId: function (modelName, properties) { var adapter = this.adapterFor(modelName); if (adapter && adapter.generateIdForRecord) { return adapter.generateIdForRecord(this, modelName, properties); } return null; }, // ................. // . DELETE RECORD . // ................. /** For symmetry, a record can be deleted via the store. Example ```javascript let post = store.createRecord('post', { title: 'Rails is omakase' }); store.deleteRecord(post); ``` @method deleteRecord @param {DS.Model} record */ deleteRecord: function (record) { record.deleteRecord(); }, /** For symmetry, a record can be unloaded via the store. This will cause the record to be destroyed and freed up for garbage collection. Example ```javascript store.findRecord('post', 1).then(function(post) { store.unloadRecord(post); }); ``` @method unloadRecord @param {DS.Model} record */ unloadRecord: function (record) { record.unloadRecord(); }, // ................ // . FIND RECORDS . // ................ /** @method find @param {String} modelName @param {String|Integer} id @param {Object} options @return {Promise} promise @private */ find: function (modelName, id, options) { // The default `model` hook in Ember.Route calls `find(modelName, id)`, // that's why we have to keep this method around even though `findRecord` is // the public way to get a record by modelName and id. (false && _ember.default.assert('Using store.find(type) has been removed. Use store.findAll(modelName) to retrieve all records for a given type.', arguments.length !== 1)); (false && _ember.default.assert('Calling store.find(modelName, id, { preload: preload }) is no longer supported. Use store.findRecord(modelName, id, { preload: preload }) instead.', !options)); (false && _ember.default.assert('You need to pass the model name and id to the store\'s find method', arguments.length === 2)); (false && _ember.default.assert('You cannot pass \'' + id + '\' as id to the store\'s find method', typeof id === 'string' || typeof id === 'number')); (false && _ember.default.assert('Calling store.find() with a query object is no longer supported. Use store.query() instead.', typeof id !== 'object')); (false && _ember.default.assert('Passing classes to store methods has been removed. Please pass a dasherized string instead of ' + modelName, typeof modelName === 'string')); var normalizedModelName = (0, _normalizeModelName.default)(modelName); return this.findRecord(normalizedModelName, id); }, /** This method returns a record for a given type and id combination. The `findRecord` method will always resolve its promise with the same object for a given type and `id`. The `findRecord` method will always return a **promise** that will be resolved with the record. Example ```app/routes/post.js import Ember from 'ember'; export default Ember.Route.extend({ model(params) { return this.store.findRecord('post', params.post_id); } }); ``` If the record is not yet available, the store will ask the adapter's `find` method to find the necessary data. If the record is already present in the store, it depends on the reload behavior _when_ the returned promise resolves. ### Preloading You can optionally `preload` specific attributes and relationships that you know of by passing them via the passed `options`. For example, if your Ember route looks like `/posts/1/comments/2` and your API route for the comment also looks like `/posts/1/comments/2` if you want to fetch the comment without fetching the post you can pass in the post to the `findRecord` call: ```javascript store.findRecord('comment', 2, { preload: { post: 1 } }); ``` If you have access to the post model you can also pass the model itself: ```javascript store.findRecord('post', 1).then(function (myPostModel) { store.findRecord('comment', 2, { post: myPostModel }); }); ``` ### Reloading The reload behavior is configured either via the passed `options` hash or the result of the adapter's `shouldReloadRecord`. If `{ reload: true }` is passed or `adapter.shouldReloadRecord` evaluates to `true`, then the returned promise resolves once the adapter returns data, regardless if the requested record is already in the store: ```js store.push({ data: { id: 1, type: 'post', revision: 1 } }); // adapter#findRecord resolves with // [ // { // id: 1, // type: 'post', // revision: 2 // } // ] store.findRecord('post', 1, { reload: true }).then(function(post) { post.get('revision'); // 2 }); ``` If no reload is indicated via the abovementioned ways, then the promise immediately resolves with the cached version in the store. ### Background Reloading Optionally, if `adapter.shouldBackgroundReloadRecord` evaluates to `true`, then a background reload is started, which updates the records' data, once it is available: ```js // app/adapters/post.js import ApplicationAdapter from "./application"; export default ApplicationAdapter.extend({ shouldReloadRecord(store, snapshot) { return false; }, shouldBackgroundReloadRecord(store, snapshot) { return true; } }); // ... store.push({ data: { id: 1, type: 'post', revision: 1 } }); let blogPost = store.findRecord('post', 1).then(function(post) { post.get('revision'); // 1 }); // later, once adapter#findRecord resolved with // [ // { // id: 1, // type: 'post', // revision: 2 // } // ] blogPost.get('revision'); // 2 ``` If you would like to force or prevent background reloading, you can set a boolean value for `backgroundReload` in the options object for `findRecord`. ```app/routes/post/edit.js import Ember from 'ember'; export default Ember.Route.extend({ model(params) { return this.store.findRecord('post', params.post_id, { backgroundReload: false }); } }); ``` If you pass an object on the `adapterOptions` property of the options argument it will be passed to you adapter via the snapshot ```app/routes/post/edit.js import Ember from 'ember'; export default Ember.Route.extend({ model(params) { return this.store.findRecord('post', params.post_id, { adapterOptions: { subscribe: false } }); } }); ``` ```app/adapters/post.js import MyCustomAdapter from './custom-adapter'; export default MyCustomAdapter.extend({ findRecord(store, type, id, snapshot) { if (snapshot.adapterOptions.subscribe) { // ... } // ... } }); ``` See [peekRecord](#method_peekRecord) to get the cached version of a record. ### Retrieving Related Model Records If you use an adapter such as Ember's default [`JSONAPIAdapter`](https://emberjs.com/api/data/classes/DS.JSONAPIAdapter.html) that supports the [JSON API specification](http://jsonapi.org/) and if your server endpoint supports the use of an ['include' query parameter](http://jsonapi.org/format/#fetching-includes), you can use `findRecord()` to automatically retrieve additional records related to the one you request by supplying an `include` parameter in the `options` object. For example, given a `post` model that has a `hasMany` relationship with a `comment` model, when we retrieve a specific post we can have the server also return that post's comments in the same request: ```app/routes/post.js import Ember from 'ember'; export default Ember.Route.extend({ model(params) { return this.store.findRecord('post', params.post_id, { include: 'comments' }); } }); ``` In this case, the post's comments would then be available in your template as `model.comments`. Multiple relationships can be requested using an `include` parameter consisting of a comma-separated list (without white-space) while nested relationships can be specified using a dot-separated sequence of relationship names. So to request both the post's comments and the authors of those comments the request would look like this: ```app/routes/post.js import Ember from 'ember'; export default Ember.Route.extend({ model(params) { return this.store.findRecord('post', params.post_id, { include: 'comments,comments.author' }); } }); ``` @since 1.13.0 @method findRecord @param {String} modelName @param {(String|Integer)} id @param {Object} options @return {Promise} promise */ findRecord: function (modelName, id, options) { (false && _ember.default.assert('You need to pass a model name to the store\'s findRecord method', isPresent(modelName))); (false && _ember.default.assert('Passing classes to store methods has been removed. Please pass a dasherized string instead of ' + modelName, typeof modelName === 'string')); (false && _ember.default.assert(badIdFormatAssertion, typeof id === 'string' && id.length > 0 || typeof id === 'number' && !isNaN(id))); var normalizedModelName = (0, _normalizeModelName.default)(modelName); var internalModel = this._internalModelForId(normalizedModelName, id); options = options || {}; if (!this.hasRecordForId(normalizedModelName, id)) { return this._findByInternalModel(internalModel, options); } var fetchedInternalModel = this._findRecord(internalModel, options); return promiseRecord(fetchedInternalModel, 'DS: Store#findRecord ' + normalizedModelName + ' with id: ' + id); }, _findRecord: function (internalModel, options) { // Refetch if the reload option is passed if (options.reload) { return this._scheduleFetch(internalModel, options); } var snapshot = internalModel.createSnapshot(options); var adapter = this.adapterFor(internalModel.modelName); // Refetch the record if the adapter thinks the record is stale if (adapter.shouldReloadRecord(this, snapshot)) { return this._scheduleFetch(internalModel, options); } if (options.backgroundReload === false) { return Promise.resolve(internalModel); } // Trigger the background refetch if backgroundReload option is passed if (options.backgroundReload || adapter.shouldBackgroundReloadRecord(this, snapshot)) { this._scheduleFetch(internalModel, options); } // Return the cached record return Promise.resolve(internalModel); }, _findByInternalModel: function (internalModel) { var options = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : {}; if (options.preload) { internalModel.preloadData(options.preload); } var fetchedInternalModel = this._findEmptyInternalModel(internalModel, options); return promiseRecord(fetchedInternalModel, 'DS: Store#findRecord ' + internalModel.modelName + ' with id: ' + internalModel.id); }, _findEmptyInternalModel: function (internalModel, options) { if (internalModel.isEmpty()) { return this._scheduleFetch(internalModel, options); } //TODO double check about reloading if (internalModel.isLoading()) { return internalModel._loadingPromise; } return Promise.resolve(internalModel); }, /** This method makes a series of requests to the adapter's `find` method and returns a promise that resolves once they are all loaded. @private @method findByIds @param {String} modelName @param {Array} ids @return {Promise} promise */ findByIds: function (modelName, ids) { (false && _ember.default.assert('You need to pass a model name to the store\'s findByIds method', isPresent(modelName))); (false && _ember.default.assert('Passing classes to store methods has been removed. Please pass a dasherized string instead of ' + modelName, typeof modelName === 'string')); var promises = new Array(ids.length); var normalizedModelName = (0, _normalizeModelName.default)(modelName); for (var i = 0; i < ids.length; i++) { promises[i] = this.findRecord(normalizedModelName, ids[i]); } return (0, _promiseProxies.promiseArray)(RSVP.all(promises).then(A, null, 'DS: Store#findByIds of ' + normalizedModelName + ' complete')); }, /** This method is called by `findRecord` if it discovers that a particular type/id pair hasn't been loaded yet to kick off a request to the adapter. @method _fetchRecord @private @param {InternalModel} internalModel model @return {Promise} promise */ _fetchRecord: function (internalModel, options) { var modelName = internalModel.modelName; var adapter = this.adapterFor(modelName); (false && _ember.default.assert('You tried to find a record but you have no adapter (for ' + modelName + ')', adapter)); (false && _ember.default.assert('You tried to find a record but your adapter (for ' + modelName + ') does not implement \'findRecord\'', typeof adapter.findRecord === 'function')); return (0, _finders._find)(adapter, this, internalModel.type, internalModel.id, internalModel, options); }, _scheduleFetchMany: function (internalModels) { var fetches = new Array(internalModels.length); for (var i = 0; i < internalModels.length; i++) { fetches[i] = this._scheduleFetch(internalModels[i]); } return Promise.all(fetches); }, _scheduleFetch: function (internalModel, options) { if (internalModel._loadingPromise) { return internalModel._loadingPromise; } var id = internalModel.id, modelName = internalModel.modelName; var resolver = RSVP.defer('Fetching ' + modelName + '\' with id: ' + id); var pendingFetchItem = { internalModel: internalModel, resolver: resolver, options: options }; var promise = resolver.promise; internalModel.loadingData(promise); if (this._pendingFetch.size === 0) { emberRun.schedule('afterRender', this, this.flushAllPendingFetches); } this._pendingFetch.get(modelName).push(pendingFetchItem); return promise; }, flushAllPendingFetches: function () { if (this.isDestroyed || this.isDestroying) { return; } this._pendingFetch.forEach(this._flushPendingFetchForType, this); this._pendingFetch.clear(); }, _flushPendingFetchForType: function (pendingFetchItems, modelName) { var store = this; var adapter = store.adapterFor(modelName); var shouldCoalesce = !!adapter.findMany && adapter.coalesceFindRequests; var totalItems = pendingFetchItems.length; var internalModels = new Array(totalItems); var seeking = Object.create(null); for (var _i = 0; _i < totalItems; _i++) { var pendingItem = pendingFetchItems[_i]; var _internalModel = pendingItem.internalModel; internalModels[_i] = _internalModel; seeking[_internalModel.id] = pendingItem; } function _fetchRecord(recordResolverPair) { var recordFetch = store._fetchRecord(recordResolverPair.internalModel, recordResolverPair.options); // TODO adapter options recordResolverPair.resolver.resolve(recordFetch); } function handleFoundRecords(foundInternalModels, expectedInternalModels) { // resolve found records var found = Object.create(null); for (var _i2 = 0, _l = foundInternalModels.length; _i2 < _l; _i2++) { var _internalModel2 = foundInternalModels[_i2]; var _pair = seeking[_internalModel2.id]; found[_internalModel2.id] = _internalModel2; if (_pair) { var resolver = _pair.resolver; resolver.resolve(_internalModel2); } } // reject missing records var missingInternalModels = []; for (var _i3 = 0, _l2 = expectedInternalModels.length; _i3 < _l2; _i3++) { var _internalModel3 = expectedInternalModels[_i3]; if (!found[_internalModel3.id]) { missingInternalModels.push(_internalModel3); } } if (missingInternalModels.length) { (false && _ember.default.warn('Ember Data expected to find records with the following ids in the adapter response but they were missing: ' + inspect(missingInternalModels.map(function (r) { return r.id; })), false, { id: 'ds.store.missing-records-from-adapter' })); rejectInternalModels(missingInternalModels); } } function rejectInternalModels(internalModels, error) { for (var _i4 = 0, _l3 = internalModels.length; _i4 < _l3; _i4++) { var _internalModel4 = internalModels[_i4]; var _pair2 = seeking[_internalModel4.id]; if (_pair2) { _pair2.resolver.reject(error || new Error('Expected: \'' + _internalModel4 + '\' to be present in the adapter provided payload, but it was not found.')); } } } if (shouldCoalesce) { // TODO: Improve records => snapshots => records => snapshots // // We want to provide records to all store methods and snapshots to all // adapter methods. To make sure we're doing that we're providing an array // of snapshots to adapter.groupRecordsForFindMany(), which in turn will // return grouped snapshots instead of grouped records. // // But since the _findMany() finder is a store method we need to get the // records from the grouped snapshots even though the _findMany() finder // will once again convert the records to snapshots for adapter.findMany() var snapshots = new Array(totalItems); for (var _i5 = 0; _i5 < totalItems; _i5++) { snapshots[_i5] = internalModels[_i5].createSnapshot(); } var groups = adapter.groupRecordsForFindMany(this, snapshots); for (var i = 0, l = groups.length; i < l; i++) { var group = groups[i]; var totalInGroup = groups[i].length; var ids = new Array(totalInGroup); var groupedInternalModels = new Array(totalInGroup); for (var j = 0; j < totalInGroup; j++) { var internalModel = group[j]._internalModel; groupedInternalModels[j] = internalModel; ids[j] = internalModel.id; } if (totalInGroup > 1) { (function (groupedInternalModels) { (0, _finders._findMany)(adapter, store, modelName, ids, groupedInternalModels).then(function (foundInternalModels) { handleFoundRecords(foundInternalModels, groupedInternalModels); }).catch(function (error) { rejectInternalModels(groupedInternalModels, error); }); })(groupedInternalModels); } else if (ids.length === 1) { var pair = seeking[groupedInternalModels[0].id]; _fetchRecord(pair); } else { (false && _ember.default.assert("You cannot return an empty array from adapter's method groupRecordsForFindMany", false)); } } } else { for (var _i6 = 0; _i6 < totalItems; _i6++) { _fetchRecord(pendingFetchItems[_i6]); } } }, /** Get the reference for the specified record. Example ```javascript let userRef = store.getReference('user', 1); // check if the user is loaded let isLoaded = userRef.value() !== null; // get the record of the reference (null if not yet available) let user = userRef.value(); // get the identifier of the reference if (userRef.remoteType() === 'id') { let id = userRef.id(); } // load user (via store.find) userRef.load().then(...) // or trigger a reload userRef.reload().then(...) // provide data for reference userRef.push({ id: 1, username: '@user' }).then(function(user) { userRef.value() === user; }); ``` @method getReference @param {String} modelName @param {String|Integer} id @since 2.5.0 @return {RecordReference} */ getReference: function (modelName, id) { var normalizedModelName = (0, _normalizeModelName.default)(modelName); return this._internalModelForId(normalizedModelName, id).recordReference; }, /** Get a record by a given type and ID without triggering a fetch. This method will synchronously return the record if it is available in the store, otherwise it will return `null`. A record is available if it has been fetched earlier, or pushed manually into the store. See [findRecord](#method_findRecord) if you would like to request this record from the backend. _Note: This is a synchronous method and does not return a promise._ ```js let post = store.peekRecord('post', 1); post.get('id'); // 1 ``` @since 1.13.0 @method peekRecord @param {String} modelName @param {String|Integer} id @return {DS.Model|null} record */ peekRecord: function (modelName, id) { (false && _ember.default.assert('You need to pass a model name to the store\'s peekRecord method', isPresent(modelName))); (false && _ember.default.assert('Passing classes to store methods has been removed. Please pass a dasherized string instead of ' + modelName, typeof modelName === 'string')); var normalizedModelName = (0, _normalizeModelName.default)(modelName); if (this.hasRecordForId(normalizedModelName, id)) { return this._internalModelForId(normalizedModelName, id).getRecord(); } else { return null; } }, /** This method is called by the record's `reload` method. This method calls the adapter's `find` method, which returns a promise. When **that** promise resolves, `reloadRecord` will resolve the promise returned by the record's `reload`. @method reloadRecord @private @param {DS.Model} internalModel @return {Promise} promise */ _reloadRecord: function (internalModel) { var id = internalModel.id, modelName = internalModel.modelName; var adapter = this.adapterFor(modelName); (false && _ember.default.assert('You cannot reload a record without an ID', id)); (false && _ember.default.assert('You tried to reload a record but you have no adapter (for ' + modelName + ')', adapter)); (false && _ember.default.assert('You tried to reload a record but your adapter does not implement \'findRecord\'', typeof adapter.findRecord === 'function' || typeof adapter.find === 'function')); return this._scheduleFetch(internalModel); }, /** This method returns true if a record for a given modelName and id is already loaded in the store. Use this function to know beforehand if a findRecord() will result in a request or that it will be a cache hit. Example ```javascript store.hasRecordForId('post', 1); // false store.findRecord('post', 1).then(function() { store.hasRecordForId('post', 1); // true }); ``` @method hasRecordForId @param {String} modelName @param {(String|Integer)} id @return {Boolean} */ hasRecordForId: function (modelName, id) { (false && _ember.default.assert('You need to pass a model name to the store\'s hasRecordForId method', isPresent(modelName))); (false && _ember.default.assert('Passing classes to store methods has been removed. Please pass a dasherized string instead of ' + modelName, typeof modelName === 'string')); var normalizedModelName = (0, _normalizeModelName.default)(modelName); var trueId = (0, _coerceId.default)(id); var internalModel = this._internalModelsFor(normalizedModelName).get(trueId); return !!internalModel && internalModel.isLoaded(); }, /** Returns id record for a given type and ID. If one isn't already loaded, it builds a new record and leaves it in the `empty` state. @method recordForId @private @param {String} modelName @param {(String|Integer)} id @return {DS.Model} record */ recordForId: function (modelName, id) { (false && _ember.default.assert('You need to pass a model name to the store\'s recordForId method', isPresent(modelName))); (false && _ember.default.assert('Passing classes to store methods has been removed. Please pass a dasherized string instead of ' + modelName, typeof modelName === 'string')); return this._internalModelForId(modelName, id).getRecord(); }, _internalModelForId: function (modelName, id) { var trueId = (0, _coerceId.default)(id); var internalModel = this._internalModelsFor(modelName).get(trueId); if (internalModel) { if (internalModel.hasScheduledDestroy()) { internalModel.destroySync(); return this._buildInternalModel(modelName, trueId); } else { return internalModel; } } else { return this._buildInternalModel(modelName, trueId); } }, _internalModelDidReceiveRelationshipData: function (modelName, id, relationshipData) { this._relationshipsPayloads.push(modelName, id, relationshipData); }, _internalModelDestroyed: function (internalModel) { this._removeFromIdMap(internalModel); this._relationshipsPayloads.unload(internalModel.modelName, internalModel.id); }, /** @method findMany @private @param {Array} internalModels @return {Promise} promise */ findMany: function (internalModels) { var finds = new Array(internalModels.length); for (var i = 0; i < internalModels.length; i++) { finds[i] = this._findEmptyInternalModel(internalModels[i]); } return Promise.all(finds); }, /** If a relationship was originally populated by the adapter as a link (as opposed to a list of IDs), this method is called when the relationship is fetched. The link (which is usually a URL) is passed through unchanged, so the adapter can make whatever request it wants. The usual use-case is for the server to register a URL as a link, and then use that URL in the future to make a request for the relationship. @method findHasMany @private @param {InternalModel} internalModel @param {any} link @param {(Relationship)} relationship @return {Promise} promise */ findHasMany: function (internalModel, link, relationship) { var adapter = this.adapterFor(internalModel.modelName); (false && _ember.default.assert('You tried to load a hasMany relationship but you have no adapter (for ' + internalModel.modelName + ')', adapter)); (false && _ember.default.assert('You tried to load a hasMany relationship from a specified \'link\' in the original payload but your adapter does not implement \'findHasMany\'', typeof adapter.findHasMany === 'function')); return (0, _finders._findHasMany)(adapter, this, internalModel, link, relationship); }, /** @method findBelongsTo @private @param {InternalModel} internalModel @param {any} link @param {Relationship} relationship @return {Promise} promise */ findBelongsTo: function (internalModel, link, relationship) { var adapter = this.adapterFor(internalModel.modelName); (false && _ember.default.assert('You tried to load a belongsTo relationship but you have no adapter (for ' + internalModel.modelName + ')', adapter)); (false && _ember.default.assert('You tried to load a belongsTo relationship from a specified \'link\' in the original payload but your adapter does not implement \'findBelongsTo\'', typeof adapter.findBelongsTo === 'function')); return (0, _finders._findBelongsTo)(adapter, this, internalModel, link, relationship); }, /** This method delegates a query to the adapter. This is the one place where adapter-level semantics are exposed to the application. Each time this method is called a new request is made through the adapter. Exposing queries this way seems preferable to creating an abstract query language for all server-side queries, and then require all adapters to implement them. --- If you do something like this: ```javascript store.query('person', { page: 1 }); ``` The call made to the server, using a Rails backend, will look something like this: ``` Started GET "/api/v1/person?page=1" Processing by Api::V1::PersonsController#index as HTML Parameters: { "page"=>"1" } ``` --- If you do something like this: ```javascript store.query('person', { ids: [1, 2, 3] }); ``` The call to the server, using a Rails backend, will look something like this: ``` Started GET "/api/v1/person?ids%5B%5D=1&ids%5B%5D=2&ids%5B%5D=3" Processing by Api::V1::PersonsController#index as HTML Parameters: { "ids" => ["1", "2", "3"] } ``` This method returns a promise, which is resolved with an [`AdapterPopulatedRecordArray`](https://emberjs.com/api/data/classes/DS.AdapterPopulatedRecordArray.html) once the server returns. @since 1.13.0 @method query @param {String} modelName @param {any} query an opaque query to be used by the adapter @return {Promise} promise */ query: function (modelName, query) { (false && _ember.default.assert('You need to pass a model name to the store\'s query method', isPresent(modelName))); (false && _ember.default.assert('You need to pass a query hash to the store\'s query method', query)); (false && _ember.default.assert('Passing classes to store methods has been removed. Please pass a dasherized string instead of ' + modelName, typeof modelName === 'string')); var normalizedModelName = (0, _normalizeModelName.default)(modelName); return this._query(normalizedModelName, query); }, _query: function (modelName, query, array) { (false && _ember.default.assert('You need to pass a model name to the store\'s query method', isPresent(modelName))); (false && _ember.default.assert('You need to pass a query hash to the store\'s query method', query)); (false && _ember.default.assert('Passing classes to store methods has been removed. Please pass a dasherized string instead of ' + modelName, typeof modelName === 'string')); var adapter = this.adapterFor(modelName); (false && _ember.default.assert('You tried to load a query but you have no adapter (for ' + modelName + ')', adapter)); (false && _ember.default.assert('You tried to load a query but your adapter does not implement \'query\'', typeof adapter.query === 'function')); var pA = (0, _promiseProxies.promiseArray)((0, _finders._query)(adapter, this, modelName, query, array)); return pA; }, /** This method makes a request for one record, where the `id` is not known beforehand (if the `id` is known, use [`findRecord`](#method_findRecord) instead). This method can be used when it is certain that the server will return a single object for the primary data. Each time this method is called a new request is made through the adapter. Let's assume our API provides an endpoint for the currently logged in user via: ``` // GET /api/current_user { user: { id: 1234, username: 'admin' } } ``` Since the specific `id` of the `user` is not known beforehand, we can use `queryRecord` to get the user: ```javascript store.queryRecord('user', {}).then(function(user) { let username = user.get('username'); console.log(`Currently logged in as ${username}`); }); ``` The request is made through the adapters' `queryRecord`: ```app/adapters/user.js import DS from 'ember-data'; export default DS.Adapter.extend({ queryRecord(modelName, query) { return Ember.$.getJSON('/api/current_user'); } }); ``` Note: the primary use case for `store.queryRecord` is when a single record is queried and the `id` is not known beforehand. In all other cases `store.query` and using the first item of the array is likely the preferred way: ``` // GET /users?username=unique { data: [{ id: 1234, type: 'user', attributes: { username: "unique" } }] } ``` ```javascript store.query('user', { username: 'unique' }).then(function(users) { return users.get('firstObject'); }).then(function(user) { let id = user.get('id'); }); ``` This method returns a promise, which resolves with the found record. If the adapter returns no data for the primary data of the payload, then `queryRecord` resolves with `null`: ``` // GET /users?username=unique { data: null } ``` ```javascript store.queryRecord('user', { username: 'unique' }).then(function(user) { console.log(user); // null }); ``` @since 1.13.0 @method queryRecord @param {String} modelName @param {any} query an opaque query to be used by the adapter @return {Promise} promise which resolves with the found record or `null` */ queryRecord: function (modelName, query) { (false && _ember.default.assert('You need to pass a model name to the store\'s queryRecord method', isPresent(modelName))); (false && _ember.default.assert('You need to pass a query hash to the store\'s queryRecord method', query)); (false && _ember.default.assert('Passing classes to store methods has been removed. Please pass a dasherized string instead of ' + modelName, typeof modelName === 'string')); var normalizedModelName = (0, _normalizeModelName.default)(modelName); var adapter = this.adapterFor(normalizedModelName); (false && _ember.default.assert('You tried to make a query but you have no adapter (for ' + normalizedModelName + ')', adapter)); (false && _ember.default.assert('You tried to make a query but your adapter does not implement \'queryRecord\'', typeof adapter.queryRecord === 'function')); return (0, _promiseProxies.promiseObject)((0, _finders._queryRecord)(adapter, this, modelName, query).then(function (internalModel) { // the promise returned by store.queryRecord is expected to resolve with // an instance of DS.Model if (internalModel) { return internalModel.getRecord(); } return null; })); }, /** `findAll` asks the adapter's `findAll` method to find the records for the given type, and returns a promise which will resolve with all records of this type present in the store, even if the adapter only returns a subset of them. ```app/routes/authors.js import Ember from 'ember'; export default Ember.Route.extend({ model(params) { return this.store.findAll('author'); } }); ``` _When_ the returned promise resolves depends on the reload behavior, configured via the passed `options` hash and the result of the adapter's `shouldReloadAll` method. ### Reloading If `{ reload: true }` is passed or `adapter.shouldReloadAll` evaluates to `true`, then the returned promise resolves once the adapter returns data, regardless if there are already records in the store: ```js store.push({ data: { id: 'first', type: 'author' } }); // adapter#findAll resolves with // [ // { // id: 'second', // type: 'author' // } // ] store.findAll('author', { reload: true }).then(function(authors) { authors.getEach('id'); // ['first', 'second'] }); ``` If no reload is indicated via the abovementioned ways, then the promise immediately resolves with all the records currently loaded in the store. ### Background Reloading Optionally, if `adapter.shouldBackgroundReloadAll` evaluates to `true`, then a background reload is started. Once this resolves, the array with which the promise resolves, is updated automatically so it contains all the records in the store: ```js // app/adapters/application.js export default DS.Adapter.extend({ shouldReloadAll(store, snapshotsArray) { return false; }, shouldBackgroundReloadAll(store, snapshotsArray) { return true; } }); // ... store.push({ data: { id: 'first', type: 'author' } }); let allAuthors; store.findAll('author').then(function(authors) { authors.getEach('id'); // ['first'] allAuthors = authors; }); // later, once adapter#findAll resolved with // [ // { // id: 'second', // type: 'author' // } // ] allAuthors.getEach('id'); // ['first', 'second'] ``` If you would like to force or prevent background reloading, you can set a boolean value for `backgroundReload` in the options object for `findAll`. ```app/routes/post/edit.js import Ember from 'ember'; export default Ember.Route.extend({ model() { return this.store.findAll('post', { backgroundReload: false }); } }); ``` If you pass an object on the `adapterOptions` property of the options argument it will be passed to you adapter via the `snapshotRecordArray` ```app/routes/posts.js import Ember from 'ember'; export default Ember.Route.extend({ model(params) { return this.store.findAll('post', { adapterOptions: { subscribe: false } }); } }); ``` ```app/adapters/post.js import MyCustomAdapter from './custom-adapter'; export default MyCustomAdapter.extend({ findAll(store, type, sinceToken, snapshotRecordArray) { if (snapshotRecordArray.adapterOptions.subscribe) { // ... } // ... } }); ``` See [peekAll](#method_peekAll) to get an array of current records in the store, without waiting until a reload is finished. ### Retrieving Related Model Records If you use an adapter such as Ember's default [`JSONAPIAdapter`](https://emberjs.com/api/data/classes/DS.JSONAPIAdapter.html) that supports the [JSON API specification](http://jsonapi.org/) and if your server endpoint supports the use of an ['include' query parameter](http://jsonapi.org/format/#fetching-includes), you can use `findAll()` to automatically retrieve additional records related to those requested by supplying an `include` parameter in the `options` object. For example, given a `post` model that has a `hasMany` relationship with a `comment` model, when we retrieve all of the post records we can have the server also return all of the posts' comments in the same request: ```app/routes/posts.js import Ember from 'ember'; export default Ember.Route.extend({ model() { return this.store.findAll('post', { include: 'comments' }); } }); ``` Multiple relationships can be requested using an `include` parameter consisting of a comma-separated list (without white-space) while nested relationships can be specified using a dot-separated sequence of relationship names. So to request both the posts' comments and the authors of those comments the request would look like this: ```app/routes/posts.js import Ember from 'ember'; export default Ember.Route.extend({ model() { return this.store.findAll('post', { include: 'comments,comments.author' }); } }); ``` See [query](#method_query) to only get a subset of records from the server. @since 1.13.0 @method findAll @param {String} modelName @param {Object} options @return {Promise} promise */ findAll: function (modelName, options) { (false && _ember.default.assert('You need to pass a model name to the store\'s findAll method', isPresent(modelName))); (false && _ember.default.assert('Passing classes to store methods has been removed. Please pass a dasherized string instead of ' + modelName, typeof modelName === 'string')); var normalizedModelName = (0, _normalizeModelName.default)(modelName); var fetch = this._fetchAll(normalizedModelName, this.peekAll(normalizedModelName), options); return fetch; }, /** @method _fetchAll @private @param {DS.Model} modelName @param {DS.RecordArray} array @return {Promise} promise */ _fetchAll: function (modelName, array) { var options = arguments.length > 2 && arguments[2] !== undefined ? arguments[2] : {}; var adapter = this.adapterFor(modelName); var sinceToken = this._internalModelsFor(modelName).metadata.since; (false && _ember.default.assert('You tried to load all records but you have no adapter (for ' + modelName + ')', adapter)); (false && _ember.default.assert('You tried to load all records but your adapter does not implement \'findAll\'', typeof adapter.findAll === 'function')); if (options.reload) { set(array, 'isUpdating', true); return (0, _promiseProxies.promiseArray)((0, _finders._findAll)(adapter, this, modelName, sinceToken, options)); } var snapshotArray = array._createSnapshot(options); if (adapter.shouldReloadAll(this, snapshotArray)) { set(array, 'isUpdating', true); return (0, _promiseProxies.promiseArray)((0, _finders._findAll)(adapter, this, modelName, sinceToken, options)); } if (options.backgroundReload === false) { return (0, _promiseProxies.promiseArray)(Promise.resolve(array)); } if (options.backgroundReload || adapter.shouldBackgroundReloadAll(this, snapshotArray)) { set(array, 'isUpdating', true); (0, _finders._findAll)(adapter, this, modelName, sinceToken, options); } return (0, _promiseProxies.promiseArray)(Promise.resolve(array)); }, /** @method _didUpdateAll @param {String} modelName @private */ _didUpdateAll: function (modelName) { this.recordArrayManager._didUpdateAll(modelName); }, didUpdateAll: function (modelName) { (false && !(false) && _ember.default.deprecate('didUpdateAll was documented as private and will be removed in the next version of Ember Data.', false, { id: 'ember-data.didUpdateAll', until: '2.17.0' })); return this._didUpdateAll(modelName); }, /** This method returns a filtered array that contains all of the known records for a given type in the store. Note that because it's just a filter, the result will contain any locally created records of the type, however, it will not make a request to the backend to retrieve additional records. If you would like to request all the records from the backend please use [store.findAll](#method_findAll). Also note that multiple calls to `peekAll` for a given type will always return the same `RecordArray`. Example ```javascript let localPosts = store.peekAll('post'); ``` @since 1.13.0 @method peekAll @param {String} modelName @return {DS.RecordArray} */ peekAll: function (modelName) { (false && _ember.default.assert('You need to pass a model name to the store\'s peekAll method', isPresent(modelName))); (false && _ember.default.assert('Passing classes to store methods has been removed. Please pass a dasherized string instead of ' + modelName, typeof modelName === 'string')); var normalizedModelName = (0, _normalizeModelName.default)(modelName); return this.recordArrayManager.liveRecordArrayFor(normalizedModelName); }, /** This method unloads all records in the store. It schedules unloading to happen during the next run loop. Optionally you can pass a type which unload all records for a given type. ```javascript store.unloadAll(); store.unloadAll('post'); ``` @method unloadAll @param {String} modelName */ unloadAll: function (modelName) { (false && _ember.default.assert('Passing classes to store methods has been removed. Please pass a dasherized string instead of ' + modelName, !modelName || typeof modelName === 'string')); if (arguments.length === 0) { this._identityMap.clear(); } else { var normalizedModelName = (0, _normalizeModelName.default)(modelName); this._internalModelsFor(normalizedModelName).clear(); } }, /** Takes a type and filter function, and returns a live RecordArray that remains up to date as new records are loaded into the store or created locally. The filter function takes a materialized record, and returns true if the record should be included in the filter and false if it should not. Example ```javascript store.filter('post', function(post) { return post.get('unread'); }); ``` The filter function is called once on all records for the type when it is created, and then once on each newly loaded or created record. If any of a record's properties change, or if it changes state, the filter function will be invoked again to determine whether it should still be in the array. Optionally you can pass a query, which is the equivalent of calling [query](#method_query) with that same query, to fetch additional records from the server. The results returned by the server could then appear in the filter if they match the filter function. The query itself is not used to filter records, it's only sent to your server for you to be able to do server-side filtering. The filter function will be applied on the returned results regardless. Example ```javascript store.filter('post', { unread: true }, function(post) { return post.get('unread'); }).then(function(unreadPosts) { unreadPosts.get('length'); // 5 let unreadPost = unreadPosts.objectAt(0); unreadPost.set('unread', false); unreadPosts.get('length'); // 4 }); ``` @method filter @private @param {String} modelName @param {Object} query optional query @param {Function} filter @return {DS.PromiseArray} @deprecated */ filter: function (modelName, query, filter) { (false && _ember.default.assert('You need to pass a model name to the store\'s filter method', isPresent(modelName))); (false && _ember.default.assert('Passing classes to store methods has been removed. Please pass a dasherized string instead of ' + modelName, typeof modelName === 'string')); if (!ENV.ENABLE_DS_FILTER) { (false && _ember.default.assert('The filter API has been moved to a plugin. To enable store.filter using an environment flag, or to use an alternative, you can visit the ember-data-filter addon page. https://github.com/ember-data/ember-data-filter', false)); } var promise = void 0; var length = arguments.length; var array = void 0; var hasQuery = length === 3; var normalizedModelName = (0, _normalizeModelName.default)(modelName); // allow an optional server query if (hasQuery) { promise = this.query(normalizedModelName, query); } else if (arguments.length === 2) { filter = query; } if (hasQuery) { array = this.recordArrayManager.createFilteredRecordArray(normalizedModelName, filter, query); } else { array = this.recordArrayManager.createFilteredRecordArray(normalizedModelName, filter); } promise = promise || Promise.resolve(array); return (0, _promiseProxies.promiseArray)(promise.then(function () { return array; }, null, 'DS: Store#filter of ' + normalizedModelName)); }, /** This method has been deprecated and is an alias for store.hasRecordForId, which should be used instead. @deprecated @method recordIsLoaded @param {String} modelName @param {string} id @return {boolean} */ recordIsLoaded: function (modelName, id) { (false && !(false) && _ember.default.deprecate('Use of recordIsLoaded is deprecated, use hasRecordForId instead.', false, { id: 'ds.store.recordIsLoaded', until: '3.0' })); return this.hasRecordForId(modelName, id); }, // .............. // . PERSISTING . // .............. /** This method is called by `record.save`, and gets passed a resolver for the promise that `record.save` returns. It schedules saving to happen at the end of the run loop. @method scheduleSave @private @param {InternalModel} internalModel @param {Resolver} resolver @param {Object} options */ scheduleSave: function (internalModel, resolver, options) { var snapshot = internalModel.createSnapshot(options); internalModel.flushChangedAttributes(); internalModel.adapterWillCommit(); this._pendingSave.push({ snapshot: snapshot, resolver: resolver }); emberRun.once(this, this.flushPendingSave); }, /** This method is called at the end of the run loop, and flushes any records passed into `scheduleSave` @method flushPendingSave @private */ flushPendingSave: function () { var pending = this._pendingSave.slice(); this._pendingSave = []; for (var i = 0, j = pending.length; i < j; i++) { var pendingItem = pending[i]; var snapshot = pendingItem.snapshot; var resolver = pendingItem.resolver; var internalModel = snapshot._internalModel; var adapter = this.adapterFor(internalModel.modelName); var operation = void 0; if (internalModel.currentState.stateName === 'root.deleted.saved') { resolver.resolve(); continue; } else if (internalModel.isNew()) { operation = 'createRecord'; } else if (internalModel.isDeleted()) { operation = 'deleteRecord'; } else { operation = 'updateRecord'; } resolver.resolve(_commit(adapter, this, operation, snapshot)); } }, /** This method is called once the promise returned by an adapter's `createRecord`, `updateRecord` or `deleteRecord` is resolved. If the data provides a server-generated ID, it will update the record and the store's indexes. @method didSaveRecord @private @param {InternalModel} internalModel the in-flight internal model @param {Object} data optional data (see above) */ didSaveRecord: function (internalModel, dataArg) { var data = void 0; if (dataArg) { data = dataArg.data; } if (data) { // normalize relationship IDs into records this.updateId(internalModel, data); this._setupRelationshipsForModel(internalModel, data); } else { (false && _ember.default.assert('Your ' + internalModel.modelName + ' record was saved to the server, but the response does not have an id and no id has been set client side. Records must have ids. Please update the server response to provide an id in the response or generate the id on the client side either before saving the record or while normalizing the response.', internalModel.id)); } //We first make sure the primary data has been updated //TODO try to move notification to the user to the end of the runloop internalModel.adapterDidCommit(data); }, /** This method is called once the promise returned by an adapter's `createRecord`, `updateRecord` or `deleteRecord` is rejected with a `DS.InvalidError`. @method recordWasInvalid @private @param {InternalModel} internalModel @param {Object} errors */ recordWasInvalid: function (internalModel, errors) { internalModel.adapterDidInvalidate(errors); }, /** This method is called once the promise returned by an adapter's `createRecord`, `updateRecord` or `deleteRecord` is rejected (with anything other than a `DS.InvalidError`). @method recordWasError @private @param {InternalModel} internalModel @param {Error} error */ recordWasError: function (internalModel, error) { internalModel.adapterDidError(error); }, /** When an adapter's `createRecord`, `updateRecord` or `deleteRecord` resolves with data, this method extracts the ID from the supplied data. @method updateId @private @param {InternalModel} internalModel @param {Object} data */ updateId: function (internalModel, data) { var oldId = internalModel.id; var modelName = internalModel.modelName; var id = (0, _coerceId.default)(data.id); // ID absolutely can't be missing if the oldID is empty (missing Id in response for a new record) (false && _ember.default.assert('\'' + modelName + '\' was saved to the server, but the response does not have an id and your record does not either.', !(id === null && oldId === null))); // ID absolutely can't be different than oldID if oldID is not null (false && _ember.default.assert('\'' + modelName + ':' + oldId + '\' was saved to the server, but the response returned the new id \'' + id + '\'. The store cannot assign a new id to a record that already has an id.', !(oldId !== null && id !== oldId))); // ID can be null if oldID is not null (altered ID in response for a record) // however, this is more than likely a developer error. if (oldId !== null && id === null) { (false && _ember.default.warn('Your ' + modelName + ' record was saved to the server, but the response does not have an id.', !(oldId !== null && id === null))); return; } var existingInternalModel = this._existingInternalModelForId(modelName, id); (false && _ember.default.assert('\'' + modelName + '\' was saved to the server, but the response returned the new id \'' + id + '\', which has already been used with another record.\'', isNone(existingInternalModel) || existingInternalModel === internalModel)); this._internalModelsFor(internalModel.modelName).set(id, internalModel); internalModel.setId(id); }, /** Returns a map of IDs to client IDs for a given modelName. @method _internalModelsFor @private @param {String} modelName @return {Object} recordMap */ _internalModelsFor: function (modelName) { return this._identityMap.retrieve(modelName); }, // ................ // . LOADING DATA . // ................ /** This internal method is used by `push`. @method _load @private @param {Object} data */ _load: function (data) { var internalModel = this._internalModelForId(data.type, data.id); var isUpdate = internalModel.currentState.isEmpty === false; internalModel.setupData(data); if (isUpdate) { this.recordArrayManager.recordDidChange(internalModel); } else { this.recordArrayManager.recordWasLoaded(internalModel); } return internalModel; }, /* In case someone defined a relationship to a mixin, for example: ``` let Comment = DS.Model.extend({ owner: belongsTo('commentable'. { polymorphic: true }) }); let Commentable = Ember.Mixin.create({ comments: hasMany('comment') }); ``` we want to look up a Commentable class which has all the necessary relationship metadata. Thus, we look up the mixin and create a mock DS.Model, so we can access the relationship CPs of the mixin (`comments`) in this case @private */ _modelForMixin: function (normalizedModelName) { // container.registry = 2.1 // container._registry = 1.11 - 2.0 // container = < 1.11 var owner = (0, _utils.getOwner)(this); var mixin = void 0; if (owner.factoryFor) { var MaybeMixin = owner.factoryFor('mixin:' + normalizedModelName); mixin = MaybeMixin && MaybeMixin.class; } else { mixin = owner._lookupFactory('mixin:' + normalizedModelName); } if (mixin) { var ModelForMixin = _model.default.extend(mixin); ModelForMixin.reopenClass({ __isMixin: true, __mixin: mixin }); //Cache the class as a model owner.register('model:' + normalizedModelName, ModelForMixin); } return this.modelFactoryFor(normalizedModelName); }, /** Returns the model class for the particular `modelName`. The class of a model might be useful if you want to get a list of all the relationship names of the model, see [`relationshipNames`](https://emberjs.com/api/data/classes/DS.Model.html#property_relationshipNames) for example. @method modelFor @param {String} modelName @return {DS.Model} */ modelFor: function (modelName) { (false && _ember.default.assert('You need to pass a model name to the store\'s modelFor method', isPresent(modelName))); (false && _ember.default.assert('Passing classes to store methods has been removed. Please pass a dasherized string instead of ' + modelName, typeof modelName === 'string')); var normalizedModelName = (0, _normalizeModelName.default)(modelName); return this._modelFor(normalizedModelName); }, /* @private */ _modelFor: function (modelName) { var maybeFactory = this._modelFactoryFor(modelName); // for factorFor factory/class split return maybeFactory.class ? maybeFactory.class : maybeFactory; }, _modelFactoryFor: function (modelName) { var factory = this._modelFactoryCache[modelName]; if (!factory) { factory = this.modelFactoryFor(modelName); if (!factory) { //Support looking up mixins as base types for polymorphic relationships factory = this._modelForMixin(modelName); } if (!factory) { throw new EmberError('No model was found for \'' + modelName + '\''); } // interopt with the future var klass = (0, _utils.getOwner)(this).factoryFor ? factory.class : factory; (false && _ember.default.assert('\'' + inspect(klass) + '\' does not appear to be an ember-data model', klass.isModel)); // TODO: deprecate this klass.modelName = klass.modelName || modelName; this._modelFactoryCache[modelName] = factory; } return factory; }, /* @private */ modelFactoryFor: function (modelName) { (false && _ember.default.assert('You need to pass a model name to the store\'s modelFactoryFor method', isPresent(modelName))); (false && _ember.default.assert('Passing classes to store methods has been removed. Please pass a dasherized string instead of ' + modelName, typeof modelName === 'string')); var normalizedModelName = (0, _normalizeModelName.default)(modelName); var owner = (0, _utils.getOwner)(this); if (owner.factoryFor) { return owner.factoryFor('model:' + normalizedModelName); } else { return owner._lookupFactory('model:' + normalizedModelName); } }, /** Push some data for a given type into the store. This method expects normalized [JSON API](http://jsonapi.org/) document. This means you have to follow [JSON API specification](http://jsonapi.org/format/) with few minor adjustments: - record's `type` should always be in singular, dasherized form - members (properties) should be camelCased [Your primary data should be wrapped inside `data` property](http://jsonapi.org/format/#document-top-level): ```js store.push({ data: { // primary data for single record of type `Person` id: '1', type: 'person', attributes: { firstName: 'Daniel', lastName: 'Kmak' } } }); ``` [Demo.](http://ember-twiddle.com/fb99f18cd3b4d3e2a4c7) `data` property can also hold an array (of records): ```js store.push({ data: [ // an array of records { id: '1', type: 'person', attributes: { firstName: 'Daniel', lastName: 'Kmak' } }, { id: '2', type: 'person', attributes: { firstName: 'Tom', lastName: 'Dale' } } ] }); ``` [Demo.](http://ember-twiddle.com/69cdbeaa3702159dc355) There are some typical properties for `JSONAPI` payload: * `id` - mandatory, unique record's key * `type` - mandatory string which matches `model`'s dasherized name in singular form * `attributes` - object which holds data for record attributes - `DS.attr`'s declared in model * `relationships` - object which must contain any of the following properties under each relationships' respective key (example path is `relationships.achievements.data`): - [`links`](http://jsonapi.org/format/#document-links) - [`data`](http://jsonapi.org/format/#document-resource-object-linkage) - place for primary data - [`meta`](http://jsonapi.org/format/#document-meta) - object which contains meta-information about relationship For this model: ```app/models/person.js import DS from 'ember-data'; export default DS.Model.extend({ firstName: DS.attr('string'), lastName: DS.attr('string'), children: DS.hasMany('person') }); ``` To represent the children as IDs: ```js { data: { id: '1', type: 'person', attributes: { firstName: 'Tom', lastName: 'Dale' }, relationships: { children: { data: [ { id: '2', type: 'person' }, { id: '3', type: 'person' }, { id: '4', type: 'person' } ] } } } } ``` [Demo.](http://ember-twiddle.com/343e1735e034091f5bde) To represent the children relationship as a URL: ```js { data: { id: '1', type: 'person', attributes: { firstName: 'Tom', lastName: 'Dale' }, relationships: { children: { links: { related: '/people/1/children' } } } } } ``` If you're streaming data or implementing an adapter, make sure that you have converted the incoming data into this form. The store's [normalize](#method_normalize) method is a convenience helper for converting a json payload into the form Ember Data expects. ```js store.push(store.normalize('person', data)); ``` This method can be used both to push in brand new records, as well as to update existing records. @method push @param {Object} data @return {DS.Model|Array} the record(s) that was created or updated. */ push: function (data) { var pushed = this._push(data); if (Array.isArray(pushed)) { var records = pushed.map(function (internalModel) { return internalModel.getRecord(); }); return records; } if (pushed === null) { return null; } var record = pushed.getRecord(); return record; }, /* Push some data in the form of a json-api document into the store, without creating materialized records. @method _push @private @param {Object} jsonApiDoc @return {DS.InternalModel|Array<DS.InternalModel>} pushed InternalModel(s) */ _push: function (jsonApiDoc) { var _this = this; var internalModelOrModels = this._backburner.join(function () { var included = jsonApiDoc.included; var i = void 0, length = void 0; if (included) { for (i = 0, length = included.length; i < length; i++) { _this._pushInternalModel(included[i]); } } if (Array.isArray(jsonApiDoc.data)) { length = jsonApiDoc.data.length; var internalModels = new Array(length); for (i = 0; i < length; i++) { internalModels[i] = _this._pushInternalModel(jsonApiDoc.data[i]); } return internalModels; } if (jsonApiDoc.data === null) { return null; } (false && _ember.default.assert('Expected an object in the \'data\' property in a call to \'push\' for ' + jsonApiDoc.type + ', but was ' + typeOf(jsonApiDoc.data), typeOf(jsonApiDoc.data) === 'object')); return _this._pushInternalModel(jsonApiDoc.data); }); return internalModelOrModels; }, _hasModelFor: function (modelName) { var owner = (0, _utils.getOwner)(this); modelName = (0, _normalizeModelName.default)(modelName); if (owner.factoryFor) { return !!owner.factoryFor('model:' + modelName); } else { return !!owner._lookupFactory('model:' + modelName); } }, _pushInternalModel: function (data) { var modelName = data.type; (false && _ember.default.assert('You must include an \'id\' for ' + modelName + ' in an object passed to \'push\'', data.id !== null && data.id !== undefined && data.id !== '')); (false && _ember.default.assert('You tried to push data with a type \'' + modelName + '\' but no model could be found with that name.', this._hasModelFor(modelName))); if (false) { // If ENV.DS_WARN_ON_UNKNOWN_KEYS is set to true and the payload // contains unknown attributes or relationships, log a warning. if (ENV.DS_WARN_ON_UNKNOWN_KEYS) { var modelClass = this._modelFor(modelName); // Check unknown attributes var unknownAttributes = Object.keys(data.attributes || {}).filter(function (key) { return !get(modelClass, 'fields').has(key); }); var unknownAttributesMessage = 'The payload for \'' + modelName + '\' contains these unknown attributes: ' + unknownAttributes + '. Make sure they\'ve been defined in your model.'; (false && _ember.default.warn(unknownAttributesMessage, unknownAttributes.length === 0, { id: 'ds.store.unknown-keys-in-payload' })); // Check unknown relationships var unknownRelationships = Object.keys(data.relationships || {}).filter(function (key) { return !get(modelClass, 'fields').has(key); }); var unknownRelationshipsMessage = 'The payload for \'' + modelName + '\' contains these unknown relationships: ' + unknownRelationships + '. Make sure they\'ve been defined in your model.'; (false && _ember.default.warn(unknownRelationshipsMessage, unknownRelationships.length === 0, { id: 'ds.store.unknown-keys-in-payload' })); } } // Actually load the record into the store. var internalModel = this._load(data); this._setupRelationshipsForModel(internalModel, data); return internalModel; }, _setupRelationshipsForModel: function (internalModel, data) { if (data.relationships === undefined) { return; } if (this._pushedInternalModels.push(internalModel, data) !== 2) { return; } this._backburner.schedule('normalizeRelationships', this, this._setupRelationships); }, _setupRelationships: function () { var pushed = this._pushedInternalModels; // Cache the inverse maps for each modelClass that we visit during this // payload push. In the common case where we are pushing many more // instances than types we want to minimize the cost of looking up the // inverse map and the overhead of Ember.get adds up. var modelNameToInverseMap = void 0; for (var i = 0, l = pushed.length; i < l; i += 2) { modelNameToInverseMap = modelNameToInverseMap || Object.create(null); // This will convert relationships specified as IDs into DS.Model instances // (possibly unloaded) and also create the data structures used to track // relationships. var internalModel = pushed[i]; var data = pushed[i + 1]; setupRelationships(this, internalModel, data, modelNameToInverseMap); } pushed.length = 0; }, /** Push some raw data into the store. This method can be used both to push in brand new records, as well as to update existing records. You can push in more than one type of object at once. All objects should be in the format expected by the serializer. ```app/serializers/application.js import DS from 'ember-data'; export default DS.ActiveModelSerializer; ``` ```js let pushData = { posts: [ { id: 1, post_title: "Great post", comment_ids: [2] } ], comments: [ { id: 2, comment_body: "Insightful comment" } ] } store.pushPayload(pushData); ``` By default, the data will be deserialized using a default serializer (the application serializer if it exists). Alternatively, `pushPayload` will accept a model type which will determine which serializer will process the payload. ```app/serializers/application.js import DS from 'ember-data'; export default DS.ActiveModelSerializer; ``` ```app/serializers/post.js import DS from 'ember-data'; export default DS.JSONSerializer; ``` ```js store.pushPayload('comment', pushData); // Will use the application serializer store.pushPayload('post', pushData); // Will use the post serializer ``` @method pushPayload @param {String} modelName Optionally, a model type used to determine which serializer will be used @param {Object} inputPayload */ pushPayload: function (modelName, inputPayload) { var serializer = void 0; var payload = void 0; if (!inputPayload) { payload = modelName; serializer = defaultSerializer(this); (false && _ember.default.assert('You cannot use \'store#pushPayload\' without a modelName unless your default serializer defines \'pushPayload\'', typeof serializer.pushPayload === 'function')); } else { payload = inputPayload; (false && _ember.default.assert('Passing classes to store methods has been removed. Please pass a dasherized string instead of ' + modelName, typeof modelName === 'string')); var normalizedModelName = (0, _normalizeModelName.default)(modelName); serializer = this.serializerFor(normalizedModelName); } if ((0, _features.default)('ds-pushpayload-return')) { return serializer.pushPayload(this, payload); } else { serializer.pushPayload(this, payload); } }, /** `normalize` converts a json payload into the normalized form that [push](#method_push) expects. Example ```js socket.on('message', function(message) { let modelName = message.model; let data = message.data; store.push(store.normalize(modelName, data)); }); ``` @method normalize @param {String} modelName The name of the model type for this payload @param {Object} payload @return {Object} The normalized payload */ normalize: function (modelName, payload) { (false && _ember.default.assert('You need to pass a model name to the store\'s normalize method', isPresent(modelName))); (false && _ember.default.assert('Passing classes to store methods has been removed. Please pass a dasherized string instead of ' + inspect(modelName), typeof modelName === 'string')); var normalizedModelName = (0, _normalizeModelName.default)(modelName); var serializer = this.serializerFor(normalizedModelName); var model = this._modelFor(normalizedModelName); return serializer.normalize(model, payload); }, /** Build a brand new record for a given type, ID, and initial data. @method _buildInternalModel @private @param {String} modelName @param {String} id @param {Object} data @return {InternalModel} internal model */ _buildInternalModel: function (modelName, id, data) { (false && _ember.default.assert('You can no longer pass a modelClass as the first argument to store._buildInternalModel. Pass modelName instead.', typeof modelName === 'string')); var existingInternalModel = this._existingInternalModelForId(modelName, id); (false && _ember.default.assert('The id ' + id + ' has already been used with another record for modelClass \'' + modelName + '\'.', !existingInternalModel)); // lookupFactory should really return an object that creates // instances with the injections applied var internalModel = new _internalModel5.default(modelName, id, this, data); this._internalModelsFor(modelName).add(internalModel, id); return internalModel; }, _existingInternalModelForId: function (modelName, id) { var internalModel = this._internalModelsFor(modelName).get(id); if (internalModel && internalModel.hasScheduledDestroy()) { // unloadRecord is async, if one attempts to unload + then sync create, // we must ensure the unload is complete before starting the create internalModel.destroySync(); internalModel = null; } return internalModel; }, buildInternalModel: function (modelName, id, data) { (false && !(false) && _ember.default.deprecate('buildInternalModel was documented as private and will be removed in the next version of Ember Data.', false, { id: 'ember-data.buildInternalModel', until: '2.17.0' })); return this._buildInternalModel(modelName, id, data); }, //Called by the state machine to notify the store that the record is ready to be interacted with recordWasLoaded: function (record) { this.recordArrayManager.recordWasLoaded(record); }, // ............... // . DESTRUCTION . // ............... /** When a record is destroyed, this un-indexes it and removes it from any record arrays so it can be GCed. @method _removeFromIdMap @private @param {InternalModel} internalModel */ _removeFromIdMap: function (internalModel) { var recordMap = this._internalModelsFor(internalModel.modelName); var id = internalModel.id; recordMap.remove(internalModel, id); }, // ...................... // . PER-TYPE ADAPTERS // ...................... /** Returns an instance of the adapter for a given type. For example, `adapterFor('person')` will return an instance of `App.PersonAdapter`. If no `App.PersonAdapter` is found, this method will look for an `App.ApplicationAdapter` (the default adapter for your entire application). If no `App.ApplicationAdapter` is found, it will return the value of the `defaultAdapter`. @method adapterFor @public @param {String} modelName @return DS.Adapter */ adapterFor: function (modelName) { (false && _ember.default.assert('You need to pass a model name to the store\'s adapterFor method', isPresent(modelName))); (false && _ember.default.assert('Passing classes to store.adapterFor has been removed. Please pass a dasherized string instead of ' + modelName, typeof modelName === 'string')); var normalizedModelName = (0, _normalizeModelName.default)(modelName); return this._instanceCache.get('adapter', normalizedModelName); }, // .............................. // . RECORD CHANGE NOTIFICATION . // .............................. /** Returns an instance of the serializer for a given type. For example, `serializerFor('person')` will return an instance of `App.PersonSerializer`. If no `App.PersonSerializer` is found, this method will look for an `App.ApplicationSerializer` (the default serializer for your entire application). if no `App.ApplicationSerializer` is found, it will attempt to get the `defaultSerializer` from the `PersonAdapter` (`adapterFor('person')`). If a serializer cannot be found on the adapter, it will fall back to an instance of `DS.JSONSerializer`. @method serializerFor @public @param {String} modelName the record to serialize @return {DS.Serializer} */ serializerFor: function (modelName) { (false && _ember.default.assert('You need to pass a model name to the store\'s serializerFor method', isPresent(modelName))); (false && _ember.default.assert('Passing classes to store.serializerFor has been removed. Please pass a dasherized string instead of ' + modelName, typeof modelName === 'string')); var normalizedModelName = (0, _normalizeModelName.default)(modelName); return this._instanceCache.get('serializer', normalizedModelName); }, lookupAdapter: function (name) { (false && !(false) && _ember.default.deprecate('Use of lookupAdapter is deprecated, use adapterFor instead.', false, { id: 'ds.store.lookupAdapter', until: '3.0' })); return this.adapterFor(name); }, lookupSerializer: function (name) { (false && !(false) && _ember.default.deprecate('Use of lookupSerializer is deprecated, use serializerFor instead.', false, { id: 'ds.store.lookupSerializer', until: '3.0' })); return this.serializerFor(name); }, willDestroy: function () { this._super.apply(this, arguments); this._pushedInternalModels = null; this.recordArrayManager.destroy(); this._instanceCache.destroy(); this.unloadAll(); }, _updateRelationshipState: function (relationship) { var _this2 = this; if (this._updatedRelationships.push(relationship) !== 1) { return; } this._backburner.join(function () { _this2._backburner.schedule('syncRelationships', _this2, _this2._flushUpdatedRelationships); }); }, _flushUpdatedRelationships: function () { var updated = this._updatedRelationships; for (var i = 0, l = updated.length; i < l; i++) { updated[i].flushCanonical(); } updated.length = 0; }, _updateInternalModel: function (internalModel) { if (this._updatedInternalModels.push(internalModel) !== 1) { return; } emberRun.schedule('actions', this, this._flushUpdatedInternalModels); }, _flushUpdatedInternalModels: function () { var updated = this._updatedInternalModels; for (var i = 0, l = updated.length; i < l; i++) { updated[i]._triggerDeferredTriggers(); } updated.length = 0; }, _pushResourceIdentifier: function (relationship, resourceIdentifier) { if (isNone(resourceIdentifier)) { return; } (false && _ember.default.assert('A ' + relationship.internalModel.modelName + ' record was pushed into the store with the value of ' + relationship.key + ' being ' + inspect(resourceIdentifier) + ', but ' + relationship.key + ' is a belongsTo relationship so the value must not be an array. You should probably check your data payload or serializer.', !Array.isArray(resourceIdentifier))); //TODO:Better asserts return this._internalModelForId(resourceIdentifier.type, resourceIdentifier.id); }, _pushResourceIdentifiers: function (relationship, resourceIdentifiers) { if (isNone(resourceIdentifiers)) { return; } (false && _ember.default.assert('A ' + relationship.internalModel.modelName + ' record was pushed into the store with the value of ' + relationship.key + ' being \'' + inspect(resourceIdentifiers) + '\', but ' + relationship.key + ' is a hasMany relationship so the value must be an array. You should probably check your data payload or serializer.', Array.isArray(resourceIdentifiers))); var _internalModels = new Array(resourceIdentifiers.length); for (var i = 0; i < resourceIdentifiers.length; i++) { _internalModels[i] = this._pushResourceIdentifier(relationship, resourceIdentifiers[i]); } return _internalModels; } }); // Delegation to the adapter and promise management function defaultSerializer(store) { return store.serializerFor('application'); } function _commit(adapter, store, operation, snapshot) { var internalModel = snapshot._internalModel; var modelName = snapshot.modelName; var modelClass = store._modelFor(modelName); (false && _ember.default.assert('You tried to update a record but you have no adapter (for ' + modelName + ')', adapter)); (false && _ember.default.assert('You tried to update a record but your adapter (for ' + modelName + ') does not implement \'' + operation + '\'', typeof adapter[operation] === 'function')); var promise = adapter[operation](store, modelClass, snapshot); var serializer = (0, _serializers.serializerForAdapter)(store, adapter, modelName); var label = 'DS: Extract and notify about ' + operation + ' completion of ' + internalModel; (false && _ember.default.assert('Your adapter\'s \'' + operation + '\' method must return a value, but it returned \'undefined\'', promise !== undefined)); promise = Promise.resolve(promise, label); promise = (0, _common._guard)(promise, (0, _common._bind)(_common._objectIsAlive, store)); promise = (0, _common._guard)(promise, (0, _common._bind)(_common._objectIsAlive, internalModel)); return promise.then(function (adapterPayload) { /* Note to future spelunkers hoping to optimize. We rely on this `run` to create a run loop if needed that `store._push` and `store.didSaveRecord` will both share. We use `join` because it is often the case that we have an outer run loop available still from the first call to `store._push`; */ store._backburner.join(function () { var payload = void 0, data = void 0; if (adapterPayload) { payload = (0, _serializerResponse.normalizeResponseHelper)(serializer, store, modelClass, adapterPayload, snapshot.id, operation); if (payload.included) { store._push({ data: null, included: payload.included }); } data = payload.data; } store.didSaveRecord(internalModel, { data: data }); }); return internalModel; }, function (error) { if (error instanceof _errors.InvalidError) { var errors = serializer.extractErrors(store, modelClass, error, snapshot.id); store.recordWasInvalid(internalModel, errors); } else { store.recordWasError(internalModel, error); } throw error; }, label); } function isInverseRelationshipInitialized(store, internalModel, data, key, modelNameToInverseMap) { var relationshipData = data.relationships[key].data; if (!relationshipData) { // can't check inverse for eg { comments: { links: { related: URL }}} return false; } var inverseMap = modelNameToInverseMap[internalModel.modelName]; if (!inverseMap) { inverseMap = modelNameToInverseMap[internalModel.modelName] = get(internalModel.type, 'inverseMap'); } var inverseRelationshipMetadata = inverseMap[key]; if (inverseRelationshipMetadata === undefined) { inverseRelationshipMetadata = internalModel.type.inverseFor(key, store); } if (!inverseRelationshipMetadata) { return false; } var _inverseRelationshipM = inverseRelationshipMetadata, inverseRelationshipName = _inverseRelationshipM.name; if (Array.isArray(relationshipData)) { for (var i = 0; i < relationshipData.length; ++i) { var inverseInternalModel = store._internalModelsFor(relationshipData[i].type).get(relationshipData[i].id); if (inverseInternalModel && inverseInternalModel._relationships.has(inverseRelationshipName)) { return true; } } return false; } else { var _inverseInternalModel = store._internalModelsFor(relationshipData.type).get(relationshipData.id); return _inverseInternalModel && _inverseInternalModel._relationships.has(inverseRelationshipName); } } function setupRelationships(store, internalModel, data, modelNameToInverseMap) { Object.keys(data.relationships).forEach(function (relationshipName) { var relationships = internalModel._relationships; var relationshipRequiresNotification = relationships.has(relationshipName) || isInverseRelationshipInitialized(store, internalModel, data, relationshipName, modelNameToInverseMap); if (relationshipRequiresNotification) { var relationshipData = data.relationships[relationshipName]; relationships.get(relationshipName).push(relationshipData, false); } // in debug, assert payload validity eagerly if (false) { var relationshipMeta = get(internalModel.type, 'relationshipsByName').get(relationshipName); var _relationshipData = data.relationships[relationshipName]; if (!_relationshipData || !relationshipMeta) { return; } if (_relationshipData.links) { var isAsync = relationshipMeta.options && relationshipMeta.options.async !== false; (false && _ember.default.warn('You pushed a record of type \'' + internalModel.type.modelName + '\' with a relationship \'' + relationshipName + '\' configured as \'async: false\'. You\'ve included a link but no primary data, this may be an error in your payload.', isAsync || _relationshipData.data, { id: 'ds.store.push-link-for-sync-relationship' })); } else if (_relationshipData.data) { if (relationshipMeta.kind === 'belongsTo') { (false && _ember.default.assert('A ' + internalModel.type.modelName + ' record was pushed into the store with the value of ' + relationshipName + ' being ' + inspect(_relationshipData.data) + ', but ' + relationshipName + ' is a belongsTo relationship so the value must not be an array. You should probably check your data payload or serializer.', !Array.isArray(_relationshipData.data))); } else if (relationshipMeta.kind === 'hasMany') { (false && _ember.default.assert('A ' + internalModel.type.modelName + ' record was pushed into the store with the value of ' + relationshipName + ' being \'' + inspect(_relationshipData.data) + '\', but ' + relationshipName + ' is a hasMany relationship so the value must be an array. You should probably check your data payload or serializer.', Array.isArray(_relationshipData.data))); } } } }); } exports.Store = Store; exports.default = Store; }); define('ember-data/-private/system/store/common', ['exports', 'ember'], function (exports, _ember) { 'use strict'; exports.__esModule = true; exports._bind = _bind; exports._guard = _guard; exports._objectIsAlive = _objectIsAlive; var get = _ember.default.get; function _bind(fn) { for (var _len = arguments.length, args = Array(_len > 1 ? _len - 1 : 0), _key = 1; _key < _len; _key++) { args[_key - 1] = arguments[_key]; } return function () { return fn.apply(undefined, args); }; } function _guard(promise, test) { var guarded = promise['finally'](function () { if (!test()) { guarded._subscribers.length = 0; } }); return guarded; } function _objectIsAlive(object) { return !(get(object, "isDestroyed") || get(object, "isDestroying")); } }); define('ember-data/-private/system/store/container-instance-cache', ['exports', 'ember'], function (exports, _ember) { 'use strict'; exports.__esModule = true; function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } } var set = _ember.default.set; var ContainerInstanceCache = function () { function ContainerInstanceCache(owner, store) { this.isDestroying = false; this.isDestroyed = false; this._owner = owner; this._store = store; this._namespaces = { adapter: Object.create(null), serializer: Object.create(null) }; } ContainerInstanceCache.prototype.get = function get(namespace, preferredKey) { var cache = this._namespaces[namespace]; if (cache[preferredKey]) { return cache[preferredKey]; } var preferredLookupKey = namespace + ':' + preferredKey; var instance = this._instanceFor(preferredLookupKey) || this._findInstance(namespace, this._fallbacksFor(namespace, preferredKey)); if (instance) { cache[preferredKey] = instance; set(instance, 'store', this._store); } return cache[preferredKey]; }; ContainerInstanceCache.prototype._fallbacksFor = function _fallbacksFor(namespace, preferredKey) { if (namespace === 'adapter') { return ['application', this._store.get('adapter'), '-json-api']; } // serializer return ['application', this.get('adapter', preferredKey).get('defaultSerializer'), '-default']; }; ContainerInstanceCache.prototype._findInstance = function _findInstance(namespace, fallbacks) { var cache = this._namespaces[namespace]; for (var i = 0, length = fallbacks.length; i < length; i++) { var fallback = fallbacks[i]; if (cache[fallback]) { return cache[fallback]; } var lookupKey = namespace + ':' + fallback; var instance = this._instanceFor(lookupKey); if (instance) { cache[fallback] = instance; return instance; } } }; ContainerInstanceCache.prototype._instanceFor = function _instanceFor(key) { return this._owner.lookup(key); }; ContainerInstanceCache.prototype.destroyCache = function destroyCache(cache) { var cacheEntries = Object.keys(cache); for (var i = 0, length = cacheEntries.length; i < length; i++) { var cacheKey = cacheEntries[i]; var cacheEntry = cache[cacheKey]; if (cacheEntry) { cacheEntry.destroy(); } } }; ContainerInstanceCache.prototype.destroy = function destroy() { this.isDestroying = true; this.destroyCache(this._namespaces.adapter); this.destroyCache(this._namespaces.serializer); this.isDestroyed = true; }; ContainerInstanceCache.prototype.toString = function toString() { return 'ContainerInstanceCache'; }; return ContainerInstanceCache; }(); exports.default = ContainerInstanceCache; }); define('ember-data/-private/system/store/finders', ['exports', 'ember', 'ember-data/-private/system/store/common', 'ember-data/-private/system/store/serializer-response', 'ember-data/-private/system/store/serializers'], function (exports, _ember, _common, _serializerResponse, _serializers) { 'use strict'; exports.__esModule = true; exports._find = _find; exports._findMany = _findMany; exports._findHasMany = _findHasMany; exports._findBelongsTo = _findBelongsTo; exports._findAll = _findAll; exports._query = _query; exports._queryRecord = _queryRecord; var Promise = _ember.default.RSVP.Promise; function payloadIsNotBlank(adapterPayload) { if (Array.isArray(adapterPayload)) { return true; } else { return Object.keys(adapterPayload || {}).length; } } function _find(adapter, store, modelClass, id, internalModel, options) { var snapshot = internalModel.createSnapshot(options); var modelName = internalModel.modelName; var promise = adapter.findRecord(store, modelClass, id, snapshot); var label = 'DS: Handle Adapter#findRecord of \'' + modelName + '\' with id: \'' + id + '\''; promise = Promise.resolve(promise, label); promise = (0, _common._guard)(promise, (0, _common._bind)(_common._objectIsAlive, store)); return promise.then(function (adapterPayload) { (false && _ember.default.assert('You made a \'findRecord\' request for a \'' + modelName + '\' with id \'' + id + '\', but the adapter\'s response did not have any data', payloadIsNotBlank(adapterPayload))); var serializer = (0, _serializers.serializerForAdapter)(store, adapter, modelName); var payload = (0, _serializerResponse.normalizeResponseHelper)(serializer, store, modelClass, adapterPayload, id, 'findRecord'); (false && _ember.default.assert('Ember Data expected the primary data returned from a \'findRecord\' response to be an object but instead it found an array.', !Array.isArray(payload.data))); (false && _ember.default.warn('You requested a record of type \'' + modelName + '\' with id \'' + id + '\' but the adapter returned a payload with primary data having an id of \'' + payload.data.id + '\'. Use \'store.findRecord()\' when the requested id is the same as the one returned by the adapter. In other cases use \'store.queryRecord()\' instead https://emberjs.com/api/data/classes/DS.Store.html#method_queryRecord', payload.data.id === id, { id: 'ds.store.findRecord.id-mismatch' })); return store._push(payload); }, function (error) { internalModel.notFound(); if (internalModel.isEmpty()) { internalModel.unloadRecord(); } throw error; }, 'DS: Extract payload of \'' + modelName + '\''); } function _findMany(adapter, store, modelName, ids, internalModels) { var snapshots = _ember.default.A(internalModels).invoke('createSnapshot'); var modelClass = store.modelFor(modelName); // `adapter.findMany` gets the modelClass still var promise = adapter.findMany(store, modelClass, ids, snapshots); var label = 'DS: Handle Adapter#findMany of \'' + modelName + '\''; if (promise === undefined) { throw new Error('adapter.findMany returned undefined, this was very likely a mistake'); } promise = Promise.resolve(promise, label); promise = (0, _common._guard)(promise, (0, _common._bind)(_common._objectIsAlive, store)); return promise.then(function (adapterPayload) { (false && _ember.default.assert('You made a \'findMany\' request for \'' + modelName + '\' records with ids \'[' + ids + ']\', but the adapter\'s response did not have any data', payloadIsNotBlank(adapterPayload))); var serializer = (0, _serializers.serializerForAdapter)(store, adapter, modelName); var payload = (0, _serializerResponse.normalizeResponseHelper)(serializer, store, modelClass, adapterPayload, null, 'findMany'); return store._push(payload); }, null, 'DS: Extract payload of ' + modelName); } function _findHasMany(adapter, store, internalModel, link, relationship) { var snapshot = internalModel.createSnapshot(); var modelClass = store.modelFor(relationship.type); var promise = adapter.findHasMany(store, snapshot, link, relationship); var label = 'DS: Handle Adapter#findHasMany of \'' + internalModel.modelName + '\' : \'' + relationship.type + '\''; promise = Promise.resolve(promise, label); promise = (0, _common._guard)(promise, (0, _common._bind)(_common._objectIsAlive, store)); promise = (0, _common._guard)(promise, (0, _common._bind)(_common._objectIsAlive, internalModel)); return promise.then(function (adapterPayload) { (false && _ember.default.assert('You made a \'findHasMany\' request for a ' + internalModel.modelName + '\'s \'' + relationship.key + '\' relationship, using link \'' + link + '\' , but the adapter\'s response did not have any data', payloadIsNotBlank(adapterPayload))); var serializer = (0, _serializers.serializerForAdapter)(store, adapter, relationship.type); var payload = (0, _serializerResponse.normalizeResponseHelper)(serializer, store, modelClass, adapterPayload, null, 'findHasMany'); var internalModelArray = store._push(payload); internalModelArray.meta = payload.meta; return internalModelArray; }, null, 'DS: Extract payload of \'' + internalModel.modelName + '\' : hasMany \'' + relationship.type + '\''); } function _findBelongsTo(adapter, store, internalModel, link, relationship) { var snapshot = internalModel.createSnapshot(); var modelClass = store.modelFor(relationship.type); var promise = adapter.findBelongsTo(store, snapshot, link, relationship); var label = 'DS: Handle Adapter#findBelongsTo of ' + internalModel.modelName + ' : ' + relationship.type; promise = Promise.resolve(promise, label); promise = (0, _common._guard)(promise, (0, _common._bind)(_common._objectIsAlive, store)); promise = (0, _common._guard)(promise, (0, _common._bind)(_common._objectIsAlive, internalModel)); return promise.then(function (adapterPayload) { var serializer = (0, _serializers.serializerForAdapter)(store, adapter, relationship.type); var payload = (0, _serializerResponse.normalizeResponseHelper)(serializer, store, modelClass, adapterPayload, null, 'findBelongsTo'); if (!payload.data) { return null; } return store._push(payload); }, null, 'DS: Extract payload of ' + internalModel.modelName + ' : ' + relationship.type); } function _findAll(adapter, store, modelName, sinceToken, options) { var modelClass = store.modelFor(modelName); // adapter.findAll depends on the class var recordArray = store.peekAll(modelName); var snapshotArray = recordArray._createSnapshot(options); var promise = adapter.findAll(store, modelClass, sinceToken, snapshotArray); var label = "DS: Handle Adapter#findAll of " + modelClass; promise = Promise.resolve(promise, label); promise = (0, _common._guard)(promise, (0, _common._bind)(_common._objectIsAlive, store)); return promise.then(function (adapterPayload) { (false && _ember.default.assert('You made a \'findAll\' request for \'' + modelName + '\' records, but the adapter\'s response did not have any data', payloadIsNotBlank(adapterPayload))); var serializer = (0, _serializers.serializerForAdapter)(store, adapter, modelName); var payload = (0, _serializerResponse.normalizeResponseHelper)(serializer, store, modelClass, adapterPayload, null, 'findAll'); store._push(payload); store._didUpdateAll(modelName); return recordArray; }, null, 'DS: Extract payload of findAll ${modelName}'); } function _query(adapter, store, modelName, query, recordArray) { var modelClass = store.modelFor(modelName); // adapter.query needs the class var promise = void 0; if (adapter.query.length > 3) { recordArray = recordArray || store.recordArrayManager.createAdapterPopulatedRecordArray(modelName, query); promise = adapter.query(store, modelClass, query, recordArray); } else { promise = adapter.query(store, modelClass, query); } var label = 'DS: Handle Adapter#query of ' + modelClass; promise = Promise.resolve(promise, label); promise = (0, _common._guard)(promise, (0, _common._bind)(_common._objectIsAlive, store)); return promise.then(function (adapterPayload) { var serializer = (0, _serializers.serializerForAdapter)(store, adapter, modelName); var payload = (0, _serializerResponse.normalizeResponseHelper)(serializer, store, modelClass, adapterPayload, null, 'query'); var internalModels = store._push(payload); (false && _ember.default.assert('The response to store.query is expected to be an array but it was a single record. Please wrap your response in an array or use `store.queryRecord` to query for a single record.', Array.isArray(internalModels))); if (recordArray) { recordArray._setInternalModels(internalModels, payload); } else { recordArray = store.recordArrayManager.createAdapterPopulatedRecordArray(modelName, query, internalModels, payload); } return recordArray; }, null, 'DS: Extract payload of query ' + modelName); } function _queryRecord(adapter, store, modelName, query) { var modelClass = store.modelFor(modelName); // adapter.queryRecord needs the class var promise = adapter.queryRecord(store, modelClass, query); var label = 'DS: Handle Adapter#queryRecord of ' + modelName; promise = Promise.resolve(promise, label); promise = (0, _common._guard)(promise, (0, _common._bind)(_common._objectIsAlive, store)); return promise.then(function (adapterPayload) { var serializer = (0, _serializers.serializerForAdapter)(store, adapter, modelName); var payload = (0, _serializerResponse.normalizeResponseHelper)(serializer, store, modelClass, adapterPayload, null, 'queryRecord'); (false && _ember.default.assert('Expected the primary data returned by the serializer for a \'queryRecord\' response to be a single object or null but instead it was an array.', !Array.isArray(payload.data), { id: 'ds.store.queryRecord-array-response' })); return store._push(payload); }, null, 'DS: Extract payload of queryRecord ' + modelName); } }); define('ember-data/-private/system/store/serializer-response', ['exports', 'ember'], function (exports, _ember) { 'use strict'; exports.__esModule = true; exports.validateDocumentStructure = validateDocumentStructure; exports.normalizeResponseHelper = normalizeResponseHelper; /* This is a helper method that validates a JSON API top-level document The format of a document is described here: http://jsonapi.org/format/#document-top-level @method validateDocumentStructure @param {Object} doc JSON API document @return {array} An array of errors found in the document structure */ function validateDocumentStructure(doc) { var errors = []; if (!doc || typeof doc !== 'object') { errors.push('Top level of a JSON API document must be an object'); } else { if (!('data' in doc) && !('errors' in doc) && !('meta' in doc)) { errors.push('One or more of the following keys must be present: "data", "errors", "meta".'); } else { if ('data' in doc && 'errors' in doc) { errors.push('Top level keys "errors" and "data" cannot both be present in a JSON API document'); } } if ('data' in doc) { if (!(doc.data === null || Array.isArray(doc.data) || typeof doc.data === 'object')) { errors.push('data must be null, an object, or an array'); } } if ('meta' in doc) { if (typeof doc.meta !== 'object') { errors.push('meta must be an object'); } } if ('errors' in doc) { if (!Array.isArray(doc.errors)) { errors.push('errors must be an array'); } } if ('links' in doc) { if (typeof doc.links !== 'object') { errors.push('links must be an object'); } } if ('jsonapi' in doc) { if (typeof doc.jsonapi !== 'object') { errors.push('jsonapi must be an object'); } } if ('included' in doc) { if (typeof doc.included !== 'object') { errors.push('included must be an array'); } } } return errors; } /* This is a helper method that always returns a JSON-API Document. @method normalizeResponseHelper @param {DS.Serializer} serializer @param {DS.Store} store @param {subclass of DS.Model} modelClass @param {Object} payload @param {String|Number} id @param {String} requestType @return {Object} JSON-API Document */ function normalizeResponseHelper(serializer, store, modelClass, payload, id, requestType) { var normalizedResponse = serializer.normalizeResponse(store, modelClass, payload, id, requestType); var validationErrors = []; if (false) { validationErrors = validateDocumentStructure(normalizedResponse); } (false && _ember.default.assert('normalizeResponse must return a valid JSON API document:\n\t* ' + validationErrors.join('\n\t* '), _ember.default.isEmpty(validationErrors))); return normalizedResponse; } }); define("ember-data/-private/system/store/serializers", ["exports"], function (exports) { "use strict"; exports.__esModule = true; exports.serializerForAdapter = serializerForAdapter; function serializerForAdapter(store, adapter, modelName) { var serializer = adapter.serializer; if (serializer === undefined) { serializer = store.serializerFor(modelName); } if (serializer === null || serializer === undefined) { serializer = { extract: function (store, type, payload) { return payload; } }; } return serializer; } }); define('ember-data/-private/utils', ['exports', 'ember'], function (exports, _ember) { 'use strict'; exports.__esModule = true; exports.getOwner = exports.modelHasAttributeOrRelationshipNamedType = undefined; var get = _ember.default.get; /* Check if the passed model has a `type` attribute or a relationship named `type`. @method modelHasAttributeOrRelationshipNamedType @param modelClass */ function modelHasAttributeOrRelationshipNamedType(modelClass) { return get(modelClass, 'attributes').has('type') || get(modelClass, 'relationshipsByName').has('type'); } /* ember-container-inject-owner is a new feature in Ember 2.3 that finally provides a public API for looking items up. This function serves as a super simple polyfill to avoid triggering deprecations. */ function getOwner(context) { var owner = void 0; if (_ember.default.getOwner) { owner = _ember.default.getOwner(context); } else if (context.container) { owner = context.container; } if (owner && owner.lookupFactory && !owner._lookupFactory) { // `owner` is a container, we are just making this work owner._lookupFactory = function () { var _owner; return (_owner = owner).lookupFactory.apply(_owner, arguments); }; owner.register = function () { var registry = owner.registry || owner._registry || owner; return registry.register.apply(registry, arguments); }; } return owner; } exports.modelHasAttributeOrRelationshipNamedType = modelHasAttributeOrRelationshipNamedType; exports.getOwner = getOwner; }); define('ember-data/-private/utils/parse-response-headers', ['exports'], function (exports) { 'use strict'; exports.__esModule = true; exports.default = parseResponseHeaders; var CLRF = '\u000d\u000a'; function parseResponseHeaders(headersString) { var headers = Object.create(null); if (!headersString) { return headers; } var headerPairs = headersString.split(CLRF); for (var i = 0; i < headerPairs.length; i++) { var header = headerPairs[i]; var j = 0; var foundSep = false; for (; j < header.length; j++) { if (header.charCodeAt(j) === 58 /* ':' */) { foundSep = true; break; } } if (foundSep === false) { continue; } var field = header.substring(0, j).trim(); var value = header.substring(j + 1, header.length).trim(); if (value) { headers[field] = value; } } return headers; } }); define('ember-data/adapter', ['exports', 'ember'], function (exports, _ember) { 'use strict'; exports.__esModule = true; exports.default = _ember.default.Object.extend({ /** If you would like your adapter to use a custom serializer you can set the `defaultSerializer` property to be the name of the custom serializer. Note the `defaultSerializer` serializer has a lower priority than a model specific serializer (i.e. `PostSerializer`) or the `application` serializer. ```app/adapters/django.js import DS from 'ember-data'; export default DS.Adapter.extend({ defaultSerializer: 'django' }); ``` @property defaultSerializer @type {String} */ defaultSerializer: '-default', /** The `findRecord()` method is invoked when the store is asked for a record that has not previously been loaded. In response to `findRecord()` being called, you should query your persistence layer for a record with the given ID. The `findRecord` method should return a promise that will resolve to a JavaScript object that will be normalized by the serializer. Here is an example `findRecord` implementation: ```app/adapters/application.js import Ember from 'ember'; import DS from 'ember-data'; export default DS.Adapter.extend({ findRecord(store, type, id, snapshot) { return new Ember.RSVP.Promise(function(resolve, reject) { Ember.$.getJSON(`/${type.modelName}/${id}`).then(function(data) { resolve(data); }, function(jqXHR) { reject(jqXHR); }); }); } }); ``` @method findRecord @param {DS.Store} store @param {DS.Model} type @param {String} id @param {DS.Snapshot} snapshot @return {Promise} promise */ findRecord: null, /** The `findAll()` method is used to retrieve all records for a given type. Example ```app/adapters/application.js import Ember from 'ember'; import DS from 'ember-data'; export default DS.Adapter.extend({ findAll(store, type, sinceToken) { let query = { since: sinceToken }; return new Ember.RSVP.Promise(function(resolve, reject) { Ember.$.getJSON(`/${type.modelName}`, query).then(function(data) { resolve(data); }, function(jqXHR) { reject(jqXHR); }); }); } }); ``` @method findAll @param {DS.Store} store @param {DS.Model} type @param {String} sinceToken @param {DS.SnapshotRecordArray} snapshotRecordArray @return {Promise} promise */ findAll: null, /** This method is called when you call `query` on the store. Example ```app/adapters/application.js import Ember from 'ember'; import DS from 'ember-data'; export default DS.Adapter.extend({ query(store, type, query) { return new Ember.RSVP.Promise(function(resolve, reject) { Ember.$.getJSON(`/${type.modelName}`, query).then(function(data) { resolve(data); }, function(jqXHR) { reject(jqXHR); }); }); } }); ``` @method query @param {DS.Store} store @param {DS.Model} type @param {Object} query @param {DS.AdapterPopulatedRecordArray} recordArray @return {Promise} promise */ query: null, /** The `queryRecord()` method is invoked when the store is asked for a single record through a query object. In response to `queryRecord()` being called, you should always fetch fresh data. Once found, you can asynchronously call the store's `push()` method to push the record into the store. Here is an example `queryRecord` implementation: Example ```app/adapters/application.js import Ember from 'ember'; import DS from 'ember-data'; export default DS.Adapter.extend(DS.BuildURLMixin, { queryRecord(store, type, query) { return new Ember.RSVP.Promise(function(resolve, reject) { Ember.$.getJSON(`/${type.modelName}`, query).then(function(data) { resolve(data); }, function(jqXHR) { reject(jqXHR); }); }); } }); ``` @method queryRecord @param {DS.Store} store @param {subclass of DS.Model} type @param {Object} query @return {Promise} promise */ queryRecord: null, /** If the globally unique IDs for your records should be generated on the client, implement the `generateIdForRecord()` method. This method will be invoked each time you create a new record, and the value returned from it will be assigned to the record's `primaryKey`. Most traditional REST-like HTTP APIs will not use this method. Instead, the ID of the record will be set by the server, and your adapter will update the store with the new ID when it calls `didCreateRecord()`. Only implement this method if you intend to generate record IDs on the client-side. The `generateIdForRecord()` method will be invoked with the requesting store as the first parameter and the newly created record as the second parameter: ```javascript import DS from 'ember-data'; import { v4 } from 'uuid'; export default DS.Adapter.extend({ generateIdForRecord(store, inputProperties) { return v4(); } }); ``` @method generateIdForRecord @param {DS.Store} store @param {DS.Model} type the DS.Model class of the record @param {Object} inputProperties a hash of properties to set on the newly created record. @return {(String|Number)} id */ generateIdForRecord: null, /** Proxies to the serializer's `serialize` method. Example ```app/adapters/application.js import DS from 'ember-data'; export default DS.Adapter.extend({ createRecord(store, type, snapshot) { let data = this.serialize(snapshot, { includeId: true }); let url = `/${type.modelName}`; // ... } }); ``` @method serialize @param {DS.Snapshot} snapshot @param {Object} options @return {Object} serialized snapshot */ serialize: function (snapshot, options) { return snapshot.serialize(options); }, /** Implement this method in a subclass to handle the creation of new records. Serializes the record and sends it to the server. Example ```app/adapters/application.js import Ember from 'ember'; import DS from 'ember-data'; export default DS.Adapter.extend({ createRecord(store, type, snapshot) { let data = this.serialize(snapshot, { includeId: true }); return new Ember.RSVP.Promise(function(resolve, reject) { Ember.$.ajax({ type: 'POST', url: `/${type.modelName}`, dataType: 'json', data: data }).then(function(data) { Ember.run(null, resolve, data); }, function(jqXHR) { jqXHR.then = null; // tame jQuery's ill mannered promises Ember.run(null, reject, jqXHR); }); }); } }); ``` @method createRecord @param {DS.Store} store @param {DS.Model} type the DS.Model class of the record @param {DS.Snapshot} snapshot @return {Promise} promise */ createRecord: null, /** Implement this method in a subclass to handle the updating of a record. Serializes the record update and sends it to the server. The updateRecord method is expected to return a promise that will resolve with the serialized record. This allows the backend to inform the Ember Data store the current state of this record after the update. If it is not possible to return a serialized record the updateRecord promise can also resolve with `undefined` and the Ember Data store will assume all of the updates were successfully applied on the backend. Example ```app/adapters/application.js import Ember from 'ember'; import DS from 'ember-data'; export default DS.Adapter.extend({ updateRecord(store, type, snapshot) { let data = this.serialize(snapshot, { includeId: true }); let id = snapshot.id; return new Ember.RSVP.Promise(function(resolve, reject) { Ember.$.ajax({ type: 'PUT', url: `/${type.modelName}/${id}`, dataType: 'json', data: data }).then(function(data) { Ember.run(null, resolve, data); }, function(jqXHR) { jqXHR.then = null; // tame jQuery's ill mannered promises Ember.run(null, reject, jqXHR); }); }); } }); ``` @method updateRecord @param {DS.Store} store @param {DS.Model} type the DS.Model class of the record @param {DS.Snapshot} snapshot @return {Promise} promise */ updateRecord: null, /** Implement this method in a subclass to handle the deletion of a record. Sends a delete request for the record to the server. Example ```app/adapters/application.js import Ember from 'ember'; import DS from 'ember-data'; export default DS.Adapter.extend({ deleteRecord(store, type, snapshot) { let data = this.serialize(snapshot, { includeId: true }); let id = snapshot.id; return new Ember.RSVP.Promise(function(resolve, reject) { Ember.$.ajax({ type: 'DELETE', url: `/${type.modelName}/${id}`, dataType: 'json', data: data }).then(function(data) { Ember.run(null, resolve, data); }, function(jqXHR) { jqXHR.then = null; // tame jQuery's ill mannered promises Ember.run(null, reject, jqXHR); }); }); } }); ``` @method deleteRecord @param {DS.Store} store @param {DS.Model} type the DS.Model class of the record @param {DS.Snapshot} snapshot @return {Promise} promise */ deleteRecord: null, /** By default the store will try to coalesce all `fetchRecord` calls within the same runloop into as few requests as possible by calling groupRecordsForFindMany and passing it into a findMany call. You can opt out of this behaviour by either not implementing the findMany hook or by setting coalesceFindRequests to false. @property coalesceFindRequests @type {boolean} */ coalesceFindRequests: true, /** The store will call `findMany` instead of multiple `findRecord` requests to find multiple records at once if coalesceFindRequests is true. ```app/adapters/application.js import Ember from 'ember'; import DS from 'ember-data'; export default DS.Adapter.extend({ findMany(store, type, ids, snapshots) { return new Ember.RSVP.Promise(function(resolve, reject) { Ember.$.ajax({ type: 'GET', url: `/${type.modelName}/`, dataType: 'json', data: { filter: { id: ids.join(',') } } }).then(function(data) { Ember.run(null, resolve, data); }, function(jqXHR) { jqXHR.then = null; // tame jQuery's ill mannered promises Ember.run(null, reject, jqXHR); }); }); } }); ``` @method findMany @param {DS.Store} store @param {DS.Model} type the DS.Model class of the records @param {Array} ids @param {Array} snapshots @return {Promise} promise */ findMany: null, /** Organize records into groups, each of which is to be passed to separate calls to `findMany`. For example, if your api has nested URLs that depend on the parent, you will want to group records by their parent. The default implementation returns the records as a single group. @method groupRecordsForFindMany @param {DS.Store} store @param {Array} snapshots @return {Array} an array of arrays of records, each of which is to be loaded separately by `findMany`. */ groupRecordsForFindMany: function (store, snapshots) { return [snapshots]; }, /** This method is used by the store to determine if the store should reload a record from the adapter when a record is requested by `store.findRecord`. If this method returns `true`, the store will re-fetch a record from the adapter. If this method returns `false`, the store will resolve immediately using the cached record. For example, if you are building an events ticketing system, in which users can only reserve tickets for 20 minutes at a time, and want to ensure that in each route you have data that is no more than 20 minutes old you could write: ```javascript shouldReloadRecord(store, ticketSnapshot) { let lastAccessedAt = ticketSnapshot.attr('lastAccessedAt'); let timeDiff = moment().diff(lastAccessedAt, 'minutes'); if (timeDiff > 20) { return true; } else { return false; } } ``` This method would ensure that whenever you do `store.findRecord('ticket', id)` you will always get a ticket that is no more than 20 minutes old. In case the cached version is more than 20 minutes old, `findRecord` will not resolve until you fetched the latest version. By default this hook returns `false`, as most UIs should not block user interactions while waiting on data update. Note that, with default settings, `shouldBackgroundReloadRecord` will always re-fetch the records in the background even if `shouldReloadRecord` returns `false`. You can override `shouldBackgroundReloadRecord` if this does not suit your use case. @since 1.13.0 @method shouldReloadRecord @param {DS.Store} store @param {DS.Snapshot} snapshot @return {Boolean} */ shouldReloadRecord: function (store, snapshot) { return false; }, /** This method is used by the store to determine if the store should reload all records from the adapter when records are requested by `store.findAll`. If this method returns `true`, the store will re-fetch all records from the adapter. If this method returns `false`, the store will resolve immediately using the cached records. For example, if you are building an events ticketing system, in which users can only reserve tickets for 20 minutes at a time, and want to ensure that in each route you have data that is no more than 20 minutes old you could write: ```javascript shouldReloadAll(store, snapshotArray) { let snapshots = snapshotArray.snapshots(); return snapshots.any((ticketSnapshot) => { let lastAccessedAt = ticketSnapshot.attr('lastAccessedAt'); let timeDiff = moment().diff(lastAccessedAt, 'minutes'); if (timeDiff > 20) { return true; } else { return false; } }); } ``` This method would ensure that whenever you do `store.findAll('ticket')` you will always get a list of tickets that are no more than 20 minutes old. In case a cached version is more than 20 minutes old, `findAll` will not resolve until you fetched the latest versions. By default this methods returns `true` if the passed `snapshotRecordArray` is empty (meaning that there are no records locally available yet), otherwise it returns `false`. Note that, with default settings, `shouldBackgroundReloadAll` will always re-fetch all the records in the background even if `shouldReloadAll` returns `false`. You can override `shouldBackgroundReloadAll` if this does not suit your use case. @since 1.13.0 @method shouldReloadAll @param {DS.Store} store @param {DS.SnapshotRecordArray} snapshotRecordArray @return {Boolean} */ shouldReloadAll: function (store, snapshotRecordArray) { return !snapshotRecordArray.length; }, /** This method is used by the store to determine if the store should reload a record after the `store.findRecord` method resolves a cached record. This method is *only* checked by the store when the store is returning a cached record. If this method returns `true` the store will re-fetch a record from the adapter. For example, if you do not want to fetch complex data over a mobile connection, or if the network is down, you can implement `shouldBackgroundReloadRecord` as follows: ```javascript shouldBackgroundReloadRecord(store, snapshot) { let connection = window.navigator.connection; if (connection === 'cellular' || connection === 'none') { return false; } else { return true; } } ``` By default this hook returns `true` so the data for the record is updated in the background. @since 1.13.0 @method shouldBackgroundReloadRecord @param {DS.Store} store @param {DS.Snapshot} snapshot @return {Boolean} */ shouldBackgroundReloadRecord: function (store, snapshot) { return true; }, /** This method is used by the store to determine if the store should reload a record array after the `store.findAll` method resolves with a cached record array. This method is *only* checked by the store when the store is returning a cached record array. If this method returns `true` the store will re-fetch all records from the adapter. For example, if you do not want to fetch complex data over a mobile connection, or if the network is down, you can implement `shouldBackgroundReloadAll` as follows: ```javascript shouldBackgroundReloadAll(store, snapshotArray) { let connection = window.navigator.connection; if (connection === 'cellular' || connection === 'none') { return false; } else { return true; } } ``` By default this method returns `true`, indicating that a background reload should always be triggered. @since 1.13.0 @method shouldBackgroundReloadAll @param {DS.Store} store @param {DS.SnapshotRecordArray} snapshotRecordArray @return {Boolean} */ shouldBackgroundReloadAll: function (store, snapshotRecordArray) { return true; } }); }); define('ember-data/adapters/errors', ['exports', 'ember-data/-private'], function (exports, _private) { 'use strict'; exports.__esModule = true; Object.defineProperty(exports, 'AdapterError', { enumerable: true, get: function () { return _private.AdapterError; } }); Object.defineProperty(exports, 'InvalidError', { enumerable: true, get: function () { return _private.InvalidError; } }); Object.defineProperty(exports, 'UnauthorizedError', { enumerable: true, get: function () { return _private.UnauthorizedError; } }); Object.defineProperty(exports, 'ForbiddenError', { enumerable: true, get: function () { return _private.ForbiddenError; } }); Object.defineProperty(exports, 'NotFoundError', { enumerable: true, get: function () { return _private.NotFoundError; } }); Object.defineProperty(exports, 'ConflictError', { enumerable: true, get: function () { return _private.ConflictError; } }); Object.defineProperty(exports, 'ServerError', { enumerable: true, get: function () { return _private.ServerError; } }); Object.defineProperty(exports, 'TimeoutError', { enumerable: true, get: function () { return _private.TimeoutError; } }); Object.defineProperty(exports, 'AbortError', { enumerable: true, get: function () { return _private.AbortError; } }); Object.defineProperty(exports, 'errorsHashToArray', { enumerable: true, get: function () { return _private.errorsHashToArray; } }); Object.defineProperty(exports, 'errorsArrayToHash', { enumerable: true, get: function () { return _private.errorsArrayToHash; } }); }); define('ember-data/adapters/json-api', ['exports', 'ember', 'ember-inflector', 'ember-data/adapters/rest', 'ember-data/-private'], function (exports, _ember, _emberInflector, _rest, _private) { 'use strict'; exports.__esModule = true; /** The `JSONAPIAdapter` is the default adapter used by Ember Data. It is responsible for transforming the store's requests into HTTP requests that follow the [JSON API](http://jsonapi.org/format/) format. ## JSON API Conventions The JSONAPIAdapter uses JSON API conventions for building the url for a record and selecting the HTTP verb to use with a request. The actions you can take on a record map onto the following URLs in the JSON API adapter: <table> <tr> <th> Action </th> <th> HTTP Verb </th> <th> URL </th> </tr> <tr> <th> `store.findRecord('post', 123)` </th> <td> GET </td> <td> /posts/123 </td> </tr> <tr> <th> `store.findAll('post')` </th> <td> GET </td> <td> /posts </td> </tr> <tr> <th> Update `postRecord.save()` </th> <td> PATCH </td> <td> /posts/123 </td> </tr> <tr> <th> Create `store.createRecord('post').save()` </th> <td> POST </td> <td> /posts </td> </tr> <tr> <th> Delete `postRecord.destroyRecord()` </th> <td> DELETE </td> <td> /posts/123 </td> </tr> </table> ## Success and failure The JSONAPIAdapter will consider a success any response with a status code of the 2xx family ("Success"), as well as 304 ("Not Modified"). Any other status code will be considered a failure. On success, the request promise will be resolved with the full response payload. Failed responses with status code 422 ("Unprocessable Entity") will be considered "invalid". The response will be discarded, except for the `errors` key. The request promise will be rejected with a `DS.InvalidError`. This error object will encapsulate the saved `errors` value. Any other status codes will be treated as an adapter error. The request promise will be rejected, similarly to the invalid case, but with an instance of `DS.AdapterError` instead. ### Endpoint path customization Endpoint paths can be prefixed with a `namespace` by setting the namespace property on the adapter: ```app/adapters/application.js import DS from 'ember-data'; export default DS.JSONAPIAdapter.extend({ namespace: 'api/1' }); ``` Requests for the `person` model would now target `/api/1/people/1`. ### Host customization An adapter can target other hosts by setting the `host` property. ```app/adapters/application.js import DS from 'ember-data'; export default DS.JSONAPIAdapter.extend({ host: 'https://api.example.com' }); ``` Requests for the `person` model would now target `https://api.example.com/people/1`. @since 1.13.0 @class JSONAPIAdapter @constructor @namespace DS @extends DS.RESTAdapter */ /* global heimdall */ /** @module ember-data */ var JSONAPIAdapter = _rest.default.extend({ defaultSerializer: '-json-api', ajaxOptions: function (url, type, options) { var hash = this._super.apply(this, arguments); if (hash.contentType) { hash.contentType = 'application/vnd.api+json'; } var beforeSend = hash.beforeSend; hash.beforeSend = function (xhr) { xhr.setRequestHeader('Accept', 'application/vnd.api+json'); if (beforeSend) { beforeSend(xhr); } }; return hash; }, /** By default the JSONAPIAdapter will send each find request coming from a `store.find` or from accessing a relationship separately to the server. If your server supports passing ids as a query string, you can set coalesceFindRequests to true to coalesce all find requests within a single runloop. For example, if you have an initial payload of: ```javascript { data: { id: 1, type: 'post', relationship: { comments: { data: [ { id: 1, type: 'comment' }, { id: 2, type: 'comment' } ] } } } } ``` By default calling `post.get('comments')` will trigger the following requests(assuming the comments haven't been loaded before): ``` GET /comments/1 GET /comments/2 ``` If you set coalesceFindRequests to `true` it will instead trigger the following request: ``` GET /comments?filter[id]=1,2 ``` Setting coalesceFindRequests to `true` also works for `store.find` requests and `belongsTo` relationships accessed within the same runloop. If you set `coalesceFindRequests: true` ```javascript store.findRecord('comment', 1); store.findRecord('comment', 2); ``` will also send a request to: `GET /comments?filter[id]=1,2` Note: Requests coalescing rely on URL building strategy. So if you override `buildURL` in your app `groupRecordsForFindMany` more likely should be overridden as well in order for coalescing to work. @property coalesceFindRequests @type {boolean} */ coalesceFindRequests: false, findMany: function (store, type, ids, snapshots) { if ((0, _private.isEnabled)('ds-improved-ajax') && !this._hasCustomizedAjax()) { return this._super.apply(this, arguments); } else { var url = this.buildURL(type.modelName, ids, snapshots, 'findMany'); return this.ajax(url, 'GET', { data: { filter: { id: ids.join(',') } } }); } }, pathForType: function (modelName) { var dasherized = _ember.default.String.dasherize(modelName); return (0, _emberInflector.pluralize)(dasherized); }, updateRecord: function (store, type, snapshot) { if ((0, _private.isEnabled)('ds-improved-ajax') && !this._hasCustomizedAjax()) { return this._super.apply(this, arguments); } else { var data = {}; var serializer = store.serializerFor(type.modelName); serializer.serializeIntoHash(data, type, snapshot, { includeId: true }); var url = this.buildURL(type.modelName, snapshot.id, snapshot, 'updateRecord'); return this.ajax(url, 'PATCH', { data: data }); } }, _hasCustomizedAjax: function () { if (this.ajax !== JSONAPIAdapter.prototype.ajax) { (false && !(false) && _ember.default.deprecate('JSONAPIAdapter#ajax has been deprecated please use. `methodForRequest`, `urlForRequest`, `headersForRequest` or `dataForRequest` instead.', false, { id: 'ds.json-api-adapter.ajax', until: '3.0.0' })); return true; } if (this.ajaxOptions !== JSONAPIAdapter.prototype.ajaxOptions) { (false && !(false) && _ember.default.deprecate('JSONAPIAdapterr#ajaxOptions has been deprecated please use. `methodForRequest`, `urlForRequest`, `headersForRequest` or `dataForRequest` instead.', false, { id: 'ds.json-api-adapter.ajax-options', until: '3.0.0' })); return true; } return false; } }); if ((0, _private.isEnabled)('ds-improved-ajax')) { JSONAPIAdapter.reopen({ methodForRequest: function (params) { if (params.requestType === 'updateRecord') { return 'PATCH'; } return this._super.apply(this, arguments); }, dataForRequest: function (params) { var requestType = params.requestType, ids = params.ids; if (requestType === 'findMany') { return { filter: { id: ids.join(',') } }; } if (requestType === 'updateRecord') { var store = params.store, type = params.type, snapshot = params.snapshot; var data = {}; var serializer = store.serializerFor(type.modelName); serializer.serializeIntoHash(data, type, snapshot, { includeId: true }); return data; } return this._super.apply(this, arguments); }, headersForRequest: function () { var headers = this._super.apply(this, arguments) || {}; headers['Accept'] = 'application/vnd.api+json'; return headers; }, _requestToJQueryAjaxHash: function () { var hash = this._super.apply(this, arguments); if (hash.contentType) { hash.contentType = 'application/vnd.api+json'; } return hash; } }); } exports.default = JSONAPIAdapter; }); define('ember-data/adapters/rest', ['exports', 'ember', 'ember-data/adapter', 'ember-data/-private'], function (exports, _ember, _adapter, _private) { 'use strict'; exports.__esModule = true; var MapWithDefault = _ember.default.MapWithDefault, get = _ember.default.get, run = _ember.default.run; var Promise = _ember.default.RSVP.Promise; /** The REST adapter allows your store to communicate with an HTTP server by transmitting JSON via XHR. Most Ember.js apps that consume a JSON API should use the REST adapter. This adapter is designed around the idea that the JSON exchanged with the server should be conventional. ## Success and failure The REST adapter will consider a success any response with a status code of the 2xx family ("Success"), as well as 304 ("Not Modified"). Any other status code will be considered a failure. On success, the request promise will be resolved with the full response payload. Failed responses with status code 422 ("Unprocessable Entity") will be considered "invalid". The response will be discarded, except for the `errors` key. The request promise will be rejected with a `DS.InvalidError`. This error object will encapsulate the saved `errors` value. Any other status codes will be treated as an "adapter error". The request promise will be rejected, similarly to the "invalid" case, but with an instance of `DS.AdapterError` instead. ## JSON Structure The REST adapter expects the JSON returned from your server to follow these conventions. ### Object Root The JSON payload should be an object that contains the record inside a root property. For example, in response to a `GET` request for `/posts/1`, the JSON should look like this: ```js { "posts": { "id": 1, "title": "I'm Running to Reform the W3C's Tag", "author": "Yehuda Katz" } } ``` Similarly, in response to a `GET` request for `/posts`, the JSON should look like this: ```js { "posts": [ { "id": 1, "title": "I'm Running to Reform the W3C's Tag", "author": "Yehuda Katz" }, { "id": 2, "title": "Rails is omakase", "author": "D2H" } ] } ``` Note that the object root can be pluralized for both a single-object response and an array response: the REST adapter is not strict on this. Further, if the HTTP server responds to a `GET` request to `/posts/1` (e.g. the response to a `findRecord` query) with more than one object in the array, Ember Data will only display the object with the matching ID. ### Conventional Names Attribute names in your JSON payload should be the camelCased versions of the attributes in your Ember.js models. For example, if you have a `Person` model: ```app/models/person.js import DS from 'ember-data'; export default DS.Model.extend({ firstName: DS.attr('string'), lastName: DS.attr('string'), occupation: DS.attr('string') }); ``` The JSON returned should look like this: ```js { "people": { "id": 5, "firstName": "Zaphod", "lastName": "Beeblebrox", "occupation": "President" } } ``` #### Relationships Relationships are usually represented by ids to the record in the relationship. The related records can then be sideloaded in the response under a key for the type. ```js { "posts": { "id": 5, "title": "I'm Running to Reform the W3C's Tag", "author": "Yehuda Katz", "comments": [1, 2] }, "comments": [{ "id": 1, "author": "User 1", "message": "First!", }, { "id": 2, "author": "User 2", "message": "Good Luck!", }] } ``` If the records in the relationship are not known when the response is serialized its also possible to represent the relationship as a url using the `links` key in the response. Ember Data will fetch this url to resolve the relationship when it is accessed for the first time. ```js { "posts": { "id": 5, "title": "I'm Running to Reform the W3C's Tag", "author": "Yehuda Katz", "links": { "comments": "/posts/5/comments" } } } ``` ### Errors If a response is considered a failure, the JSON payload is expected to include a top-level key `errors`, detailing any specific issues. For example: ```js { "errors": { "msg": "Something went wrong" } } ``` This adapter does not make any assumptions as to the format of the `errors` object. It will simply be passed along as is, wrapped in an instance of `DS.InvalidError` or `DS.AdapterError`. The serializer can interpret it afterwards. ## Customization ### Endpoint path customization Endpoint paths can be prefixed with a `namespace` by setting the namespace property on the adapter: ```app/adapters/application.js import DS from 'ember-data'; export default DS.RESTAdapter.extend({ namespace: 'api/1' }); ``` Requests for the `Person` model would now target `/api/1/people/1`. ### Host customization An adapter can target other hosts by setting the `host` property. ```app/adapters/application.js import DS from 'ember-data'; export default DS.RESTAdapter.extend({ host: 'https://api.example.com' }); ``` ### Headers customization Some APIs require HTTP headers, e.g. to provide an API key. Arbitrary headers can be set as key/value pairs on the `RESTAdapter`'s `headers` object and Ember Data will send them along with each ajax request. ```app/adapters/application.js import DS from 'ember-data'; export default DS.RESTAdapter.extend({ headers: { 'API_KEY': 'secret key', 'ANOTHER_HEADER': 'Some header value' } }); ``` `headers` can also be used as a computed property to support dynamic headers. In the example below, the `session` object has been injected into an adapter by Ember's container. ```app/adapters/application.js import DS from 'ember-data'; export default DS.RESTAdapter.extend({ headers: Ember.computed('session.authToken', function() { return { 'API_KEY': this.get('session.authToken'), 'ANOTHER_HEADER': 'Some header value' }; }) }); ``` In some cases, your dynamic headers may require data from some object outside of Ember's observer system (for example `document.cookie`). You can use the [volatile](/api/classes/Ember.ComputedProperty.html#method_volatile) function to set the property into a non-cached mode causing the headers to be recomputed with every request. ```app/adapters/application.js import DS from 'ember-data'; export default DS.RESTAdapter.extend({ headers: Ember.computed(function() { return { 'API_KEY': Ember.get(document.cookie.match(/apiKey\=([^;]*)/), '1'), 'ANOTHER_HEADER': 'Some header value' }; }).volatile() }); ``` @class RESTAdapter @constructor @namespace DS @extends DS.Adapter @uses DS.BuildURLMixin */ var RESTAdapter = _adapter.default.extend(_private.BuildURLMixin, { defaultSerializer: '-rest', sortQueryParams: function (obj) { var keys = Object.keys(obj); var len = keys.length; if (len < 2) { return obj; } var newQueryParams = {}; var sortedKeys = keys.sort(); for (var i = 0; i < len; i++) { newQueryParams[sortedKeys[i]] = obj[sortedKeys[i]]; } return newQueryParams; }, /** By default the RESTAdapter will send each find request coming from a `store.find` or from accessing a relationship separately to the server. If your server supports passing ids as a query string, you can set coalesceFindRequests to true to coalesce all find requests within a single runloop. For example, if you have an initial payload of: ```javascript { post: { id: 1, comments: [1, 2] } } ``` By default calling `post.get('comments')` will trigger the following requests(assuming the comments haven't been loaded before): ``` GET /comments/1 GET /comments/2 ``` If you set coalesceFindRequests to `true` it will instead trigger the following request: ``` GET /comments?ids[]=1&ids[]=2 ``` Setting coalesceFindRequests to `true` also works for `store.find` requests and `belongsTo` relationships accessed within the same runloop. If you set `coalesceFindRequests: true` ```javascript store.findRecord('comment', 1); store.findRecord('comment', 2); ``` will also send a request to: `GET /comments?ids[]=1&ids[]=2` Note: Requests coalescing rely on URL building strategy. So if you override `buildURL` in your app `groupRecordsForFindMany` more likely should be overridden as well in order for coalescing to work. @property coalesceFindRequests @type {boolean} */ coalesceFindRequests: false, findRecord: function (store, type, id, snapshot) { if ((0, _private.isEnabled)('ds-improved-ajax') && !this._hasCustomizedAjax()) { var request = this._requestFor({ store: store, type: type, id: id, snapshot: snapshot, requestType: 'findRecord' }); return this._makeRequest(request); } else { var url = this.buildURL(type.modelName, id, snapshot, 'findRecord'); var query = this.buildQuery(snapshot); return this.ajax(url, 'GET', { data: query }); } }, findAll: function (store, type, sinceToken, snapshotRecordArray) { var query = this.buildQuery(snapshotRecordArray); if ((0, _private.isEnabled)('ds-improved-ajax') && !this._hasCustomizedAjax()) { var request = this._requestFor({ store: store, type: type, sinceToken: sinceToken, query: query, snapshots: snapshotRecordArray, requestType: 'findAll' }); return this._makeRequest(request); } else { var url = this.buildURL(type.modelName, null, snapshotRecordArray, 'findAll'); if (sinceToken) { query.since = sinceToken; } return this.ajax(url, 'GET', { data: query }); } }, query: function (store, type, query) { if ((0, _private.isEnabled)('ds-improved-ajax') && !this._hasCustomizedAjax()) { var request = this._requestFor({ store: store, type: type, query: query, requestType: 'query' }); return this._makeRequest(request); } else { var url = this.buildURL(type.modelName, null, null, 'query', query); if (this.sortQueryParams) { query = this.sortQueryParams(query); } return this.ajax(url, 'GET', { data: query }); } }, queryRecord: function (store, type, query) { if ((0, _private.isEnabled)('ds-improved-ajax') && !this._hasCustomizedAjax()) { var request = this._requestFor({ store: store, type: type, query: query, requestType: 'queryRecord' }); return this._makeRequest(request); } else { var url = this.buildURL(type.modelName, null, null, 'queryRecord', query); if (this.sortQueryParams) { query = this.sortQueryParams(query); } return this.ajax(url, 'GET', { data: query }); } }, findMany: function (store, type, ids, snapshots) { if ((0, _private.isEnabled)('ds-improved-ajax') && !this._hasCustomizedAjax()) { var request = this._requestFor({ store: store, type: type, ids: ids, snapshots: snapshots, requestType: 'findMany' }); return this._makeRequest(request); } else { var url = this.buildURL(type.modelName, ids, snapshots, 'findMany'); return this.ajax(url, 'GET', { data: { ids: ids } }); } }, findHasMany: function (store, snapshot, url, relationship) { if ((0, _private.isEnabled)('ds-improved-ajax') && !this._hasCustomizedAjax()) { var request = this._requestFor({ store: store, snapshot: snapshot, url: url, relationship: relationship, requestType: 'findHasMany' }); return this._makeRequest(request); } else { var id = snapshot.id; var type = snapshot.modelName; url = this.urlPrefix(url, this.buildURL(type, id, snapshot, 'findHasMany')); return this.ajax(url, 'GET'); } }, findBelongsTo: function (store, snapshot, url, relationship) { if ((0, _private.isEnabled)('ds-improved-ajax') && !this._hasCustomizedAjax()) { var request = this._requestFor({ store: store, snapshot: snapshot, url: url, relationship: relationship, requestType: 'findBelongsTo' }); return this._makeRequest(request); } else { var id = snapshot.id; var type = snapshot.modelName; url = this.urlPrefix(url, this.buildURL(type, id, snapshot, 'findBelongsTo')); return this.ajax(url, 'GET'); } }, createRecord: function (store, type, snapshot) { if ((0, _private.isEnabled)('ds-improved-ajax') && !this._hasCustomizedAjax()) { var request = this._requestFor({ store: store, type: type, snapshot: snapshot, requestType: 'createRecord' }); return this._makeRequest(request); } else { var data = {}; var serializer = store.serializerFor(type.modelName); var url = this.buildURL(type.modelName, null, snapshot, 'createRecord'); serializer.serializeIntoHash(data, type, snapshot, { includeId: true }); return this.ajax(url, "POST", { data: data }); } }, updateRecord: function (store, type, snapshot) { if ((0, _private.isEnabled)('ds-improved-ajax') && !this._hasCustomizedAjax()) { var request = this._requestFor({ store: store, type: type, snapshot: snapshot, requestType: 'updateRecord' }); return this._makeRequest(request); } else { var data = {}; var serializer = store.serializerFor(type.modelName); serializer.serializeIntoHash(data, type, snapshot); var id = snapshot.id; var url = this.buildURL(type.modelName, id, snapshot, 'updateRecord'); return this.ajax(url, "PUT", { data: data }); } }, deleteRecord: function (store, type, snapshot) { if ((0, _private.isEnabled)('ds-improved-ajax') && !this._hasCustomizedAjax()) { var request = this._requestFor({ store: store, type: type, snapshot: snapshot, requestType: 'deleteRecord' }); return this._makeRequest(request); } else { var id = snapshot.id; return this.ajax(this.buildURL(type.modelName, id, snapshot, 'deleteRecord'), "DELETE"); } }, _stripIDFromURL: function (store, snapshot) { var url = this.buildURL(snapshot.modelName, snapshot.id, snapshot); var expandedURL = url.split('/'); // Case when the url is of the format ...something/:id // We are decodeURIComponent-ing the lastSegment because if it represents // the id, it has been encodeURIComponent-ified within `buildURL`. If we // don't do this, then records with id having special characters are not // coalesced correctly (see GH #4190 for the reported bug) var lastSegment = expandedURL[expandedURL.length - 1]; var id = snapshot.id; if (decodeURIComponent(lastSegment) === id) { expandedURL[expandedURL.length - 1] = ""; } else if (endsWith(lastSegment, '?id=' + id)) { //Case when the url is of the format ...something?id=:id expandedURL[expandedURL.length - 1] = lastSegment.substring(0, lastSegment.length - id.length - 1); } return expandedURL.join('/'); }, // http://stackoverflow.com/questions/417142/what-is-the-maximum-length-of-a-url-in-different-browsers maxURLLength: 2048, groupRecordsForFindMany: function (store, snapshots) { var groups = MapWithDefault.create({ defaultValue: function () { return []; } }); var adapter = this; var maxURLLength = this.maxURLLength; snapshots.forEach(function (snapshot) { var baseUrl = adapter._stripIDFromURL(store, snapshot); groups.get(baseUrl).push(snapshot); }); function splitGroupToFitInUrl(group, maxURLLength, paramNameLength) { var idsSize = 0; var baseUrl = adapter._stripIDFromURL(store, group[0]); var splitGroups = [[]]; group.forEach(function (snapshot) { var additionalLength = encodeURIComponent(snapshot.id).length + paramNameLength; if (baseUrl.length + idsSize + additionalLength >= maxURLLength) { idsSize = 0; splitGroups.push([]); } idsSize += additionalLength; var lastGroupIndex = splitGroups.length - 1; splitGroups[lastGroupIndex].push(snapshot); }); return splitGroups; } var groupsArray = []; groups.forEach(function (group, key) { var paramNameLength = '&ids%5B%5D='.length; var splitGroups = splitGroupToFitInUrl(group, maxURLLength, paramNameLength); splitGroups.forEach(function (splitGroup) { return groupsArray.push(splitGroup); }); }); return groupsArray; }, handleResponse: function (status, headers, payload, requestData) { if (this.isSuccess(status, headers, payload)) { return payload; } else if (this.isInvalid(status, headers, payload)) { return new _private.InvalidError(payload.errors); } var errors = this.normalizeErrorResponse(status, headers, payload); var detailedMessage = this.generatedDetailedMessage(status, headers, payload, requestData); switch (status) { case 401: return new _private.UnauthorizedError(errors, detailedMessage); case 403: return new _private.ForbiddenError(errors, detailedMessage); case 404: return new _private.NotFoundError(errors, detailedMessage); case 409: return new _private.ConflictError(errors, detailedMessage); default: if (status >= 500) { return new _private.ServerError(errors, detailedMessage); } } return new _private.AdapterError(errors, detailedMessage); }, isSuccess: function (status, headers, payload) { return status >= 200 && status < 300 || status === 304; }, isInvalid: function (status, headers, payload) { return status === 422; }, ajax: function (url, type, options) { var adapter = this; var requestData = { url: url, method: type }; return new Promise(function (resolve, reject) { var hash = adapter.ajaxOptions(url, type, options); hash.success = function (payload, textStatus, jqXHR) { var response = ajaxSuccess(adapter, jqXHR, payload, requestData); run.join(null, resolve, response); }; hash.error = function (jqXHR, textStatus, errorThrown) { var responseData = { textStatus: textStatus, errorThrown: errorThrown }; var error = ajaxError(adapter, jqXHR, requestData, responseData); run.join(null, reject, error); }; adapter._ajaxRequest(hash); }, 'DS: RESTAdapter#ajax ' + type + ' to ' + url); }, _ajaxRequest: function (options) { _ember.default.$.ajax(options); }, ajaxOptions: function (url, type, options) { var hash = options || {}; hash.url = url; hash.type = type; hash.dataType = 'json'; hash.context = this; if (hash.data && type !== 'GET') { hash.contentType = 'application/json; charset=utf-8'; hash.data = JSON.stringify(hash.data); } var headers = get(this, 'headers'); if (headers !== undefined) { hash.beforeSend = function (xhr) { Object.keys(headers).forEach(function (key) { return xhr.setRequestHeader(key, headers[key]); }); }; } return hash; }, parseErrorResponse: function (responseText) { var json = responseText; try { json = _ember.default.$.parseJSON(responseText); } catch (e) { // ignored } return json; }, normalizeErrorResponse: function (status, headers, payload) { if (payload && typeof payload === 'object' && payload.errors) { return payload.errors; } else { return [{ status: '' + status, title: "The backend responded with an error", detail: '' + payload }]; } }, /** Generates a detailed ("friendly") error message, with plenty of information for debugging (good luck!) @method generatedDetailedMessage @private @param {Number} status @param {Object} headers @param {Object} payload @param {Object} requestData @return {String} detailed error message */ generatedDetailedMessage: function (status, headers, payload, requestData) { var shortenedPayload = void 0; var payloadContentType = headers["Content-Type"] || "Empty Content-Type"; if (payloadContentType === "text/html" && payload.length > 250) { shortenedPayload = "[Omitted Lengthy HTML]"; } else { shortenedPayload = payload; } var requestDescription = requestData.method + ' ' + requestData.url; var payloadDescription = 'Payload (' + payloadContentType + ')'; return ['Ember Data Request ' + requestDescription + ' returned a ' + status, payloadDescription, shortenedPayload].join('\n'); }, buildQuery: function (snapshot) { var query = {}; if (snapshot) { var include = snapshot.include; if (include) { query.include = include; } } return query; }, _hasCustomizedAjax: function () { if (this.ajax !== RESTAdapter.prototype.ajax) { (false && !(false) && _ember.default.deprecate('RESTAdapter#ajax has been deprecated please use. `methodForRequest`, `urlForRequest`, `headersForRequest` or `dataForRequest` instead.', false, { id: 'ds.rest-adapter.ajax', until: '3.0.0' })); return true; } if (this.ajaxOptions !== RESTAdapter.prototype.ajaxOptions) { (false && !(false) && _ember.default.deprecate('RESTAdapter#ajaxOptions has been deprecated please use. `methodForRequest`, `urlForRequest`, `headersForRequest` or `dataForRequest` instead.', false, { id: 'ds.rest-adapter.ajax-options', until: '3.0.0' })); return true; } return false; } }); if ((0, _private.isEnabled)('ds-improved-ajax')) { RESTAdapter.reopen({ dataForRequest: function (params) { var store = params.store, type = params.type, snapshot = params.snapshot, requestType = params.requestType, query = params.query; // type is not passed to findBelongsTo and findHasMany type = type || snapshot && snapshot.type; var serializer = store.serializerFor(type.modelName); var data = {}; switch (requestType) { case 'createRecord': serializer.serializeIntoHash(data, type, snapshot, { includeId: true }); break; case 'updateRecord': serializer.serializeIntoHash(data, type, snapshot); break; case 'findRecord': data = this.buildQuery(snapshot); break; case 'findAll': if (params.sinceToken) { query = query || {}; query.since = params.sinceToken; } data = query; break; case 'query': case 'queryRecord': if (this.sortQueryParams) { query = this.sortQueryParams(query); } data = query; break; case 'findMany': data = { ids: params.ids }; break; default: data = undefined; break; } return data; }, methodForRequest: function (params) { var requestType = params.requestType; switch (requestType) { case 'createRecord': return 'POST'; case 'updateRecord': return 'PUT'; case 'deleteRecord': return 'DELETE'; } return 'GET'; }, urlForRequest: function (params) { var type = params.type, id = params.id, ids = params.ids, snapshot = params.snapshot, snapshots = params.snapshots, requestType = params.requestType, query = params.query; // type and id are not passed from updateRecord and deleteRecord, hence they // are defined if not set type = type || snapshot && snapshot.type; id = id || snapshot && snapshot.id; switch (requestType) { case 'findAll': return this.buildURL(type.modelName, null, snapshots, requestType); case 'query': case 'queryRecord': return this.buildURL(type.modelName, null, null, requestType, query); case 'findMany': return this.buildURL(type.modelName, ids, snapshots, requestType); case 'findHasMany': case 'findBelongsTo': { var url = this.buildURL(type.modelName, id, snapshot, requestType); return this.urlPrefix(params.url, url); } } return this.buildURL(type.modelName, id, snapshot, requestType, query); }, headersForRequest: function (params) { return this.get('headers'); }, _requestFor: function (params) { var method = this.methodForRequest(params); var url = this.urlForRequest(params); var headers = this.headersForRequest(params); var data = this.dataForRequest(params); return { method: method, url: url, headers: headers, data: data }; }, _requestToJQueryAjaxHash: function (request) { var hash = {}; hash.type = request.method; hash.url = request.url; hash.dataType = 'json'; hash.context = this; if (request.data) { if (request.method !== 'GET') { hash.contentType = 'application/json; charset=utf-8'; hash.data = JSON.stringify(request.data); } else { hash.data = request.data; } } var headers = request.headers; if (headers !== undefined) { hash.beforeSend = function (xhr) { Object.keys(headers).forEach(function (key) { return xhr.setRequestHeader(key, headers[key]); }); }; } return hash; }, _makeRequest: function (request) { var adapter = this; var hash = this._requestToJQueryAjaxHash(request); var method = request.method, url = request.url; var requestData = { method: method, url: url }; return new Promise(function (resolve, reject) { hash.success = function (payload, textStatus, jqXHR) { var response = ajaxSuccess(adapter, jqXHR, payload, requestData); run.join(null, resolve, response); }; hash.error = function (jqXHR, textStatus, errorThrown) { var responseData = { textStatus: textStatus, errorThrown: errorThrown }; var error = ajaxError(adapter, jqXHR, requestData, responseData); run.join(null, reject, error); }; adapter._ajaxRequest(hash); }, 'DS: RESTAdapter#makeRequest: ' + method + ' ' + url); } }); } function ajaxSuccess(adapter, jqXHR, payload, requestData) { var response = void 0; try { response = adapter.handleResponse(jqXHR.status, (0, _private.parseResponseHeaders)(jqXHR.getAllResponseHeaders()), payload, requestData); } catch (error) { return Promise.reject(error); } if (response && response.isAdapterError) { return Promise.reject(response); } else { return response; } } function ajaxError(adapter, jqXHR, requestData, responseData) { if (false) { var message = 'The server returned an empty string for ' + requestData.method + ' ' + requestData.url + ', which cannot be parsed into a valid JSON. Return either null or {}.'; var validJSONString = !(responseData.textStatus === "parsererror" && jqXHR.responseText === ""); (false && _ember.default.warn(message, validJSONString, { id: 'ds.adapter.returned-empty-string-as-JSON' })); } var error = void 0; if (responseData.errorThrown instanceof Error) { error = responseData.errorThrown; } else if (responseData.textStatus === 'timeout') { error = new _private.TimeoutError(); } else if (responseData.textStatus === 'abort' || jqXHR.status === 0) { error = new _private.AbortError(); } else { try { error = adapter.handleResponse(jqXHR.status, (0, _private.parseResponseHeaders)(jqXHR.getAllResponseHeaders()), adapter.parseErrorResponse(jqXHR.responseText) || responseData.errorThrown, requestData); } catch (e) { error = e; } } return error; } //From http://stackoverflow.com/questions/280634/endswith-in-javascript function endsWith(string, suffix) { if (typeof String.prototype.endsWith !== 'function') { return string.indexOf(suffix, string.length - suffix.length) !== -1; } else { return string.endsWith(suffix); } } exports.default = RESTAdapter; }); define('ember-data/attr', ['exports', 'ember'], function (exports, _ember) { 'use strict'; exports.__esModule = true; exports.default = attr; /** @module ember-data */ function getDefaultValue(record, options, key) { if (typeof options.defaultValue === 'function') { return options.defaultValue.apply(null, arguments); } else { var defaultValue = options.defaultValue; (false && !(typeof defaultValue !== 'object' || defaultValue === null) && _ember.default.deprecate('Non primitive defaultValues are deprecated because they are shared between all instances. If you would like to use a complex object as a default value please provide a function that returns the complex object.', typeof defaultValue !== 'object' || defaultValue === null, { id: 'ds.defaultValue.complex-object', until: '3.0.0' })); return defaultValue; } } function hasValue(record, key) { return key in record._attributes || key in record._inFlightAttributes || key in record._data; } function getValue(record, key) { if (key in record._attributes) { return record._attributes[key]; } else if (key in record._inFlightAttributes) { return record._inFlightAttributes[key]; } else { return record._data[key]; } } /** `DS.attr` defines an attribute on a [DS.Model](/api/data/classes/DS.Model.html). By default, attributes are passed through as-is, however you can specify an optional type to have the value automatically transformed. Ember Data ships with four basic transform types: `string`, `number`, `boolean` and `date`. You can define your own transforms by subclassing [DS.Transform](/api/data/classes/DS.Transform.html). Note that you cannot use `attr` to define an attribute of `id`. `DS.attr` takes an optional hash as a second parameter, currently supported options are: - `defaultValue`: Pass a string or a function to be called to set the attribute to a default value if none is supplied. Example ```app/models/user.js import DS from 'ember-data'; export default DS.Model.extend({ username: DS.attr('string'), email: DS.attr('string'), verified: DS.attr('boolean', { defaultValue: false }) }); ``` Default value can also be a function. This is useful it you want to return a new object for each attribute. ```app/models/user.js import DS from 'ember-data'; export default DS.Model.extend({ username: DS.attr('string'), email: DS.attr('string'), settings: DS.attr({ defaultValue() { return {}; } }) }); ``` The `options` hash is passed as second argument to a transforms' `serialize` and `deserialize` method. This allows to configure a transformation and adapt the corresponding value, based on the config: ```app/models/post.js import DS from 'ember-data'; export default DS.Model.extend({ text: DS.attr('text', { uppercase: true }) }); ``` ```app/transforms/text.js import DS from 'ember-data'; export default DS.Transform.extend({ serialize(value, options) { if (options.uppercase) { return value.toUpperCase(); } return value; }, deserialize(value) { return value; } }) ``` @namespace @method attr @for DS @param {String|Object} type the attribute type @param {Object} options a hash of options @return {Attribute} */ function attr(type, options) { if (typeof type === 'object') { options = type; type = undefined; } else { options = options || {}; } var meta = { type: type, isAttribute: true, options: options }; return _ember.default.computed({ get: function (key) { var internalModel = this._internalModel; if (hasValue(internalModel, key)) { return getValue(internalModel, key); } else { return getDefaultValue(this, options, key); } }, set: function (key, value) { var internalModel = this._internalModel; var oldValue = getValue(internalModel, key); var originalValue = void 0; if (value !== oldValue) { // Add the new value to the changed attributes hash; it will get deleted by // the 'didSetProperty' handler if it is no different from the original value internalModel._attributes[key] = value; if (key in internalModel._inFlightAttributes) { originalValue = internalModel._inFlightAttributes[key]; } else { originalValue = internalModel._data[key]; } this._internalModel.send('didSetProperty', { name: key, oldValue: oldValue, originalValue: originalValue, value: value }); } return value; } }).meta(meta); } }); define("ember-data", ["exports", "ember", "ember-data/-private", "ember-data/setup-container", "ember-data/instance-initializers/initialize-store-service", "ember-data/transforms/transform", "ember-data/transforms/number", "ember-data/transforms/date", "ember-data/transforms/string", "ember-data/transforms/boolean", "ember-data/adapter", "ember-data/adapters/json-api", "ember-data/adapters/rest", "ember-data/serializer", "ember-data/serializers/json-api", "ember-data/serializers/json", "ember-data/serializers/rest", "ember-data/serializers/embedded-records-mixin", "ember-data/attr", "ember-inflector"], function (exports, _ember, _private, _setupContainer, _initializeStoreService, _transform, _number, _date, _string, _boolean, _adapter, _jsonApi, _rest, _serializer, _jsonApi2, _json, _rest2, _embeddedRecordsMixin, _attr) { "use strict"; exports.__esModule = true; /** Ember Data @module ember-data @main ember-data */ if (_ember.default.VERSION.match(/^1\.([0-9]|1[0-2])\./)) { throw new _ember.default.Error("Ember Data requires at least Ember 1.13.0, but you have " + _ember.default.VERSION + ". Please upgrade your version of Ember, then upgrade Ember Data."); } _private.DS.Store = _private.Store; _private.DS.PromiseArray = _private.PromiseArray; _private.DS.PromiseObject = _private.PromiseObject; _private.DS.PromiseManyArray = _private.PromiseManyArray; _private.DS.Model = _private.Model; _private.DS.RootState = _private.RootState; _private.DS.attr = _attr.default; _private.DS.Errors = _private.Errors; _private.DS.InternalModel = _private.InternalModel; _private.DS.Snapshot = _private.Snapshot; _private.DS.Adapter = _adapter.default; _private.DS.AdapterError = _private.AdapterError; _private.DS.InvalidError = _private.InvalidError; _private.DS.TimeoutError = _private.TimeoutError; _private.DS.AbortError = _private.AbortError; _private.DS.UnauthorizedError = _private.UnauthorizedError; _private.DS.ForbiddenError = _private.ForbiddenError; _private.DS.NotFoundError = _private.NotFoundError; _private.DS.ConflictError = _private.ConflictError; _private.DS.ServerError = _private.ServerError; _private.DS.errorsHashToArray = _private.errorsHashToArray; _private.DS.errorsArrayToHash = _private.errorsArrayToHash; _private.DS.Serializer = _serializer.default; _private.DS.DebugAdapter = _private.DebugAdapter; _private.DS.RecordArray = _private.RecordArray; _private.DS.FilteredRecordArray = _private.FilteredRecordArray; _private.DS.AdapterPopulatedRecordArray = _private.AdapterPopulatedRecordArray; _private.DS.ManyArray = _private.ManyArray; _private.DS.RecordArrayManager = _private.RecordArrayManager; _private.DS.RESTAdapter = _rest.default; _private.DS.BuildURLMixin = _private.BuildURLMixin; _private.DS.RESTSerializer = _rest2.default; _private.DS.JSONSerializer = _json.default; _private.DS.JSONAPIAdapter = _jsonApi.default; _private.DS.JSONAPISerializer = _jsonApi2.default; _private.DS.Transform = _transform.default; _private.DS.DateTransform = _date.default; _private.DS.StringTransform = _string.default; _private.DS.NumberTransform = _number.default; _private.DS.BooleanTransform = _boolean.default; _private.DS.EmbeddedRecordsMixin = _embeddedRecordsMixin.default; _private.DS.belongsTo = _private.belongsTo; _private.DS.hasMany = _private.hasMany; _private.DS.Relationship = _private.Relationship; _private.DS._setupContainer = _setupContainer.default; _private.DS._initializeStoreService = _initializeStoreService.default; Object.defineProperty(_private.DS, 'normalizeModelName', { enumerable: true, writable: false, configurable: false, value: _private.normalizeModelName }); Object.defineProperty(_private.global, 'DS', { configurable: true, get: function () { (false && !(false) && _ember.default.deprecate('Using the global version of DS is deprecated. Please either import ' + 'the specific modules needed or `import DS from \'ember-data\';`.', false, { id: 'ember-data.global-ds', until: '3.0.0' })); return _private.DS; } }); exports.default = _private.DS; }); define('ember-data/initializers/data-adapter', ['exports'], function (exports) { 'use strict'; exports.__esModule = true; exports.default = { name: 'data-adapter', before: 'store', initialize: function () {} }; }); define('ember-data/initializers/ember-data', ['exports', 'ember-data/setup-container', 'ember-data'], function (exports, _setupContainer) { 'use strict'; exports.__esModule = true; exports.default = { name: 'ember-data', initialize: _setupContainer.default }; }); define('ember-data/initializers/injectStore', ['exports'], function (exports) { 'use strict'; exports.__esModule = true; exports.default = { name: 'injectStore', before: 'store', initialize: function () {} }; }); define('ember-data/initializers/store', ['exports'], function (exports) { 'use strict'; exports.__esModule = true; exports.default = { name: 'store', after: 'ember-data', initialize: function () {} }; }); define('ember-data/initializers/transforms', ['exports'], function (exports) { 'use strict'; exports.__esModule = true; exports.default = { name: 'transforms', before: 'store', initialize: function () {} }; }); define("ember-data/instance-initializers/ember-data", ["exports", "ember-data/instance-initializers/initialize-store-service"], function (exports, _initializeStoreService) { "use strict"; exports.__esModule = true; exports.default = { name: "ember-data", initialize: _initializeStoreService.default }; }); define('ember-data/instance-initializers/initialize-store-service', ['exports'], function (exports) { 'use strict'; exports.__esModule = true; exports.default = initializeStoreService; var deprecateOldEmberDataInitializers = void 0; /* Configures a registry for use with an Ember-Data store. @method initializeStoreService @param {Ember.ApplicationInstance | Ember.EngineInstance} instance */ function initializeStoreService(instance) { // instance.lookup supports Ember 2.1 and higher // instance.container supports Ember 1.11 - 2.0 var container = instance.lookup ? instance : instance.container; // Eagerly generate the store so defaultStore is populated. container.lookup('service:store'); if (false) { // In Ember 2.4+ instance.base is the `Ember.Application` or `Ember.Engine` instance // In Ember 1.11 - 2.3 we fallback to `instance.application` var base = instance.base || instance.application; deprecateOldEmberDataInitializers(base.constructor.initializers); } } if (false) { var DEPRECATED_INITIALIZER_NAMES = ['data-adapter', 'injectStore', 'transforms', 'store']; var matchesDeprecatedInititalizer = function matchesDeprecatedInititalizer(name) { return DEPRECATED_INITIALIZER_NAMES.indexOf(name) !== -1; }; var warnForDeprecatedInitializers = function warnForDeprecatedInitializers(initializer) { var deprecatedBeforeInitializer = matchesDeprecatedInititalizer(initializer.before); var deprecatedAfterInitializer = matchesDeprecatedInititalizer(initializer.after); var deprecatedProp = deprecatedBeforeInitializer ? 'before' : 'after'; (false && !(!(deprecatedBeforeInitializer || deprecatedAfterInitializer)) && Ember.deprecate('The initializer `' + initializer[deprecatedProp] + '` has been deprecated. Please update your `' + initializer.name + '` initializer to use use `' + deprecatedProp + ': \'ember-data\'` instead.', !(deprecatedBeforeInitializer || deprecatedAfterInitializer), { id: 'ds.deprecated-initializers', until: '3.0.0' })); }; deprecateOldEmberDataInitializers = function deprecateOldEmberDataInitializers(initializers) { // collect all of the initializers var keys = Object.keys(initializers); for (var i = 0; i < keys.length; i++) { var name = keys[i]; // filter out all of the Ember Data initializer. We have some // deprecated initializers that depend on other deprecated // initializers which may trigger the deprecation warning // unintentionally. if (!matchesDeprecatedInititalizer(name)) { warnForDeprecatedInitializers(initializers[name]); } } }; } }); define('ember-data/model', ['exports', 'ember-data/-private'], function (exports, _private) { 'use strict'; exports.__esModule = true; Object.defineProperty(exports, 'default', { enumerable: true, get: function () { return _private.Model; } }); }); define('ember-data/relationships', ['exports', 'ember-data/-private'], function (exports, _private) { 'use strict'; exports.__esModule = true; Object.defineProperty(exports, 'belongsTo', { enumerable: true, get: function () { return _private.belongsTo; } }); Object.defineProperty(exports, 'hasMany', { enumerable: true, get: function () { return _private.hasMany; } }); }); define('ember-data/serializer', ['exports', 'ember'], function (exports, _ember) { 'use strict'; exports.__esModule = true; exports.default = _ember.default.Object.extend({ /** The `store` property is the application's `store` that contains all records. It can be used to look up serializers for other model types that may be nested inside the payload response. Example: ```js Serializer.extend({ extractRelationship(relationshipModelName, relationshipHash) { var modelClass = this.store.modelFor(relationshipModelName); var relationshipSerializer = this.store.serializerFor(relationshipModelName); return relationshipSerializer.normalize(modelClass, relationshipHash); } }); ``` @property store @type {DS.Store} @public */ /** The `normalizeResponse` method is used to normalize a payload from the server to a JSON-API Document. http://jsonapi.org/format/#document-structure Example: ```js Serializer.extend({ normalizeResponse(store, primaryModelClass, payload, id, requestType) { if (requestType === 'findRecord') { return this.normalize(primaryModelClass, payload); } else { return payload.reduce(function(documentHash, item) { let { data, included } = this.normalize(primaryModelClass, item); documentHash.included.push(...included); documentHash.data.push(data); return documentHash; }, { data: [], included: [] }) } } }); ``` @since 1.13.0 @method normalizeResponse @param {DS.Store} store @param {DS.Model} primaryModelClass @param {Object} payload @param {String|Number} id @param {String} requestType @return {Object} JSON-API Document */ normalizeResponse: null, /** The `serialize` method is used when a record is saved in order to convert the record into the form that your external data source expects. `serialize` takes an optional `options` hash with a single option: - `includeId`: If this is `true`, `serialize` should include the ID in the serialized object it builds. Example: ```js Serializer.extend({ serialize(snapshot, options) { var json = { id: snapshot.id }; snapshot.eachAttribute((key, attribute) => { json[key] = snapshot.attr(key); }); snapshot.eachRelationship((key, relationship) => { if (relationship.kind === 'belongsTo') { json[key] = snapshot.belongsTo(key, { id: true }); } else if (relationship.kind === 'hasMany') { json[key] = snapshot.hasMany(key, { ids: true }); } }); return json; }, }); ``` @method serialize @param {DS.Snapshot} snapshot @param {Object} [options] @return {Object} */ serialize: null, /** The `normalize` method is used to convert a payload received from your external data source into the normalized form `store.push()` expects. You should override this method, munge the hash and return the normalized payload. Example: ```js Serializer.extend({ normalize(modelClass, resourceHash) { var data = { id: resourceHash.id, type: modelClass.modelName, attributes: resourceHash }; return { data: data }; } }) ``` @method normalize @param {DS.Model} typeClass @param {Object} hash @return {Object} */ normalize: function (typeClass, hash) { return hash; } }); }); define('ember-data/serializers/embedded-records-mixin', ['exports', 'ember'], function (exports, _ember) { 'use strict'; exports.__esModule = true; function _toConsumableArray(arr) { if (Array.isArray(arr)) { for (var i = 0, arr2 = Array(arr.length); i < arr.length; i++) { arr2[i] = arr[i]; } return arr2; } else { return Array.from(arr); } } var get = _ember.default.get, set = _ember.default.set; var camelize = _ember.default.String.camelize; exports.default = _ember.default.Mixin.create({ /** Normalize the record and recursively normalize/extract all the embedded records while pushing them into the store as they are encountered A payload with an attr configured for embedded records needs to be extracted: ```js { "post": { "id": "1" "title": "Rails is omakase", "comments": [{ "id": "1", "body": "Rails is unagi" }, { "id": "2", "body": "Omakase O_o" }] } } ``` @method normalize @param {DS.Model} typeClass @param {Object} hash to be normalized @param {String} prop the hash has been referenced by @return {Object} the normalized hash **/ normalize: function (typeClass, hash, prop) { var normalizedHash = this._super(typeClass, hash, prop); return this._extractEmbeddedRecords(this, this.store, typeClass, normalizedHash); }, keyForRelationship: function (key, typeClass, method) { if (method === 'serialize' && this.hasSerializeRecordsOption(key) || method === 'deserialize' && this.hasDeserializeRecordsOption(key)) { return this.keyForAttribute(key, method); } else { return this._super(key, typeClass, method) || key; } }, /** Serialize `belongsTo` relationship when it is configured as an embedded object. This example of an author model belongs to a post model: ```js Post = DS.Model.extend({ title: DS.attr('string'), body: DS.attr('string'), author: DS.belongsTo('author') }); Author = DS.Model.extend({ name: DS.attr('string'), post: DS.belongsTo('post') }); ``` Use a custom (type) serializer for the post model to configure embedded author ```app/serializers/post.js import DS from 'ember-data'; export default DS.RESTSerializer.extend(DS.EmbeddedRecordsMixin, { attrs: { author: { embedded: 'always' } } }) ``` A payload with an attribute configured for embedded records can serialize the records together under the root attribute's payload: ```js { "post": { "id": "1" "title": "Rails is omakase", "author": { "id": "2" "name": "dhh" } } } ``` @method serializeBelongsTo @param {DS.Snapshot} snapshot @param {Object} json @param {Object} relationship */ serializeBelongsTo: function (snapshot, json, relationship) { var attr = relationship.key; if (this.noSerializeOptionSpecified(attr)) { this._super(snapshot, json, relationship); return; } var includeIds = this.hasSerializeIdsOption(attr); var includeRecords = this.hasSerializeRecordsOption(attr); var embeddedSnapshot = snapshot.belongsTo(attr); if (includeIds) { var serializedKey = this._getMappedKey(relationship.key, snapshot.type); if (serializedKey === relationship.key && this.keyForRelationship) { serializedKey = this.keyForRelationship(relationship.key, relationship.kind, "serialize"); } if (!embeddedSnapshot) { json[serializedKey] = null; } else { json[serializedKey] = embeddedSnapshot.id; if (relationship.options.polymorphic) { this.serializePolymorphicType(snapshot, json, relationship); } } } else if (includeRecords) { this._serializeEmbeddedBelongsTo(snapshot, json, relationship); } }, _serializeEmbeddedBelongsTo: function (snapshot, json, relationship) { var embeddedSnapshot = snapshot.belongsTo(relationship.key); var serializedKey = this._getMappedKey(relationship.key, snapshot.type); if (serializedKey === relationship.key && this.keyForRelationship) { serializedKey = this.keyForRelationship(relationship.key, relationship.kind, "serialize"); } if (!embeddedSnapshot) { json[serializedKey] = null; } else { json[serializedKey] = embeddedSnapshot.serialize({ includeId: true }); this.removeEmbeddedForeignKey(snapshot, embeddedSnapshot, relationship, json[serializedKey]); if (relationship.options.polymorphic) { this.serializePolymorphicType(snapshot, json, relationship); } } }, /** Serializes `hasMany` relationships when it is configured as embedded objects. This example of a post model has many comments: ```js Post = DS.Model.extend({ title: DS.attr('string'), body: DS.attr('string'), comments: DS.hasMany('comment') }); Comment = DS.Model.extend({ body: DS.attr('string'), post: DS.belongsTo('post') }); ``` Use a custom (type) serializer for the post model to configure embedded comments ```app/serializers/post.js import DS from 'ember-data; export default DS.RESTSerializer.extend(DS.EmbeddedRecordsMixin, { attrs: { comments: { embedded: 'always' } } }) ``` A payload with an attribute configured for embedded records can serialize the records together under the root attribute's payload: ```js { "post": { "id": "1" "title": "Rails is omakase", "body": "I want this for my ORM, I want that for my template language..." "comments": [{ "id": "1", "body": "Rails is unagi" }, { "id": "2", "body": "Omakase O_o" }] } } ``` The attrs options object can use more specific instruction for extracting and serializing. When serializing, an option to embed `ids`, `ids-and-types` or `records` can be set. When extracting the only option is `records`. So `{ embedded: 'always' }` is shorthand for: `{ serialize: 'records', deserialize: 'records' }` To embed the `ids` for a related object (using a hasMany relationship): ```app/serializers/post.js import DS from 'ember-data; export default DS.RESTSerializer.extend(DS.EmbeddedRecordsMixin, { attrs: { comments: { serialize: 'ids', deserialize: 'records' } } }) ``` ```js { "post": { "id": "1" "title": "Rails is omakase", "body": "I want this for my ORM, I want that for my template language..." "comments": ["1", "2"] } } ``` To embed the relationship as a collection of objects with `id` and `type` keys, set `ids-and-types` for the related object. This is particularly useful for polymorphic relationships where records don't share the same table and the `id` is not enough information. By example having a user that has many pets: ```js User = DS.Model.extend({ name: DS.attr('string'), pets: DS.hasMany('pet', { polymorphic: true }) }); Pet = DS.Model.extend({ name: DS.attr('string'), }); Cat = Pet.extend({ // ... }); Parrot = Pet.extend({ // ... }); ``` ```app/serializers/user.js import DS from 'ember-data; export default DS.RESTSerializer.extend(DS.EmbeddedRecordsMixin, { attrs: { pets: { serialize: 'ids-and-types', deserialize: 'records' } } }); ``` ```js { "user": { "id": "1" "name": "Bertin Osborne", "pets": [ { "id": "1", "type": "Cat" }, { "id": "1", "type": "Parrot"} ] } } ``` @method serializeHasMany @param {DS.Snapshot} snapshot @param {Object} json @param {Object} relationship */ serializeHasMany: function (snapshot, json, relationship) { var attr = relationship.key; if (this.noSerializeOptionSpecified(attr)) { this._super(snapshot, json, relationship); return; } if (this.hasSerializeIdsOption(attr)) { var serializedKey = this._getMappedKey(relationship.key, snapshot.type); if (serializedKey === relationship.key && this.keyForRelationship) { serializedKey = this.keyForRelationship(relationship.key, relationship.kind, "serialize"); } json[serializedKey] = snapshot.hasMany(attr, { ids: true }); } else if (this.hasSerializeRecordsOption(attr)) { this._serializeEmbeddedHasMany(snapshot, json, relationship); } else { if (this.hasSerializeIdsAndTypesOption(attr)) { this._serializeHasManyAsIdsAndTypes(snapshot, json, relationship); } } }, /* Serializes a hasMany relationship as an array of objects containing only `id` and `type` keys. This has its use case on polymorphic hasMany relationships where the server is not storing all records in the same table using STI, and therefore the `id` is not enough information TODO: Make the default in Ember-data 3.0?? */ _serializeHasManyAsIdsAndTypes: function (snapshot, json, relationship) { var serializedKey = this.keyForAttribute(relationship.key, 'serialize'); var hasMany = snapshot.hasMany(relationship.key); json[serializedKey] = _ember.default.A(hasMany).map(function (recordSnapshot) { // // I'm sure I'm being utterly naive here. Propably id is a configurate property and // type too, and the modelName has to be normalized somehow. // return { id: recordSnapshot.id, type: recordSnapshot.modelName }; }); }, _serializeEmbeddedHasMany: function (snapshot, json, relationship) { var serializedKey = this._getMappedKey(relationship.key, snapshot.type); if (serializedKey === relationship.key && this.keyForRelationship) { serializedKey = this.keyForRelationship(relationship.key, relationship.kind, "serialize"); } (false && _ember.default.warn('The embedded relationship \'' + serializedKey + '\' is undefined for \'' + snapshot.modelName + '\' with id \'' + snapshot.id + '\'. Please include it in your original payload.', _ember.default.typeOf(snapshot.hasMany(relationship.key)) !== 'undefined', { id: 'ds.serializer.embedded-relationship-undefined' })); json[serializedKey] = this._generateSerializedHasMany(snapshot, relationship); }, /* Returns an array of embedded records serialized to JSON */ _generateSerializedHasMany: function (snapshot, relationship) { var hasMany = snapshot.hasMany(relationship.key); var manyArray = _ember.default.A(hasMany); var ret = new Array(manyArray.length); for (var i = 0; i < manyArray.length; i++) { var embeddedSnapshot = manyArray[i]; var embeddedJson = embeddedSnapshot.serialize({ includeId: true }); this.removeEmbeddedForeignKey(snapshot, embeddedSnapshot, relationship, embeddedJson); ret[i] = embeddedJson; } return ret; }, /** When serializing an embedded record, modify the property (in the json payload) that refers to the parent record (foreign key for relationship). Serializing a `belongsTo` relationship removes the property that refers to the parent record Serializing a `hasMany` relationship does not remove the property that refers to the parent record. @method removeEmbeddedForeignKey @param {DS.Snapshot} snapshot @param {DS.Snapshot} embeddedSnapshot @param {Object} relationship @param {Object} json */ removeEmbeddedForeignKey: function (snapshot, embeddedSnapshot, relationship, json) { if (relationship.kind === 'belongsTo') { var parentRecord = snapshot.type.inverseFor(relationship.key, this.store); if (parentRecord) { var name = parentRecord.name; var embeddedSerializer = this.store.serializerFor(embeddedSnapshot.modelName); var parentKey = embeddedSerializer.keyForRelationship(name, parentRecord.kind, 'deserialize'); if (parentKey) { delete json[parentKey]; } } } /*else if (relationship.kind === 'hasMany') { return; }*/ }, // checks config for attrs option to embedded (always) - serialize and deserialize hasEmbeddedAlwaysOption: function (attr) { var option = this.attrsOption(attr); return option && option.embedded === 'always'; }, // checks config for attrs option to serialize ids hasSerializeRecordsOption: function (attr) { var alwaysEmbed = this.hasEmbeddedAlwaysOption(attr); var option = this.attrsOption(attr); return alwaysEmbed || option && option.serialize === 'records'; }, // checks config for attrs option to serialize records hasSerializeIdsOption: function (attr) { var option = this.attrsOption(attr); return option && (option.serialize === 'ids' || option.serialize === 'id'); }, // checks config for attrs option to serialize records as objects containing id and types hasSerializeIdsAndTypesOption: function (attr) { var option = this.attrsOption(attr); return option && (option.serialize === 'ids-and-types' || option.serialize === 'id-and-type'); }, // checks config for attrs option to serialize records noSerializeOptionSpecified: function (attr) { var option = this.attrsOption(attr); return !(option && (option.serialize || option.embedded)); }, // checks config for attrs option to deserialize records // a defined option object for a resource is treated the same as // `deserialize: 'records'` hasDeserializeRecordsOption: function (attr) { var alwaysEmbed = this.hasEmbeddedAlwaysOption(attr); var option = this.attrsOption(attr); return alwaysEmbed || option && option.deserialize === 'records'; }, attrsOption: function (attr) { var attrs = this.get('attrs'); return attrs && (attrs[camelize(attr)] || attrs[attr]); }, /** @method _extractEmbeddedRecords @private */ _extractEmbeddedRecords: function (serializer, store, typeClass, partial) { var _this = this; typeClass.eachRelationship(function (key, relationship) { if (serializer.hasDeserializeRecordsOption(key)) { if (relationship.kind === "hasMany") { _this._extractEmbeddedHasMany(store, key, partial, relationship); } if (relationship.kind === "belongsTo") { _this._extractEmbeddedBelongsTo(store, key, partial, relationship); } } }); return partial; }, /** @method _extractEmbeddedHasMany @private */ _extractEmbeddedHasMany: function (store, key, hash, relationshipMeta) { var relationshipHash = get(hash, 'data.relationships.' + key + '.data'); if (!relationshipHash) { return; } var hasMany = new Array(relationshipHash.length); for (var i = 0; i < relationshipHash.length; i++) { var item = relationshipHash[i]; var _normalizeEmbeddedRel = this._normalizeEmbeddedRelationship(store, relationshipMeta, item), data = _normalizeEmbeddedRel.data, included = _normalizeEmbeddedRel.included; hash.included = hash.included || []; hash.included.push(data); if (included) { var _hash$included; (_hash$included = hash.included).push.apply(_hash$included, _toConsumableArray(included)); } hasMany[i] = { id: data.id, type: data.type }; } var relationship = { data: hasMany }; set(hash, 'data.relationships.' + key, relationship); }, /** @method _extractEmbeddedBelongsTo @private */ _extractEmbeddedBelongsTo: function (store, key, hash, relationshipMeta) { var relationshipHash = get(hash, 'data.relationships.' + key + '.data'); if (!relationshipHash) { return; } var _normalizeEmbeddedRel2 = this._normalizeEmbeddedRelationship(store, relationshipMeta, relationshipHash), data = _normalizeEmbeddedRel2.data, included = _normalizeEmbeddedRel2.included; hash.included = hash.included || []; hash.included.push(data); if (included) { var _hash$included2; (_hash$included2 = hash.included).push.apply(_hash$included2, _toConsumableArray(included)); } var belongsTo = { id: data.id, type: data.type }; var relationship = { data: belongsTo }; set(hash, 'data.relationships.' + key, relationship); }, /** @method _normalizeEmbeddedRelationship @private */ _normalizeEmbeddedRelationship: function (store, relationshipMeta, relationshipHash) { var modelName = relationshipMeta.type; if (relationshipMeta.options.polymorphic) { modelName = relationshipHash.type; } var modelClass = store.modelFor(modelName); var serializer = store.serializerFor(modelName); return serializer.normalize(modelClass, relationshipHash, null); }, isEmbeddedRecordsMixin: true }); }); define('ember-data/serializers/json-api', ['exports', 'ember', 'ember-inflector', 'ember-data/serializers/json', 'ember-data/-private'], function (exports, _ember, _emberInflector, _json, _private) { 'use strict'; exports.__esModule = true; /** @module ember-data */ var dasherize = _ember.default.String.dasherize; /** Ember Data 2.0 Serializer: In Ember Data a Serializer is used to serialize and deserialize records when they are transferred in and out of an external source. This process involves normalizing property names, transforming attribute values and serializing relationships. `JSONAPISerializer` supports the http://jsonapi.org/ spec and is the serializer recommended by Ember Data. This serializer normalizes a JSON API payload that looks like: ```app/models/player.js import DS from 'ember-data'; export default DS.Model.extend({ name: DS.attr('string'), skill: DS.attr('string'), gamesPlayed: DS.attr('number'), club: DS.belongsTo('club') }); ``` ```app/models/club.js import DS from 'ember-data'; export default DS.Model.extend({ name: DS.attr('string'), location: DS.attr('string'), players: DS.hasMany('player') }); ``` ```js { "data": [ { "attributes": { "name": "Benfica", "location": "Portugal" }, "id": "1", "relationships": { "players": { "data": [ { "id": "3", "type": "players" } ] } }, "type": "clubs" } ], "included": [ { "attributes": { "name": "Eusebio Silva Ferreira", "skill": "Rocket shot", "games-played": 431 }, "id": "3", "relationships": { "club": { "data": { "id": "1", "type": "clubs" } } }, "type": "players" } ] } ``` to the format that the Ember Data store expects. ### Customizing meta Since a JSON API Document can have meta defined in multiple locations you can use the specific serializer hooks if you need to customize the meta. One scenario would be to camelCase the meta keys of your payload. The example below shows how this could be done using `normalizeArrayResponse` and `extractRelationship`. ```app/serializers/application.js export default JSONAPISerializer.extend({ normalizeArrayResponse(store, primaryModelClass, payload, id, requestType) { let normalizedDocument = this._super(...arguments); // Customize document meta normalizedDocument.meta = camelCaseKeys(normalizedDocument.meta); return normalizedDocument; }, extractRelationship(relationshipHash) { let normalizedRelationship = this._super(...arguments); // Customize relationship meta normalizedRelationship.meta = camelCaseKeys(normalizedRelationship.meta); return normalizedRelationship; } }); ``` @since 1.13.0 @class JSONAPISerializer @namespace DS @extends DS.JSONSerializer */ var JSONAPISerializer = _json.default.extend({ _normalizeDocumentHelper: function (documentHash) { if (_ember.default.typeOf(documentHash.data) === 'object') { documentHash.data = this._normalizeResourceHelper(documentHash.data); } else if (Array.isArray(documentHash.data)) { var ret = new Array(documentHash.data.length); for (var i = 0; i < documentHash.data.length; i++) { var data = documentHash.data[i]; ret[i] = this._normalizeResourceHelper(data); } documentHash.data = ret; } if (Array.isArray(documentHash.included)) { var _ret = new Array(); for (var _i = 0; _i < documentHash.included.length; _i++) { var included = documentHash.included[_i]; var normalized = this._normalizeResourceHelper(included); if (normalized !== null) { // can be null when unknown type is encountered _ret.push(normalized); } } documentHash.included = _ret; } return documentHash; }, _normalizeRelationshipDataHelper: function (relationshipDataHash) { if ((0, _private.isEnabled)("ds-payload-type-hooks")) { var modelName = this.modelNameFromPayloadType(relationshipDataHash.type); var deprecatedModelNameLookup = this.modelNameFromPayloadKey(relationshipDataHash.type); if (modelName !== deprecatedModelNameLookup && this._hasCustomModelNameFromPayloadKey()) { (false && !(false) && _ember.default.deprecate("You are using modelNameFromPayloadKey to normalize the type for a relationship. This has been deprecated in favor of modelNameFromPayloadType", false, { id: 'ds.json-api-serializer.deprecated-model-name-for-relationship', until: '3.0.0' })); modelName = deprecatedModelNameLookup; } relationshipDataHash.type = modelName; } else { relationshipDataHash.type = this.modelNameFromPayloadKey(relationshipDataHash.type); } return relationshipDataHash; }, _normalizeResourceHelper: function (resourceHash) { (false && _ember.default.assert(this.warnMessageForUndefinedType(), !_ember.default.isNone(resourceHash.type), { id: 'ds.serializer.type-is-undefined' })); var modelName = void 0, usedLookup = void 0; if ((0, _private.isEnabled)("ds-payload-type-hooks")) { modelName = this.modelNameFromPayloadType(resourceHash.type); var deprecatedModelNameLookup = this.modelNameFromPayloadKey(resourceHash.type); usedLookup = 'modelNameFromPayloadType'; if (modelName !== deprecatedModelNameLookup && this._hasCustomModelNameFromPayloadKey()) { (false && !(false) && _ember.default.deprecate("You are using modelNameFromPayloadKey to normalize the type for a resource. This has been deprecated in favor of modelNameFromPayloadType", false, { id: 'ds.json-api-serializer.deprecated-model-name-for-resource', until: '3.0.0' })); modelName = deprecatedModelNameLookup; usedLookup = 'modelNameFromPayloadKey'; } } else { modelName = this.modelNameFromPayloadKey(resourceHash.type); usedLookup = 'modelNameFromPayloadKey'; } if (!this.store._hasModelFor(modelName)) { (false && _ember.default.warn(this.warnMessageNoModelForType(modelName, resourceHash.type, usedLookup), false, { id: 'ds.serializer.model-for-type-missing' })); return null; } var modelClass = this.store._modelFor(modelName); var serializer = this.store.serializerFor(modelName); var _serializer$normalize = serializer.normalize(modelClass, resourceHash), data = _serializer$normalize.data; return data; }, pushPayload: function (store, payload) { var normalizedPayload = this._normalizeDocumentHelper(payload); if ((0, _private.isEnabled)('ds-pushpayload-return')) { return store.push(normalizedPayload); } else { store.push(normalizedPayload); } }, _normalizeResponse: function (store, primaryModelClass, payload, id, requestType, isSingle) { var normalizedPayload = this._normalizeDocumentHelper(payload); return normalizedPayload; }, normalizeQueryRecordResponse: function () { var normalized = this._super.apply(this, arguments); (false && _ember.default.assert('Expected the primary data returned by the serializer for a `queryRecord` response to be a single object but instead it was an array.', !Array.isArray(normalized.data), { id: 'ds.serializer.json-api.queryRecord-array-response' })); return normalized; }, extractAttributes: function (modelClass, resourceHash) { var _this = this; var attributes = {}; if (resourceHash.attributes) { modelClass.eachAttribute(function (key) { var attributeKey = _this.keyForAttribute(key, 'deserialize'); if (resourceHash.attributes[attributeKey] !== undefined) { attributes[key] = resourceHash.attributes[attributeKey]; } if (false) { if (resourceHash.attributes[attributeKey] === undefined && resourceHash.attributes[key] !== undefined) { (false && _ember.default.assert('Your payload for \'' + modelClass.modelName + '\' contains \'' + key + '\', but your serializer is setup to look for \'' + attributeKey + '\'. This is most likely because Ember Data\'s JSON API serializer dasherizes attribute keys by default. You should subclass JSONAPISerializer and implement \'keyForAttribute(key) { return key; }\' to prevent Ember Data from customizing your attribute keys.', false)); } } }); } return attributes; }, extractRelationship: function (relationshipHash) { if (_ember.default.typeOf(relationshipHash.data) === 'object') { relationshipHash.data = this._normalizeRelationshipDataHelper(relationshipHash.data); } if (Array.isArray(relationshipHash.data)) { var ret = new Array(relationshipHash.data.length); for (var i = 0; i < relationshipHash.data.length; i++) { var data = relationshipHash.data[i]; ret[i] = this._normalizeRelationshipDataHelper(data); } relationshipHash.data = ret; } return relationshipHash; }, extractRelationships: function (modelClass, resourceHash) { var _this2 = this; var relationships = {}; if (resourceHash.relationships) { modelClass.eachRelationship(function (key, relationshipMeta) { var relationshipKey = _this2.keyForRelationship(key, relationshipMeta.kind, 'deserialize'); if (resourceHash.relationships[relationshipKey] !== undefined) { var relationshipHash = resourceHash.relationships[relationshipKey]; relationships[key] = _this2.extractRelationship(relationshipHash); } if (false) { if (resourceHash.relationships[relationshipKey] === undefined && resourceHash.relationships[key] !== undefined) { (false && _ember.default.assert('Your payload for \'' + modelClass.modelName + '\' contains \'' + key + '\', but your serializer is setup to look for \'' + relationshipKey + '\'. This is most likely because Ember Data\'s JSON API serializer dasherizes relationship keys by default. You should subclass JSONAPISerializer and implement \'keyForRelationship(key) { return key; }\' to prevent Ember Data from customizing your relationship keys.', false)); } } }); } return relationships; }, _extractType: function (modelClass, resourceHash) { if ((0, _private.isEnabled)("ds-payload-type-hooks")) { var modelName = this.modelNameFromPayloadType(resourceHash.type); var deprecatedModelNameLookup = this.modelNameFromPayloadKey(resourceHash.type); if (modelName !== deprecatedModelNameLookup && this._hasCustomModelNameFromPayloadKey()) { (false && !(false) && _ember.default.deprecate("You are using modelNameFromPayloadKey to normalize the type for a polymorphic relationship. This has been deprecated in favor of modelNameFromPayloadType", false, { id: 'ds.json-api-serializer.deprecated-model-name-for-polymorphic-type', until: '3.0.0' })); modelName = deprecatedModelNameLookup; } return modelName; } else { return this.modelNameFromPayloadKey(resourceHash.type); } }, modelNameFromPayloadKey: function (key) { return (0, _emberInflector.singularize)((0, _private.normalizeModelName)(key)); }, payloadKeyFromModelName: function (modelName) { return (0, _emberInflector.pluralize)(modelName); }, normalize: function (modelClass, resourceHash) { if (resourceHash.attributes) { this.normalizeUsingDeclaredMapping(modelClass, resourceHash.attributes); } if (resourceHash.relationships) { this.normalizeUsingDeclaredMapping(modelClass, resourceHash.relationships); } var data = { id: this.extractId(modelClass, resourceHash), type: this._extractType(modelClass, resourceHash), attributes: this.extractAttributes(modelClass, resourceHash), relationships: this.extractRelationships(modelClass, resourceHash) }; this.applyTransforms(modelClass, data.attributes); return { data: data }; }, keyForAttribute: function (key, method) { return dasherize(key); }, keyForRelationship: function (key, typeClass, method) { return dasherize(key); }, serialize: function (snapshot, options) { var data = this._super.apply(this, arguments); var payloadType = void 0; if ((0, _private.isEnabled)("ds-payload-type-hooks")) { payloadType = this.payloadTypeFromModelName(snapshot.modelName); var deprecatedPayloadTypeLookup = this.payloadKeyFromModelName(snapshot.modelName); if (payloadType !== deprecatedPayloadTypeLookup && this._hasCustomPayloadKeyFromModelName()) { (false && !(false) && _ember.default.deprecate("You used payloadKeyFromModelName to customize how a type is serialized. Use payloadTypeFromModelName instead.", false, { id: 'ds.json-api-serializer.deprecated-payload-type-for-model', until: '3.0.0' })); payloadType = deprecatedPayloadTypeLookup; } } else { payloadType = this.payloadKeyFromModelName(snapshot.modelName); } data.type = payloadType; return { data: data }; }, serializeAttribute: function (snapshot, json, key, attribute) { var type = attribute.type; if (this._canSerialize(key)) { json.attributes = json.attributes || {}; var value = snapshot.attr(key); if (type) { var transform = this.transformFor(type); value = transform.serialize(value, attribute.options); } var payloadKey = this._getMappedKey(key, snapshot.type); if (payloadKey === key) { payloadKey = this.keyForAttribute(key, 'serialize'); } json.attributes[payloadKey] = value; } }, serializeBelongsTo: function (snapshot, json, relationship) { var key = relationship.key; if (this._canSerialize(key)) { var belongsTo = snapshot.belongsTo(key); if (belongsTo !== undefined) { json.relationships = json.relationships || {}; var payloadKey = this._getMappedKey(key, snapshot.type); if (payloadKey === key) { payloadKey = this.keyForRelationship(key, 'belongsTo', 'serialize'); } var data = null; if (belongsTo) { var payloadType = void 0; if ((0, _private.isEnabled)("ds-payload-type-hooks")) { payloadType = this.payloadTypeFromModelName(belongsTo.modelName); var deprecatedPayloadTypeLookup = this.payloadKeyFromModelName(belongsTo.modelName); if (payloadType !== deprecatedPayloadTypeLookup && this._hasCustomPayloadKeyFromModelName()) { (false && !(false) && _ember.default.deprecate("You used payloadKeyFromModelName to serialize type for belongs-to relationship. Use payloadTypeFromModelName instead.", false, { id: 'ds.json-api-serializer.deprecated-payload-type-for-belongs-to', until: '3.0.0' })); payloadType = deprecatedPayloadTypeLookup; } } else { payloadType = this.payloadKeyFromModelName(belongsTo.modelName); } data = { type: payloadType, id: belongsTo.id }; } json.relationships[payloadKey] = { data: data }; } } }, serializeHasMany: function (snapshot, json, relationship) { var key = relationship.key; var shouldSerializeHasMany = '_shouldSerializeHasMany'; if ((0, _private.isEnabled)("ds-check-should-serialize-relationships")) { shouldSerializeHasMany = 'shouldSerializeHasMany'; } if (this[shouldSerializeHasMany](snapshot, key, relationship)) { var hasMany = snapshot.hasMany(key); if (hasMany !== undefined) { json.relationships = json.relationships || {}; var payloadKey = this._getMappedKey(key, snapshot.type); if (payloadKey === key && this.keyForRelationship) { payloadKey = this.keyForRelationship(key, 'hasMany', 'serialize'); } var data = new Array(hasMany.length); for (var i = 0; i < hasMany.length; i++) { var item = hasMany[i]; var payloadType = void 0; if ((0, _private.isEnabled)("ds-payload-type-hooks")) { payloadType = this.payloadTypeFromModelName(item.modelName); var deprecatedPayloadTypeLookup = this.payloadKeyFromModelName(item.modelName); if (payloadType !== deprecatedPayloadTypeLookup && this._hasCustomPayloadKeyFromModelName()) { (false && !(false) && _ember.default.deprecate("You used payloadKeyFromModelName to serialize type for belongs-to relationship. Use payloadTypeFromModelName instead.", false, { id: 'ds.json-api-serializer.deprecated-payload-type-for-has-many', until: '3.0.0' })); payloadType = deprecatedPayloadTypeLookup; } } else { payloadType = this.payloadKeyFromModelName(item.modelName); } data[i] = { type: payloadType, id: item.id }; } json.relationships[payloadKey] = { data: data }; } } } }); if ((0, _private.isEnabled)("ds-payload-type-hooks")) { JSONAPISerializer.reopen({ modelNameFromPayloadType: function (type) { return (0, _emberInflector.singularize)((0, _private.normalizeModelName)(type)); }, payloadTypeFromModelName: function (modelName) { return (0, _emberInflector.pluralize)(modelName); }, _hasCustomModelNameFromPayloadKey: function () { return this.modelNameFromPayloadKey !== JSONAPISerializer.prototype.modelNameFromPayloadKey; }, _hasCustomPayloadKeyFromModelName: function () { return this.payloadKeyFromModelName !== JSONAPISerializer.prototype.payloadKeyFromModelName; } }); } if (false) { JSONAPISerializer.reopen({ willMergeMixin: function (props) { var constructor = this.constructor; (false && _ember.default.warn('You\'ve defined \'extractMeta\' in ' + constructor.toString() + ' which is not used for serializers extending JSONAPISerializer. Read more at https://emberjs.com/api/data/classes/DS.JSONAPISerializer.html#toc_customizing-meta on how to customize meta when using JSON API.', _ember.default.isNone(props.extractMeta) || props.extractMeta === _json.default.prototype.extractMeta, { id: 'ds.serializer.json-api.extractMeta' })); (false && _ember.default.warn('The JSONAPISerializer does not work with the EmbeddedRecordsMixin because the JSON API spec does not describe how to format embedded resources.', !props.isEmbeddedRecordsMixin, { id: 'ds.serializer.embedded-records-mixin-not-supported' })); }, warnMessageForUndefinedType: function () { return 'Encountered a resource object with an undefined type (resolved resource using ' + this.constructor.toString() + ')'; }, warnMessageNoModelForType: function (modelName, originalType, usedLookup) { return 'Encountered a resource object with type "' + originalType + '", but no model was found for model name "' + modelName + '" (resolved model name using \'' + this.constructor.toString() + '.' + usedLookup + '("' + originalType + '")\').'; } }); } exports.default = JSONAPISerializer; }); define('ember-data/serializers/json', ['exports', 'ember', 'ember-data/serializer', 'ember-data/-private'], function (exports, _ember, _serializer, _private) { 'use strict'; exports.__esModule = true; function _toConsumableArray(arr) { if (Array.isArray(arr)) { for (var i = 0, arr2 = Array(arr.length); i < arr.length; i++) { arr2[i] = arr[i]; } return arr2; } else { return Array.from(arr); } } var get = _ember.default.get; var isNone = _ember.default.isNone; var assign = _ember.default.assign || _ember.default.merge; /** Ember Data 2.0 Serializer: In Ember Data a Serializer is used to serialize and deserialize records when they are transferred in and out of an external source. This process involves normalizing property names, transforming attribute values and serializing relationships. By default, Ember Data uses and recommends the `JSONAPISerializer`. `JSONSerializer` is useful for simpler or legacy backends that may not support the http://jsonapi.org/ spec. For example, given the following `User` model and JSON payload: ```app/models/user.js import DS from 'ember-data'; export default DS.Model.extend({ friends: DS.hasMany('user'), house: DS.belongsTo('location'), name: DS.attr('string') }); ``` ```js { id: 1, name: 'Sebastian', friends: [3, 4], links: { house: '/houses/lefkada' } } ``` `JSONSerializer` will normalize the JSON payload to the JSON API format that the Ember Data store expects. You can customize how JSONSerializer processes its payload by passing options in the `attrs` hash or by subclassing the `JSONSerializer` and overriding hooks: - To customize how a single record is normalized, use the `normalize` hook. - To customize how `JSONSerializer` normalizes the whole server response, use the `normalizeResponse` hook. - To customize how `JSONSerializer` normalizes a specific response from the server, use one of the many specific `normalizeResponse` hooks. - To customize how `JSONSerializer` normalizes your id, attributes or relationships, use the `extractId`, `extractAttributes` and `extractRelationships` hooks. The `JSONSerializer` normalization process follows these steps: - `normalizeResponse` - entry method to the serializer. - `normalizeCreateRecordResponse` - a `normalizeResponse` for a specific operation is called. - `normalizeSingleResponse`|`normalizeArrayResponse` - for methods like `createRecord` we expect a single record back, while for methods like `findAll` we expect multiple records back. - `normalize` - `normalizeArray` iterates and calls `normalize` for each of its records while `normalizeSingle` calls it once. This is the method you most likely want to subclass. - `extractId` | `extractAttributes` | `extractRelationships` - `normalize` delegates to these methods to turn the record payload into the JSON API format. @class JSONSerializer @namespace DS @extends DS.Serializer */ var JSONSerializer = _serializer.default.extend({ /** The `primaryKey` is used when serializing and deserializing data. Ember Data always uses the `id` property to store the id of the record. The external source may not always follow this convention. In these cases it is useful to override the `primaryKey` property to match the `primaryKey` of your external store. Example ```app/serializers/application.js import DS from 'ember-data'; export default DS.JSONSerializer.extend({ primaryKey: '_id' }); ``` @property primaryKey @type {String} @default 'id' */ primaryKey: 'id', /** The `attrs` object can be used to declare a simple mapping between property names on `DS.Model` records and payload keys in the serialized JSON object representing the record. An object with the property `key` can also be used to designate the attribute's key on the response payload. Example ```app/models/person.js import DS from 'ember-data'; export default DS.Model.extend({ firstName: DS.attr('string'), lastName: DS.attr('string'), occupation: DS.attr('string'), admin: DS.attr('boolean') }); ``` ```app/serializers/person.js import DS from 'ember-data'; export default DS.JSONSerializer.extend({ attrs: { admin: 'is_admin', occupation: { key: 'career' } } }); ``` You can also remove attributes by setting the `serialize` key to `false` in your mapping object. Example ```app/serializers/person.js import DS from 'ember-data'; export default DS.JSONSerializer.extend({ attrs: { admin: { serialize: false }, occupation: { key: 'career' } } }); ``` When serialized: ```javascript { "firstName": "Harry", "lastName": "Houdini", "career": "magician" } ``` Note that the `admin` is now not included in the payload. @property attrs @type {Object} */ mergedProperties: ['attrs'], applyTransforms: function (typeClass, data) { var _this = this; var attributes = get(typeClass, 'attributes'); typeClass.eachTransformedAttribute(function (key, typeClass) { if (data[key] === undefined) { return; } var transform = _this.transformFor(typeClass); var transformMeta = attributes.get(key); data[key] = transform.deserialize(data[key], transformMeta.options); }); return data; }, normalizeResponse: function (store, primaryModelClass, payload, id, requestType) { switch (requestType) { case 'findRecord': return this.normalizeFindRecordResponse.apply(this, arguments); case 'queryRecord': return this.normalizeQueryRecordResponse.apply(this, arguments); case 'findAll': return this.normalizeFindAllResponse.apply(this, arguments); case 'findBelongsTo': return this.normalizeFindBelongsToResponse.apply(this, arguments); case 'findHasMany': return this.normalizeFindHasManyResponse.apply(this, arguments); case 'findMany': return this.normalizeFindManyResponse.apply(this, arguments); case 'query': return this.normalizeQueryResponse.apply(this, arguments); case 'createRecord': return this.normalizeCreateRecordResponse.apply(this, arguments); case 'deleteRecord': return this.normalizeDeleteRecordResponse.apply(this, arguments); case 'updateRecord': return this.normalizeUpdateRecordResponse.apply(this, arguments); } }, normalizeFindRecordResponse: function (store, primaryModelClass, payload, id, requestType) { return this.normalizeSingleResponse.apply(this, arguments); }, normalizeQueryRecordResponse: function (store, primaryModelClass, payload, id, requestType) { return this.normalizeSingleResponse.apply(this, arguments); }, normalizeFindAllResponse: function (store, primaryModelClass, payload, id, requestType) { return this.normalizeArrayResponse.apply(this, arguments); }, normalizeFindBelongsToResponse: function (store, primaryModelClass, payload, id, requestType) { return this.normalizeSingleResponse.apply(this, arguments); }, normalizeFindHasManyResponse: function (store, primaryModelClass, payload, id, requestType) { return this.normalizeArrayResponse.apply(this, arguments); }, normalizeFindManyResponse: function (store, primaryModelClass, payload, id, requestType) { return this.normalizeArrayResponse.apply(this, arguments); }, normalizeQueryResponse: function (store, primaryModelClass, payload, id, requestType) { return this.normalizeArrayResponse.apply(this, arguments); }, normalizeCreateRecordResponse: function (store, primaryModelClass, payload, id, requestType) { return this.normalizeSaveResponse.apply(this, arguments); }, normalizeDeleteRecordResponse: function (store, primaryModelClass, payload, id, requestType) { return this.normalizeSaveResponse.apply(this, arguments); }, normalizeUpdateRecordResponse: function (store, primaryModelClass, payload, id, requestType) { return this.normalizeSaveResponse.apply(this, arguments); }, normalizeSaveResponse: function (store, primaryModelClass, payload, id, requestType) { return this.normalizeSingleResponse.apply(this, arguments); }, normalizeSingleResponse: function (store, primaryModelClass, payload, id, requestType) { return this._normalizeResponse(store, primaryModelClass, payload, id, requestType, true); }, normalizeArrayResponse: function (store, primaryModelClass, payload, id, requestType) { return this._normalizeResponse(store, primaryModelClass, payload, id, requestType, false); }, _normalizeResponse: function (store, primaryModelClass, payload, id, requestType, isSingle) { var documentHash = { data: null, included: [] }; var meta = this.extractMeta(store, primaryModelClass, payload); if (meta) { (false && _ember.default.assert('The `meta` returned from `extractMeta` has to be an object, not "' + _ember.default.typeOf(meta) + '".', _ember.default.typeOf(meta) === 'object')); documentHash.meta = meta; } if (isSingle) { var _normalize = this.normalize(primaryModelClass, payload), data = _normalize.data, included = _normalize.included; documentHash.data = data; if (included) { documentHash.included = included; } } else { var ret = new Array(payload.length); for (var i = 0, l = payload.length; i < l; i++) { var item = payload[i]; var _normalize2 = this.normalize(primaryModelClass, item), _data = _normalize2.data, _included = _normalize2.included; if (_included) { var _documentHash$include; (_documentHash$include = documentHash.included).push.apply(_documentHash$include, _toConsumableArray(_included)); } ret[i] = _data; } documentHash.data = ret; } return documentHash; }, normalize: function (modelClass, resourceHash) { var data = null; if (resourceHash) { this.normalizeUsingDeclaredMapping(modelClass, resourceHash); if (_ember.default.typeOf(resourceHash.links) === 'object') { this.normalizeUsingDeclaredMapping(modelClass, resourceHash.links); } data = { id: this.extractId(modelClass, resourceHash), type: modelClass.modelName, attributes: this.extractAttributes(modelClass, resourceHash), relationships: this.extractRelationships(modelClass, resourceHash) }; this.applyTransforms(modelClass, data.attributes); } return { data: data }; }, extractId: function (modelClass, resourceHash) { var primaryKey = get(this, 'primaryKey'); var id = resourceHash[primaryKey]; return (0, _private.coerceId)(id); }, extractAttributes: function (modelClass, resourceHash) { var _this2 = this; var attributeKey = void 0; var attributes = {}; modelClass.eachAttribute(function (key) { attributeKey = _this2.keyForAttribute(key, 'deserialize'); if (resourceHash[attributeKey] !== undefined) { attributes[key] = resourceHash[attributeKey]; } }); return attributes; }, extractRelationship: function (relationshipModelName, relationshipHash) { if (_ember.default.isNone(relationshipHash)) { return null; } /* When `relationshipHash` is an object it usually means that the relationship is polymorphic. It could however also be embedded resources that the EmbeddedRecordsMixin has be able to process. */ if (_ember.default.typeOf(relationshipHash) === 'object') { if (relationshipHash.id) { relationshipHash.id = (0, _private.coerceId)(relationshipHash.id); } var modelClass = this.store.modelFor(relationshipModelName); if (relationshipHash.type && !(0, _private.modelHasAttributeOrRelationshipNamedType)(modelClass)) { if ((0, _private.isEnabled)("ds-payload-type-hooks")) { var modelName = this.modelNameFromPayloadType(relationshipHash.type); var deprecatedModelNameLookup = this.modelNameFromPayloadKey(relationshipHash.type); if (modelName !== deprecatedModelNameLookup && this._hasCustomModelNameFromPayloadKey()) { (false && !(false) && _ember.default.deprecate("You used modelNameFromPayloadKey to customize how a type is normalized. Use modelNameFromPayloadType instead", false, { id: 'ds.json-serializer.deprecated-type-for-polymorphic-relationship', until: '3.0.0' })); modelName = deprecatedModelNameLookup; } relationshipHash.type = modelName; } else { relationshipHash.type = this.modelNameFromPayloadKey(relationshipHash.type); } } return relationshipHash; } return { id: (0, _private.coerceId)(relationshipHash), type: relationshipModelName }; }, extractPolymorphicRelationship: function (relationshipModelName, relationshipHash, relationshipOptions) { return this.extractRelationship(relationshipModelName, relationshipHash); }, extractRelationships: function (modelClass, resourceHash) { var _this3 = this; var relationships = {}; modelClass.eachRelationship(function (key, relationshipMeta) { var relationship = null; var relationshipKey = _this3.keyForRelationship(key, relationshipMeta.kind, 'deserialize'); if (resourceHash[relationshipKey] !== undefined) { var data = null; var relationshipHash = resourceHash[relationshipKey]; if (relationshipMeta.kind === 'belongsTo') { if (relationshipMeta.options.polymorphic) { // extracting a polymorphic belongsTo may need more information // than the type and the hash (which might only be an id) for the // relationship, hence we pass the key, resource and // relationshipMeta too data = _this3.extractPolymorphicRelationship(relationshipMeta.type, relationshipHash, { key: key, resourceHash: resourceHash, relationshipMeta: relationshipMeta }); } else { data = _this3.extractRelationship(relationshipMeta.type, relationshipHash); } } else if (relationshipMeta.kind === 'hasMany') { if (!_ember.default.isNone(relationshipHash)) { data = new Array(relationshipHash.length); for (var i = 0, l = relationshipHash.length; i < l; i++) { var item = relationshipHash[i]; data[i] = _this3.extractRelationship(relationshipMeta.type, item); } } } relationship = { data: data }; } var linkKey = _this3.keyForLink(key, relationshipMeta.kind); if (resourceHash.links && resourceHash.links[linkKey] !== undefined) { var related = resourceHash.links[linkKey]; relationship = relationship || {}; relationship.links = { related: related }; } if (relationship) { relationships[key] = relationship; } }); return relationships; }, modelNameFromPayloadKey: function (key) { return (0, _private.normalizeModelName)(key); }, normalizeRelationships: function (typeClass, hash) { var _this4 = this; var payloadKey = void 0; if (this.keyForRelationship) { typeClass.eachRelationship(function (key, relationship) { payloadKey = _this4.keyForRelationship(key, relationship.kind, 'deserialize'); if (key === payloadKey) { return; } if (hash[payloadKey] === undefined) { return; } hash[key] = hash[payloadKey]; delete hash[payloadKey]; }); } }, normalizeUsingDeclaredMapping: function (modelClass, hash) { var attrs = get(this, 'attrs'); var normalizedKey = void 0; var payloadKey = void 0; if (attrs) { for (var key in attrs) { normalizedKey = payloadKey = this._getMappedKey(key, modelClass); if (hash[payloadKey] === undefined) { continue; } if (get(modelClass, 'attributes').has(key)) { normalizedKey = this.keyForAttribute(key); } if (get(modelClass, 'relationshipsByName').has(key)) { normalizedKey = this.keyForRelationship(key); } if (payloadKey !== normalizedKey) { hash[normalizedKey] = hash[payloadKey]; delete hash[payloadKey]; } } } }, _getMappedKey: function (key, modelClass) { (false && _ember.default.warn('There is no attribute or relationship with the name `' + key + '` on `' + modelClass.modelName + '`. Check your serializers attrs hash.', get(modelClass, 'attributes').has(key) || get(modelClass, 'relationshipsByName').has(key), { id: 'ds.serializer.no-mapped-attrs-key' })); var attrs = get(this, 'attrs'); var mappedKey = void 0; if (attrs && attrs[key]) { mappedKey = attrs[key]; //We need to account for both the { title: 'post_title' } and //{ title: { key: 'post_title' }} forms if (mappedKey.key) { mappedKey = mappedKey.key; } if (typeof mappedKey === 'string') { key = mappedKey; } } return key; }, _canSerialize: function (key) { var attrs = get(this, 'attrs'); return !attrs || !attrs[key] || attrs[key].serialize !== false; }, _mustSerialize: function (key) { var attrs = get(this, 'attrs'); return attrs && attrs[key] && attrs[key].serialize === true; }, shouldSerializeHasMany: function (snapshot, key, relationship) { if (this._shouldSerializeHasMany !== JSONSerializer.prototype._shouldSerializeHasMany) { (false && !(false) && _ember.default.deprecate('The private method _shouldSerializeHasMany has been promoted to the public API. Please remove the underscore to use the public shouldSerializeHasMany method.', false, { id: 'ds.serializer.private-should-serialize-has-many', until: '3.0.0' })); } return this._shouldSerializeHasMany(snapshot, key, relationship); }, _shouldSerializeHasMany: function (snapshot, key, relationship) { var relationshipType = snapshot.type.determineRelationshipType(relationship, this.store); if (this._mustSerialize(key)) { return true; } return this._canSerialize(key) && (relationshipType === 'manyToNone' || relationshipType === 'manyToMany'); }, serialize: function (snapshot, options) { var _this5 = this; var json = {}; if (options && options.includeId) { if ((0, _private.isEnabled)('ds-serialize-id')) { this.serializeId(snapshot, json, get(this, 'primaryKey')); } else { var id = snapshot.id; if (id) { json[get(this, 'primaryKey')] = id; } } } snapshot.eachAttribute(function (key, attribute) { _this5.serializeAttribute(snapshot, json, key, attribute); }); snapshot.eachRelationship(function (key, relationship) { if (relationship.kind === 'belongsTo') { _this5.serializeBelongsTo(snapshot, json, relationship); } else if (relationship.kind === 'hasMany') { _this5.serializeHasMany(snapshot, json, relationship); } }); return json; }, serializeIntoHash: function (hash, typeClass, snapshot, options) { assign(hash, this.serialize(snapshot, options)); }, serializeAttribute: function (snapshot, json, key, attribute) { if (this._canSerialize(key)) { var type = attribute.type; var value = snapshot.attr(key); if (type) { var transform = this.transformFor(type); value = transform.serialize(value, attribute.options); } // if provided, use the mapping provided by `attrs` in // the serializer var payloadKey = this._getMappedKey(key, snapshot.type); if (payloadKey === key && this.keyForAttribute) { payloadKey = this.keyForAttribute(key, 'serialize'); } json[payloadKey] = value; } }, serializeBelongsTo: function (snapshot, json, relationship) { var key = relationship.key; if (this._canSerialize(key)) { var belongsToId = snapshot.belongsTo(key, { id: true }); // if provided, use the mapping provided by `attrs` in // the serializer var payloadKey = this._getMappedKey(key, snapshot.type); if (payloadKey === key && this.keyForRelationship) { payloadKey = this.keyForRelationship(key, "belongsTo", "serialize"); } //Need to check whether the id is there for new&async records if (isNone(belongsToId)) { json[payloadKey] = null; } else { json[payloadKey] = belongsToId; } if (relationship.options.polymorphic) { this.serializePolymorphicType(snapshot, json, relationship); } } }, serializeHasMany: function (snapshot, json, relationship) { var key = relationship.key; var shouldSerializeHasMany = '_shouldSerializeHasMany'; if ((0, _private.isEnabled)("ds-check-should-serialize-relationships")) { shouldSerializeHasMany = 'shouldSerializeHasMany'; } if (this[shouldSerializeHasMany](snapshot, key, relationship)) { var hasMany = snapshot.hasMany(key, { ids: true }); if (hasMany !== undefined) { // if provided, use the mapping provided by `attrs` in // the serializer var payloadKey = this._getMappedKey(key, snapshot.type); if (payloadKey === key && this.keyForRelationship) { payloadKey = this.keyForRelationship(key, "hasMany", "serialize"); } json[payloadKey] = hasMany; // TODO support for polymorphic manyToNone and manyToMany relationships } } }, serializePolymorphicType: function () {}, extractMeta: function (store, modelClass, payload) { if (payload && payload['meta'] !== undefined) { var meta = payload.meta; delete payload.meta; return meta; } }, extractErrors: function (store, typeClass, payload, id) { var _this6 = this; if (payload && typeof payload === 'object' && payload.errors) { payload = (0, _private.errorsArrayToHash)(payload.errors); this.normalizeUsingDeclaredMapping(typeClass, payload); typeClass.eachAttribute(function (name) { var key = _this6.keyForAttribute(name, 'deserialize'); if (key !== name && payload[key] !== undefined) { payload[name] = payload[key]; delete payload[key]; } }); typeClass.eachRelationship(function (name) { var key = _this6.keyForRelationship(name, 'deserialize'); if (key !== name && payload[key] !== undefined) { payload[name] = payload[key]; delete payload[key]; } }); } return payload; }, keyForAttribute: function (key, method) { return key; }, keyForRelationship: function (key, typeClass, method) { return key; }, keyForLink: function (key, kind) { return key; }, transformFor: function (attributeType, skipAssertion) { var transform = (0, _private.getOwner)(this).lookup('transform:' + attributeType); (false && _ember.default.assert("Unable to find transform for '" + attributeType + "'", skipAssertion || !!transform)); return transform; } }); if ((0, _private.isEnabled)("ds-payload-type-hooks")) { JSONSerializer.reopen({ modelNameFromPayloadType: function (type) { return (0, _private.normalizeModelName)(type); }, _hasCustomModelNameFromPayloadKey: function () { return this.modelNameFromPayloadKey !== JSONSerializer.prototype.modelNameFromPayloadKey; } }); } if ((0, _private.isEnabled)("ds-serialize-id")) { JSONSerializer.reopen({ serializeId: function (snapshot, json, primaryKey) { var id = snapshot.id; if (id) { json[primaryKey] = id; } } }); } exports.default = JSONSerializer; }); define('ember-data/serializers/rest', ['exports', 'ember', 'ember-inflector', 'ember-data/serializers/json', 'ember-data/-private'], function (exports, _ember, _emberInflector, _json, _private) { 'use strict'; exports.__esModule = true; function _toConsumableArray(arr) { if (Array.isArray(arr)) { for (var i = 0, arr2 = Array(arr.length); i < arr.length; i++) { arr2[i] = arr[i]; } return arr2; } else { return Array.from(arr); } } var camelize = _ember.default.String.camelize; /** Normally, applications will use the `RESTSerializer` by implementing the `normalize` method. This allows you to do whatever kind of munging you need, and is especially useful if your server is inconsistent and you need to do munging differently for many different kinds of responses. See the `normalize` documentation for more information. ## Across the Board Normalization There are also a number of hooks that you might find useful to define across-the-board rules for your payload. These rules will be useful if your server is consistent, or if you're building an adapter for an infrastructure service, like Firebase, and want to encode service conventions. For example, if all of your keys are underscored and all-caps, but otherwise consistent with the names you use in your models, you can implement across-the-board rules for how to convert an attribute name in your model to a key in your JSON. ```app/serializers/application.js import DS from 'ember-data'; export default DS.RESTSerializer.extend({ keyForAttribute(attr, method) { return Ember.String.underscore(attr).toUpperCase(); } }); ``` You can also implement `keyForRelationship`, which takes the name of the relationship as the first parameter, the kind of relationship (`hasMany` or `belongsTo`) as the second parameter, and the method (`serialize` or `deserialize`) as the third parameter. @class RESTSerializer @namespace DS @extends DS.JSONSerializer */ var RESTSerializer = _json.default.extend({ keyForPolymorphicType: function (key, typeClass, method) { var relationshipKey = this.keyForRelationship(key); return relationshipKey + 'Type'; }, normalize: function (modelClass, resourceHash, prop) { if (this.normalizeHash && this.normalizeHash[prop]) { (false && !(false) && _ember.default.deprecate('`RESTSerializer.normalizeHash` has been deprecated. Please use `serializer.normalize` to modify the payload of single resources.', false, { id: 'ds.serializer.normalize-hash-deprecated', until: '3.0.0' })); this.normalizeHash[prop](resourceHash); } return this._super(modelClass, resourceHash); }, _normalizeArray: function (store, modelName, arrayHash, prop) { var _this = this; var documentHash = { data: [], included: [] }; var modelClass = store.modelFor(modelName); var serializer = store.serializerFor(modelName); _ember.default.makeArray(arrayHash).forEach(function (hash) { var _normalizePolymorphic = _this._normalizePolymorphicRecord(store, hash, prop, modelClass, serializer), data = _normalizePolymorphic.data, included = _normalizePolymorphic.included; documentHash.data.push(data); if (included) { var _documentHash$include; (_documentHash$include = documentHash.included).push.apply(_documentHash$include, _toConsumableArray(included)); } }); return documentHash; }, _normalizePolymorphicRecord: function (store, hash, prop, primaryModelClass, primarySerializer) { var serializer = primarySerializer; var modelClass = primaryModelClass; var primaryHasTypeAttribute = (0, _private.modelHasAttributeOrRelationshipNamedType)(primaryModelClass); if (!primaryHasTypeAttribute && hash.type) { // Support polymorphic records in async relationships var modelName = void 0; if ((0, _private.isEnabled)("ds-payload-type-hooks")) { modelName = this.modelNameFromPayloadType(hash.type); var deprecatedModelNameLookup = this.modelNameFromPayloadKey(hash.type); if (modelName !== deprecatedModelNameLookup && !this._hasCustomModelNameFromPayloadType() && this._hasCustomModelNameFromPayloadKey()) { (false && !(false) && _ember.default.deprecate("You are using modelNameFromPayloadKey to normalize the type for a polymorphic relationship. This is has been deprecated in favor of modelNameFromPayloadType", false, { id: 'ds.rest-serializer.deprecated-model-name-for-polymorphic-type', until: '3.0.0' })); modelName = deprecatedModelNameLookup; } } else { modelName = this.modelNameFromPayloadKey(hash.type); } if (store._hasModelFor(modelName)) { serializer = store.serializerFor(modelName); modelClass = store.modelFor(modelName); } } return serializer.normalize(modelClass, hash, prop); }, _normalizeResponse: function (store, primaryModelClass, payload, id, requestType, isSingle) { var documentHash = { data: null, included: [] }; var meta = this.extractMeta(store, primaryModelClass, payload); if (meta) { (false && _ember.default.assert('The `meta` returned from `extractMeta` has to be an object, not "' + _ember.default.typeOf(meta) + '".', _ember.default.typeOf(meta) === 'object')); documentHash.meta = meta; } var keys = Object.keys(payload); for (var i = 0, length = keys.length; i < length; i++) { var prop = keys[i]; var modelName = prop; var forcedSecondary = false; /* If you want to provide sideloaded records of the same type that the primary data you can do that by prefixing the key with `_`. Example ``` { users: [ { id: 1, title: 'Tom', manager: 3 }, { id: 2, title: 'Yehuda', manager: 3 } ], _users: [ { id: 3, title: 'Tomster' } ] } ``` This forces `_users` to be added to `included` instead of `data`. */ if (prop.charAt(0) === '_') { forcedSecondary = true; modelName = prop.substr(1); } var typeName = this.modelNameFromPayloadKey(modelName); if (!store.modelFactoryFor(typeName)) { (false && _ember.default.warn(this.warnMessageNoModelForKey(modelName, typeName), false, { id: 'ds.serializer.model-for-key-missing' })); continue; } var isPrimary = !forcedSecondary && this.isPrimaryType(store, typeName, primaryModelClass); var value = payload[prop]; if (value === null) { continue; } if (false) { var isQueryRecordAnArray = requestType === 'queryRecord' && isPrimary && Array.isArray(value); var message = "The adapter returned an array for the primary data of a `queryRecord` response. This is deprecated as `queryRecord` should return a single record."; (false && !(!isQueryRecordAnArray) && _ember.default.deprecate(message, !isQueryRecordAnArray, { id: 'ds.serializer.rest.queryRecord-array-response', until: '3.0' })); } /* Support primary data as an object instead of an array. Example ``` { user: { id: 1, title: 'Tom', manager: 3 } } ``` */ if (isPrimary && !Array.isArray(value)) { var _normalizePolymorphic2 = this._normalizePolymorphicRecord(store, value, prop, primaryModelClass, this), _data = _normalizePolymorphic2.data, _included = _normalizePolymorphic2.included; documentHash.data = _data; if (_included) { var _documentHash$include2; (_documentHash$include2 = documentHash.included).push.apply(_documentHash$include2, _toConsumableArray(_included)); } continue; } var _normalizeArray = this._normalizeArray(store, typeName, value, prop), data = _normalizeArray.data, included = _normalizeArray.included; if (included) { var _documentHash$include3; (_documentHash$include3 = documentHash.included).push.apply(_documentHash$include3, _toConsumableArray(included)); } if (isSingle) { data.forEach(function (resource) { /* Figures out if this is the primary record or not. It's either: 1. The record with the same ID as the original request 2. If it's a newly created record without an ID, the first record in the array */ var isUpdatedRecord = isPrimary && (0, _private.coerceId)(resource.id) === id; var isFirstCreatedRecord = isPrimary && !id && !documentHash.data; if (isFirstCreatedRecord || isUpdatedRecord) { documentHash.data = resource; } else { documentHash.included.push(resource); } }); } else { if (isPrimary) { documentHash.data = data; } else { if (data) { var _documentHash$include4; (_documentHash$include4 = documentHash.included).push.apply(_documentHash$include4, _toConsumableArray(data)); } } } } return documentHash; }, isPrimaryType: function (store, typeName, primaryTypeClass) { return store.modelFor(typeName) === primaryTypeClass; }, pushPayload: function (store, payload) { var documentHash = { data: [], included: [] }; for (var prop in payload) { var modelName = this.modelNameFromPayloadKey(prop); if (!store.modelFactoryFor(modelName)) { (false && _ember.default.warn(this.warnMessageNoModelForKey(prop, modelName), false, { id: 'ds.serializer.model-for-key-missing' })); continue; } var type = store.modelFor(modelName); var typeSerializer = store.serializerFor(type.modelName); _ember.default.makeArray(payload[prop]).forEach(function (hash) { var _typeSerializer$norma = typeSerializer.normalize(type, hash, prop), data = _typeSerializer$norma.data, included = _typeSerializer$norma.included; documentHash.data.push(data); if (included) { var _documentHash$include5; (_documentHash$include5 = documentHash.included).push.apply(_documentHash$include5, _toConsumableArray(included)); } }); } if ((0, _private.isEnabled)('ds-pushpayload-return')) { return store.push(documentHash); } else { store.push(documentHash); } }, modelNameFromPayloadKey: function (key) { return (0, _emberInflector.singularize)((0, _private.normalizeModelName)(key)); }, serialize: function (snapshot, options) { return this._super.apply(this, arguments); }, serializeIntoHash: function (hash, typeClass, snapshot, options) { var normalizedRootKey = this.payloadKeyFromModelName(typeClass.modelName); hash[normalizedRootKey] = this.serialize(snapshot, options); }, payloadKeyFromModelName: function (modelName) { return camelize(modelName); }, serializePolymorphicType: function (snapshot, json, relationship) { var key = relationship.key; var typeKey = this.keyForPolymorphicType(key, relationship.type, 'serialize'); var belongsTo = snapshot.belongsTo(key); // old way of getting the key for the polymorphic type key = this.keyForAttribute ? this.keyForAttribute(key, "serialize") : key; key = key + 'Type'; // The old way of serializing the type of a polymorphic record used // `keyForAttribute`, which is not correct. The next code checks if the old // way is used and if it differs from the new way of using // `keyForPolymorphicType`. If this is the case, a deprecation warning is // logged and the old way is restored (so nothing breaks). if (key !== typeKey && this.keyForPolymorphicType === RESTSerializer.prototype.keyForPolymorphicType) { (false && !(false) && _ember.default.deprecate("The key to serialize the type of a polymorphic record is created via keyForAttribute which has been deprecated. Use the keyForPolymorphicType hook instead.", false, { id: 'ds.rest-serializer.deprecated-key-for-polymorphic-type', until: '3.0.0' })); typeKey = key; } if (_ember.default.isNone(belongsTo)) { json[typeKey] = null; } else { if ((0, _private.isEnabled)("ds-payload-type-hooks")) { json[typeKey] = this.payloadTypeFromModelName(belongsTo.modelName); } else { json[typeKey] = camelize(belongsTo.modelName); } } }, extractPolymorphicRelationship: function (relationshipType, relationshipHash, relationshipOptions) { var key = relationshipOptions.key, resourceHash = relationshipOptions.resourceHash, relationshipMeta = relationshipOptions.relationshipMeta; // A polymorphic belongsTo relationship can be present in the payload // either in the form where the `id` and the `type` are given: // // { // message: { id: 1, type: 'post' } // } // // or by the `id` and a `<relationship>Type` attribute: // // { // message: 1, // messageType: 'post' // } // // The next code checks if the latter case is present and returns the // corresponding JSON-API representation. The former case is handled within // the base class JSONSerializer. var isPolymorphic = relationshipMeta.options.polymorphic; var typeProperty = this.keyForPolymorphicType(key, relationshipType, 'deserialize'); if (isPolymorphic && resourceHash[typeProperty] !== undefined && typeof relationshipHash !== 'object') { if ((0, _private.isEnabled)("ds-payload-type-hooks")) { var payloadType = resourceHash[typeProperty]; var type = this.modelNameFromPayloadType(payloadType); var deprecatedTypeLookup = this.modelNameFromPayloadKey(payloadType); if (payloadType !== deprecatedTypeLookup && !this._hasCustomModelNameFromPayloadType() && this._hasCustomModelNameFromPayloadKey()) { (false && !(false) && _ember.default.deprecate("You are using modelNameFromPayloadKey to normalize the type for a polymorphic relationship. This has been deprecated in favor of modelNameFromPayloadType", false, { id: 'ds.rest-serializer.deprecated-model-name-for-polymorphic-type', until: '3.0.0' })); type = deprecatedTypeLookup; } return { id: relationshipHash, type: type }; } else { var _type = this.modelNameFromPayloadKey(resourceHash[typeProperty]); return { id: relationshipHash, type: _type }; } } return this._super.apply(this, arguments); } }); if ((0, _private.isEnabled)("ds-payload-type-hooks")) { RESTSerializer.reopen({ modelNameFromPayloadType: function (payloadType) { return (0, _emberInflector.singularize)((0, _private.normalizeModelName)(payloadType)); }, payloadTypeFromModelName: function (modelName) { return camelize(modelName); }, _hasCustomModelNameFromPayloadKey: function () { return this.modelNameFromPayloadKey !== RESTSerializer.prototype.modelNameFromPayloadKey; }, _hasCustomModelNameFromPayloadType: function () { return this.modelNameFromPayloadType !== RESTSerializer.prototype.modelNameFromPayloadType; }, _hasCustomPayloadTypeFromModelName: function () { return this.payloadTypeFromModelName !== RESTSerializer.prototype.payloadTypeFromModelName; }, _hasCustomPayloadKeyFromModelName: function () { return this.payloadKeyFromModelName !== RESTSerializer.prototype.payloadKeyFromModelName; } }); } if (false) { RESTSerializer.reopen({ warnMessageNoModelForKey: function (prop, typeKey) { return 'Encountered "' + prop + '" in payload, but no model was found for model name "' + typeKey + '" (resolved model name using ' + this.constructor.toString() + '.modelNameFromPayloadKey("' + prop + '"))'; } }); } exports.default = RESTSerializer; }); define('ember-data/setup-container', ['exports', 'ember-data/-private', 'ember-data/serializers/json-api', 'ember-data/serializers/json', 'ember-data/serializers/rest', 'ember-data/adapters/json-api', 'ember-data/adapters/rest', 'ember-data/transforms/number', 'ember-data/transforms/date', 'ember-data/transforms/string', 'ember-data/transforms/boolean'], function (exports, _private, _jsonApi, _json, _rest, _jsonApi2, _rest2, _number, _date, _string, _boolean) { 'use strict'; exports.__esModule = true; exports.default = setupContainer; function has(applicationOrRegistry, fullName) { if (applicationOrRegistry.has) { // < 2.1.0 return applicationOrRegistry.has(fullName); } else { // 2.1.0+ return applicationOrRegistry.hasRegistration(fullName); } } /* Configures a registry for use with an Ember-Data store. Accepts an optional namespace argument. @method initializeStore @param {Ember.Registry} registry */ function initializeStore(registry) { // registry.optionsForType for Ember < 2.1.0 // application.registerOptionsForType for Ember 2.1.0+ var registerOptionsForType = registry.registerOptionsForType || registry.optionsForType; registerOptionsForType.call(registry, 'serializer', { singleton: false }); registerOptionsForType.call(registry, 'adapter', { singleton: false }); registry.register('serializer:-default', _json.default); registry.register('serializer:-rest', _rest.default); registry.register('adapter:-rest', _rest2.default); registry.register('adapter:-json-api', _jsonApi2.default); registry.register('serializer:-json-api', _jsonApi.default); if (!has(registry, 'service:store')) { registry.register('service:store', _private.Store); } } /* Configures a registry with injections on Ember applications for the Ember-Data store. Accepts an optional namespace argument. @method initializeDebugAdapter @param {Ember.Registry} registry */ function initializeDataAdapter(registry) { registry.register('data-adapter:main', _private.DebugAdapter); } /* Configures a registry with injections on Ember applications for the Ember-Data store. Accepts an optional namespace argument. @method initializeStoreInjections @param {Ember.Registry} registry */ function initializeStoreInjections(registry) { // registry.injection for Ember < 2.1.0 // application.inject for Ember 2.1.0+ var inject = registry.inject || registry.injection; inject.call(registry, 'controller', 'store', 'service:store'); inject.call(registry, 'route', 'store', 'service:store'); inject.call(registry, 'data-adapter', 'store', 'service:store'); } /* Configures a registry for use with Ember-Data transforms. @method initializeTransforms @param {Ember.Registry} registry */ function initializeTransforms(registry) { registry.register('transform:boolean', _boolean.default); registry.register('transform:date', _date.default); registry.register('transform:number', _number.default); registry.register('transform:string', _string.default); } function setupContainer(application) { initializeDataAdapter(application); initializeTransforms(application); initializeStoreInjections(application); initializeStore(application); } }); define('ember-data/store', ['exports', 'ember-data/-private'], function (exports, _private) { 'use strict'; exports.__esModule = true; Object.defineProperty(exports, 'default', { enumerable: true, get: function () { return _private.Store; } }); }); define('ember-data/transform', ['exports', 'ember-data/transforms/transform'], function (exports, _transform) { 'use strict'; exports.__esModule = true; Object.defineProperty(exports, 'default', { enumerable: true, get: function () { return _transform.default; } }); }); define('ember-data/transforms/boolean', ['exports', 'ember', 'ember-data/transforms/transform'], function (exports, _ember, _transform) { 'use strict'; exports.__esModule = true; var isNone = _ember.default.isNone; exports.default = _transform.default.extend({ deserialize: function (serialized, options) { var type = typeof serialized; if (isNone(serialized) && options.allowNull === true) { return null; } if (type === "boolean") { return serialized; } else if (type === "string") { return serialized.match(/^true$|^t$|^1$/i) !== null; } else if (type === "number") { return serialized === 1; } else { return false; } }, serialize: function (deserialized, options) { if (isNone(deserialized) && options.allowNull === true) { return null; } return Boolean(deserialized); } }); }); define('ember-data/transforms/date', ['exports', 'ember-data/transforms/transform', 'ember'], function (exports, _transform, _ember) { 'use strict'; exports.__esModule = true; _ember.default.Date = _ember.default.Date || {}; /** Date.parse with progressive enhancement for ISO 8601 <https://github.com/csnover/js-iso8601> © 2011 Colin Snover <http://zetafleet.com> Released under MIT license. @class Date @namespace Ember @static @deprecated */ _ember.default.Date.parse = function (date) { (false && !(false) && _ember.default.deprecate('Ember.Date.parse is deprecated because Safari 5-, IE8-, and\n Firefox 3.6- are no longer supported (see\n https://github.com/csnover/js-iso8601 for the history of this issue).\n Please use Date.parse instead', false, { id: 'ds.ember.date.parse-deprecate', until: '3.0.0' })); return Date.parse(date); }; /** The `DS.DateTransform` class is used to serialize and deserialize date attributes on Ember Data record objects. This transform is used when `date` is passed as the type parameter to the [DS.attr](../../data#method_attr) function. It uses the [`ISO 8601`](https://en.wikipedia.org/wiki/ISO_8601) standard. ```app/models/score.js import DS from 'ember-data'; export default DS.Model.extend({ value: DS.attr('number'), player: DS.belongsTo('player'), date: DS.attr('date') }); ``` @class DateTransform @extends DS.Transform @namespace DS */ exports.default = _transform.default.extend({ deserialize: function (serialized) { var type = typeof serialized; if (type === "string") { var offset = serialized.indexOf('+'); if (offset !== -1 && serialized.length - 3 === offset) { (false && !(false) && _ember.default.deprecate('The ECMA2015 Spec for ISO 8601 dates does not allow for shorthand timezone offsets such as +00.\n Ember Data\'s normalization of date\'s allowing for this shorthand has been deprecated, please update your API to return\n UTC dates formatted with \xB1hh:mm timezone offsets or implement a custom UTC transform.', false, { id: 'ds.attr.date.normalize-utc', until: '3.0.0' })); return new Date(serialized + ':00'); // this is a phantom specific bug fix in which +0000 is not supported } else if (offset !== -1 && serialized.length - 5 === offset) { offset += 3; return new Date(serialized.slice(0, offset) + ':' + serialized.slice(offset)); } return new Date(serialized); } else if (type === "number") { return new Date(serialized); } else if (serialized === null || serialized === undefined) { // if the value is null return null // if the value is not present in the data return undefined return serialized; } else { return null; } }, serialize: function (date) { if (date instanceof Date && !isNaN(date)) { return date.toISOString(); } else { return null; } } }); }); define('ember-data/transforms/number', ['exports', 'ember', 'ember-data/transforms/transform'], function (exports, _ember, _transform) { 'use strict'; exports.__esModule = true; var empty = _ember.default.isEmpty; function isNumber(value) { return value === value && value !== Infinity && value !== -Infinity; } /** The `DS.NumberTransform` class is used to serialize and deserialize numeric attributes on Ember Data record objects. This transform is used when `number` is passed as the type parameter to the [DS.attr](../../data#method_attr) function. Usage ```app/models/score.js import DS from 'ember-data'; export default DS.Model.extend({ value: DS.attr('number'), player: DS.belongsTo('player'), date: DS.attr('date') }); ``` @class NumberTransform @extends DS.Transform @namespace DS */ exports.default = _transform.default.extend({ deserialize: function (serialized) { var transformed = void 0; if (empty(serialized)) { return null; } else { transformed = Number(serialized); return isNumber(transformed) ? transformed : null; } }, serialize: function (deserialized) { var transformed = void 0; if (empty(deserialized)) { return null; } else { transformed = Number(deserialized); return isNumber(transformed) ? transformed : null; } } }); }); define('ember-data/transforms/string', ['exports', 'ember', 'ember-data/transforms/transform'], function (exports, _ember, _transform) { 'use strict'; exports.__esModule = true; var none = _ember.default.isNone; /** The `DS.StringTransform` class is used to serialize and deserialize string attributes on Ember Data record objects. This transform is used when `string` is passed as the type parameter to the [DS.attr](../../data#method_attr) function. Usage ```app/models/user.js import DS from 'ember-data'; export default DS.Model.extend({ isAdmin: DS.attr('boolean'), name: DS.attr('string'), email: DS.attr('string') }); ``` @class StringTransform @extends DS.Transform @namespace DS */ exports.default = _transform.default.extend({ deserialize: function (serialized) { return none(serialized) ? null : String(serialized); }, serialize: function (deserialized) { return none(deserialized) ? null : String(deserialized); } }); }); define('ember-data/transforms/transform', ['exports', 'ember'], function (exports, _ember) { 'use strict'; exports.__esModule = true; exports.default = _ember.default.Object.extend({ /** When given a deserialized value from a record attribute this method must return the serialized value. Example ```javascript serialize(deserialized, options) { return Ember.isEmpty(deserialized) ? null : Number(deserialized); } ``` @method serialize @param deserialized The deserialized value @param options hash of options passed to `DS.attr` @return The serialized value */ serialize: null, /** When given a serialize value from a JSON object this method must return the deserialized value for the record attribute. Example ```javascript deserialize(serialized, options) { return empty(serialized) ? null : Number(serialized); } ``` @method deserialize @param serialized The serialized value @param options hash of options passed to `DS.attr` @return The deserialized value */ deserialize: null }); }); define("ember-data/version", ["exports"], function (exports) { "use strict"; exports.__esModule = true; exports.default = "2.17.0-beta.1"; }); define("ember-inflector", ["module", "exports", "ember", "ember-inflector/lib/system", "ember-inflector/lib/ext/string"], function (module, exports, _ember, _system) { "use strict"; exports.__esModule = true; exports.defaultRules = exports.singularize = exports.pluralize = undefined; /* global define, module */ _system.Inflector.defaultRules = _system.defaultRules; _ember.default.Inflector = _system.Inflector; _ember.default.String.pluralize = _system.pluralize; _ember.default.String.singularize = _system.singularize; exports.default = _system.Inflector; exports.pluralize = _system.pluralize; exports.singularize = _system.singularize; exports.defaultRules = _system.defaultRules; if (typeof define !== 'undefined' && define.amd) { define('ember-inflector', ['exports'], function (__exports__) { __exports__['default'] = _system.Inflector; __exports__.pluralize = _system.pluralize; __exports__.singularize = _system.singularize; return __exports__; }); } else if (typeof module !== 'undefined' && module['exports']) { module['exports'] = _system.Inflector; _system.Inflector.singularize = _system.singularize; _system.Inflector.pluralize = _system.pluralize; } }); define('ember-inflector/lib/ext/string', ['ember', 'ember-inflector/lib/system/string'], function (_ember, _string) { 'use strict'; if (_ember.default.EXTEND_PROTOTYPES === true || _ember.default.EXTEND_PROTOTYPES.String) { /** See {{#crossLink "Ember.String/pluralize"}}{{/crossLink}} @method pluralize @for String */ String.prototype.pluralize = function () { return (0, _string.pluralize)(this); }; /** See {{#crossLink "Ember.String/singularize"}}{{/crossLink}} @method singularize @for String */ String.prototype.singularize = function () { return (0, _string.singularize)(this); }; } }); define('ember-inflector/lib/helpers/pluralize', ['exports', 'ember-inflector', 'ember-inflector/lib/utils/make-helper'], function (exports, _emberInflector, _makeHelper) { 'use strict'; exports.__esModule = true; exports.default = (0, _makeHelper.default)(function (params, hash) { var count = void 0, word = void 0, withoutCount = false; if (params.length === 1) { word = params[0]; return (0, _emberInflector.pluralize)(word); } else { count = params[0]; word = params[1]; if (hash["without-count"]) { withoutCount = hash["without-count"]; } if (parseFloat(count) !== 1) { word = (0, _emberInflector.pluralize)(word); } return withoutCount ? word : count + " " + word; } }); }); define('ember-inflector/lib/helpers/singularize', ['exports', 'ember-inflector', 'ember-inflector/lib/utils/make-helper'], function (exports, _emberInflector, _makeHelper) { 'use strict'; exports.__esModule = true; exports.default = (0, _makeHelper.default)(function (params) { return (0, _emberInflector.singularize)(params[0]); }); }); define("ember-inflector/lib/system", ["exports", "ember-inflector/lib/system/inflector", "ember-inflector/lib/system/string", "ember-inflector/lib/system/inflections"], function (exports, _inflector, _string, _inflections) { "use strict"; exports.__esModule = true; exports.defaultRules = exports.pluralize = exports.singularize = exports.Inflector = undefined; _inflector.default.inflector = new _inflector.default(_inflections.default); exports.Inflector = _inflector.default; exports.singularize = _string.singularize; exports.pluralize = _string.pluralize; exports.defaultRules = _inflections.default; }); define('ember-inflector/lib/system/inflections', ['exports'], function (exports) { 'use strict'; exports.__esModule = true; exports.default = { plurals: [[/$/, 's'], [/s$/i, 's'], [/^(ax|test)is$/i, '$1es'], [/(octop|vir)us$/i, '$1i'], [/(octop|vir)i$/i, '$1i'], [/(alias|status|bonus)$/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|bonus)(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'] }; }); define('ember-inflector/lib/system/inflector', ['exports', 'ember'], function (exports, _ember) { 'use strict'; exports.__esModule = true; var capitalize = _ember.default.String.capitalize; var BLANK_REGEX = /^\s*$/; var LAST_WORD_DASHED_REGEX = /([\w/-]+[_/\s-])([a-z\d]+$)/; var LAST_WORD_CAMELIZED_REGEX = /([\w/\s-]+)([A-Z][a-z\d]*$)/; var CAMELIZED_REGEX = /[A-Z][a-z\d]*$/; function loadUncountable(rules, uncountable) { for (var i = 0, length = uncountable.length; i < length; i++) { rules.uncountable[uncountable[i].toLowerCase()] = true; } } function loadIrregular(rules, irregularPairs) { var pair; for (var i = 0, length = irregularPairs.length; i < length; i++) { pair = irregularPairs[i]; //pluralizing rules.irregular[pair[0].toLowerCase()] = pair[1]; rules.irregular[pair[1].toLowerCase()] = pair[1]; //singularizing rules.irregularInverse[pair[1].toLowerCase()] = pair[0]; rules.irregularInverse[pair[0].toLowerCase()] = pair[0]; } } /** Inflector.Ember provides a mechanism for supplying inflection rules for your application. Ember includes a default set of inflection rules, and provides an API for providing additional rules. Examples: Creating an inflector with no rules. ```js var inflector = new Ember.Inflector(); ``` Creating an inflector with the default ember ruleset. ```js var inflector = new Ember.Inflector(Ember.Inflector.defaultRules); inflector.pluralize('cow'); //=> 'kine' inflector.singularize('kine'); //=> 'cow' ``` Creating an inflector and adding rules later. ```javascript var inflector = Ember.Inflector.inflector; inflector.pluralize('advice'); // => 'advices' inflector.uncountable('advice'); inflector.pluralize('advice'); // => 'advice' inflector.pluralize('formula'); // => 'formulas' inflector.irregular('formula', 'formulae'); inflector.pluralize('formula'); // => 'formulae' // you would not need to add these as they are the default rules inflector.plural(/$/, 's'); inflector.singular(/s$/i, ''); ``` Creating an inflector with a nondefault ruleset. ```javascript var rules = { plurals: [ [ /$/, 's' ] ], singular: [ [ /\s$/, '' ] ], irregularPairs: [ [ 'cow', 'kine' ] ], uncountable: [ 'fish' ] }; var inflector = new Ember.Inflector(rules); ``` @class Inflector @namespace Ember */ function Inflector(ruleSet) { ruleSet = ruleSet || {}; ruleSet.uncountable = ruleSet.uncountable || makeDictionary(); ruleSet.irregularPairs = ruleSet.irregularPairs || makeDictionary(); var rules = this.rules = { plurals: ruleSet.plurals || [], singular: ruleSet.singular || [], irregular: makeDictionary(), irregularInverse: makeDictionary(), uncountable: makeDictionary() }; loadUncountable(rules, ruleSet.uncountable); loadIrregular(rules, ruleSet.irregularPairs); this.enableCache(); } if (!Object.create && !Object.create(null).hasOwnProperty) { throw new Error("This browser does not support Object.create(null), please polyfil with es5-sham: http://git.io/yBU2rg"); } function makeDictionary() { var cache = Object.create(null); cache['_dict'] = null; delete cache['_dict']; return cache; } Inflector.prototype = { /** @public As inflections can be costly, and commonly the same subset of words are repeatedly inflected an optional cache is provided. @method enableCache */ enableCache: function () { this.purgeCache(); this.singularize = function (word) { this._cacheUsed = true; return this._sCache[word] || (this._sCache[word] = this._singularize(word)); }; this.pluralize = function (word) { this._cacheUsed = true; return this._pCache[word] || (this._pCache[word] = this._pluralize(word)); }; }, /** @public @method purgedCache */ purgeCache: function () { this._cacheUsed = false; this._sCache = makeDictionary(); this._pCache = makeDictionary(); }, /** @public disable caching @method disableCache; */ disableCache: function () { this._sCache = null; this._pCache = null; this.singularize = function (word) { return this._singularize(word); }; this.pluralize = function (word) { return this._pluralize(word); }; }, /** @method plural @param {RegExp} regex @param {String} string */ plural: function (regex, string) { if (this._cacheUsed) { this.purgeCache(); } this.rules.plurals.push([regex, string.toLowerCase()]); }, /** @method singular @param {RegExp} regex @param {String} string */ singular: function (regex, string) { if (this._cacheUsed) { this.purgeCache(); } this.rules.singular.push([regex, string.toLowerCase()]); }, /** @method uncountable @param {String} regex */ uncountable: function (string) { if (this._cacheUsed) { this.purgeCache(); } loadUncountable(this.rules, [string.toLowerCase()]); }, /** @method irregular @param {String} singular @param {String} plural */ irregular: function (singular, plural) { if (this._cacheUsed) { this.purgeCache(); } loadIrregular(this.rules, [[singular, plural]]); }, /** @method pluralize @param {String} word */ pluralize: function (word) { return this._pluralize(word); }, _pluralize: function (word) { return this.inflect(word, this.rules.plurals, this.rules.irregular); }, /** @method singularize @param {String} word */ singularize: function (word) { return this._singularize(word); }, _singularize: function (word) { return this.inflect(word, this.rules.singular, this.rules.irregularInverse); }, /** @protected @method inflect @param {String} word @param {Object} typeRules @param {Object} irregular */ inflect: function (word, typeRules, irregular) { var inflection, substitution, result, lowercase, wordSplit, firstPhrase, lastWord, isBlank, isCamelized, rule, isUncountable; isBlank = !word || BLANK_REGEX.test(word); isCamelized = CAMELIZED_REGEX.test(word); firstPhrase = ""; if (isBlank) { return word; } lowercase = word.toLowerCase(); wordSplit = LAST_WORD_DASHED_REGEX.exec(word) || LAST_WORD_CAMELIZED_REGEX.exec(word); if (wordSplit) { firstPhrase = wordSplit[1]; lastWord = wordSplit[2].toLowerCase(); } isUncountable = this.rules.uncountable[lowercase] || this.rules.uncountable[lastWord]; if (isUncountable) { return word; } for (rule in irregular) { if (lowercase.match(rule + "$")) { substitution = irregular[rule]; if (isCamelized && irregular[lastWord]) { substitution = capitalize(substitution); rule = capitalize(rule); } return word.replace(new RegExp(rule, 'i'), substitution); } } for (var i = typeRules.length, min = 0; i > min; i--) { inflection = typeRules[i - 1]; rule = inflection[0]; if (rule.test(word)) { break; } } inflection = inflection || []; rule = inflection[0]; substitution = inflection[1]; result = word.replace(rule, substitution); return result; } }; exports.default = Inflector; }); define('ember-inflector/lib/system/string', ['exports', 'ember-inflector/lib/system/inflector'], function (exports, _inflector) { 'use strict'; exports.__esModule = true; exports.singularize = exports.pluralize = undefined; function pluralize(word) { return _inflector.default.inflector.pluralize(word); } function singularize(word) { return _inflector.default.inflector.singularize(word); } exports.pluralize = pluralize; exports.singularize = singularize; }); define('ember-inflector/lib/utils/make-helper', ['exports', 'ember'], function (exports, _ember) { 'use strict'; exports.__esModule = true; exports.default = makeHelper; function makeHelper(helperFunction) { if (_ember.default.Helper) { return _ember.default.Helper.helper(helperFunction); } if (_ember.default.HTMLBars) { return _ember.default.HTMLBars.makeBoundHelper(helperFunction); } return _ember.default.Handlebars.makeBoundHelper(helperFunction); } }); define('ember-load-initializers', ['exports'], function (exports) { 'use strict'; exports.__esModule = true; exports.default = function (app, prefix) { var initializerPrefix = prefix + '/initializers/'; var instanceInitializerPrefix = prefix + '/instance-initializers/'; var initializers = []; var instanceInitializers = []; // this is 2 pass because generally the first pass is the problem // and is reduced, and resolveInitializer has potential to deopt var moduleNames = Object.keys(requirejs._eak_seen); for (var i = 0; i < moduleNames.length; i++) { var moduleName = moduleNames[i]; if (moduleName.lastIndexOf(initializerPrefix, 0) === 0) { initializers.push(moduleName); } else if (moduleName.lastIndexOf(instanceInitializerPrefix, 0) === 0) { instanceInitializers.push(moduleName); } } registerInitializers(app, initializers); registerInstanceInitializers(app, instanceInitializers); }; function resolveInitializer(moduleName) { var module = require(moduleName, null, null, true); if (!module) { throw new Error(moduleName + ' must export an initializer.'); } var initializer = module['default']; if (!initializer.name) { initializer.name = moduleName.slice(moduleName.lastIndexOf('/') + 1); } return initializer; } function registerInitializers(app, moduleNames) { for (var i = 0; i < moduleNames.length; i++) { app.initializer(resolveInitializer(moduleNames[i])); } } function registerInstanceInitializers(app, moduleNames) { for (var i = 0; i < moduleNames.length; i++) { app.instanceInitializer(resolveInitializer(moduleNames[i])); } } }); define('ember', [], function() { return { default: Ember }; }); require("ember-data"); require("ember-load-initializers")["default"](Ember.Application, "ember-data"); ;(function() { var global = require('ember-data/-private/global').default; var DS = require('ember-data').default; Object.defineProperty(global, 'DS', { get: function() { return DS; } }); })(); }).call(this); ;(function() { function processEmberDataShims() { var shims = { 'ember-data': { default: DS }, 'ember-data/model': { default: DS.Model }, 'ember-data/mixins/embedded-records': { default: DS.EmbeddedRecordsMixin }, 'ember-data/serializers/rest': { default: DS.RESTSerializer }, 'ember-data/serializers/active-model': { default: DS.ActiveModelSerializer }, 'ember-data/serializers/json': { default: DS.JSONSerializer }, 'ember-data/serializers/json-api': { default: DS.JSONAPISerializer }, 'ember-data/serializer': { default: DS.Serializer }, 'ember-data/adapters/json-api': { default: DS.JSONAPIAdapter }, 'ember-data/adapters/rest': { default: DS.RESTAdapter }, 'ember-data/adapter': { default: DS.Adapter }, 'ember-data/adapters/active-model': { default: DS.ActiveModelAdapter }, 'ember-data/store': { default: DS.Store }, 'ember-data/transform': { default: DS.Transform }, 'ember-data/attr': { default: DS.attr }, 'ember-data/relationships': { hasMany: DS.hasMany, belongsTo: DS.belongsTo } }; for (var moduleName in shims) { generateModule(moduleName, shims[moduleName]); } } function generateModule(name, values) { define(name, [], function() { 'use strict'; return values; }); } if (typeof define !== 'undefined' && define && define.petal) { processEmberDataShims(); } })(); //# sourceMappingURL=ember-data.prod.map
src/actions/fetchNews.js
merlingerin/f7news
// import React from 'react'; import axios from 'axios'; function fetchNews(category, cb) { const params = new URLSearchParams(); params.append('page', '1'); axios.post(`http://fakty.ictv.ua/ua/widgets_api/${category}/`, params) .then((res) => { arguments.length == 2 ? cb(res) : false; }) .catch((err) => { throw new Error('Can\'t fetch the news.'); }) } export {fetchNews}; // lazyLoad = () => { // } // const params = new URLSearchParams(); // params.append('page', '' + currentPage); // axios.post(`http://fakty.ictv.ua/ua/widgets_api/${category}/`, params) // .then((res) => { // let noPage = false; // this.state.news.filter(function(item) { // return res.data.news[0].id === item.id ? noPage = true : false; // }); // if(onScroll) { // if(!noPage) { // const newState = [...this.state.news, ...res.data.news]; // this.setState({ // news: [...this.state.news, ...res.data.news], // currentPage: ++currentPage, // infinitePreloader: false // }); // } else { // false; // } // } else { // this.setState({ // news: res.data.news, // currentPage: 1, // loading: false // }); // } // arguments.length == 2 ? cb() : false; // }) // .catch((err) => { // console.log(err); // })
packages/material-ui-icons/src/ScreenLockPortraitRounded.js
Kagami/material-ui
import React from 'react'; import createSvgIcon from './utils/createSvgIcon'; export default createSvgIcon( <React.Fragment><path fill="none" d="M0 0h24v24H0V0z" /><g><path d="M10 16h4c.55 0 1-.45 1-1v-3c0-.55-.45-1-1-1v-1c0-1.11-.9-2-2-2-1.11 0-2 .9-2 2v1c-.55 0-1 .45-1 1v3c0 .55.45 1 1 1zm.8-6c0-.66.54-1.2 1.2-1.2s1.2.54 1.2 1.2v1h-2.4v-1zM17 1H7c-1.1 0-2 .9-2 2v18c0 1.1.9 2 2 2h10c1.1 0 2-.9 2-2V3c0-1.1-.9-2-2-2zm0 18H7V5h10v14z" /></g></React.Fragment> , 'ScreenLockPortraitRounded');
tests/components/testOperator.js
notfier/touristique-client
import React from 'react'; import { shallow } from 'enzyme'; import { Operator } from '../../src/js/components/Operator'; describe( 'Test Operator component |', function() { it( 'test componentWillMount logic', function() { localStorage.setItem( 'token', 'olalah' ); var test; const wrapper = shallow( <Operator findTourist={ () => {} } resetTouristCardData={ () => {} } turnOnTouristCardCreation={ () => {} } getDepartments={ ( token ) => { test = token; } } isTouristCardDataChange={ false } isTouristCardCreation={ false } /> ); expect( test ).toBe( 'olalah' ); } ); it( 'test componentWillReceiveProps logic', function() { const wrapper = shallow( <Operator findTourist={ () => {} } resetTouristCardData={ () => {} } turnOnTouristCardCreation={ () => {} } getDepartments={ ( token ) => {} } isTouristCardDataChange={ false } isTouristCardCreation={ false } /> ); wrapper.setState({touristCardPk: 1}); expect( wrapper.state( 'touristCardPk' ) ).toBe( 1 ); // simulate new props update wrapper.setProps({fake: true}); expect( wrapper.state( 'touristCardPk' ) ).toBe( '' ); } ); it( 'test findTourist method', function() { localStorage.setItem( 'token', 'ololo' ); var test; const wrapper = shallow( <Operator findTourist={ ( val1, val2 ) => { test = {val1: val1, val2: val2} } } resetTouristCardData={ () => {} } turnOnTouristCardCreation={ () => {} } getDepartments={ ( token ) => {} } isTouristCardDataChange={ false } isTouristCardCreation={ false } /> ); // check error changing in the state wrapper.setState({error: 'ERROR!', touristCardPk: 'CARD!'}); wrapper.find( 'button' ).first().simulate( 'click', { preventDefault() {} }); expect( wrapper.state( 'error' ) ).toBe( '' ); expect( test.val1 ).toBe( 'ololo' ); expect( test.val2 ).toBe( 'CARD!' ); } ); it( 'test findTourist method getting error', function() { localStorage.setItem( 'token', 'ololo' ); var test; const wrapper = shallow( <Operator findTourist={ ( val1, val2 ) => { test = {val1: val1, val2: val2} } } resetTouristCardData={ () => {} } turnOnTouristCardCreation={ () => {} } getDepartments={ ( token ) => {} } isTouristCardDataChange={ false } isTouristCardCreation={ false } /> ); wrapper.find( 'button' ).first().simulate( 'click', { preventDefault() {} }); expect( wrapper.state( 'error' ) ).toBe( 'Enter a card id in the beginning' ); expect( test ).toBe( undefined ); } ); } );
src/svg-icons/notification/airline-seat-individual-suite.js
jacklam718/react-svg-iconx
import React from 'react'; import pure from 'recompose/pure'; import SvgIcon from '../../SvgIcon'; let NotificationAirlineSeatIndividualSuite = (props) => ( <SvgIcon {...props}> <path d="M7 13c1.65 0 3-1.35 3-3S8.65 7 7 7s-3 1.35-3 3 1.35 3 3 3zm12-6h-8v7H3V7H1v10h22v-6c0-2.21-1.79-4-4-4z"/> </SvgIcon> ); NotificationAirlineSeatIndividualSuite = pure(NotificationAirlineSeatIndividualSuite); NotificationAirlineSeatIndividualSuite.displayName = 'NotificationAirlineSeatIndividualSuite'; NotificationAirlineSeatIndividualSuite.muiName = 'SvgIcon'; export default NotificationAirlineSeatIndividualSuite;
packages/react-server-test-pages/pages/root/when.js
emecell/react-server
import {ReactServerAgent, RootElement} from "react-server"; export default class RootWhenPage { handleRoute(next) { this.data = ReactServerAgent.get('/data/delay?ms=1000'); return next(); } getElements() { return [ <div>Immediate</div>, <RootElement when={this.data}> <div>After one second data request</div> </RootElement>, <div>Immediate</div>, ] } }
docs/src/sections/MediaSection.js
dozoisch/react-bootstrap
import React from 'react'; import Anchor from '../Anchor'; import PropTable from '../PropTable'; import ReactPlayground from '../ReactPlayground'; import Samples from '../Samples'; export default function MediaSection() { return ( <div className="bs-docs-section"> <h2 className="page-header"> <Anchor id="media-objects">Media objects</Anchor> <small>Media, Media.Left, Media.Right, Media.Heading, Media.List, Media.ListItem</small> </h2> <p>Abstract object styles for building various types of components (like blog comments, Tweets, etc) that feature a <code>left</code> or <code>right</code> aligned image alongside textual content.</p> <ReactPlayground codeText={Samples.MediaObject} /> <h3><Anchor id="media-alignment">Media Alignment</Anchor></h3> <p>The images or other media can be aligned top, middle, or bottom. The default is top aligned.</p> <ReactPlayground codeText={Samples.MediaAlignment} /> <h3> <Anchor id="media-list">Media list</Anchor> </h3> <p>You can use media inside list (useful for comment threads or articles lists).</p> <ReactPlayground codeText={Samples.MediaList} /> <h3><Anchor id="media-props">Props</Anchor></h3> <h4><Anchor id="media-media-props">Media</Anchor></h4> <PropTable component="Media"/> <h4><Anchor id="media-left-props">Media.Left</Anchor></h4> <PropTable component="Media.Left"/> <h4><Anchor id="media-right-props">Media.Right</Anchor></h4> <PropTable component="Media.Right"/> <h4><Anchor id="media-heading-props">Media.Heading</Anchor></h4> <PropTable component="Media.Heading"/> <h4><Anchor id="media-body-props">Media.Body</Anchor></h4> <PropTable component="Media.Body"/> </div> ); }
src/mui/input/SelectInput.spec.js
RestUI/rest-ui
import React from 'react'; import assert from 'assert'; import { shallow } from 'enzyme'; import SelectInput from './SelectInput'; describe('<SelectInput />', () => { const defaultProps = { source: 'foo', meta: {}, input: {}, }; it('should use a mui SelectField', () => { const wrapper = shallow(<SelectInput {...defaultProps} input={{ value: 'hello' }} />); const SelectFieldElement = wrapper.find('SelectField'); assert.equal(SelectFieldElement.length, 1); assert.equal(SelectFieldElement.prop('value'), 'hello'); }); it('should use the input parameter value as the initial input value', () => { const wrapper = shallow(<SelectInput {...defaultProps} input={{ value: 2 }} />); const SelectFieldElement = wrapper.find('SelectField').first(); assert.equal(SelectFieldElement.prop('value'), '2'); }); it('should render choices as mui MenuItem components', () => { const wrapper = shallow(<SelectInput {...defaultProps} choices={[ { id: 'M', name: 'Male' }, { id: 'F', name: 'Female' }, ]} />); const MenuItemElements = wrapper.find('MenuItem'); assert.equal(MenuItemElements.length, 2); const MenuItemElement1 = MenuItemElements.first(); assert.equal(MenuItemElement1.prop('value'), 'M'); assert.equal(MenuItemElement1.prop('primaryText'), 'Male'); const MenuItemElement2 = MenuItemElements.at(1); assert.equal(MenuItemElement2.prop('value'), 'F'); assert.equal(MenuItemElement2.prop('primaryText'), 'Female'); }); it('should add an empty menu when allowEmpty is true', () => { const wrapper = shallow(<SelectInput allowEmpty {...defaultProps} choices={[ { id: 'M', name: 'Male' }, { id: 'F', name: 'Female' }, ]} />); const MenuItemElements = wrapper.find('MenuItem'); assert.equal(MenuItemElements.length, 3); const MenuItemElement1 = MenuItemElements.first(); assert.equal(MenuItemElement1.prop('value'), null); assert.equal(MenuItemElement1.prop('primaryText'), ''); }); it('should use optionValue as value identifier', () => { const wrapper = shallow(<SelectInput {...defaultProps} optionValue="foobar" choices={[ { foobar: 'M', name: 'Male' }, ]} />); const MenuItemElements = wrapper.find('MenuItem'); const MenuItemElement1 = MenuItemElements.first(); assert.equal(MenuItemElement1.prop('value'), 'M'); assert.equal(MenuItemElement1.prop('primaryText'), 'Male'); }); it('should use optionText with a string value as text identifier', () => { const wrapper = shallow(<SelectInput {...defaultProps} optionText="foobar" choices={[ { id: 'M', foobar: 'Male' }, ]} />); const MenuItemElements = wrapper.find('MenuItem'); const MenuItemElement1 = MenuItemElements.first(); assert.equal(MenuItemElement1.prop('value'), 'M'); assert.equal(MenuItemElement1.prop('primaryText'), 'Male'); }); it('should use optionText with a function value as text identifier', () => { const wrapper = shallow(<SelectInput {...defaultProps} optionText={choice => choice.foobar} choices={[ { id: 'M', foobar: 'Male' }, ]} />); const MenuItemElements = wrapper.find('MenuItem'); const MenuItemElement1 = MenuItemElements.first(); assert.equal(MenuItemElement1.prop('value'), 'M'); assert.equal(MenuItemElement1.prop('primaryText'), 'Male'); }); it('should use optionText with an element value as text identifier', () => { const Foobar = ({ record }) => <span>{record.foobar}</span>; const wrapper = shallow(<SelectInput {...defaultProps} optionText={<Foobar />} choices={[ { id: 'M', foobar: 'Male' }, ]} />); const MenuItemElements = wrapper.find('MenuItem'); const MenuItemElement1 = MenuItemElements.first(); assert.equal(MenuItemElement1.prop('value'), 'M'); assert.deepEqual(MenuItemElement1.prop('primaryText'), <Foobar record={{ id: 'M', foobar: 'Male' }} />); }); describe('error message', () => { it('should not be displayed if field is pristine', () => { const wrapper = shallow(<SelectInput {...defaultProps} meta={{ touched: false }} />); const SelectFieldElement = wrapper.find('SelectField'); assert.equal(SelectFieldElement.prop('errorText'), false); }); it('should not be displayed if field has been touched but is valid', () => { const wrapper = shallow(<SelectInput {...defaultProps} meta={{ touched: true, error: false }} />); const SelectFieldElement = wrapper.find('SelectField'); assert.equal(SelectFieldElement.prop('errorText'), false); }); it('should be displayed if field has been touched and is invalid', () => { const wrapper = shallow(<SelectInput {...defaultProps} meta={{ touched: true, error: 'Required field.' }} />); const SelectFieldElement = wrapper.find('SelectField'); assert.equal(SelectFieldElement.prop('errorText'), 'Required field.'); }); }); });
examples/web/todo/src/components/todo-mui-component.js
tuantle/hyperflow
'use strict'; // eslint-disable-line import moment from 'moment'; import React from 'react'; import { Paper, List, ListItem, ListItemIcon, ListItemText, ListItemSecondaryAction, Button, Input, OutlinedInput, Checkbox, IconButton, Typography, FormControl, FormControlLabel, RadioGroup, Radio } from '@material-ui/core'; import { Delete as DeleteIcon } from '@material-ui/icons'; import { MuiThemeProvider, createMuiTheme } from '@material-ui/core/styles'; import { makeStyles } from '@material-ui/core/styles'; const useStyles = makeStyles((theme) => ({ root: { justifyContent: `center`, alignContent: `center`, alignItems: `center`, alignSelf: `center`, padding: `20px`, margin: `20px` }, inputForm: { display: `flex`, textAlign: `left`, width: `100%` }, inputNew: { width: `100%`, height: `55px`, fontSize: `1.5em`, marginLeft: theme.spacing(2), marginRight: theme.spacing(2) }, inputEdit: { width: `100%`, height: `30px`, fontSize: `0.9em` }, setting: { justifyContent: `center`, alignContent: `center`, alignItems: `center`, alignSelf: `center` // backgroundColor: `red` } })); const theme = createMuiTheme({ palette: { primary: { main: `#03a9f4` }, secondary: { main: `#ff3d00` } } }); const NewTaskMessageInput = React.forwardRef(({ placeholder = ``, value = ``, onSubmit }, ref) => { const classes = useStyles(); const [ message, setMessage ] = React.useState(value); return ( <form className = { classes.inputForm } ref = { ref } noValidate autoComplete = 'off' onBlur = {() => { if (message !== ``) { onSubmit(message); setMessage(``); } }} onSubmit = {(event) => { event.preventDefault(); if (message !== ``) { onSubmit(message); setMessage(``); } }} > <OutlinedInput className = { classes.inputNew } placeholder = { placeholder} value = { message } onChange = {(event) => { setMessage(event.target.value); }} /> </form> ); }); const EditTaskMessageInput = React.forwardRef(({ placeholder = ``, value = ``, timestamp = ``, color = theme.palette.primary.main, readOnly = false, lineThrough = false, onSubmit }, ref) => { const classes = useStyles(); const [ message, setMessage ] = React.useState(value); return ( <ListItemText primary = { <form ref = { ref } className = { classes.inputForm } noValidate autoComplete = 'off' onBlur = {() => { if (message !== ``) { onSubmit(message); } }} onSubmit = {(event) => { event.preventDefault(); if (message !== ``) { onSubmit(message); } }} > <Input className = { classes.inputEdit } style = {{ color, textDecoration: lineThrough ? `line-through` : `inherit` }} readOnly = { readOnly } disableUnderline = { true } placeholder = { placeholder} value = { message } onChange = {(event) => { setMessage(event.target.value); }} /> </form> } secondary = { <Typography variant = 'caption' display = 'block' color = 'textSecondary' align = 'left' gutterBottom >{ moment(timestamp).format(`L`) }</Typography> }/> ); }); const TaskList = ({ tasks, onEditTask, onDeleteTask }) => ( <List> { tasks.map(({ timestamp, message, editing, completed }) => { const labelId = `task-list-label-${timestamp}`; return ( <ListItem key = { timestamp } role = { undefined } button = { false } divider > <ListItemIcon > <Checkbox edge = 'start' checked = { completed } disabled = { editing } tabIndex = { -1 } inputProps = {{ 'aria-labelledby': labelId }} onChange = {(event) => { onEditTask({ timestamp, completed: event.target.checked }); }} /> </ListItemIcon> <EditTaskMessageInput value = { message } timestamp = { timestamp } color = { editing ? theme.palette.secondary.main : theme.palette.primary.main } lineThrough = { completed } readOnly = { completed } onSubmit = {(editedMessage) => onEditTask({ timestamp, message: editedMessage, editing: false })} /> <ListItemSecondaryAction> <IconButton edge = 'end' aria-label = 'comments' onClick = {() => onDeleteTask(timestamp)} > <DeleteIcon/> </IconButton> </ListItemSecondaryAction> </ListItem> ); }) } < /List> ); const Todo = ({ setting, tasks, filteredTasks, status, onInsertTask, onEditTask, onDeleteTask, onDeleteCompletedTask, onChangeFilter }) => { const classes = useStyles(); const hasTasks = tasks.length; const hasCompletion = tasks.some((task) => task.completed); return ( <MuiThemeProvider theme = { theme }> <Paper className = { classes.root } > <Typography variant = 'h3' component = 'h4' color = 'textSecondary' align = 'center' gutterBottom > Todos </Typography> <NewTaskMessageInput placeholder = 'What needs to be done?' onSubmit = { onInsertTask } /> <TaskList tasks = { filteredTasks } onEditTask = { onEditTask } onDeleteTask = { onDeleteTask } /> <Typography variant = 'caption' display = 'block' color = 'textSecondary' align = 'left' gutterBottom >{ status }</Typography> <div className = { classes.setting } >{ hasTasks ? <FormControl component = 'fieldset' > <RadioGroup aria-label = 'setting' name = 'setting' row value = { setting.currentFilter } onChange = {(event) => onChangeFilter(event.target.value)} > <FormControlLabel value = 'all' control = { <Radio color = 'primary' size = 'small' /> } label = 'All' labelPlacement = 'bottom' color = 'textSecondary' /> <FormControlLabel value = 'active' control = { <Radio color = 'primary' size = 'small' /> } label = 'Active' labelPlacement = 'bottom' color = 'textSecondary' /> <FormControlLabel value = 'completed' control = { <Radio color = 'primary' size = 'small' /> } label = 'Completed' labelPlacement = 'bottom' color = 'textSecondary' /> </RadioGroup> { hasCompletion ? <Button color = 'secondary' onClick = {() => onDeleteCompletedTask()} > Clear Completion </Button> : null } </FormControl> : null }</div> </Paper> </MuiThemeProvider> ); }; export default Todo;
html/lib/jquery.min.js
eddiewangmw/eddie-gateway
/*! jQuery v1.7.1 jquery.com | jquery.org/license */ (function(a,b){function cy(a){return f.isWindow(a)?a:a.nodeType===9?a.defaultView||a.parentWindow:!1}function cv(a){if(!ck[a]){var b=c.body,d=f("<"+a+">").appendTo(b),e=d.css("display");d.remove();if(e==="none"||e===""){cl||(cl=c.createElement("iframe"),cl.frameBorder=cl.width=cl.height=0),b.appendChild(cl);if(!cm||!cl.createElement)cm=(cl.contentWindow||cl.contentDocument).document,cm.write((c.compatMode==="CSS1Compat"?"<!doctype html>":"")+"<html><body>"),cm.close();d=cm.createElement(a),cm.body.appendChild(d),e=f.css(d,"display"),b.removeChild(cl)}ck[a]=e}return ck[a]}function cu(a,b){var c={};f.each(cq.concat.apply([],cq.slice(0,b)),function(){c[this]=a});return c}function ct(){cr=b}function cs(){setTimeout(ct,0);return cr=f.now()}function cj(){try{return new a.ActiveXObject("Microsoft.XMLHTTP")}catch(b){}}function ci(){try{return new a.XMLHttpRequest}catch(b){}}function cc(a,c){a.dataFilter&&(c=a.dataFilter(c,a.dataType));var d=a.dataTypes,e={},g,h,i=d.length,j,k=d[0],l,m,n,o,p;for(g=1;g<i;g++){if(g===1)for(h in a.converters)typeof h=="string"&&(e[h.toLowerCase()]=a.converters[h]);l=k,k=d[g];if(k==="*")k=l;else if(l!=="*"&&l!==k){m=l+" "+k,n=e[m]||e["* "+k];if(!n){p=b;for(o in e){j=o.split(" ");if(j[0]===l||j[0]==="*"){p=e[j[1]+" "+k];if(p){o=e[o],o===!0?n=p:p===!0&&(n=o);break}}}}!n&&!p&&f.error("No conversion from "+m.replace(" "," to ")),n!==!0&&(c=n?n(c):p(o(c)))}}return c}function cb(a,c,d){var e=a.contents,f=a.dataTypes,g=a.responseFields,h,i,j,k;for(i in g)i in d&&(c[g[i]]=d[i]);while(f[0]==="*")f.shift(),h===b&&(h=a.mimeType||c.getResponseHeader("content-type"));if(h)for(i in e)if(e[i]&&e[i].test(h)){f.unshift(i);break}if(f[0]in d)j=f[0];else{for(i in d){if(!f[0]||a.converters[i+" "+f[0]]){j=i;break}k||(k=i)}j=j||k}if(j){j!==f[0]&&f.unshift(j);return d[j]}}function ca(a,b,c,d){if(f.isArray(b))f.each(b,function(b,e){c||bE.test(a)?d(a,e):ca(a+"["+(typeof e=="object"||f.isArray(e)?b:"")+"]",e,c,d)});else if(!c&&b!=null&&typeof b=="object")for(var e in b)ca(a+"["+e+"]",b[e],c,d);else d(a,b)}function b_(a,c){var d,e,g=f.ajaxSettings.flatOptions||{};for(d in c)c[d]!==b&&((g[d]?a:e||(e={}))[d]=c[d]);e&&f.extend(!0,a,e)}function b$(a,c,d,e,f,g){f=f||c.dataTypes[0],g=g||{},g[f]=!0;var h=a[f],i=0,j=h?h.length:0,k=a===bT,l;for(;i<j&&(k||!l);i++)l=h[i](c,d,e),typeof l=="string"&&(!k||g[l]?l=b:(c.dataTypes.unshift(l),l=b$(a,c,d,e,l,g)));(k||!l)&&!g["*"]&&(l=b$(a,c,d,e,"*",g));return l}function bZ(a){return function(b,c){typeof b!="string"&&(c=b,b="*");if(f.isFunction(c)){var d=b.toLowerCase().split(bP),e=0,g=d.length,h,i,j;for(;e<g;e++)h=d[e],j=/^\+/.test(h),j&&(h=h.substr(1)||"*"),i=a[h]=a[h]||[],i[j?"unshift":"push"](c)}}}function bC(a,b,c){var d=b==="width"?a.offsetWidth:a.offsetHeight,e=b==="width"?bx:by,g=0,h=e.length;if(d>0){if(c!=="border")for(;g<h;g++)c||(d-=parseFloat(f.css(a,"padding"+e[g]))||0),c==="margin"?d+=parseFloat(f.css(a,c+e[g]))||0:d-=parseFloat(f.css(a,"border"+e[g]+"Width"))||0;return d+"px"}d=bz(a,b,b);if(d<0||d==null)d=a.style[b]||0;d=parseFloat(d)||0;if(c)for(;g<h;g++)d+=parseFloat(f.css(a,"padding"+e[g]))||0,c!=="padding"&&(d+=parseFloat(f.css(a,"border"+e[g]+"Width"))||0),c==="margin"&&(d+=parseFloat(f.css(a,c+e[g]))||0);return d+"px"}function bp(a,b){b.src?f.ajax({url:b.src,async:!1,dataType:"script"}):f.globalEval((b.text||b.textContent||b.innerHTML||"").replace(bf,"/*$0*/")),b.parentNode&&b.parentNode.removeChild(b)}function bo(a){var b=c.createElement("div");bh.appendChild(b),b.innerHTML=a.outerHTML;return b.firstChild}function bn(a){var b=(a.nodeName||"").toLowerCase();b==="input"?bm(a):b!=="script"&&typeof a.getElementsByTagName!="undefined"&&f.grep(a.getElementsByTagName("input"),bm)}function bm(a){if(a.type==="checkbox"||a.type==="radio")a.defaultChecked=a.checked}function bl(a){return typeof a.getElementsByTagName!="undefined"?a.getElementsByTagName("*"):typeof a.querySelectorAll!="undefined"?a.querySelectorAll("*"):[]}function bk(a,b){var c;if(b.nodeType===1){b.clearAttributes&&b.clearAttributes(),b.mergeAttributes&&b.mergeAttributes(a),c=b.nodeName.toLowerCase();if(c==="object")b.outerHTML=a.outerHTML;else if(c!=="input"||a.type!=="checkbox"&&a.type!=="radio"){if(c==="option")b.selected=a.defaultSelected;else if(c==="input"||c==="textarea")b.defaultValue=a.defaultValue}else a.checked&&(b.defaultChecked=b.checked=a.checked),b.value!==a.value&&(b.value=a.value);b.removeAttribute(f.expando)}}function bj(a,b){if(b.nodeType===1&&!!f.hasData(a)){var c,d,e,g=f._data(a),h=f._data(b,g),i=g.events;if(i){delete h.handle,h.events={};for(c in i)for(d=0,e=i[c].length;d<e;d++)f.event.add(b,c+(i[c][d].namespace?".":"")+i[c][d].namespace,i[c][d],i[c][d].data)}h.data&&(h.data=f.extend({},h.data))}}function bi(a,b){return f.nodeName(a,"table")?a.getElementsByTagName("tbody")[0]||a.appendChild(a.ownerDocument.createElement("tbody")):a}function U(a){var b=V.split("|"),c=a.createDocumentFragment();if(c.createElement)while(b.length)c.createElement(b.pop());return c}function T(a,b,c){b=b||0;if(f.isFunction(b))return f.grep(a,function(a,d){var e=!!b.call(a,d,a);return e===c});if(b.nodeType)return f.grep(a,function(a,d){return a===b===c});if(typeof b=="string"){var d=f.grep(a,function(a){return a.nodeType===1});if(O.test(b))return f.filter(b,d,!c);b=f.filter(b,d)}return f.grep(a,function(a,d){return f.inArray(a,b)>=0===c})}function S(a){return!a||!a.parentNode||a.parentNode.nodeType===11}function K(){return!0}function J(){return!1}function n(a,b,c){var d=b+"defer",e=b+"queue",g=b+"mark",h=f._data(a,d);h&&(c==="queue"||!f._data(a,e))&&(c==="mark"||!f._data(a,g))&&setTimeout(function(){!f._data(a,e)&&!f._data(a,g)&&(f.removeData(a,d,!0),h.fire())},0)}function m(a){for(var b in a){if(b==="data"&&f.isEmptyObject(a[b]))continue;if(b!=="toJSON")return!1}return!0}function l(a,c,d){if(d===b&&a.nodeType===1){var e="data-"+c.replace(k,"-$1").toLowerCase();d=a.getAttribute(e);if(typeof d=="string"){try{d=d==="true"?!0:d==="false"?!1:d==="null"?null:f.isNumeric(d)?parseFloat(d):j.test(d)?f.parseJSON(d):d}catch(g){}f.data(a,c,d)}else d=b}return d}function h(a){var b=g[a]={},c,d;a=a.split(/\s+/);for(c=0,d=a.length;c<d;c++)b[a[c]]=!0;return b}var c=a.document,d=a.navigator,e=a.location,f=function(){function J(){if(!e.isReady){try{c.documentElement.doScroll("left")}catch(a){setTimeout(J,1);return}e.ready()}}var e=function(a,b){return new e.fn.init(a,b,h)},f=a.jQuery,g=a.$,h,i=/^(?:[^#<]*(<[\w\W]+>)[^>]*$|#([\w\-]*)$)/,j=/\S/,k=/^\s+/,l=/\s+$/,m=/^<(\w+)\s*\/?>(?:<\/\1>)?$/,n=/^[\],:{}\s]*$/,o=/\\(?:["\\\/bfnrt]|u[0-9a-fA-F]{4})/g,p=/"[^"\\\n\r]*"|true|false|null|-?\d+(?:\.\d*)?(?:[eE][+\-]?\d+)?/g,q=/(?:^|:|,)(?:\s*\[)+/g,r=/(webkit)[ \/]([\w.]+)/,s=/(opera)(?:.*version)?[ \/]([\w.]+)/,t=/(msie) ([\w.]+)/,u=/(mozilla)(?:.*? rv:([\w.]+))?/,v=/-([a-z]|[0-9])/ig,w=/^-ms-/,x=function(a,b){return(b+"").toUpperCase()},y=d.userAgent,z,A,B,C=Object.prototype.toString,D=Object.prototype.hasOwnProperty,E=Array.prototype.push,F=Array.prototype.slice,G=String.prototype.trim,H=Array.prototype.indexOf,I={};e.fn=e.prototype={constructor:e,init:function(a,d,f){var g,h,j,k;if(!a)return this;if(a.nodeType){this.context=this[0]=a,this.length=1;return this}if(a==="body"&&!d&&c.body){this.context=c,this[0]=c.body,this.selector=a,this.length=1;return this}if(typeof a=="string"){a.charAt(0)!=="<"||a.charAt(a.length-1)!==">"||a.length<3?g=i.exec(a):g=[null,a,null];if(g&&(g[1]||!d)){if(g[1]){d=d instanceof e?d[0]:d,k=d?d.ownerDocument||d:c,j=m.exec(a),j?e.isPlainObject(d)?(a=[c.createElement(j[1])],e.fn.attr.call(a,d,!0)):a=[k.createElement(j[1])]:(j=e.buildFragment([g[1]],[k]),a=(j.cacheable?e.clone(j.fragment):j.fragment).childNodes);return e.merge(this,a)}h=c.getElementById(g[2]);if(h&&h.parentNode){if(h.id!==g[2])return f.find(a);this.length=1,this[0]=h}this.context=c,this.selector=a;return this}return!d||d.jquery?(d||f).find(a):this.constructor(d).find(a)}if(e.isFunction(a))return f.ready(a);a.selector!==b&&(this.selector=a.selector,this.context=a.context);return e.makeArray(a,this)},selector:"",jquery:"1.7.1",length:0,size:function(){return this.length},toArray:function(){return F.call(this,0)},get:function(a){return a==null?this.toArray():a<0?this[this.length+a]:this[a]},pushStack:function(a,b,c){var d=this.constructor();e.isArray(a)?E.apply(d,a):e.merge(d,a),d.prevObject=this,d.context=this.context,b==="find"?d.selector=this.selector+(this.selector?" ":"")+c:b&&(d.selector=this.selector+"."+b+"("+c+")");return d},each:function(a,b){return e.each(this,a,b)},ready:function(a){e.bindReady(),A.add(a);return this},eq:function(a){a=+a;return a===-1?this.slice(a):this.slice(a,a+1)},first:function(){return this.eq(0)},last:function(){return this.eq(-1)},slice:function(){return this.pushStack(F.apply(this,arguments),"slice",F.call(arguments).join(","))},map:function(a){return this.pushStack(e.map(this,function(b,c){return a.call(b,c,b)}))},end:function(){return this.prevObject||this.constructor(null)},push:E,sort:[].sort,splice:[].splice},e.fn.init.prototype=e.fn,e.extend=e.fn.extend=function(){var a,c,d,f,g,h,i=arguments[0]||{},j=1,k=arguments.length,l=!1;typeof i=="boolean"&&(l=i,i=arguments[1]||{},j=2),typeof i!="object"&&!e.isFunction(i)&&(i={}),k===j&&(i=this,--j);for(;j<k;j++)if((a=arguments[j])!=null)for(c in a){d=i[c],f=a[c];if(i===f)continue;l&&f&&(e.isPlainObject(f)||(g=e.isArray(f)))?(g?(g=!1,h=d&&e.isArray(d)?d:[]):h=d&&e.isPlainObject(d)?d:{},i[c]=e.extend(l,h,f)):f!==b&&(i[c]=f)}return i},e.extend({noConflict:function(b){a.$===e&&(a.$=g),b&&a.jQuery===e&&(a.jQuery=f);return e},isReady:!1,readyWait:1,holdReady:function(a){a?e.readyWait++:e.ready(!0)},ready:function(a){if(a===!0&&!--e.readyWait||a!==!0&&!e.isReady){if(!c.body)return setTimeout(e.ready,1);e.isReady=!0;if(a!==!0&&--e.readyWait>0)return;A.fireWith(c,[e]),e.fn.trigger&&e(c).trigger("ready").off("ready")}},bindReady:function(){if(!A){A=e.Callbacks("once memory");if(c.readyState==="complete")return setTimeout(e.ready,1);if(c.addEventListener)c.addEventListener("DOMContentLoaded",B,!1),a.addEventListener("load",e.ready,!1);else if(c.attachEvent){c.attachEvent("onreadystatechange",B),a.attachEvent("onload",e.ready);var b=!1;try{b=a.frameElement==null}catch(d){}c.documentElement.doScroll&&b&&J()}}},isFunction:function(a){return e.type(a)==="function"},isArray:Array.isArray||function(a){return e.type(a)==="array"},isWindow:function(a){return a&&typeof a=="object"&&"setInterval"in a},isNumeric:function(a){return!isNaN(parseFloat(a))&&isFinite(a)},type:function(a){return a==null?String(a):I[C.call(a)]||"object"},isPlainObject:function(a){if(!a||e.type(a)!=="object"||a.nodeType||e.isWindow(a))return!1;try{if(a.constructor&&!D.call(a,"constructor")&&!D.call(a.constructor.prototype,"isPrototypeOf"))return!1}catch(c){return!1}var d;for(d in a);return d===b||D.call(a,d)},isEmptyObject:function(a){for(var b in a)return!1;return!0},error:function(a){throw new Error(a)},parseJSON:function(b){if(typeof b!="string"||!b)return null;b=e.trim(b);if(a.JSON&&a.JSON.parse)return a.JSON.parse(b);if(n.test(b.replace(o,"@").replace(p,"]").replace(q,"")))return(new Function("return "+b))();e.error("Invalid JSON: "+b)},parseXML:function(c){var d,f;try{a.DOMParser?(f=new DOMParser,d=f.parseFromString(c,"text/xml")):(d=new ActiveXObject("Microsoft.XMLDOM"),d.async="false",d.loadXML(c))}catch(g){d=b}(!d||!d.documentElement||d.getElementsByTagName("parsererror").length)&&e.error("Invalid XML: "+c);return d},noop:function(){},globalEval:function(b){b&&j.test(b)&&(a.execScript||function(b){a.eval.call(a,b)})(b)},camelCase:function(a){return a.replace(w,"ms-").replace(v,x)},nodeName:function(a,b){return a.nodeName&&a.nodeName.toUpperCase()===b.toUpperCase()},each:function(a,c,d){var f,g=0,h=a.length,i=h===b||e.isFunction(a);if(d){if(i){for(f in a)if(c.apply(a[f],d)===!1)break}else for(;g<h;)if(c.apply(a[g++],d)===!1)break}else if(i){for(f in a)if(c.call(a[f],f,a[f])===!1)break}else for(;g<h;)if(c.call(a[g],g,a[g++])===!1)break;return a},trim:G?function(a){return a==null?"":G.call(a)}:function(a){return a==null?"":(a+"").replace(k,"").replace(l,"")},makeArray:function(a,b){var c=b||[];if(a!=null){var d=e.type(a);a.length==null||d==="string"||d==="function"||d==="regexp"||e.isWindow(a)?E.call(c,a):e.merge(c,a)}return c},inArray:function(a,b,c){var d;if(b){if(H)return H.call(b,a,c);d=b.length,c=c?c<0?Math.max(0,d+c):c:0;for(;c<d;c++)if(c in b&&b[c]===a)return c}return-1},merge:function(a,c){var d=a.length,e=0;if(typeof c.length=="number")for(var f=c.length;e<f;e++)a[d++]=c[e];else while(c[e]!==b)a[d++]=c[e++];a.length=d;return a},grep:function(a,b,c){var d=[],e;c=!!c;for(var f=0,g=a.length;f<g;f++)e=!!b(a[f],f),c!==e&&d.push(a[f]);return d},map:function(a,c,d){var f,g,h=[],i=0,j=a.length,k=a instanceof e||j!==b&&typeof j=="number"&&(j>0&&a[0]&&a[j-1]||j===0||e.isArray(a));if(k)for(;i<j;i++)f=c(a[i],i,d),f!=null&&(h[h.length]=f);else for(g in a)f=c(a[g],g,d),f!=null&&(h[h.length]=f);return h.concat.apply([],h)},guid:1,proxy:function(a,c){if(typeof c=="string"){var d=a[c];c=a,a=d}if(!e.isFunction(a))return b;var f=F.call(arguments,2),g=function(){return a.apply(c,f.concat(F.call(arguments)))};g.guid=a.guid=a.guid||g.guid||e.guid++;return g},access:function(a,c,d,f,g,h){var i=a.length;if(typeof c=="object"){for(var j in c)e.access(a,j,c[j],f,g,d);return a}if(d!==b){f=!h&&f&&e.isFunction(d);for(var k=0;k<i;k++)g(a[k],c,f?d.call(a[k],k,g(a[k],c)):d,h);return a}return i?g(a[0],c):b},now:function(){return(new Date).getTime()},uaMatch:function(a){a=a.toLowerCase();var b=r.exec(a)||s.exec(a)||t.exec(a)||a.indexOf("compatible")<0&&u.exec(a)||[];return{browser:b[1]||"",version:b[2]||"0"}},sub:function(){function a(b,c){return new a.fn.init(b,c)}e.extend(!0,a,this),a.superclass=this,a.fn=a.prototype=this(),a.fn.constructor=a,a.sub=this.sub,a.fn.init=function(d,f){f&&f instanceof e&&!(f instanceof a)&&(f=a(f));return e.fn.init.call(this,d,f,b)},a.fn.init.prototype=a.fn;var b=a(c);return a},browser:{}}),e.each("Boolean Number String Function Array Date RegExp Object".split(" "),function(a,b){I["[object "+b+"]"]=b.toLowerCase()}),z=e.uaMatch(y),z.browser&&(e.browser[z.browser]=!0,e.browser.version=z.version),e.browser.webkit&&(e.browser.safari=!0),j.test(" ")&&(k=/^[\s\xA0]+/,l=/[\s\xA0]+$/),h=e(c),c.addEventListener?B=function(){c.removeEventListener("DOMContentLoaded",B,!1),e.ready()}:c.attachEvent&&(B=function(){c.readyState==="complete"&&(c.detachEvent("onreadystatechange",B),e.ready())});return e}(),g={};f.Callbacks=function(a){a=a?g[a]||h(a):{};var c=[],d=[],e,i,j,k,l,m=function(b){var d,e,g,h,i;for(d=0,e=b.length;d<e;d++)g=b[d],h=f.type(g),h==="array"?m(g):h==="function"&&(!a.unique||!o.has(g))&&c.push(g)},n=function(b,f){f=f||[],e=!a.memory||[b,f],i=!0,l=j||0,j=0,k=c.length;for(;c&&l<k;l++)if(c[l].apply(b,f)===!1&&a.stopOnFalse){e=!0;break}i=!1,c&&(a.once?e===!0?o.disable():c=[]:d&&d.length&&(e=d.shift(),o.fireWith(e[0],e[1])))},o={add:function(){if(c){var a=c.length;m(arguments),i?k=c.length:e&&e!==!0&&(j=a,n(e[0],e[1]))}return this},remove:function(){if(c){var b=arguments,d=0,e=b.length;for(;d<e;d++)for(var f=0;f<c.length;f++)if(b[d]===c[f]){i&&f<=k&&(k--,f<=l&&l--),c.splice(f--,1);if(a.unique)break}}return this},has:function(a){if(c){var b=0,d=c.length;for(;b<d;b++)if(a===c[b])return!0}return!1},empty:function(){c=[];return this},disable:function(){c=d=e=b;return this},disabled:function(){return!c},lock:function(){d=b,(!e||e===!0)&&o.disable();return this},locked:function(){return!d},fireWith:function(b,c){d&&(i?a.once||d.push([b,c]):(!a.once||!e)&&n(b,c));return this},fire:function(){o.fireWith(this,arguments);return this},fired:function(){return!!e}};return o};var i=[].slice;f.extend({Deferred:function(a){var b=f.Callbacks("once memory"),c=f.Callbacks("once memory"),d=f.Callbacks("memory"),e="pending",g={resolve:b,reject:c,notify:d},h={done:b.add,fail:c.add,progress:d.add,state:function(){return e},isResolved:b.fired,isRejected:c.fired,then:function(a,b,c){i.done(a).fail(b).progress(c);return this},always:function(){i.done.apply(i,arguments).fail.apply(i,arguments);return this},pipe:function(a,b,c){return f.Deferred(function(d){f.each({done:[a,"resolve"],fail:[b,"reject"],progress:[c,"notify"]},function(a,b){var c=b[0],e=b[1],g;f.isFunction(c)?i[a](function(){g=c.apply(this,arguments),g&&f.isFunction(g.promise)?g.promise().then(d.resolve,d.reject,d.notify):d[e+"With"](this===i?d:this,[g])}):i[a](d[e])})}).promise()},promise:function(a){if(a==null)a=h;else for(var b in h)a[b]=h[b];return a}},i=h.promise({}),j;for(j in g)i[j]=g[j].fire,i[j+"With"]=g[j].fireWith;i.done(function(){e="resolved"},c.disable,d.lock).fail(function(){e="rejected"},b.disable,d.lock),a&&a.call(i,i);return i},when:function(a){function m(a){return function(b){e[a]=arguments.length>1?i.call(arguments,0):b,j.notifyWith(k,e)}}function l(a){return function(c){b[a]=arguments.length>1?i.call(arguments,0):c,--g||j.resolveWith(j,b)}}var b=i.call(arguments,0),c=0,d=b.length,e=Array(d),g=d,h=d,j=d<=1&&a&&f.isFunction(a.promise)?a:f.Deferred(),k=j.promise();if(d>1){for(;c<d;c++)b[c]&&b[c].promise&&f.isFunction(b[c].promise)?b[c].promise().then(l(c),j.reject,m(c)):--g;g||j.resolveWith(j,b)}else j!==a&&j.resolveWith(j,d?[a]:[]);return k}}),f.support=function(){var b,d,e,g,h,i,j,k,l,m,n,o,p,q=c.createElement("div"),r=c.documentElement;q.setAttribute("className","t"),q.innerHTML=" <link/><table></table><a href='/a' style='top:1px;float:left;opacity:.55;'>a</a><input type='checkbox'/>",d=q.getElementsByTagName("*"),e=q.getElementsByTagName("a")[0];if(!d||!d.length||!e)return{};g=c.createElement("select"),h=g.appendChild(c.createElement("option")),i=q.getElementsByTagName("input")[0],b={leadingWhitespace:q.firstChild.nodeType===3,tbody:!q.getElementsByTagName("tbody").length,htmlSerialize:!!q.getElementsByTagName("link").length,style:/top/.test(e.getAttribute("style")),hrefNormalized:e.getAttribute("href")==="/a",opacity:/^0.55/.test(e.style.opacity),cssFloat:!!e.style.cssFloat,checkOn:i.value==="on",optSelected:h.selected,getSetAttribute:q.className!=="t",enctype:!!c.createElement("form").enctype,html5Clone:c.createElement("nav").cloneNode(!0).outerHTML!=="<:nav></:nav>",submitBubbles:!0,changeBubbles:!0,focusinBubbles:!1,deleteExpando:!0,noCloneEvent:!0,inlineBlockNeedsLayout:!1,shrinkWrapBlocks:!1,reliableMarginRight:!0},i.checked=!0,b.noCloneChecked=i.cloneNode(!0).checked,g.disabled=!0,b.optDisabled=!h.disabled;try{delete q.test}catch(s){b.deleteExpando=!1}!q.addEventListener&&q.attachEvent&&q.fireEvent&&(q.attachEvent("onclick",function(){b.noCloneEvent=!1}),q.cloneNode(!0).fireEvent("onclick")),i=c.createElement("input"),i.value="t",i.setAttribute("type","radio"),b.radioValue=i.value==="t",i.setAttribute("checked","checked"),q.appendChild(i),k=c.createDocumentFragment(),k.appendChild(q.lastChild),b.checkClone=k.cloneNode(!0).cloneNode(!0).lastChild.checked,b.appendChecked=i.checked,k.removeChild(i),k.appendChild(q),q.innerHTML="",a.getComputedStyle&&(j=c.createElement("div"),j.style.width="0",j.style.marginRight="0",q.style.width="2px",q.appendChild(j),b.reliableMarginRight=(parseInt((a.getComputedStyle(j,null)||{marginRight:0}).marginRight,10)||0)===0);if(q.attachEvent)for(o in{submit:1,change:1,focusin:1})n="on"+o,p=n in q,p||(q.setAttribute(n,"return;"),p=typeof q[n]=="function"),b[o+"Bubbles"]=p;k.removeChild(q),k=g=h=j=q=i=null,f(function(){var a,d,e,g,h,i,j,k,m,n,o,r=c.getElementsByTagName("body")[0];!r||(j=1,k="position:absolute;top:0;left:0;width:1px;height:1px;margin:0;",m="visibility:hidden;border:0;",n="style='"+k+"border:5px solid #000;padding:0;'",o="<div "+n+"><div></div></div>"+"<table "+n+" cellpadding='0' cellspacing='0'>"+"<tr><td></td></tr></table>",a=c.createElement("div"),a.style.cssText=m+"width:0;height:0;position:static;top:0;margin-top:"+j+"px",r.insertBefore(a,r.firstChild),q=c.createElement("div"),a.appendChild(q),q.innerHTML="<table><tr><td style='padding:0;border:0;display:none'></td><td>t</td></tr></table>",l=q.getElementsByTagName("td"),p=l[0].offsetHeight===0,l[0].style.display="",l[1].style.display="none",b.reliableHiddenOffsets=p&&l[0].offsetHeight===0,q.innerHTML="",q.style.width=q.style.paddingLeft="1px",f.boxModel=b.boxModel=q.offsetWidth===2,typeof q.style.zoom!="undefined"&&(q.style.display="inline",q.style.zoom=1,b.inlineBlockNeedsLayout=q.offsetWidth===2,q.style.display="",q.innerHTML="<div style='width:4px;'></div>",b.shrinkWrapBlocks=q.offsetWidth!==2),q.style.cssText=k+m,q.innerHTML=o,d=q.firstChild,e=d.firstChild,h=d.nextSibling.firstChild.firstChild,i={doesNotAddBorder:e.offsetTop!==5,doesAddBorderForTableAndCells:h.offsetTop===5},e.style.position="fixed",e.style.top="20px",i.fixedPosition=e.offsetTop===20||e.offsetTop===15,e.style.position=e.style.top="",d.style.overflow="hidden",d.style.position="relative",i.subtractsBorderForOverflowNotVisible=e.offsetTop===-5,i.doesNotIncludeMarginInBodyOffset=r.offsetTop!==j,r.removeChild(a),q=a=null,f.extend(b,i))});return b}();var j=/^(?:\{.*\}|\[.*\])$/,k=/([A-Z])/g;f.extend({cache:{},uuid:0,expando:"jQuery"+(f.fn.jquery+Math.random()).replace(/\D/g,""),noData:{embed:!0,object:"clsid:D27CDB6E-AE6D-11cf-96B8-444553540000",applet:!0},hasData:function(a){a=a.nodeType?f.cache[a[f.expando]]:a[f.expando];return!!a&&!m(a)},data:function(a,c,d,e){if(!!f.acceptData(a)){var g,h,i,j=f.expando,k=typeof c=="string",l=a.nodeType,m=l?f.cache:a,n=l?a[j]:a[j]&&j,o=c==="events";if((!n||!m[n]||!o&&!e&&!m[n].data)&&k&&d===b)return;n||(l?a[j]=n=++f.uuid:n=j),m[n]||(m[n]={},l||(m[n].toJSON=f.noop));if(typeof c=="object"||typeof c=="function")e?m[n]=f.extend(m[n],c):m[n].data=f.extend(m[n].data,c);g=h=m[n],e||(h.data||(h.data={}),h=h.data),d!==b&&(h[f.camelCase(c)]=d);if(o&&!h[c])return g.events;k?(i=h[c],i==null&&(i=h[f.camelCase(c)])):i=h;return i}},removeData:function(a,b,c){if(!!f.acceptData(a)){var d,e,g,h=f.expando,i=a.nodeType,j=i?f.cache:a,k=i?a[h]:h;if(!j[k])return;if(b){d=c?j[k]:j[k].data;if(d){f.isArray(b)||(b in d?b=[b]:(b=f.camelCase(b),b in d?b=[b]:b=b.split(" ")));for(e=0,g=b.length;e<g;e++)delete d[b[e]];if(!(c?m:f.isEmptyObject)(d))return}}if(!c){delete j[k].data;if(!m(j[k]))return}f.support.deleteExpando||!j.setInterval?delete j[k]:j[k]=null,i&&(f.support.deleteExpando?delete a[h]:a.removeAttribute?a.removeAttribute(h):a[h]=null)}},_data:function(a,b,c){return f.data(a,b,c,!0)},acceptData:function(a){if(a.nodeName){var b=f.noData[a.nodeName.toLowerCase()];if(b)return b!==!0&&a.getAttribute("classid")===b}return!0}}),f.fn.extend({data:function(a,c){var d,e,g,h=null;if(typeof a=="undefined"){if(this.length){h=f.data(this[0]);if(this[0].nodeType===1&&!f._data(this[0],"parsedAttrs")){e=this[0].attributes;for(var i=0,j=e.length;i<j;i++)g=e[i].name,g.indexOf("data-")===0&&(g=f.camelCase(g.substring(5)),l(this[0],g,h[g]));f._data(this[0],"parsedAttrs",!0)}}return h}if(typeof a=="object")return this.each(function(){f.data(this,a)});d=a.split("."),d[1]=d[1]?"."+d[1]:"";if(c===b){h=this.triggerHandler("getData"+d[1]+"!",[d[0]]),h===b&&this.length&&(h=f.data(this[0],a),h=l(this[0],a,h));return h===b&&d[1]?this.data(d[0]):h}return this.each(function(){var b=f(this),e=[d[0],c];b.triggerHandler("setData"+d[1]+"!",e),f.data(this,a,c),b.triggerHandler("changeData"+d[1]+"!",e)})},removeData:function(a){return this.each(function(){f.removeData(this,a)})}}),f.extend({_mark:function(a,b){a&&(b=(b||"fx")+"mark",f._data(a,b,(f._data(a,b)||0)+1))},_unmark:function(a,b,c){a!==!0&&(c=b,b=a,a=!1);if(b){c=c||"fx";var d=c+"mark",e=a?0:(f._data(b,d)||1)-1;e?f._data(b,d,e):(f.removeData(b,d,!0),n(b,c,"mark"))}},queue:function(a,b,c){var d;if(a){b=(b||"fx")+"queue",d=f._data(a,b),c&&(!d||f.isArray(c)?d=f._data(a,b,f.makeArray(c)):d.push(c));return d||[]}},dequeue:function(a,b){b=b||"fx";var c=f.queue(a,b),d=c.shift(),e={};d==="inprogress"&&(d=c.shift()),d&&(b==="fx"&&c.unshift("inprogress"),f._data(a,b+".run",e),d.call(a,function(){f.dequeue(a,b)},e)),c.length||(f.removeData(a,b+"queue "+b+".run",!0),n(a,b,"queue"))}}),f.fn.extend({queue:function(a,c){typeof a!="string"&&(c=a,a="fx");if(c===b)return f.queue(this[0],a);return this.each(function(){var b=f.queue(this,a,c);a==="fx"&&b[0]!=="inprogress"&&f.dequeue(this,a)})},dequeue:function(a){return this.each(function(){f.dequeue(this,a)})},delay:function(a,b){a=f.fx?f.fx.speeds[a]||a:a,b=b||"fx";return this.queue(b,function(b,c){var d=setTimeout(b,a);c.stop=function(){clearTimeout(d)}})},clearQueue:function(a){return this.queue(a||"fx",[])},promise:function(a,c){function m(){--h||d.resolveWith(e,[e])}typeof a!="string"&&(c=a,a=b),a=a||"fx";var d=f.Deferred(),e=this,g=e.length,h=1,i=a+"defer",j=a+"queue",k=a+"mark",l;while(g--)if(l=f.data(e[g],i,b,!0)||(f.data(e[g],j,b,!0)||f.data(e[g],k,b,!0))&&f.data(e[g],i,f.Callbacks("once memory"),!0))h++,l.add(m);m();return d.promise()}});var o=/[\n\t\r]/g,p=/\s+/,q=/\r/g,r=/^(?:button|input)$/i,s=/^(?:button|input|object|select|textarea)$/i,t=/^a(?:rea)?$/i,u=/^(?:autofocus|autoplay|async|checked|controls|defer|disabled|hidden|loop|multiple|open|readonly|required|scoped|selected)$/i,v=f.support.getSetAttribute,w,x,y;f.fn.extend({attr:function(a,b){return f.access(this,a,b,!0,f.attr)},removeAttr:function(a){return this.each(function(){f.removeAttr(this,a)})},prop:function(a,b){return f.access(this,a,b,!0,f.prop)},removeProp:function(a){a=f.propFix[a]||a;return this.each(function(){try{this[a]=b,delete this[a]}catch(c){}})},addClass:function(a){var b,c,d,e,g,h,i;if(f.isFunction(a))return this.each(function(b){f(this).addClass(a.call(this,b,this.className))});if(a&&typeof a=="string"){b=a.split(p);for(c=0,d=this.length;c<d;c++){e=this[c];if(e.nodeType===1)if(!e.className&&b.length===1)e.className=a;else{g=" "+e.className+" ";for(h=0,i=b.length;h<i;h++)~g.indexOf(" "+b[h]+" ")||(g+=b[h]+" ");e.className=f.trim(g)}}}return this},removeClass:function(a){var c,d,e,g,h,i,j;if(f.isFunction(a))return this.each(function(b){f(this).removeClass(a.call(this,b,this.className))});if(a&&typeof a=="string"||a===b){c=(a||"").split(p);for(d=0,e=this.length;d<e;d++){g=this[d];if(g.nodeType===1&&g.className)if(a){h=(" "+g.className+" ").replace(o," ");for(i=0,j=c.length;i<j;i++)h=h.replace(" "+c[i]+" "," ");g.className=f.trim(h)}else g.className=""}}return this},toggleClass:function(a,b){var c=typeof a,d=typeof b=="boolean";if(f.isFunction(a))return this.each(function(c){f(this).toggleClass(a.call(this,c,this.className,b),b)});return this.each(function(){if(c==="string"){var e,g=0,h=f(this),i=b,j=a.split(p);while(e=j[g++])i=d?i:!h.hasClass(e),h[i?"addClass":"removeClass"](e)}else if(c==="undefined"||c==="boolean")this.className&&f._data(this,"__className__",this.className),this.className=this.className||a===!1?"":f._data(this,"__className__")||""})},hasClass:function(a){var b=" "+a+" ",c=0,d=this.length;for(;c<d;c++)if(this[c].nodeType===1&&(" "+this[c].className+" ").replace(o," ").indexOf(b)>-1)return!0;return!1},val:function(a){var c,d,e,g=this[0];{if(!!arguments.length){e=f.isFunction(a);return this.each(function(d){var g=f(this),h;if(this.nodeType===1){e?h=a.call(this,d,g.val()):h=a,h==null?h="":typeof h=="number"?h+="":f.isArray(h)&&(h=f.map(h,function(a){return a==null?"":a+""})),c=f.valHooks[this.nodeName.toLowerCase()]||f.valHooks[this.type];if(!c||!("set"in c)||c.set(this,h,"value")===b)this.value=h}})}if(g){c=f.valHooks[g.nodeName.toLowerCase()]||f.valHooks[g.type];if(c&&"get"in c&&(d=c.get(g,"value"))!==b)return d;d=g.value;return typeof d=="string"?d.replace(q,""):d==null?"":d}}}}),f.extend({valHooks:{option:{get:function(a){var b=a.attributes.value;return!b||b.specified?a.value:a.text}},select:{get:function(a){var b,c,d,e,g=a.selectedIndex,h=[],i=a.options,j=a.type==="select-one";if(g<0)return null;c=j?g:0,d=j?g+1:i.length;for(;c<d;c++){e=i[c];if(e.selected&&(f.support.optDisabled?!e.disabled:e.getAttribute("disabled")===null)&&(!e.parentNode.disabled||!f.nodeName(e.parentNode,"optgroup"))){b=f(e).val();if(j)return b;h.push(b)}}if(j&&!h.length&&i.length)return f(i[g]).val();return h},set:function(a,b){var c=f.makeArray(b);f(a).find("option").each(function(){this.selected=f.inArray(f(this).val(),c)>=0}),c.length||(a.selectedIndex=-1);return c}}},attrFn:{val:!0,css:!0,html:!0,text:!0,data:!0,width:!0,height:!0,offset:!0},attr:function(a,c,d,e){var g,h,i,j=a.nodeType;if(!!a&&j!==3&&j!==8&&j!==2){if(e&&c in f.attrFn)return f(a)[c](d);if(typeof a.getAttribute=="undefined")return f.prop(a,c,d);i=j!==1||!f.isXMLDoc(a),i&&(c=c.toLowerCase(),h=f.attrHooks[c]||(u.test(c)?x:w));if(d!==b){if(d===null){f.removeAttr(a,c);return}if(h&&"set"in h&&i&&(g=h.set(a,d,c))!==b)return g;a.setAttribute(c,""+d);return d}if(h&&"get"in h&&i&&(g=h.get(a,c))!==null)return g;g=a.getAttribute(c);return g===null?b:g}},removeAttr:function(a,b){var c,d,e,g,h=0;if(b&&a.nodeType===1){d=b.toLowerCase().split(p),g=d.length;for(;h<g;h++)e=d[h],e&&(c=f.propFix[e]||e,f.attr(a,e,""),a.removeAttribute(v?e:c),u.test(e)&&c in a&&(a[c]=!1))}},attrHooks:{type:{set:function(a,b){if(r.test(a.nodeName)&&a.parentNode)f.error("type property can't be changed");else if(!f.support.radioValue&&b==="radio"&&f.nodeName(a,"input")){var c=a.value;a.setAttribute("type",b),c&&(a.value=c);return b}}},value:{get:function(a,b){if(w&&f.nodeName(a,"button"))return w.get(a,b);return b in a?a.value:null},set:function(a,b,c){if(w&&f.nodeName(a,"button"))return w.set(a,b,c);a.value=b}}},propFix:{tabindex:"tabIndex",readonly:"readOnly","for":"htmlFor","class":"className",maxlength:"maxLength",cellspacing:"cellSpacing",cellpadding:"cellPadding",rowspan:"rowSpan",colspan:"colSpan",usemap:"useMap",frameborder:"frameBorder",contenteditable:"contentEditable"},prop:function(a,c,d){var e,g,h,i=a.nodeType;if(!!a&&i!==3&&i!==8&&i!==2){h=i!==1||!f.isXMLDoc(a),h&&(c=f.propFix[c]||c,g=f.propHooks[c]);return d!==b?g&&"set"in g&&(e=g.set(a,d,c))!==b?e:a[c]=d:g&&"get"in g&&(e=g.get(a,c))!==null?e:a[c]}},propHooks:{tabIndex:{get:function(a){var c=a.getAttributeNode("tabindex");return c&&c.specified?parseInt(c.value,10):s.test(a.nodeName)||t.test(a.nodeName)&&a.href?0:b}}}}),f.attrHooks.tabindex=f.propHooks.tabIndex,x={get:function(a,c){var d,e=f.prop(a,c);return e===!0||typeof e!="boolean"&&(d=a.getAttributeNode(c))&&d.nodeValue!==!1?c.toLowerCase():b},set:function(a,b,c){var d;b===!1?f.removeAttr(a,c):(d=f.propFix[c]||c,d in a&&(a[d]=!0),a.setAttribute(c,c.toLowerCase()));return c}},v||(y={name:!0,id:!0},w=f.valHooks.button={get:function(a,c){var d;d=a.getAttributeNode(c);return d&&(y[c]?d.nodeValue!=="":d.specified)?d.nodeValue:b},set:function(a,b,d){var e=a.getAttributeNode(d);e||(e=c.createAttribute(d),a.setAttributeNode(e));return e.nodeValue=b+""}},f.attrHooks.tabindex.set=w.set,f.each(["width","height"],function(a,b){f.attrHooks[b]=f.extend(f.attrHooks[b],{set:function(a,c){if(c===""){a.setAttribute(b,"auto");return c}}})}),f.attrHooks.contenteditable={get:w.get,set:function(a,b,c){b===""&&(b="false"),w.set(a,b,c)}}),f.support.hrefNormalized||f.each(["href","src","width","height"],function(a,c){f.attrHooks[c]=f.extend(f.attrHooks[c],{get:function(a){var d=a.getAttribute(c,2);return d===null?b:d}})}),f.support.style||(f.attrHooks.style={get:function(a){return a.style.cssText.toLowerCase()||b},set:function(a,b){return a.style.cssText=""+b}}),f.support.optSelected||(f.propHooks.selected=f.extend(f.propHooks.selected,{get:function(a){var b=a.parentNode;b&&(b.selectedIndex,b.parentNode&&b.parentNode.selectedIndex);return null}})),f.support.enctype||(f.propFix.enctype="encoding"),f.support.checkOn||f.each(["radio","checkbox"],function(){f.valHooks[this]={get:function(a){return a.getAttribute("value")===null?"on":a.value}}}),f.each(["radio","checkbox"],function(){f.valHooks[this]=f.extend(f.valHooks[this],{set:function(a,b){if(f.isArray(b))return a.checked=f.inArray(f(a).val(),b)>=0}})});var z=/^(?:textarea|input|select)$/i,A=/^([^\.]*)?(?:\.(.+))?$/,B=/\bhover(\.\S+)?\b/,C=/^key/,D=/^(?:mouse|contextmenu)|click/,E=/^(?:focusinfocus|focusoutblur)$/,F=/^(\w*)(?:#([\w\-]+))?(?:\.([\w\-]+))?$/,G=function(a){var b=F.exec(a);b&&(b[1]=(b[1]||"").toLowerCase(),b[3]=b[3]&&new RegExp("(?:^|\\s)"+b[3]+"(?:\\s|$)"));return b},H=function(a,b){var c=a.attributes||{};return(!b[1]||a.nodeName.toLowerCase()===b[1])&&(!b[2]||(c.id||{}).value===b[2])&&(!b[3]||b[3].test((c["class"]||{}).value))},I=function(a){return f.event.special.hover?a:a.replace(B,"mouseenter$1 mouseleave$1")}; f.event={add:function(a,c,d,e,g){var h,i,j,k,l,m,n,o,p,q,r,s;if(!(a.nodeType===3||a.nodeType===8||!c||!d||!(h=f._data(a)))){d.handler&&(p=d,d=p.handler),d.guid||(d.guid=f.guid++),j=h.events,j||(h.events=j={}),i=h.handle,i||(h.handle=i=function(a){return typeof f!="undefined"&&(!a||f.event.triggered!==a.type)?f.event.dispatch.apply(i.elem,arguments):b},i.elem=a),c=f.trim(I(c)).split(" ");for(k=0;k<c.length;k++){l=A.exec(c[k])||[],m=l[1],n=(l[2]||"").split(".").sort(),s=f.event.special[m]||{},m=(g?s.delegateType:s.bindType)||m,s=f.event.special[m]||{},o=f.extend({type:m,origType:l[1],data:e,handler:d,guid:d.guid,selector:g,quick:G(g),namespace:n.join(".")},p),r=j[m];if(!r){r=j[m]=[],r.delegateCount=0;if(!s.setup||s.setup.call(a,e,n,i)===!1)a.addEventListener?a.addEventListener(m,i,!1):a.attachEvent&&a.attachEvent("on"+m,i)}s.add&&(s.add.call(a,o),o.handler.guid||(o.handler.guid=d.guid)),g?r.splice(r.delegateCount++,0,o):r.push(o),f.event.global[m]=!0}a=null}},global:{},remove:function(a,b,c,d,e){var g=f.hasData(a)&&f._data(a),h,i,j,k,l,m,n,o,p,q,r,s;if(!!g&&!!(o=g.events)){b=f.trim(I(b||"")).split(" ");for(h=0;h<b.length;h++){i=A.exec(b[h])||[],j=k=i[1],l=i[2];if(!j){for(j in o)f.event.remove(a,j+b[h],c,d,!0);continue}p=f.event.special[j]||{},j=(d?p.delegateType:p.bindType)||j,r=o[j]||[],m=r.length,l=l?new RegExp("(^|\\.)"+l.split(".").sort().join("\\.(?:.*\\.)?")+"(\\.|$)"):null;for(n=0;n<r.length;n++)s=r[n],(e||k===s.origType)&&(!c||c.guid===s.guid)&&(!l||l.test(s.namespace))&&(!d||d===s.selector||d==="**"&&s.selector)&&(r.splice(n--,1),s.selector&&r.delegateCount--,p.remove&&p.remove.call(a,s));r.length===0&&m!==r.length&&((!p.teardown||p.teardown.call(a,l)===!1)&&f.removeEvent(a,j,g.handle),delete o[j])}f.isEmptyObject(o)&&(q=g.handle,q&&(q.elem=null),f.removeData(a,["events","handle"],!0))}},customEvent:{getData:!0,setData:!0,changeData:!0},trigger:function(c,d,e,g){if(!e||e.nodeType!==3&&e.nodeType!==8){var h=c.type||c,i=[],j,k,l,m,n,o,p,q,r,s;if(E.test(h+f.event.triggered))return;h.indexOf("!")>=0&&(h=h.slice(0,-1),k=!0),h.indexOf(".")>=0&&(i=h.split("."),h=i.shift(),i.sort());if((!e||f.event.customEvent[h])&&!f.event.global[h])return;c=typeof c=="object"?c[f.expando]?c:new f.Event(h,c):new f.Event(h),c.type=h,c.isTrigger=!0,c.exclusive=k,c.namespace=i.join("."),c.namespace_re=c.namespace?new RegExp("(^|\\.)"+i.join("\\.(?:.*\\.)?")+"(\\.|$)"):null,o=h.indexOf(":")<0?"on"+h:"";if(!e){j=f.cache;for(l in j)j[l].events&&j[l].events[h]&&f.event.trigger(c,d,j[l].handle.elem,!0);return}c.result=b,c.target||(c.target=e),d=d!=null?f.makeArray(d):[],d.unshift(c),p=f.event.special[h]||{};if(p.trigger&&p.trigger.apply(e,d)===!1)return;r=[[e,p.bindType||h]];if(!g&&!p.noBubble&&!f.isWindow(e)){s=p.delegateType||h,m=E.test(s+h)?e:e.parentNode,n=null;for(;m;m=m.parentNode)r.push([m,s]),n=m;n&&n===e.ownerDocument&&r.push([n.defaultView||n.parentWindow||a,s])}for(l=0;l<r.length&&!c.isPropagationStopped();l++)m=r[l][0],c.type=r[l][1],q=(f._data(m,"events")||{})[c.type]&&f._data(m,"handle"),q&&q.apply(m,d),q=o&&m[o],q&&f.acceptData(m)&&q.apply(m,d)===!1&&c.preventDefault();c.type=h,!g&&!c.isDefaultPrevented()&&(!p._default||p._default.apply(e.ownerDocument,d)===!1)&&(h!=="click"||!f.nodeName(e,"a"))&&f.acceptData(e)&&o&&e[h]&&(h!=="focus"&&h!=="blur"||c.target.offsetWidth!==0)&&!f.isWindow(e)&&(n=e[o],n&&(e[o]=null),f.event.triggered=h,e[h](),f.event.triggered=b,n&&(e[o]=n));return c.result}},dispatch:function(c){c=f.event.fix(c||a.event);var d=(f._data(this,"events")||{})[c.type]||[],e=d.delegateCount,g=[].slice.call(arguments,0),h=!c.exclusive&&!c.namespace,i=[],j,k,l,m,n,o,p,q,r,s,t;g[0]=c,c.delegateTarget=this;if(e&&!c.target.disabled&&(!c.button||c.type!=="click")){m=f(this),m.context=this.ownerDocument||this;for(l=c.target;l!=this;l=l.parentNode||this){o={},q=[],m[0]=l;for(j=0;j<e;j++)r=d[j],s=r.selector,o[s]===b&&(o[s]=r.quick?H(l,r.quick):m.is(s)),o[s]&&q.push(r);q.length&&i.push({elem:l,matches:q})}}d.length>e&&i.push({elem:this,matches:d.slice(e)});for(j=0;j<i.length&&!c.isPropagationStopped();j++){p=i[j],c.currentTarget=p.elem;for(k=0;k<p.matches.length&&!c.isImmediatePropagationStopped();k++){r=p.matches[k];if(h||!c.namespace&&!r.namespace||c.namespace_re&&c.namespace_re.test(r.namespace))c.data=r.data,c.handleObj=r,n=((f.event.special[r.origType]||{}).handle||r.handler).apply(p.elem,g),n!==b&&(c.result=n,n===!1&&(c.preventDefault(),c.stopPropagation()))}}return c.result},props:"attrChange attrName relatedNode srcElement altKey bubbles cancelable ctrlKey currentTarget eventPhase metaKey relatedTarget shiftKey target timeStamp view which".split(" "),fixHooks:{},keyHooks:{props:"char charCode key keyCode".split(" "),filter:function(a,b){a.which==null&&(a.which=b.charCode!=null?b.charCode:b.keyCode);return a}},mouseHooks:{props:"button buttons clientX clientY fromElement offsetX offsetY pageX pageY screenX screenY toElement".split(" "),filter:function(a,d){var e,f,g,h=d.button,i=d.fromElement;a.pageX==null&&d.clientX!=null&&(e=a.target.ownerDocument||c,f=e.documentElement,g=e.body,a.pageX=d.clientX+(f&&f.scrollLeft||g&&g.scrollLeft||0)-(f&&f.clientLeft||g&&g.clientLeft||0),a.pageY=d.clientY+(f&&f.scrollTop||g&&g.scrollTop||0)-(f&&f.clientTop||g&&g.clientTop||0)),!a.relatedTarget&&i&&(a.relatedTarget=i===a.target?d.toElement:i),!a.which&&h!==b&&(a.which=h&1?1:h&2?3:h&4?2:0);return a}},fix:function(a){if(a[f.expando])return a;var d,e,g=a,h=f.event.fixHooks[a.type]||{},i=h.props?this.props.concat(h.props):this.props;a=f.Event(g);for(d=i.length;d;)e=i[--d],a[e]=g[e];a.target||(a.target=g.srcElement||c),a.target.nodeType===3&&(a.target=a.target.parentNode),a.metaKey===b&&(a.metaKey=a.ctrlKey);return h.filter?h.filter(a,g):a},special:{ready:{setup:f.bindReady},load:{noBubble:!0},focus:{delegateType:"focusin"},blur:{delegateType:"focusout"},beforeunload:{setup:function(a,b,c){f.isWindow(this)&&(this.onbeforeunload=c)},teardown:function(a,b){this.onbeforeunload===b&&(this.onbeforeunload=null)}}},simulate:function(a,b,c,d){var e=f.extend(new f.Event,c,{type:a,isSimulated:!0,originalEvent:{}});d?f.event.trigger(e,null,b):f.event.dispatch.call(b,e),e.isDefaultPrevented()&&c.preventDefault()}},f.event.handle=f.event.dispatch,f.removeEvent=c.removeEventListener?function(a,b,c){a.removeEventListener&&a.removeEventListener(b,c,!1)}:function(a,b,c){a.detachEvent&&a.detachEvent("on"+b,c)},f.Event=function(a,b){if(!(this instanceof f.Event))return new f.Event(a,b);a&&a.type?(this.originalEvent=a,this.type=a.type,this.isDefaultPrevented=a.defaultPrevented||a.returnValue===!1||a.getPreventDefault&&a.getPreventDefault()?K:J):this.type=a,b&&f.extend(this,b),this.timeStamp=a&&a.timeStamp||f.now(),this[f.expando]=!0},f.Event.prototype={preventDefault:function(){this.isDefaultPrevented=K;var a=this.originalEvent;!a||(a.preventDefault?a.preventDefault():a.returnValue=!1)},stopPropagation:function(){this.isPropagationStopped=K;var a=this.originalEvent;!a||(a.stopPropagation&&a.stopPropagation(),a.cancelBubble=!0)},stopImmediatePropagation:function(){this.isImmediatePropagationStopped=K,this.stopPropagation()},isDefaultPrevented:J,isPropagationStopped:J,isImmediatePropagationStopped:J},f.each({mouseenter:"mouseover",mouseleave:"mouseout"},function(a,b){f.event.special[a]={delegateType:b,bindType:b,handle:function(a){var c=this,d=a.relatedTarget,e=a.handleObj,g=e.selector,h;if(!d||d!==c&&!f.contains(c,d))a.type=e.origType,h=e.handler.apply(this,arguments),a.type=b;return h}}}),f.support.submitBubbles||(f.event.special.submit={setup:function(){if(f.nodeName(this,"form"))return!1;f.event.add(this,"click._submit keypress._submit",function(a){var c=a.target,d=f.nodeName(c,"input")||f.nodeName(c,"button")?c.form:b;d&&!d._submit_attached&&(f.event.add(d,"submit._submit",function(a){this.parentNode&&!a.isTrigger&&f.event.simulate("submit",this.parentNode,a,!0)}),d._submit_attached=!0)})},teardown:function(){if(f.nodeName(this,"form"))return!1;f.event.remove(this,"._submit")}}),f.support.changeBubbles||(f.event.special.change={setup:function(){if(z.test(this.nodeName)){if(this.type==="checkbox"||this.type==="radio")f.event.add(this,"propertychange._change",function(a){a.originalEvent.propertyName==="checked"&&(this._just_changed=!0)}),f.event.add(this,"click._change",function(a){this._just_changed&&!a.isTrigger&&(this._just_changed=!1,f.event.simulate("change",this,a,!0))});return!1}f.event.add(this,"beforeactivate._change",function(a){var b=a.target;z.test(b.nodeName)&&!b._change_attached&&(f.event.add(b,"change._change",function(a){this.parentNode&&!a.isSimulated&&!a.isTrigger&&f.event.simulate("change",this.parentNode,a,!0)}),b._change_attached=!0)})},handle:function(a){var b=a.target;if(this!==b||a.isSimulated||a.isTrigger||b.type!=="radio"&&b.type!=="checkbox")return a.handleObj.handler.apply(this,arguments)},teardown:function(){f.event.remove(this,"._change");return z.test(this.nodeName)}}),f.support.focusinBubbles||f.each({focus:"focusin",blur:"focusout"},function(a,b){var d=0,e=function(a){f.event.simulate(b,a.target,f.event.fix(a),!0)};f.event.special[b]={setup:function(){d++===0&&c.addEventListener(a,e,!0)},teardown:function(){--d===0&&c.removeEventListener(a,e,!0)}}}),f.fn.extend({on:function(a,c,d,e,g){var h,i;if(typeof a=="object"){typeof c!="string"&&(d=c,c=b);for(i in a)this.on(i,c,d,a[i],g);return this}d==null&&e==null?(e=c,d=c=b):e==null&&(typeof c=="string"?(e=d,d=b):(e=d,d=c,c=b));if(e===!1)e=J;else if(!e)return this;g===1&&(h=e,e=function(a){f().off(a);return h.apply(this,arguments)},e.guid=h.guid||(h.guid=f.guid++));return this.each(function(){f.event.add(this,a,e,d,c)})},one:function(a,b,c,d){return this.on.call(this,a,b,c,d,1)},off:function(a,c,d){if(a&&a.preventDefault&&a.handleObj){var e=a.handleObj;f(a.delegateTarget).off(e.namespace?e.type+"."+e.namespace:e.type,e.selector,e.handler);return this}if(typeof a=="object"){for(var g in a)this.off(g,c,a[g]);return this}if(c===!1||typeof c=="function")d=c,c=b;d===!1&&(d=J);return this.each(function(){f.event.remove(this,a,d,c)})},bind:function(a,b,c){return this.on(a,null,b,c)},unbind:function(a,b){return this.off(a,null,b)},live:function(a,b,c){f(this.context).on(a,this.selector,b,c);return this},die:function(a,b){f(this.context).off(a,this.selector||"**",b);return this},delegate:function(a,b,c,d){return this.on(b,a,c,d)},undelegate:function(a,b,c){return arguments.length==1?this.off(a,"**"):this.off(b,a,c)},trigger:function(a,b){return this.each(function(){f.event.trigger(a,b,this)})},triggerHandler:function(a,b){if(this[0])return f.event.trigger(a,b,this[0],!0)},toggle:function(a){var b=arguments,c=a.guid||f.guid++,d=0,e=function(c){var e=(f._data(this,"lastToggle"+a.guid)||0)%d;f._data(this,"lastToggle"+a.guid,e+1),c.preventDefault();return b[e].apply(this,arguments)||!1};e.guid=c;while(d<b.length)b[d++].guid=c;return this.click(e)},hover:function(a,b){return this.mouseenter(a).mouseleave(b||a)}}),f.each("blur focus focusin focusout load resize scroll unload click dblclick mousedown mouseup mousemove mouseover mouseout mouseenter mouseleave change select submit keydown keypress keyup error contextmenu".split(" "),function(a,b){f.fn[b]=function(a,c){c==null&&(c=a,a=null);return arguments.length>0?this.on(b,null,a,c):this.trigger(b)},f.attrFn&&(f.attrFn[b]=!0),C.test(b)&&(f.event.fixHooks[b]=f.event.keyHooks),D.test(b)&&(f.event.fixHooks[b]=f.event.mouseHooks)}),function(){function x(a,b,c,e,f,g){for(var h=0,i=e.length;h<i;h++){var j=e[h];if(j){var k=!1;j=j[a];while(j){if(j[d]===c){k=e[j.sizset];break}if(j.nodeType===1){g||(j[d]=c,j.sizset=h);if(typeof b!="string"){if(j===b){k=!0;break}}else if(m.filter(b,[j]).length>0){k=j;break}}j=j[a]}e[h]=k}}}function w(a,b,c,e,f,g){for(var h=0,i=e.length;h<i;h++){var j=e[h];if(j){var k=!1;j=j[a];while(j){if(j[d]===c){k=e[j.sizset];break}j.nodeType===1&&!g&&(j[d]=c,j.sizset=h);if(j.nodeName.toLowerCase()===b){k=j;break}j=j[a]}e[h]=k}}}var a=/((?:\((?:\([^()]+\)|[^()]+)+\)|\[(?:\[[^\[\]]*\]|['"][^'"]*['"]|[^\[\]'"]+)+\]|\\.|[^ >+~,(\[\\]+)+|[>+~])(\s*,\s*)?((?:.|\r|\n)*)/g,d="sizcache"+(Math.random()+"").replace(".",""),e=0,g=Object.prototype.toString,h=!1,i=!0,j=/\\/g,k=/\r\n/g,l=/\W/;[0,0].sort(function(){i=!1;return 0});var m=function(b,d,e,f){e=e||[],d=d||c;var h=d;if(d.nodeType!==1&&d.nodeType!==9)return[];if(!b||typeof b!="string")return e;var i,j,k,l,n,q,r,t,u=!0,v=m.isXML(d),w=[],x=b;do{a.exec(""),i=a.exec(x);if(i){x=i[3],w.push(i[1]);if(i[2]){l=i[3];break}}}while(i);if(w.length>1&&p.exec(b))if(w.length===2&&o.relative[w[0]])j=y(w[0]+w[1],d,f);else{j=o.relative[w[0]]?[d]:m(w.shift(),d);while(w.length)b=w.shift(),o.relative[b]&&(b+=w.shift()),j=y(b,j,f)}else{!f&&w.length>1&&d.nodeType===9&&!v&&o.match.ID.test(w[0])&&!o.match.ID.test(w[w.length-1])&&(n=m.find(w.shift(),d,v),d=n.expr?m.filter(n.expr,n.set)[0]:n.set[0]);if(d){n=f?{expr:w.pop(),set:s(f)}:m.find(w.pop(),w.length===1&&(w[0]==="~"||w[0]==="+")&&d.parentNode?d.parentNode:d,v),j=n.expr?m.filter(n.expr,n.set):n.set,w.length>0?k=s(j):u=!1;while(w.length)q=w.pop(),r=q,o.relative[q]?r=w.pop():q="",r==null&&(r=d),o.relative[q](k,r,v)}else k=w=[]}k||(k=j),k||m.error(q||b);if(g.call(k)==="[object Array]")if(!u)e.push.apply(e,k);else if(d&&d.nodeType===1)for(t=0;k[t]!=null;t++)k[t]&&(k[t]===!0||k[t].nodeType===1&&m.contains(d,k[t]))&&e.push(j[t]);else for(t=0;k[t]!=null;t++)k[t]&&k[t].nodeType===1&&e.push(j[t]);else s(k,e);l&&(m(l,h,e,f),m.uniqueSort(e));return e};m.uniqueSort=function(a){if(u){h=i,a.sort(u);if(h)for(var b=1;b<a.length;b++)a[b]===a[b-1]&&a.splice(b--,1)}return a},m.matches=function(a,b){return m(a,null,null,b)},m.matchesSelector=function(a,b){return m(b,null,null,[a]).length>0},m.find=function(a,b,c){var d,e,f,g,h,i;if(!a)return[];for(e=0,f=o.order.length;e<f;e++){h=o.order[e];if(g=o.leftMatch[h].exec(a)){i=g[1],g.splice(1,1);if(i.substr(i.length-1)!=="\\"){g[1]=(g[1]||"").replace(j,""),d=o.find[h](g,b,c);if(d!=null){a=a.replace(o.match[h],"");break}}}}d||(d=typeof b.getElementsByTagName!="undefined"?b.getElementsByTagName("*"):[]);return{set:d,expr:a}},m.filter=function(a,c,d,e){var f,g,h,i,j,k,l,n,p,q=a,r=[],s=c,t=c&&c[0]&&m.isXML(c[0]);while(a&&c.length){for(h in o.filter)if((f=o.leftMatch[h].exec(a))!=null&&f[2]){k=o.filter[h],l=f[1],g=!1,f.splice(1,1);if(l.substr(l.length-1)==="\\")continue;s===r&&(r=[]);if(o.preFilter[h]){f=o.preFilter[h](f,s,d,r,e,t);if(!f)g=i=!0;else if(f===!0)continue}if(f)for(n=0;(j=s[n])!=null;n++)j&&(i=k(j,f,n,s),p=e^i,d&&i!=null?p?g=!0:s[n]=!1:p&&(r.push(j),g=!0));if(i!==b){d||(s=r),a=a.replace(o.match[h],"");if(!g)return[];break}}if(a===q)if(g==null)m.error(a);else break;q=a}return s},m.error=function(a){throw new Error("Syntax error, unrecognized expression: "+a)};var n=m.getText=function(a){var b,c,d=a.nodeType,e="";if(d){if(d===1||d===9){if(typeof a.textContent=="string")return a.textContent;if(typeof a.innerText=="string")return a.innerText.replace(k,"");for(a=a.firstChild;a;a=a.nextSibling)e+=n(a)}else if(d===3||d===4)return a.nodeValue}else for(b=0;c=a[b];b++)c.nodeType!==8&&(e+=n(c));return e},o=m.selectors={order:["ID","NAME","TAG"],match:{ID:/#((?:[\w\u00c0-\uFFFF\-]|\\.)+)/,CLASS:/\.((?:[\w\u00c0-\uFFFF\-]|\\.)+)/,NAME:/\[name=['"]*((?:[\w\u00c0-\uFFFF\-]|\\.)+)['"]*\]/,ATTR:/\[\s*((?:[\w\u00c0-\uFFFF\-]|\\.)+)\s*(?:(\S?=)\s*(?:(['"])(.*?)\3|(#?(?:[\w\u00c0-\uFFFF\-]|\\.)*)|)|)\s*\]/,TAG:/^((?:[\w\u00c0-\uFFFF\*\-]|\\.)+)/,CHILD:/:(only|nth|last|first)-child(?:\(\s*(even|odd|(?:[+\-]?\d+|(?:[+\-]?\d*)?n\s*(?:[+\-]\s*\d+)?))\s*\))?/,POS:/:(nth|eq|gt|lt|first|last|even|odd)(?:\((\d*)\))?(?=[^\-]|$)/,PSEUDO:/:((?:[\w\u00c0-\uFFFF\-]|\\.)+)(?:\((['"]?)((?:\([^\)]+\)|[^\(\)]*)+)\2\))?/},leftMatch:{},attrMap:{"class":"className","for":"htmlFor"},attrHandle:{href:function(a){return a.getAttribute("href")},type:function(a){return a.getAttribute("type")}},relative:{"+":function(a,b){var c=typeof b=="string",d=c&&!l.test(b),e=c&&!d;d&&(b=b.toLowerCase());for(var f=0,g=a.length,h;f<g;f++)if(h=a[f]){while((h=h.previousSibling)&&h.nodeType!==1);a[f]=e||h&&h.nodeName.toLowerCase()===b?h||!1:h===b}e&&m.filter(b,a,!0)},">":function(a,b){var c,d=typeof b=="string",e=0,f=a.length;if(d&&!l.test(b)){b=b.toLowerCase();for(;e<f;e++){c=a[e];if(c){var g=c.parentNode;a[e]=g.nodeName.toLowerCase()===b?g:!1}}}else{for(;e<f;e++)c=a[e],c&&(a[e]=d?c.parentNode:c.parentNode===b);d&&m.filter(b,a,!0)}},"":function(a,b,c){var d,f=e++,g=x;typeof b=="string"&&!l.test(b)&&(b=b.toLowerCase(),d=b,g=w),g("parentNode",b,f,a,d,c)},"~":function(a,b,c){var d,f=e++,g=x;typeof b=="string"&&!l.test(b)&&(b=b.toLowerCase(),d=b,g=w),g("previousSibling",b,f,a,d,c)}},find:{ID:function(a,b,c){if(typeof b.getElementById!="undefined"&&!c){var d=b.getElementById(a[1]);return d&&d.parentNode?[d]:[]}},NAME:function(a,b){if(typeof b.getElementsByName!="undefined"){var c=[],d=b.getElementsByName(a[1]);for(var e=0,f=d.length;e<f;e++)d[e].getAttribute("name")===a[1]&&c.push(d[e]);return c.length===0?null:c}},TAG:function(a,b){if(typeof b.getElementsByTagName!="undefined")return b.getElementsByTagName(a[1])}},preFilter:{CLASS:function(a,b,c,d,e,f){a=" "+a[1].replace(j,"")+" ";if(f)return a;for(var g=0,h;(h=b[g])!=null;g++)h&&(e^(h.className&&(" "+h.className+" ").replace(/[\t\n\r]/g," ").indexOf(a)>=0)?c||d.push(h):c&&(b[g]=!1));return!1},ID:function(a){return a[1].replace(j,"")},TAG:function(a,b){return a[1].replace(j,"").toLowerCase()},CHILD:function(a){if(a[1]==="nth"){a[2]||m.error(a[0]),a[2]=a[2].replace(/^\+|\s*/g,"");var b=/(-?)(\d*)(?:n([+\-]?\d*))?/.exec(a[2]==="even"&&"2n"||a[2]==="odd"&&"2n+1"||!/\D/.test(a[2])&&"0n+"+a[2]||a[2]);a[2]=b[1]+(b[2]||1)-0,a[3]=b[3]-0}else a[2]&&m.error(a[0]);a[0]=e++;return a},ATTR:function(a,b,c,d,e,f){var g=a[1]=a[1].replace(j,"");!f&&o.attrMap[g]&&(a[1]=o.attrMap[g]),a[4]=(a[4]||a[5]||"").replace(j,""),a[2]==="~="&&(a[4]=" "+a[4]+" ");return a},PSEUDO:function(b,c,d,e,f){if(b[1]==="not")if((a.exec(b[3])||"").length>1||/^\w/.test(b[3]))b[3]=m(b[3],null,null,c);else{var g=m.filter(b[3],c,d,!0^f);d||e.push.apply(e,g);return!1}else if(o.match.POS.test(b[0])||o.match.CHILD.test(b[0]))return!0;return b},POS:function(a){a.unshift(!0);return a}},filters:{enabled:function(a){return a.disabled===!1&&a.type!=="hidden"},disabled:function(a){return a.disabled===!0},checked:function(a){return a.checked===!0},selected:function(a){a.parentNode&&a.parentNode.selectedIndex;return a.selected===!0},parent:function(a){return!!a.firstChild},empty:function(a){return!a.firstChild},has:function(a,b,c){return!!m(c[3],a).length},header:function(a){return/h\d/i.test(a.nodeName)},text:function(a){var b=a.getAttribute("type"),c=a.type;return a.nodeName.toLowerCase()==="input"&&"text"===c&&(b===c||b===null)},radio:function(a){return a.nodeName.toLowerCase()==="input"&&"radio"===a.type},checkbox:function(a){return a.nodeName.toLowerCase()==="input"&&"checkbox"===a.type},file:function(a){return a.nodeName.toLowerCase()==="input"&&"file"===a.type},password:function(a){return a.nodeName.toLowerCase()==="input"&&"password"===a.type},submit:function(a){var b=a.nodeName.toLowerCase();return(b==="input"||b==="button")&&"submit"===a.type},image:function(a){return a.nodeName.toLowerCase()==="input"&&"image"===a.type},reset:function(a){var b=a.nodeName.toLowerCase();return(b==="input"||b==="button")&&"reset"===a.type},button:function(a){var b=a.nodeName.toLowerCase();return b==="input"&&"button"===a.type||b==="button"},input:function(a){return/input|select|textarea|button/i.test(a.nodeName)},focus:function(a){return a===a.ownerDocument.activeElement}},setFilters:{first:function(a,b){return b===0},last:function(a,b,c,d){return b===d.length-1},even:function(a,b){return b%2===0},odd:function(a,b){return b%2===1},lt:function(a,b,c){return b<c[3]-0},gt:function(a,b,c){return b>c[3]-0},nth:function(a,b,c){return c[3]-0===b},eq:function(a,b,c){return c[3]-0===b}},filter:{PSEUDO:function(a,b,c,d){var e=b[1],f=o.filters[e];if(f)return f(a,c,b,d);if(e==="contains")return(a.textContent||a.innerText||n([a])||"").indexOf(b[3])>=0;if(e==="not"){var g=b[3];for(var h=0,i=g.length;h<i;h++)if(g[h]===a)return!1;return!0}m.error(e)},CHILD:function(a,b){var c,e,f,g,h,i,j,k=b[1],l=a;switch(k){case"only":case"first":while(l=l.previousSibling)if(l.nodeType===1)return!1;if(k==="first")return!0;l=a;case"last":while(l=l.nextSibling)if(l.nodeType===1)return!1;return!0;case"nth":c=b[2],e=b[3];if(c===1&&e===0)return!0;f=b[0],g=a.parentNode;if(g&&(g[d]!==f||!a.nodeIndex)){i=0;for(l=g.firstChild;l;l=l.nextSibling)l.nodeType===1&&(l.nodeIndex=++i);g[d]=f}j=a.nodeIndex-e;return c===0?j===0:j%c===0&&j/c>=0}},ID:function(a,b){return a.nodeType===1&&a.getAttribute("id")===b},TAG:function(a,b){return b==="*"&&a.nodeType===1||!!a.nodeName&&a.nodeName.toLowerCase()===b},CLASS:function(a,b){return(" "+(a.className||a.getAttribute("class"))+" ").indexOf(b)>-1},ATTR:function(a,b){var c=b[1],d=m.attr?m.attr(a,c):o.attrHandle[c]?o.attrHandle[c](a):a[c]!=null?a[c]:a.getAttribute(c),e=d+"",f=b[2],g=b[4];return d==null?f==="!=":!f&&m.attr?d!=null:f==="="?e===g:f==="*="?e.indexOf(g)>=0:f==="~="?(" "+e+" ").indexOf(g)>=0:g?f==="!="?e!==g:f==="^="?e.indexOf(g)===0:f==="$="?e.substr(e.length-g.length)===g:f==="|="?e===g||e.substr(0,g.length+1)===g+"-":!1:e&&d!==!1},POS:function(a,b,c,d){var e=b[2],f=o.setFilters[e];if(f)return f(a,c,b,d)}}},p=o.match.POS,q=function(a,b){return"\\"+(b-0+1)};for(var r in o.match)o.match[r]=new RegExp(o.match[r].source+/(?![^\[]*\])(?![^\(]*\))/.source),o.leftMatch[r]=new RegExp(/(^(?:.|\r|\n)*?)/.source+o.match[r].source.replace(/\\(\d+)/g,q));var s=function(a,b){a=Array.prototype.slice.call(a,0);if(b){b.push.apply(b,a);return b}return a};try{Array.prototype.slice.call(c.documentElement.childNodes,0)[0].nodeType}catch(t){s=function(a,b){var c=0,d=b||[];if(g.call(a)==="[object Array]")Array.prototype.push.apply(d,a);else if(typeof a.length=="number")for(var e=a.length;c<e;c++)d.push(a[c]);else for(;a[c];c++)d.push(a[c]);return d}}var u,v;c.documentElement.compareDocumentPosition?u=function(a,b){if(a===b){h=!0;return 0}if(!a.compareDocumentPosition||!b.compareDocumentPosition)return a.compareDocumentPosition?-1:1;return a.compareDocumentPosition(b)&4?-1:1}:(u=function(a,b){if(a===b){h=!0;return 0}if(a.sourceIndex&&b.sourceIndex)return a.sourceIndex-b.sourceIndex;var c,d,e=[],f=[],g=a.parentNode,i=b.parentNode,j=g;if(g===i)return v(a,b);if(!g)return-1;if(!i)return 1;while(j)e.unshift(j),j=j.parentNode;j=i;while(j)f.unshift(j),j=j.parentNode;c=e.length,d=f.length;for(var k=0;k<c&&k<d;k++)if(e[k]!==f[k])return v(e[k],f[k]);return k===c?v(a,f[k],-1):v(e[k],b,1)},v=function(a,b,c){if(a===b)return c;var d=a.nextSibling;while(d){if(d===b)return-1;d=d.nextSibling}return 1}),function(){var a=c.createElement("div"),d="script"+(new Date).getTime(),e=c.documentElement;a.innerHTML="<a name='"+d+"'/>",e.insertBefore(a,e.firstChild),c.getElementById(d)&&(o.find.ID=function(a,c,d){if(typeof c.getElementById!="undefined"&&!d){var e=c.getElementById(a[1]);return e?e.id===a[1]||typeof e.getAttributeNode!="undefined"&&e.getAttributeNode("id").nodeValue===a[1]?[e]:b:[]}},o.filter.ID=function(a,b){var c=typeof a.getAttributeNode!="undefined"&&a.getAttributeNode("id");return a.nodeType===1&&c&&c.nodeValue===b}),e.removeChild(a),e=a=null}(),function(){var a=c.createElement("div");a.appendChild(c.createComment("")),a.getElementsByTagName("*").length>0&&(o.find.TAG=function(a,b){var c=b.getElementsByTagName(a[1]);if(a[1]==="*"){var d=[];for(var e=0;c[e];e++)c[e].nodeType===1&&d.push(c[e]);c=d}return c}),a.innerHTML="<a href='#'></a>",a.firstChild&&typeof a.firstChild.getAttribute!="undefined"&&a.firstChild.getAttribute("href")!=="#"&&(o.attrHandle.href=function(a){return a.getAttribute("href",2)}),a=null}(),c.querySelectorAll&&function(){var a=m,b=c.createElement("div"),d="__sizzle__";b.innerHTML="<p class='TEST'></p>";if(!b.querySelectorAll||b.querySelectorAll(".TEST").length!==0){m=function(b,e,f,g){e=e||c;if(!g&&!m.isXML(e)){var h=/^(\w+$)|^\.([\w\-]+$)|^#([\w\-]+$)/.exec(b);if(h&&(e.nodeType===1||e.nodeType===9)){if(h[1])return s(e.getElementsByTagName(b),f);if(h[2]&&o.find.CLASS&&e.getElementsByClassName)return s(e.getElementsByClassName(h[2]),f)}if(e.nodeType===9){if(b==="body"&&e.body)return s([e.body],f);if(h&&h[3]){var i=e.getElementById(h[3]);if(!i||!i.parentNode)return s([],f);if(i.id===h[3])return s([i],f)}try{return s(e.querySelectorAll(b),f)}catch(j){}}else if(e.nodeType===1&&e.nodeName.toLowerCase()!=="object"){var k=e,l=e.getAttribute("id"),n=l||d,p=e.parentNode,q=/^\s*[+~]/.test(b);l?n=n.replace(/'/g,"\\$&"):e.setAttribute("id",n),q&&p&&(e=e.parentNode);try{if(!q||p)return s(e.querySelectorAll("[id='"+n+"'] "+b),f)}catch(r){}finally{l||k.removeAttribute("id")}}}return a(b,e,f,g)};for(var e in a)m[e]=a[e];b=null}}(),function(){var a=c.documentElement,b=a.matchesSelector||a.mozMatchesSelector||a.webkitMatchesSelector||a.msMatchesSelector;if(b){var d=!b.call(c.createElement("div"),"div"),e=!1;try{b.call(c.documentElement,"[test!='']:sizzle")}catch(f){e=!0}m.matchesSelector=function(a,c){c=c.replace(/\=\s*([^'"\]]*)\s*\]/g,"='$1']");if(!m.isXML(a))try{if(e||!o.match.PSEUDO.test(c)&&!/!=/.test(c)){var f=b.call(a,c);if(f||!d||a.document&&a.document.nodeType!==11)return f}}catch(g){}return m(c,null,null,[a]).length>0}}}(),function(){var a=c.createElement("div");a.innerHTML="<div class='test e'></div><div class='test'></div>";if(!!a.getElementsByClassName&&a.getElementsByClassName("e").length!==0){a.lastChild.className="e";if(a.getElementsByClassName("e").length===1)return;o.order.splice(1,0,"CLASS"),o.find.CLASS=function(a,b,c){if(typeof b.getElementsByClassName!="undefined"&&!c)return b.getElementsByClassName(a[1])},a=null}}(),c.documentElement.contains?m.contains=function(a,b){return a!==b&&(a.contains?a.contains(b):!0)}:c.documentElement.compareDocumentPosition?m.contains=function(a,b){return!!(a.compareDocumentPosition(b)&16)}:m.contains=function(){return!1},m.isXML=function(a){var b=(a?a.ownerDocument||a:0).documentElement;return b?b.nodeName!=="HTML":!1};var y=function(a,b,c){var d,e=[],f="",g=b.nodeType?[b]:b;while(d=o.match.PSEUDO.exec(a))f+=d[0],a=a.replace(o.match.PSEUDO,"");a=o.relative[a]?a+"*":a;for(var h=0,i=g.length;h<i;h++)m(a,g[h],e,c);return m.filter(f,e)};m.attr=f.attr,m.selectors.attrMap={},f.find=m,f.expr=m.selectors,f.expr[":"]=f.expr.filters,f.unique=m.uniqueSort,f.text=m.getText,f.isXMLDoc=m.isXML,f.contains=m.contains}();var L=/Until$/,M=/^(?:parents|prevUntil|prevAll)/,N=/,/,O=/^.[^:#\[\.,]*$/,P=Array.prototype.slice,Q=f.expr.match.POS,R={children:!0,contents:!0,next:!0,prev:!0};f.fn.extend({find:function(a){var b=this,c,d;if(typeof a!="string")return f(a).filter(function(){for(c=0,d=b.length;c<d;c++)if(f.contains(b[c],this))return!0});var e=this.pushStack("","find",a),g,h,i;for(c=0,d=this.length;c<d;c++){g=e.length,f.find(a,this[c],e);if(c>0)for(h=g;h<e.length;h++)for(i=0;i<g;i++)if(e[i]===e[h]){e.splice(h--,1);break}}return e},has:function(a){var b=f(a);return this.filter(function(){for(var a=0,c=b.length;a<c;a++)if(f.contains(this,b[a]))return!0})},not:function(a){return this.pushStack(T(this,a,!1),"not",a)},filter:function(a){return this.pushStack(T(this,a,!0),"filter",a)},is:function(a){return!!a&&(typeof a=="string"?Q.test(a)?f(a,this.context).index(this[0])>=0:f.filter(a,this).length>0:this.filter(a).length>0)},closest:function(a,b){var c=[],d,e,g=this[0];if(f.isArray(a)){var h=1;while(g&&g.ownerDocument&&g!==b){for(d=0;d<a.length;d++)f(g).is(a[d])&&c.push({selector:a[d],elem:g,level:h});g=g.parentNode,h++}return c}var i=Q.test(a)||typeof a!="string"?f(a,b||this.context):0;for(d=0,e=this.length;d<e;d++){g=this[d];while(g){if(i?i.index(g)>-1:f.find.matchesSelector(g,a)){c.push(g);break}g=g.parentNode;if(!g||!g.ownerDocument||g===b||g.nodeType===11)break}}c=c.length>1?f.unique(c):c;return this.pushStack(c,"closest",a)},index:function(a){if(!a)return this[0]&&this[0].parentNode?this.prevAll().length:-1;if(typeof a=="string")return f.inArray(this[0],f(a));return f.inArray(a.jquery?a[0]:a,this)},add:function(a,b){var c=typeof a=="string"?f(a,b):f.makeArray(a&&a.nodeType?[a]:a),d=f.merge(this.get(),c);return this.pushStack(S(c[0])||S(d[0])?d:f.unique(d))},andSelf:function(){return this.add(this.prevObject)}}),f.each({parent:function(a){var b=a.parentNode;return b&&b.nodeType!==11?b:null},parents:function(a){return f.dir(a,"parentNode")},parentsUntil:function(a,b,c){return f.dir(a,"parentNode",c)},next:function(a){return f.nth(a,2,"nextSibling")},prev:function(a){return f.nth(a,2,"previousSibling")},nextAll:function(a){return f.dir(a,"nextSibling")},prevAll:function(a){return f.dir(a,"previousSibling")},nextUntil:function(a,b,c){return f.dir(a,"nextSibling",c)},prevUntil:function(a,b,c){return f.dir(a,"previousSibling",c)},siblings:function(a){return f.sibling(a.parentNode.firstChild,a)},children:function(a){return f.sibling(a.firstChild)},contents:function(a){return f.nodeName(a,"iframe")?a.contentDocument||a.contentWindow.document:f.makeArray(a.childNodes)}},function(a,b){f.fn[a]=function(c,d){var e=f.map(this,b,c);L.test(a)||(d=c),d&&typeof d=="string"&&(e=f.filter(d,e)),e=this.length>1&&!R[a]?f.unique(e):e,(this.length>1||N.test(d))&&M.test(a)&&(e=e.reverse());return this.pushStack(e,a,P.call(arguments).join(","))}}),f.extend({filter:function(a,b,c){c&&(a=":not("+a+")");return b.length===1?f.find.matchesSelector(b[0],a)?[b[0]]:[]:f.find.matches(a,b)},dir:function(a,c,d){var e=[],g=a[c];while(g&&g.nodeType!==9&&(d===b||g.nodeType!==1||!f(g).is(d)))g.nodeType===1&&e.push(g),g=g[c];return e},nth:function(a,b,c,d){b=b||1;var e=0;for(;a;a=a[c])if(a.nodeType===1&&++e===b)break;return a},sibling:function(a,b){var c=[];for(;a;a=a.nextSibling)a.nodeType===1&&a!==b&&c.push(a);return c}});var V="abbr|article|aside|audio|canvas|datalist|details|figcaption|figure|footer|header|hgroup|mark|meter|nav|output|progress|section|summary|time|video",W=/ jQuery\d+="(?:\d+|null)"/g,X=/^\s+/,Y=/<(?!area|br|col|embed|hr|img|input|link|meta|param)(([\w:]+)[^>]*)\/>/ig,Z=/<([\w:]+)/,$=/<tbody/i,_=/<|&#?\w+;/,ba=/<(?:script|style)/i,bb=/<(?:script|object|embed|option|style)/i,bc=new RegExp("<(?:"+V+")","i"),bd=/checked\s*(?:[^=]|=\s*.checked.)/i,be=/\/(java|ecma)script/i,bf=/^\s*<!(?:\[CDATA\[|\-\-)/,bg={option:[1,"<select multiple='multiple'>","</select>"],legend:[1,"<fieldset>","</fieldset>"],thead:[1,"<table>","</table>"],tr:[2,"<table><tbody>","</tbody></table>"],td:[3,"<table><tbody><tr>","</tr></tbody></table>"],col:[2,"<table><tbody></tbody><colgroup>","</colgroup></table>"],area:[1,"<map>","</map>"],_default:[0,"",""]},bh=U(c);bg.optgroup=bg.option,bg.tbody=bg.tfoot=bg.colgroup=bg.caption=bg.thead,bg.th=bg.td,f.support.htmlSerialize||(bg._default=[1,"div<div>","</div>"]),f.fn.extend({text:function(a){if(f.isFunction(a))return this.each(function(b){var c=f(this);c.text(a.call(this,b,c.text()))});if(typeof a!="object"&&a!==b)return this.empty().append((this[0]&&this[0].ownerDocument||c).createTextNode(a));return f.text(this)},wrapAll:function(a){if(f.isFunction(a))return this.each(function(b){f(this).wrapAll(a.call(this,b))});if(this[0]){var b=f(a,this[0].ownerDocument).eq(0).clone(!0);this[0].parentNode&&b.insertBefore(this[0]),b.map(function(){var a=this;while(a.firstChild&&a.firstChild.nodeType===1)a=a.firstChild;return a}).append(this)}return this},wrapInner:function(a){if(f.isFunction(a))return this.each(function(b){f(this).wrapInner(a.call(this,b))});return this.each(function(){var b=f(this),c=b.contents();c.length?c.wrapAll(a):b.append(a)})},wrap:function(a){var b=f.isFunction(a);return this.each(function(c){f(this).wrapAll(b?a.call(this,c):a)})},unwrap:function(){return this.parent().each(function(){f.nodeName(this,"body")||f(this).replaceWith(this.childNodes)}).end()},append:function(){return this.domManip(arguments,!0,function(a){this.nodeType===1&&this.appendChild(a)})},prepend:function(){return this.domManip(arguments,!0,function(a){this.nodeType===1&&this.insertBefore(a,this.firstChild)})},before:function(){if(this[0]&&this[0].parentNode)return this.domManip(arguments,!1,function(a){this.parentNode.insertBefore(a,this)});if(arguments.length){var a=f.clean(arguments);a.push.apply(a,this.toArray());return this.pushStack(a,"before",arguments)}},after:function(){if(this[0]&&this[0].parentNode)return this.domManip(arguments,!1,function(a){this.parentNode.insertBefore(a,this.nextSibling)});if(arguments.length){var a=this.pushStack(this,"after",arguments);a.push.apply(a,f.clean(arguments));return a}},remove:function(a,b){for(var c=0,d;(d=this[c])!=null;c++)if(!a||f.filter(a,[d]).length)!b&&d.nodeType===1&&(f.cleanData(d.getElementsByTagName("*")),f.cleanData([d])),d.parentNode&&d.parentNode.removeChild(d);return this},empty:function() {for(var a=0,b;(b=this[a])!=null;a++){b.nodeType===1&&f.cleanData(b.getElementsByTagName("*"));while(b.firstChild)b.removeChild(b.firstChild)}return this},clone:function(a,b){a=a==null?!1:a,b=b==null?a:b;return this.map(function(){return f.clone(this,a,b)})},html:function(a){if(a===b)return this[0]&&this[0].nodeType===1?this[0].innerHTML.replace(W,""):null;if(typeof a=="string"&&!ba.test(a)&&(f.support.leadingWhitespace||!X.test(a))&&!bg[(Z.exec(a)||["",""])[1].toLowerCase()]){a=a.replace(Y,"<$1></$2>");try{for(var c=0,d=this.length;c<d;c++)this[c].nodeType===1&&(f.cleanData(this[c].getElementsByTagName("*")),this[c].innerHTML=a)}catch(e){this.empty().append(a)}}else f.isFunction(a)?this.each(function(b){var c=f(this);c.html(a.call(this,b,c.html()))}):this.empty().append(a);return this},replaceWith:function(a){if(this[0]&&this[0].parentNode){if(f.isFunction(a))return this.each(function(b){var c=f(this),d=c.html();c.replaceWith(a.call(this,b,d))});typeof a!="string"&&(a=f(a).detach());return this.each(function(){var b=this.nextSibling,c=this.parentNode;f(this).remove(),b?f(b).before(a):f(c).append(a)})}return this.length?this.pushStack(f(f.isFunction(a)?a():a),"replaceWith",a):this},detach:function(a){return this.remove(a,!0)},domManip:function(a,c,d){var e,g,h,i,j=a[0],k=[];if(!f.support.checkClone&&arguments.length===3&&typeof j=="string"&&bd.test(j))return this.each(function(){f(this).domManip(a,c,d,!0)});if(f.isFunction(j))return this.each(function(e){var g=f(this);a[0]=j.call(this,e,c?g.html():b),g.domManip(a,c,d)});if(this[0]){i=j&&j.parentNode,f.support.parentNode&&i&&i.nodeType===11&&i.childNodes.length===this.length?e={fragment:i}:e=f.buildFragment(a,this,k),h=e.fragment,h.childNodes.length===1?g=h=h.firstChild:g=h.firstChild;if(g){c=c&&f.nodeName(g,"tr");for(var l=0,m=this.length,n=m-1;l<m;l++)d.call(c?bi(this[l],g):this[l],e.cacheable||m>1&&l<n?f.clone(h,!0,!0):h)}k.length&&f.each(k,bp)}return this}}),f.buildFragment=function(a,b,d){var e,g,h,i,j=a[0];b&&b[0]&&(i=b[0].ownerDocument||b[0]),i.createDocumentFragment||(i=c),a.length===1&&typeof j=="string"&&j.length<512&&i===c&&j.charAt(0)==="<"&&!bb.test(j)&&(f.support.checkClone||!bd.test(j))&&(f.support.html5Clone||!bc.test(j))&&(g=!0,h=f.fragments[j],h&&h!==1&&(e=h)),e||(e=i.createDocumentFragment(),f.clean(a,i,e,d)),g&&(f.fragments[j]=h?e:1);return{fragment:e,cacheable:g}},f.fragments={},f.each({appendTo:"append",prependTo:"prepend",insertBefore:"before",insertAfter:"after",replaceAll:"replaceWith"},function(a,b){f.fn[a]=function(c){var d=[],e=f(c),g=this.length===1&&this[0].parentNode;if(g&&g.nodeType===11&&g.childNodes.length===1&&e.length===1){e[b](this[0]);return this}for(var h=0,i=e.length;h<i;h++){var j=(h>0?this.clone(!0):this).get();f(e[h])[b](j),d=d.concat(j)}return this.pushStack(d,a,e.selector)}}),f.extend({clone:function(a,b,c){var d,e,g,h=f.support.html5Clone||!bc.test("<"+a.nodeName)?a.cloneNode(!0):bo(a);if((!f.support.noCloneEvent||!f.support.noCloneChecked)&&(a.nodeType===1||a.nodeType===11)&&!f.isXMLDoc(a)){bk(a,h),d=bl(a),e=bl(h);for(g=0;d[g];++g)e[g]&&bk(d[g],e[g])}if(b){bj(a,h);if(c){d=bl(a),e=bl(h);for(g=0;d[g];++g)bj(d[g],e[g])}}d=e=null;return h},clean:function(a,b,d,e){var g;b=b||c,typeof b.createElement=="undefined"&&(b=b.ownerDocument||b[0]&&b[0].ownerDocument||c);var h=[],i;for(var j=0,k;(k=a[j])!=null;j++){typeof k=="number"&&(k+="");if(!k)continue;if(typeof k=="string")if(!_.test(k))k=b.createTextNode(k);else{k=k.replace(Y,"<$1></$2>");var l=(Z.exec(k)||["",""])[1].toLowerCase(),m=bg[l]||bg._default,n=m[0],o=b.createElement("div");b===c?bh.appendChild(o):U(b).appendChild(o),o.innerHTML=m[1]+k+m[2];while(n--)o=o.lastChild;if(!f.support.tbody){var p=$.test(k),q=l==="table"&&!p?o.firstChild&&o.firstChild.childNodes:m[1]==="<table>"&&!p?o.childNodes:[];for(i=q.length-1;i>=0;--i)f.nodeName(q[i],"tbody")&&!q[i].childNodes.length&&q[i].parentNode.removeChild(q[i])}!f.support.leadingWhitespace&&X.test(k)&&o.insertBefore(b.createTextNode(X.exec(k)[0]),o.firstChild),k=o.childNodes}var r;if(!f.support.appendChecked)if(k[0]&&typeof (r=k.length)=="number")for(i=0;i<r;i++)bn(k[i]);else bn(k);k.nodeType?h.push(k):h=f.merge(h,k)}if(d){g=function(a){return!a.type||be.test(a.type)};for(j=0;h[j];j++)if(e&&f.nodeName(h[j],"script")&&(!h[j].type||h[j].type.toLowerCase()==="text/javascript"))e.push(h[j].parentNode?h[j].parentNode.removeChild(h[j]):h[j]);else{if(h[j].nodeType===1){var s=f.grep(h[j].getElementsByTagName("script"),g);h.splice.apply(h,[j+1,0].concat(s))}d.appendChild(h[j])}}return h},cleanData:function(a){var b,c,d=f.cache,e=f.event.special,g=f.support.deleteExpando;for(var h=0,i;(i=a[h])!=null;h++){if(i.nodeName&&f.noData[i.nodeName.toLowerCase()])continue;c=i[f.expando];if(c){b=d[c];if(b&&b.events){for(var j in b.events)e[j]?f.event.remove(i,j):f.removeEvent(i,j,b.handle);b.handle&&(b.handle.elem=null)}g?delete i[f.expando]:i.removeAttribute&&i.removeAttribute(f.expando),delete d[c]}}}});var bq=/alpha\([^)]*\)/i,br=/opacity=([^)]*)/,bs=/([A-Z]|^ms)/g,bt=/^-?\d+(?:px)?$/i,bu=/^-?\d/,bv=/^([\-+])=([\-+.\de]+)/,bw={position:"absolute",visibility:"hidden",display:"block"},bx=["Left","Right"],by=["Top","Bottom"],bz,bA,bB;f.fn.css=function(a,c){if(arguments.length===2&&c===b)return this;return f.access(this,a,c,!0,function(a,c,d){return d!==b?f.style(a,c,d):f.css(a,c)})},f.extend({cssHooks:{opacity:{get:function(a,b){if(b){var c=bz(a,"opacity","opacity");return c===""?"1":c}return a.style.opacity}}},cssNumber:{fillOpacity:!0,fontWeight:!0,lineHeight:!0,opacity:!0,orphans:!0,widows:!0,zIndex:!0,zoom:!0},cssProps:{"float":f.support.cssFloat?"cssFloat":"styleFloat"},style:function(a,c,d,e){if(!!a&&a.nodeType!==3&&a.nodeType!==8&&!!a.style){var g,h,i=f.camelCase(c),j=a.style,k=f.cssHooks[i];c=f.cssProps[i]||i;if(d===b){if(k&&"get"in k&&(g=k.get(a,!1,e))!==b)return g;return j[c]}h=typeof d,h==="string"&&(g=bv.exec(d))&&(d=+(g[1]+1)*+g[2]+parseFloat(f.css(a,c)),h="number");if(d==null||h==="number"&&isNaN(d))return;h==="number"&&!f.cssNumber[i]&&(d+="px");if(!k||!("set"in k)||(d=k.set(a,d))!==b)try{j[c]=d}catch(l){}}},css:function(a,c,d){var e,g;c=f.camelCase(c),g=f.cssHooks[c],c=f.cssProps[c]||c,c==="cssFloat"&&(c="float");if(g&&"get"in g&&(e=g.get(a,!0,d))!==b)return e;if(bz)return bz(a,c)},swap:function(a,b,c){var d={};for(var e in b)d[e]=a.style[e],a.style[e]=b[e];c.call(a);for(e in b)a.style[e]=d[e]}}),f.curCSS=f.css,f.each(["height","width"],function(a,b){f.cssHooks[b]={get:function(a,c,d){var e;if(c){if(a.offsetWidth!==0)return bC(a,b,d);f.swap(a,bw,function(){e=bC(a,b,d)});return e}},set:function(a,b){if(!bt.test(b))return b;b=parseFloat(b);if(b>=0)return b+"px"}}}),f.support.opacity||(f.cssHooks.opacity={get:function(a,b){return br.test((b&&a.currentStyle?a.currentStyle.filter:a.style.filter)||"")?parseFloat(RegExp.$1)/100+"":b?"1":""},set:function(a,b){var c=a.style,d=a.currentStyle,e=f.isNumeric(b)?"alpha(opacity="+b*100+")":"",g=d&&d.filter||c.filter||"";c.zoom=1;if(b>=1&&f.trim(g.replace(bq,""))===""){c.removeAttribute("filter");if(d&&!d.filter)return}c.filter=bq.test(g)?g.replace(bq,e):g+" "+e}}),f(function(){f.support.reliableMarginRight||(f.cssHooks.marginRight={get:function(a,b){var c;f.swap(a,{display:"inline-block"},function(){b?c=bz(a,"margin-right","marginRight"):c=a.style.marginRight});return c}})}),c.defaultView&&c.defaultView.getComputedStyle&&(bA=function(a,b){var c,d,e;b=b.replace(bs,"-$1").toLowerCase(),(d=a.ownerDocument.defaultView)&&(e=d.getComputedStyle(a,null))&&(c=e.getPropertyValue(b),c===""&&!f.contains(a.ownerDocument.documentElement,a)&&(c=f.style(a,b)));return c}),c.documentElement.currentStyle&&(bB=function(a,b){var c,d,e,f=a.currentStyle&&a.currentStyle[b],g=a.style;f===null&&g&&(e=g[b])&&(f=e),!bt.test(f)&&bu.test(f)&&(c=g.left,d=a.runtimeStyle&&a.runtimeStyle.left,d&&(a.runtimeStyle.left=a.currentStyle.left),g.left=b==="fontSize"?"1em":f||0,f=g.pixelLeft+"px",g.left=c,d&&(a.runtimeStyle.left=d));return f===""?"auto":f}),bz=bA||bB,f.expr&&f.expr.filters&&(f.expr.filters.hidden=function(a){var b=a.offsetWidth,c=a.offsetHeight;return b===0&&c===0||!f.support.reliableHiddenOffsets&&(a.style&&a.style.display||f.css(a,"display"))==="none"},f.expr.filters.visible=function(a){return!f.expr.filters.hidden(a)});var bD=/%20/g,bE=/\[\]$/,bF=/\r?\n/g,bG=/#.*$/,bH=/^(.*?):[ \t]*([^\r\n]*)\r?$/mg,bI=/^(?:color|date|datetime|datetime-local|email|hidden|month|number|password|range|search|tel|text|time|url|week)$/i,bJ=/^(?:about|app|app\-storage|.+\-extension|file|res|widget):$/,bK=/^(?:GET|HEAD)$/,bL=/^\/\//,bM=/\?/,bN=/<script\b[^<]*(?:(?!<\/script>)<[^<]*)*<\/script>/gi,bO=/^(?:select|textarea)/i,bP=/\s+/,bQ=/([?&])_=[^&]*/,bR=/^([\w\+\.\-]+:)(?:\/\/([^\/?#:]*)(?::(\d+))?)?/,bS=f.fn.load,bT={},bU={},bV,bW,bX=["*/"]+["*"];try{bV=e.href}catch(bY){bV=c.createElement("a"),bV.href="",bV=bV.href}bW=bR.exec(bV.toLowerCase())||[],f.fn.extend({load:function(a,c,d){if(typeof a!="string"&&bS)return bS.apply(this,arguments);if(!this.length)return this;var e=a.indexOf(" ");if(e>=0){var g=a.slice(e,a.length);a=a.slice(0,e)}var h="GET";c&&(f.isFunction(c)?(d=c,c=b):typeof c=="object"&&(c=f.param(c,f.ajaxSettings.traditional),h="POST"));var i=this;f.ajax({url:a,type:h,dataType:"html",data:c,complete:function(a,b,c){c=a.responseText,a.isResolved()&&(a.done(function(a){c=a}),i.html(g?f("<div>").append(c.replace(bN,"")).find(g):c)),d&&i.each(d,[c,b,a])}});return this},serialize:function(){return f.param(this.serializeArray())},serializeArray:function(){return this.map(function(){return this.elements?f.makeArray(this.elements):this}).filter(function(){return this.name&&!this.disabled&&(this.checked||bO.test(this.nodeName)||bI.test(this.type))}).map(function(a,b){var c=f(this).val();return c==null?null:f.isArray(c)?f.map(c,function(a,c){return{name:b.name,value:a.replace(bF,"\r\n")}}):{name:b.name,value:c.replace(bF,"\r\n")}}).get()}}),f.each("ajaxStart ajaxStop ajaxComplete ajaxError ajaxSuccess ajaxSend".split(" "),function(a,b){f.fn[b]=function(a){return this.on(b,a)}}),f.each(["get","post"],function(a,c){f[c]=function(a,d,e,g){f.isFunction(d)&&(g=g||e,e=d,d=b);return f.ajax({type:c,url:a,data:d,success:e,dataType:g})}}),f.extend({getScript:function(a,c){return f.get(a,b,c,"script")},getJSON:function(a,b,c){return f.get(a,b,c,"json")},ajaxSetup:function(a,b){b?b_(a,f.ajaxSettings):(b=a,a=f.ajaxSettings),b_(a,b);return a},ajaxSettings:{url:bV,isLocal:bJ.test(bW[1]),global:!0,type:"GET",contentType:"application/x-www-form-urlencoded",processData:!0,async:!0,accepts:{xml:"application/xml, text/xml",html:"text/html",text:"text/plain",json:"application/json, text/javascript","*":bX},contents:{xml:/xml/,html:/html/,json:/json/},responseFields:{xml:"responseXML",text:"responseText"},converters:{"* text":a.String,"text html":!0,"text json":f.parseJSON,"text xml":f.parseXML},flatOptions:{context:!0,url:!0}},ajaxPrefilter:bZ(bT),ajaxTransport:bZ(bU),ajax:function(a,c){function w(a,c,l,m){if(s!==2){s=2,q&&clearTimeout(q),p=b,n=m||"",v.readyState=a>0?4:0;var o,r,u,w=c,x=l?cb(d,v,l):b,y,z;if(a>=200&&a<300||a===304){if(d.ifModified){if(y=v.getResponseHeader("Last-Modified"))f.lastModified[k]=y;if(z=v.getResponseHeader("Etag"))f.etag[k]=z}if(a===304)w="notmodified",o=!0;else try{r=cc(d,x),w="success",o=!0}catch(A){w="parsererror",u=A}}else{u=w;if(!w||a)w="error",a<0&&(a=0)}v.status=a,v.statusText=""+(c||w),o?h.resolveWith(e,[r,w,v]):h.rejectWith(e,[v,w,u]),v.statusCode(j),j=b,t&&g.trigger("ajax"+(o?"Success":"Error"),[v,d,o?r:u]),i.fireWith(e,[v,w]),t&&(g.trigger("ajaxComplete",[v,d]),--f.active||f.event.trigger("ajaxStop"))}}typeof a=="object"&&(c=a,a=b),c=c||{};var d=f.ajaxSetup({},c),e=d.context||d,g=e!==d&&(e.nodeType||e instanceof f)?f(e):f.event,h=f.Deferred(),i=f.Callbacks("once memory"),j=d.statusCode||{},k,l={},m={},n,o,p,q,r,s=0,t,u,v={readyState:0,setRequestHeader:function(a,b){if(!s){var c=a.toLowerCase();a=m[c]=m[c]||a,l[a]=b}return this},getAllResponseHeaders:function(){return s===2?n:null},getResponseHeader:function(a){var c;if(s===2){if(!o){o={};while(c=bH.exec(n))o[c[1].toLowerCase()]=c[2]}c=o[a.toLowerCase()]}return c===b?null:c},overrideMimeType:function(a){s||(d.mimeType=a);return this},abort:function(a){a=a||"abort",p&&p.abort(a),w(0,a);return this}};h.promise(v),v.success=v.done,v.error=v.fail,v.complete=i.add,v.statusCode=function(a){if(a){var b;if(s<2)for(b in a)j[b]=[j[b],a[b]];else b=a[v.status],v.then(b,b)}return this},d.url=((a||d.url)+"").replace(bG,"").replace(bL,bW[1]+"//"),d.dataTypes=f.trim(d.dataType||"*").toLowerCase().split(bP),d.crossDomain==null&&(r=bR.exec(d.url.toLowerCase()),d.crossDomain=!(!r||r[1]==bW[1]&&r[2]==bW[2]&&(r[3]||(r[1]==="http:"?80:443))==(bW[3]||(bW[1]==="http:"?80:443)))),d.data&&d.processData&&typeof d.data!="string"&&(d.data=f.param(d.data,d.traditional)),b$(bT,d,c,v);if(s===2)return!1;t=d.global,d.type=d.type.toUpperCase(),d.hasContent=!bK.test(d.type),t&&f.active++===0&&f.event.trigger("ajaxStart");if(!d.hasContent){d.data&&(d.url+=(bM.test(d.url)?"&":"?")+d.data,delete d.data),k=d.url;if(d.cache===!1){var x=f.now(),y=d.url.replace(bQ,"$1_="+x);d.url=y+(y===d.url?(bM.test(d.url)?"&":"?")+"_="+x:"")}}(d.data&&d.hasContent&&d.contentType!==!1||c.contentType)&&v.setRequestHeader("Content-Type",d.contentType),d.ifModified&&(k=k||d.url,f.lastModified[k]&&v.setRequestHeader("If-Modified-Since",f.lastModified[k]),f.etag[k]&&v.setRequestHeader("If-None-Match",f.etag[k])),v.setRequestHeader("Accept",d.dataTypes[0]&&d.accepts[d.dataTypes[0]]?d.accepts[d.dataTypes[0]]+(d.dataTypes[0]!=="*"?", "+bX+"; q=0.01":""):d.accepts["*"]);for(u in d.headers)v.setRequestHeader(u,d.headers[u]);if(d.beforeSend&&(d.beforeSend.call(e,v,d)===!1||s===2)){v.abort();return!1}for(u in{success:1,error:1,complete:1})v[u](d[u]);p=b$(bU,d,c,v);if(!p)w(-1,"No Transport");else{v.readyState=1,t&&g.trigger("ajaxSend",[v,d]),d.async&&d.timeout>0&&(q=setTimeout(function(){v.abort("timeout")},d.timeout));try{s=1,p.send(l,w)}catch(z){if(s<2)w(-1,z);else throw z}}return v},param:function(a,c){var d=[],e=function(a,b){b=f.isFunction(b)?b():b,d[d.length]=encodeURIComponent(a)+"="+encodeURIComponent(b)};c===b&&(c=f.ajaxSettings.traditional);if(f.isArray(a)||a.jquery&&!f.isPlainObject(a))f.each(a,function(){e(this.name,this.value)});else for(var g in a)ca(g,a[g],c,e);return d.join("&").replace(bD,"+")}}),f.extend({active:0,lastModified:{},etag:{}});var cd=f.now(),ce=/(\=)\?(&|$)|\?\?/i;f.ajaxSetup({jsonp:"callback",jsonpCallback:function(){return f.expando+"_"+cd++}}),f.ajaxPrefilter("json jsonp",function(b,c,d){var e=b.contentType==="application/x-www-form-urlencoded"&&typeof b.data=="string";if(b.dataTypes[0]==="jsonp"||b.jsonp!==!1&&(ce.test(b.url)||e&&ce.test(b.data))){var g,h=b.jsonpCallback=f.isFunction(b.jsonpCallback)?b.jsonpCallback():b.jsonpCallback,i=a[h],j=b.url,k=b.data,l="$1"+h+"$2";b.jsonp!==!1&&(j=j.replace(ce,l),b.url===j&&(e&&(k=k.replace(ce,l)),b.data===k&&(j+=(/\?/.test(j)?"&":"?")+b.jsonp+"="+h))),b.url=j,b.data=k,a[h]=function(a){g=[a]},d.always(function(){a[h]=i,g&&f.isFunction(i)&&a[h](g[0])}),b.converters["script json"]=function(){g||f.error(h+" was not called");return g[0]},b.dataTypes[0]="json";return"script"}}),f.ajaxSetup({accepts:{script:"text/javascript, application/javascript, application/ecmascript, application/x-ecmascript"},contents:{script:/javascript|ecmascript/},converters:{"text script":function(a){f.globalEval(a);return a}}}),f.ajaxPrefilter("script",function(a){a.cache===b&&(a.cache=!1),a.crossDomain&&(a.type="GET",a.global=!1)}),f.ajaxTransport("script",function(a){if(a.crossDomain){var d,e=c.head||c.getElementsByTagName("head")[0]||c.documentElement;return{send:function(f,g){d=c.createElement("script"),d.async="async",a.scriptCharset&&(d.charset=a.scriptCharset),d.src=a.url,d.onload=d.onreadystatechange=function(a,c){if(c||!d.readyState||/loaded|complete/.test(d.readyState))d.onload=d.onreadystatechange=null,e&&d.parentNode&&e.removeChild(d),d=b,c||g(200,"success")},e.insertBefore(d,e.firstChild)},abort:function(){d&&d.onload(0,1)}}}});var cf=a.ActiveXObject?function(){for(var a in ch)ch[a](0,1)}:!1,cg=0,ch;f.ajaxSettings.xhr=a.ActiveXObject?function(){return!this.isLocal&&ci()||cj()}:ci,function(a){f.extend(f.support,{ajax:!!a,cors:!!a&&"withCredentials"in a})}(f.ajaxSettings.xhr()),f.support.ajax&&f.ajaxTransport(function(c){if(!c.crossDomain||f.support.cors){var d;return{send:function(e,g){var h=c.xhr(),i,j;c.username?h.open(c.type,c.url,c.async,c.username,c.password):h.open(c.type,c.url,c.async);if(c.xhrFields)for(j in c.xhrFields)h[j]=c.xhrFields[j];c.mimeType&&h.overrideMimeType&&h.overrideMimeType(c.mimeType),!c.crossDomain&&!e["X-Requested-With"]&&(e["X-Requested-With"]="XMLHttpRequest");try{for(j in e)h.setRequestHeader(j,e[j])}catch(k){}h.send(c.hasContent&&c.data||null),d=function(a,e){var j,k,l,m,n;try{if(d&&(e||h.readyState===4)){d=b,i&&(h.onreadystatechange=f.noop,cf&&delete ch[i]);if(e)h.readyState!==4&&h.abort();else{j=h.status,l=h.getAllResponseHeaders(),m={},n=h.responseXML,n&&n.documentElement&&(m.xml=n),m.text=h.responseText;try{k=h.statusText}catch(o){k=""}!j&&c.isLocal&&!c.crossDomain?j=m.text?200:404:j===1223&&(j=204)}}}catch(p){e||g(-1,p)}m&&g(j,k,m,l)},!c.async||h.readyState===4?d():(i=++cg,cf&&(ch||(ch={},f(a).unload(cf)),ch[i]=d),h.onreadystatechange=d)},abort:function(){d&&d(0,1)}}}});var ck={},cl,cm,cn=/^(?:toggle|show|hide)$/,co=/^([+\-]=)?([\d+.\-]+)([a-z%]*)$/i,cp,cq=[["height","marginTop","marginBottom","paddingTop","paddingBottom"],["width","marginLeft","marginRight","paddingLeft","paddingRight"],["opacity"]],cr;f.fn.extend({show:function(a,b,c){var d,e;if(a||a===0)return this.animate(cu("show",3),a,b,c);for(var g=0,h=this.length;g<h;g++)d=this[g],d.style&&(e=d.style.display,!f._data(d,"olddisplay")&&e==="none"&&(e=d.style.display=""),e===""&&f.css(d,"display")==="none"&&f._data(d,"olddisplay",cv(d.nodeName)));for(g=0;g<h;g++){d=this[g];if(d.style){e=d.style.display;if(e===""||e==="none")d.style.display=f._data(d,"olddisplay")||""}}return this},hide:function(a,b,c){if(a||a===0)return this.animate(cu("hide",3),a,b,c);var d,e,g=0,h=this.length;for(;g<h;g++)d=this[g],d.style&&(e=f.css(d,"display"),e!=="none"&&!f._data(d,"olddisplay")&&f._data(d,"olddisplay",e));for(g=0;g<h;g++)this[g].style&&(this[g].style.display="none");return this},_toggle:f.fn.toggle,toggle:function(a,b,c){var d=typeof a=="boolean";f.isFunction(a)&&f.isFunction(b)?this._toggle.apply(this,arguments):a==null||d?this.each(function(){var b=d?a:f(this).is(":hidden");f(this)[b?"show":"hide"]()}):this.animate(cu("toggle",3),a,b,c);return this},fadeTo:function(a,b,c,d){return this.filter(":hidden").css("opacity",0).show().end().animate({opacity:b},a,c,d)},animate:function(a,b,c,d){function g(){e.queue===!1&&f._mark(this);var b=f.extend({},e),c=this.nodeType===1,d=c&&f(this).is(":hidden"),g,h,i,j,k,l,m,n,o;b.animatedProperties={};for(i in a){g=f.camelCase(i),i!==g&&(a[g]=a[i],delete a[i]),h=a[g],f.isArray(h)?(b.animatedProperties[g]=h[1],h=a[g]=h[0]):b.animatedProperties[g]=b.specialEasing&&b.specialEasing[g]||b.easing||"swing";if(h==="hide"&&d||h==="show"&&!d)return b.complete.call(this);c&&(g==="height"||g==="width")&&(b.overflow=[this.style.overflow,this.style.overflowX,this.style.overflowY],f.css(this,"display")==="inline"&&f.css(this,"float")==="none"&&(!f.support.inlineBlockNeedsLayout||cv(this.nodeName)==="inline"?this.style.display="inline-block":this.style.zoom=1))}b.overflow!=null&&(this.style.overflow="hidden");for(i in a)j=new f.fx(this,b,i),h=a[i],cn.test(h)?(o=f._data(this,"toggle"+i)||(h==="toggle"?d?"show":"hide":0),o?(f._data(this,"toggle"+i,o==="show"?"hide":"show"),j[o]()):j[h]()):(k=co.exec(h),l=j.cur(),k?(m=parseFloat(k[2]),n=k[3]||(f.cssNumber[i]?"":"px"),n!=="px"&&(f.style(this,i,(m||1)+n),l=(m||1)/j.cur()*l,f.style(this,i,l+n)),k[1]&&(m=(k[1]==="-="?-1:1)*m+l),j.custom(l,m,n)):j.custom(l,h,""));return!0}var e=f.speed(b,c,d);if(f.isEmptyObject(a))return this.each(e.complete,[!1]);a=f.extend({},a);return e.queue===!1?this.each(g):this.queue(e.queue,g)},stop:function(a,c,d){typeof a!="string"&&(d=c,c=a,a=b),c&&a!==!1&&this.queue(a||"fx",[]);return this.each(function(){function h(a,b,c){var e=b[c];f.removeData(a,c,!0),e.stop(d)}var b,c=!1,e=f.timers,g=f._data(this);d||f._unmark(!0,this);if(a==null)for(b in g)g[b]&&g[b].stop&&b.indexOf(".run")===b.length-4&&h(this,g,b);else g[b=a+".run"]&&g[b].stop&&h(this,g,b);for(b=e.length;b--;)e[b].elem===this&&(a==null||e[b].queue===a)&&(d?e[b](!0):e[b].saveState(),c=!0,e.splice(b,1));(!d||!c)&&f.dequeue(this,a)})}}),f.each({slideDown:cu("show",1),slideUp:cu("hide",1),slideToggle:cu("toggle",1),fadeIn:{opacity:"show"},fadeOut:{opacity:"hide"},fadeToggle:{opacity:"toggle"}},function(a,b){f.fn[a]=function(a,c,d){return this.animate(b,a,c,d)}}),f.extend({speed:function(a,b,c){var d=a&&typeof a=="object"?f.extend({},a):{complete:c||!c&&b||f.isFunction(a)&&a,duration:a,easing:c&&b||b&&!f.isFunction(b)&&b};d.duration=f.fx.off?0:typeof d.duration=="number"?d.duration:d.duration in f.fx.speeds?f.fx.speeds[d.duration]:f.fx.speeds._default;if(d.queue==null||d.queue===!0)d.queue="fx";d.old=d.complete,d.complete=function(a){f.isFunction(d.old)&&d.old.call(this),d.queue?f.dequeue(this,d.queue):a!==!1&&f._unmark(this)};return d},easing:{linear:function(a,b,c,d){return c+d*a},swing:function(a,b,c,d){return(-Math.cos(a*Math.PI)/2+.5)*d+c}},timers:[],fx:function(a,b,c){this.options=b,this.elem=a,this.prop=c,b.orig=b.orig||{}}}),f.fx.prototype={update:function(){this.options.step&&this.options.step.call(this.elem,this.now,this),(f.fx.step[this.prop]||f.fx.step._default)(this)},cur:function(){if(this.elem[this.prop]!=null&&(!this.elem.style||this.elem.style[this.prop]==null))return this.elem[this.prop];var a,b=f.css(this.elem,this.prop);return isNaN(a=parseFloat(b))?!b||b==="auto"?0:b:a},custom:function(a,c,d){function h(a){return e.step(a)}var e=this,g=f.fx;this.startTime=cr||cs(),this.end=c,this.now=this.start=a,this.pos=this.state=0,this.unit=d||this.unit||(f.cssNumber[this.prop]?"":"px"),h.queue=this.options.queue,h.elem=this.elem,h.saveState=function(){e.options.hide&&f._data(e.elem,"fxshow"+e.prop)===b&&f._data(e.elem,"fxshow"+e.prop,e.start)},h()&&f.timers.push(h)&&!cp&&(cp=setInterval(g.tick,g.interval))},show:function(){var a=f._data(this.elem,"fxshow"+this.prop);this.options.orig[this.prop]=a||f.style(this.elem,this.prop),this.options.show=!0,a!==b?this.custom(this.cur(),a):this.custom(this.prop==="width"||this.prop==="height"?1:0,this.cur()),f(this.elem).show()},hide:function(){this.options.orig[this.prop]=f._data(this.elem,"fxshow"+this.prop)||f.style(this.elem,this.prop),this.options.hide=!0,this.custom(this.cur(),0)},step:function(a){var b,c,d,e=cr||cs(),g=!0,h=this.elem,i=this.options;if(a||e>=i.duration+this.startTime){this.now=this.end,this.pos=this.state=1,this.update(),i.animatedProperties[this.prop]=!0;for(b in i.animatedProperties)i.animatedProperties[b]!==!0&&(g=!1);if(g){i.overflow!=null&&!f.support.shrinkWrapBlocks&&f.each(["","X","Y"],function(a,b){h.style["overflow"+b]=i.overflow[a]}),i.hide&&f(h).hide();if(i.hide||i.show)for(b in i.animatedProperties)f.style(h,b,i.orig[b]),f.removeData(h,"fxshow"+b,!0),f.removeData(h,"toggle"+b,!0);d=i.complete,d&&(i.complete=!1,d.call(h))}return!1}i.duration==Infinity?this.now=e:(c=e-this.startTime,this.state=c/i.duration,this.pos=f.easing[i.animatedProperties[this.prop]](this.state,c,0,1,i.duration),this.now=this.start+(this.end-this.start)*this.pos),this.update();return!0}},f.extend(f.fx,{tick:function(){var a,b=f.timers,c=0;for(;c<b.length;c++)a=b[c],!a()&&b[c]===a&&b.splice(c--,1);b.length||f.fx.stop()},interval:13,stop:function(){clearInterval(cp),cp=null},speeds:{slow:600,fast:200,_default:400},step:{opacity:function(a){f.style(a.elem,"opacity",a.now)},_default:function(a){a.elem.style&&a.elem.style[a.prop]!=null?a.elem.style[a.prop]=a.now+a.unit:a.elem[a.prop]=a.now}}}),f.each(["width","height"],function(a,b){f.fx.step[b]=function(a){f.style(a.elem,b,Math.max(0,a.now)+a.unit)}}),f.expr&&f.expr.filters&&(f.expr.filters.animated=function(a){return f.grep(f.timers,function(b){return a===b.elem}).length});var cw=/^t(?:able|d|h)$/i,cx=/^(?:body|html)$/i;"getBoundingClientRect"in c.documentElement?f.fn.offset=function(a){var b=this[0],c;if(a)return this.each(function(b){f.offset.setOffset(this,a,b)});if(!b||!b.ownerDocument)return null;if(b===b.ownerDocument.body)return f.offset.bodyOffset(b);try{c=b.getBoundingClientRect()}catch(d){}var e=b.ownerDocument,g=e.documentElement;if(!c||!f.contains(g,b))return c?{top:c.top,left:c.left}:{top:0,left:0};var h=e.body,i=cy(e),j=g.clientTop||h.clientTop||0,k=g.clientLeft||h.clientLeft||0,l=i.pageYOffset||f.support.boxModel&&g.scrollTop||h.scrollTop,m=i.pageXOffset||f.support.boxModel&&g.scrollLeft||h.scrollLeft,n=c.top+l-j,o=c.left+m-k;return{top:n,left:o}}:f.fn.offset=function(a){var b=this[0];if(a)return this.each(function(b){f.offset.setOffset(this,a,b)});if(!b||!b.ownerDocument)return null;if(b===b.ownerDocument.body)return f.offset.bodyOffset(b);var c,d=b.offsetParent,e=b,g=b.ownerDocument,h=g.documentElement,i=g.body,j=g.defaultView,k=j?j.getComputedStyle(b,null):b.currentStyle,l=b.offsetTop,m=b.offsetLeft;while((b=b.parentNode)&&b!==i&&b!==h){if(f.support.fixedPosition&&k.position==="fixed")break;c=j?j.getComputedStyle(b,null):b.currentStyle,l-=b.scrollTop,m-=b.scrollLeft,b===d&&(l+=b.offsetTop,m+=b.offsetLeft,f.support.doesNotAddBorder&&(!f.support.doesAddBorderForTableAndCells||!cw.test(b.nodeName))&&(l+=parseFloat(c.borderTopWidth)||0,m+=parseFloat(c.borderLeftWidth)||0),e=d,d=b.offsetParent),f.support.subtractsBorderForOverflowNotVisible&&c.overflow!=="visible"&&(l+=parseFloat(c.borderTopWidth)||0,m+=parseFloat(c.borderLeftWidth)||0),k=c}if(k.position==="relative"||k.position==="static")l+=i.offsetTop,m+=i.offsetLeft;f.support.fixedPosition&&k.position==="fixed"&&(l+=Math.max(h.scrollTop,i.scrollTop),m+=Math.max(h.scrollLeft,i.scrollLeft));return{top:l,left:m}},f.offset={bodyOffset:function(a){var b=a.offsetTop,c=a.offsetLeft;f.support.doesNotIncludeMarginInBodyOffset&&(b+=parseFloat(f.css(a,"marginTop"))||0,c+=parseFloat(f.css(a,"marginLeft"))||0);return{top:b,left:c}},setOffset:function(a,b,c){var d=f.css(a,"position");d==="static"&&(a.style.position="relative");var e=f(a),g=e.offset(),h=f.css(a,"top"),i=f.css(a,"left"),j=(d==="absolute"||d==="fixed")&&f.inArray("auto",[h,i])>-1,k={},l={},m,n;j?(l=e.position(),m=l.top,n=l.left):(m=parseFloat(h)||0,n=parseFloat(i)||0),f.isFunction(b)&&(b=b.call(a,c,g)),b.top!=null&&(k.top=b.top-g.top+m),b.left!=null&&(k.left=b.left-g.left+n),"using"in b?b.using.call(a,k):e.css(k)}},f.fn.extend({position:function(){if(!this[0])return null;var a=this[0],b=this.offsetParent(),c=this.offset(),d=cx.test(b[0].nodeName)?{top:0,left:0}:b.offset();c.top-=parseFloat(f.css(a,"marginTop"))||0,c.left-=parseFloat(f.css(a,"marginLeft"))||0,d.top+=parseFloat(f.css(b[0],"borderTopWidth"))||0,d.left+=parseFloat(f.css(b[0],"borderLeftWidth"))||0;return{top:c.top-d.top,left:c.left-d.left}},offsetParent:function(){return this.map(function(){var a=this.offsetParent||c.body;while(a&&!cx.test(a.nodeName)&&f.css(a,"position")==="static")a=a.offsetParent;return a})}}),f.each(["Left","Top"],function(a,c){var d="scroll"+c;f.fn[d]=function(c){var e,g;if(c===b){e=this[0];if(!e)return null;g=cy(e);return g?"pageXOffset"in g?g[a?"pageYOffset":"pageXOffset"]:f.support.boxModel&&g.document.documentElement[d]||g.document.body[d]:e[d]}return this.each(function(){g=cy(this),g?g.scrollTo(a?f(g).scrollLeft():c,a?c:f(g).scrollTop()):this[d]=c})}}),f.each(["Height","Width"],function(a,c){var d=c.toLowerCase();f.fn["inner"+c]=function(){var a=this[0];return a?a.style?parseFloat(f.css(a,d,"padding")):this[d]():null},f.fn["outer"+c]=function(a){var b=this[0];return b?b.style?parseFloat(f.css(b,d,a?"margin":"border")):this[d]():null},f.fn[d]=function(a){var e=this[0];if(!e)return a==null?null:this;if(f.isFunction(a))return this.each(function(b){var c=f(this);c[d](a.call(this,b,c[d]()))});if(f.isWindow(e)){var g=e.document.documentElement["client"+c],h=e.document.body;return e.document.compatMode==="CSS1Compat"&&g||h&&h["client"+c]||g}if(e.nodeType===9)return Math.max(e.documentElement["client"+c],e.body["scroll"+c],e.documentElement["scroll"+c],e.body["offset"+c],e.documentElement["offset"+c]);if(a===b){var i=f.css(e,d),j=parseFloat(i);return f.isNumeric(j)?j:i}return this.css(d,typeof a=="string"?a:a+"px")}}),a.jQuery=a.$=f,typeof define=="function"&&define.amd&&define.amd.jQuery&&define("jquery",[],function(){return f})})(window);
ajax/libs/react-chartjs/0.8.0/react-chartjs.js
AMoo-Miki/cdnjs
(function webpackUniversalModuleDefinition(root, factory) { if(typeof exports === 'object' && typeof module === 'object') module.exports = factory(require("react"), require("react-dom"), require("Chartjs")); else if(typeof define === 'function' && define.amd) define(["react", "react-dom", "Chartjs"], factory); else if(typeof exports === 'object') exports["react-chartjs"] = factory(require("react"), require("react-dom"), require("Chartjs")); else root["react-chartjs"] = factory(root["React"], root["ReactDOM"], root["Chart"]); })(this, function(__WEBPACK_EXTERNAL_MODULE_3__, __WEBPACK_EXTERNAL_MODULE_4__, __WEBPACK_EXTERNAL_MODULE_5__) { return /******/ (function(modules) { // webpackBootstrap /******/ // The module cache /******/ var installedModules = {}; /******/ // The require function /******/ function __webpack_require__(moduleId) { /******/ // Check if module is in cache /******/ if(installedModules[moduleId]) /******/ return installedModules[moduleId].exports; /******/ // Create a new module (and put it into the cache) /******/ var module = installedModules[moduleId] = { /******/ exports: {}, /******/ id: moduleId, /******/ loaded: false /******/ }; /******/ // Execute the module function /******/ modules[moduleId].call(module.exports, module, module.exports, __webpack_require__); /******/ // Flag the module as loaded /******/ module.loaded = true; /******/ // Return the exports of the module /******/ return module.exports; /******/ } /******/ // expose the modules object (__webpack_modules__) /******/ __webpack_require__.m = modules; /******/ // expose the module cache /******/ __webpack_require__.c = installedModules; /******/ // __webpack_public_path__ /******/ __webpack_require__.p = ""; /******/ // Load entry module and return exports /******/ return __webpack_require__(0); /******/ }) /************************************************************************/ /******/ ([ /* 0 */ /***/ function(module, exports, __webpack_require__) { module.exports = { Bar: __webpack_require__(1), Doughnut: __webpack_require__(6), Line: __webpack_require__(7), Pie: __webpack_require__(8), PolarArea: __webpack_require__(9), Radar: __webpack_require__(10), createClass: __webpack_require__(2).createClass }; /***/ }, /* 1 */ /***/ function(module, exports, __webpack_require__) { var vars = __webpack_require__(2); module.exports = vars.createClass('Bar', ['getBarsAtEvent']); /***/ }, /* 2 */ /***/ function(module, exports, __webpack_require__) { var React = __webpack_require__(3); var ReactDOM = __webpack_require__(4); module.exports = { createClass: function(chartType, methodNames, dataKey) { var excludedProps = ['data', 'options', 'redraw']; var classData = { displayName: chartType + 'Chart', getInitialState: function() { return {}; }, render: function() { var _props = { ref: 'canvass' }; for (var name in this.props) { if (this.props.hasOwnProperty(name)) { if (excludedProps.indexOf(name) === -1) { _props[name] = this.props[name]; } } } return React.createElement('canvas', _props); } }; var extras = ['clear', 'stop', 'resize', 'toBase64Image', 'generateLegend', 'update', 'addData', 'removeData']; function extra(type) { classData[type] = function() { return this.state.chart[type].apply(this.state.chart, arguments); }; } classData.componentDidMount = function() { this.initializeChart(this.props); }; classData.componentWillUnmount = function() { var chart = this.state.chart; chart.destroy(); }; classData.componentWillReceiveProps = function(nextProps) { var chart = this.state.chart; if (nextProps.redraw) { chart.destroy(); this.initializeChart(nextProps); } else { dataKey = dataKey || dataKeys[chart.name]; updatePoints(nextProps, chart, dataKey); if (chart.scale) { chart.scale.xLabels = nextProps.data.labels; if (chart.scale.calculateXLabelRotation){ chart.scale.calculateXLabelRotation(); } } chart.update(); } }; classData.initializeChart = function(nextProps) { var Chart = __webpack_require__(5); var el = ReactDOM.findDOMNode(this); var ctx = el.getContext("2d"); var chart = new Chart(ctx)[chartType](nextProps.data, nextProps.options || {}); this.state.chart = chart; }; // return the chartjs instance classData.getChart = function() { return this.state.chart; }; // return the canvass element that contains the chart classData.getCanvass = function() { return this.refs.canvass; }; classData.getCanvas = classData.getCanvass; var i; for (i=0; i<extras.length; i++) { extra(extras[i]); } for (i=0; i<methodNames.length; i++) { extra(methodNames[i]); } return React.createClass(classData); } }; var dataKeys = { 'Line': 'points', 'Radar': 'points', 'Bar': 'bars' }; var updatePoints = function(nextProps, chart, dataKey) { var name = chart.name; if (name === 'PolarArea' || name === 'Pie' || name === 'Doughnut') { nextProps.data.forEach(function(segment, segmentIndex) { if (!chart.segments[segmentIndex]) { chart.addData(segment); } else { Object.keys(segment).forEach(function (key) { chart.segments[segmentIndex][key] = segment[key]; }); } }); while(nextProps.data.length < chart.segments.length) { chart.removeData(); } } else if (name === "Radar") { chart.removeData(); nextProps.data.datasets.forEach(function(set, setIndex) { set.data.forEach(function(val, pointIndex) { if (typeof(chart.datasets[setIndex][dataKey][pointIndex]) == "undefined") { addData(nextProps, chart, setIndex, pointIndex); } else { chart.datasets[setIndex][dataKey][pointIndex].value = val; } }); }); } else { while (chart.scale.xLabels.length > nextProps.data.labels.length) { chart.removeData(); } nextProps.data.datasets.forEach(function(set, setIndex) { set.data.forEach(function(val, pointIndex) { if (typeof(chart.datasets[setIndex][dataKey][pointIndex]) == "undefined") { addData(nextProps, chart, setIndex, pointIndex); } else { chart.datasets[setIndex][dataKey][pointIndex].value = val; } }); }); } }; var addData = function(nextProps, chart, setIndex, pointIndex) { var values = []; nextProps.data.datasets.forEach(function(set) { values.push(set.data[pointIndex]); }); chart.addData(values, nextProps.data.labels[setIndex]); }; /***/ }, /* 3 */ /***/ function(module, exports) { module.exports = __WEBPACK_EXTERNAL_MODULE_3__; /***/ }, /* 4 */ /***/ function(module, exports) { module.exports = __WEBPACK_EXTERNAL_MODULE_4__; /***/ }, /* 5 */ /***/ function(module, exports) { module.exports = __WEBPACK_EXTERNAL_MODULE_5__; /***/ }, /* 6 */ /***/ function(module, exports, __webpack_require__) { var vars = __webpack_require__(2); module.exports = vars.createClass('Doughnut', ['getSegmentsAtEvent']); /***/ }, /* 7 */ /***/ function(module, exports, __webpack_require__) { var vars = __webpack_require__(2); module.exports = vars.createClass('Line', ['getPointsAtEvent']); /***/ }, /* 8 */ /***/ function(module, exports, __webpack_require__) { var vars = __webpack_require__(2); module.exports = vars.createClass('Pie', ['getSegmentsAtEvent']); /***/ }, /* 9 */ /***/ function(module, exports, __webpack_require__) { var vars = __webpack_require__(2); module.exports = vars.createClass('PolarArea', ['getSegmentsAtEvent']); /***/ }, /* 10 */ /***/ function(module, exports, __webpack_require__) { var vars = __webpack_require__(2); module.exports = vars.createClass('Radar', ['getPointsAtEvent']); /***/ } /******/ ]) }); ;
ajax/libs/hyperform/0.8.11/hyperform.cjs.js
dlueth/cdnjs
/*! hyperform.js.org */ 'use strict'; var registry = Object.create(null); /** * run all actions registered for a hook * * Every action gets called with a state object as `this` argument and with the * hook's call arguments as call arguments. * * @return mixed the returned value of the action calls or undefined */ function call_hook(hook) { var result; var call_args = Array.prototype.slice.call(arguments, 1); if (hook in registry) { result = registry[hook].reduce(function (args) { return function (previousResult, currentAction) { var interimResult = currentAction.apply({ state: previousResult, hook: hook }, args); return interimResult !== undefined ? interimResult : previousResult; }; }(call_args), result); } return result; } /** * Filter a value through hooked functions * * Allows for additional parameters: * js> do_filter('foo', null, current_element) */ function do_filter(hook, initial_value) { var result = initial_value; var call_args = Array.prototype.slice.call(arguments, 1); if (hook in registry) { result = registry[hook].reduce(function (previousResult, currentAction) { call_args[0] = previousResult; var interimResult = currentAction.apply({ state: previousResult, hook: hook }, call_args); return interimResult !== undefined ? interimResult : previousResult; }, result); } return result; } /** * remove an action again */ function remove_hook(hook, action) { if (hook in registry) { for (var i = 0; i < registry[hook].length; i++) { if (registry[hook][i] === action) { registry[hook].splice(i, 1); break; } } } } /** * add an action to a hook */ function add_hook(hook, action, position) { if (!(hook in registry)) { registry[hook] = []; } if (position === undefined) { position = registry[hook].length; } registry[hook].splice(position, 0, action); } /** * return either the data of a hook call or the result of action, if the * former is undefined * * @return function a function wrapper around action */ function return_hook_or (hook, action) { return function () { var data = call_hook(hook, Array.prototype.slice.call(arguments)); if (data !== undefined) { return data; } return action.apply(this, arguments); }; } /* the following code is borrowed from the WebComponents project, licensed * under the BSD license. Source: * <https://github.com/webcomponents/webcomponentsjs/blob/5283db1459fa2323e5bfc8b9b5cc1753ed85e3d0/src/WebComponents/dom.js#L53-L78> */ // defaultPrevented is broken in IE. // https://connect.microsoft.com/IE/feedback/details/790389/event-defaultprevented-returns-false-after-preventdefault-was-called var workingDefaultPrevented = function () { var e = document.createEvent('Event'); e.initEvent('foo', true, true); e.preventDefault(); return e.defaultPrevented; }(); if (!workingDefaultPrevented) { (function () { var origPreventDefault = window.Event.prototype.preventDefault; window.Event.prototype.preventDefault = function () { if (!this.cancelable) { return; } origPreventDefault.call(this); Object.defineProperty(this, 'defaultPrevented', { get: function get() { return true; }, configurable: true }); }; })(); } /* end of borrowed code */ function trigger_event (element, event) { var _ref = arguments.length > 2 && arguments[2] !== undefined ? arguments[2] : {}; var _ref$bubbles = _ref.bubbles; var bubbles = _ref$bubbles === undefined ? true : _ref$bubbles; var _ref$cancelable = _ref.cancelable; var cancelable = _ref$cancelable === undefined ? false : _ref$cancelable; var payload = arguments.length > 3 && arguments[3] !== undefined ? arguments[3] : {}; if (!(event instanceof window.Event)) { var _event = document.createEvent('Event'); _event.initEvent(event, bubbles, cancelable); event = _event; } for (var key in payload) { if (payload.hasOwnProperty(key)) { event[key] = payload[key]; } } element.dispatchEvent(event); return event; } /* and datetime-local? Spec says “Nah!” */ var dates = ['datetime', 'date', 'month', 'week', 'time']; var plain_numbers = ['number', 'range']; /* everything that returns something meaningful for valueAsNumber and * can have the step attribute */ var numbers = dates.concat(plain_numbers, 'datetime-local'); /* the spec says to only check those for syntax in validity.typeMismatch. * ¯\_(ツ)_/¯ */ var type_checked = ['email', 'url']; /* check these for validity.badInput */ var input_checked = ['email', 'date', 'month', 'week', 'time', 'datetime', 'datetime-local', 'number', 'range', 'color']; var text_types = ['text', 'search', 'tel', 'password'].concat(type_checked); /* input element types, that are candidates for the validation API. * Missing from this set are: button, hidden, menu (from <button>), reset and * the types for non-<input> elements. */ var validation_candidates = ['checkbox', 'color', 'file', 'image', 'radio', 'submit'].concat(numbers, text_types); /* all known types of <input> */ var inputs = ['button', 'hidden', 'reset'].concat(validation_candidates); /* apparently <select> and <textarea> have types of their own */ var non_inputs = ['select-one', 'select-multiple', 'textarea']; /** * mark an object with a '__hyperform=true' property * * We use this to distinguish our properties from the native ones. Usage: * js> mark(obj); * js> assert(obj.__hyperform === true) */ function mark (obj) { if (['object', 'function'].indexOf(typeof obj) > -1) { delete obj.__hyperform; Object.defineProperty(obj, '__hyperform', { configurable: true, enumerable: false, value: true }); } return obj; } /** * the internal storage for messages */ var store = new WeakMap(); /* jshint -W053 */ var message_store = { set: function set(element, message) { var is_custom = arguments.length > 2 && arguments[2] !== undefined ? arguments[2] : false; if (element instanceof window.HTMLFieldSetElement) { var wrapped_form = get_wrapper(element); if (wrapped_form && !wrapped_form.settings.extend_fieldset) { /* make this a no-op for <fieldset> in strict mode */ return message_store; } } if (typeof message === 'string') { message = new String(message); } if (is_custom) { message.is_custom = true; } mark(message); store.set(element, message); /* allow the :invalid selector to match */ if ('_original_setCustomValidity' in element) { element._original_setCustomValidity(message.toString()); } return message_store; }, get: function get(element) { var message = store.get(element); if (message === undefined && '_original_validationMessage' in element) { /* get the browser's validation message, if we have none. Maybe it * knows more than we. */ message = new String(element._original_validationMessage); } return message ? message : new String(''); }, delete: function _delete(element) { if ('_original_setCustomValidity' in element) { element._original_setCustomValidity(''); } return store.delete(element); } }; /** * counter that will be incremented with every call * * Will enforce uniqueness, as long as no more than 1 hyperform scripts * are loaded. (In that case we still have the "random" part below.) */ var uid = 0; /** * generate a random ID * * @see https://gist.github.com/gordonbrander/2230317 */ function generate_id () { var prefix = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : 'hf_'; return prefix + uid++ + Math.random().toString(36).substr(2); } var warnings_cache = new WeakMap(); var DefaultRenderer = { /** * called when a warning should become visible */ attach_warning: function attach_warning(warning, element) { /* should also work, if element is last, * http://stackoverflow.com/a/4793630/113195 */ element.parentNode.insertBefore(warning, element.nextSibling); }, /** * called when a warning should vanish */ detach_warning: function detach_warning(warning, element) { warning.parentNode.removeChild(warning); }, /** * called when feedback to an element's state should be handled * * i.e., showing and hiding warnings */ show_warning: function show_warning(element) { var sub_radio = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : false; var msg = message_store.get(element).toString(); var warning = warnings_cache.get(element); if (msg) { if (!warning) { var wrapper = get_wrapper(element); warning = document.createElement('div'); warning.className = wrapper && wrapper.settings.classes.warning || 'hf-warning'; warning.id = generate_id(); warning.setAttribute('aria-live', 'polite'); warnings_cache.set(element, warning); } element.setAttribute('aria-errormessage', warning.id); warning.textContent = msg; Renderer.attach_warning(warning, element); } else if (warning && warning.parentNode) { element.removeAttribute('aria-errormessage'); Renderer.detach_warning(warning, element); } if (!sub_radio && element.type === 'radio' && element.form) { /* render warnings for all other same-name radios, too */ Array.prototype.filter.call(document.getElementsByName(element.name), function (radio) { return radio.name === element.name && radio.form === element.form; }).map(function (radio) { return Renderer.show_warning(radio, 'sub_radio'); }); } } }; var Renderer = { attach_warning: DefaultRenderer.attach_warning, detach_warning: DefaultRenderer.detach_warning, show_warning: DefaultRenderer.show_warning, set: function set(renderer, action) { if (!action) { action = DefaultRenderer[renderer]; } Renderer[renderer] = action; } }; /** * check element's validity and report an error back to the user */ function reportValidity(element) { /* if this is a <form>, report validity of all child inputs */ if (element instanceof window.HTMLFormElement) { return Array.prototype.map.call(element.elements, reportValidity).every(function (b) { return b; }); } /* we copy checkValidity() here, b/c we have to check if the "invalid" * event was canceled. */ var valid = ValidityState(element).valid; var event; if (valid) { var wrapped_form = get_wrapper(element); if (wrapped_form && wrapped_form.settings.valid_event) { event = trigger_event(element, 'valid', { cancelable: true }); } } else { event = trigger_event(element, 'invalid', { cancelable: true }); } if (!event || !event.defaultPrevented) { Renderer.show_warning(element); } return valid; } /** * submit a form, because `element` triggered it * * This method also dispatches a submit event on the form prior to the * submission. The event contains the trigger element as `submittedVia`. * * If the element is a button with a name, the name=value pair will be added * to the submitted data. */ function submit_form_via(element) { /* apparently, the submit event is not triggered in most browsers on * the submit() method, so we do it manually here to model a natural * submit as closely as possible. * Now to the fun fact: If you trigger a submit event from a form, what * do you think should happen? * 1) the form will be automagically submitted by the browser, or * 2) nothing. * And as you already suspected, the correct answer is: both! Firefox * opts for 1), Chrome for 2). Yay! */ var event_got_cancelled; var do_cancel = function do_cancel(e) { event_got_cancelled = e.defaultPrevented; /* we prevent the default ourselves in this (hopefully) last event * handler to keep Firefox from prematurely submitting the form. */ e.preventDefault(); }; element.form.addEventListener('submit', do_cancel); trigger_event(element.form, 'submit', { cancelable: true }, { submittedVia: element }); element.form.removeEventListener('submit', do_cancel); if (!event_got_cancelled) { add_submit_field(element); window.HTMLFormElement.prototype.submit.call(element.form); window.setTimeout(function () { return remove_submit_field(element); }); } } /** * if a submit button was clicked, add its name=value by means of a type=hidden * input field */ function add_submit_field(button) { if (['image', 'submit'].indexOf(button.type) > -1 && button.name) { var wrapper = get_wrapper(button.form) || {}; var submit_helper = wrapper.submit_helper; if (submit_helper) { if (submit_helper.parentNode) { submit_helper.parentNode.removeChild(submit_helper); } } else { submit_helper = document.createElement('input'); submit_helper.type = 'hidden'; wrapper.submit_helper = submit_helper; } submit_helper.name = button.name; submit_helper.value = button.value; button.form.appendChild(submit_helper); } } /** * remove a possible helper input, that was added by `add_submit_field` */ function remove_submit_field(button) { if (['image', 'submit'].indexOf(button.type) > -1 && button.name) { var wrapper = get_wrapper(button.form) || {}; var submit_helper = wrapper.submit_helper; if (submit_helper && submit_helper.parentNode) { submit_helper.parentNode.removeChild(submit_helper); } } } /** * check a form's validity and submit it * * The method triggers a cancellable `validate` event on the form. If the * event is cancelled, form submission will be aborted, too. * * If the form is found to contain invalid fields, focus the first field. */ function check(event) { /* trigger a "validate" event on the form to be submitted */ var val_event = trigger_event(event.target.form, 'validate', { cancelable: true }); if (val_event.defaultPrevented) { /* skip the whole submit thing, if the validation is canceled. A user * can still call form.submit() afterwards. */ return; } var valid = true; var first_invalid; Array.prototype.map.call(event.target.form.elements, function (element) { if (!reportValidity(element)) { valid = false; if (!first_invalid && 'focus' in element) { first_invalid = element; } } }); if (valid) { submit_form_via(event.target); } else if (first_invalid) { /* focus the first invalid element, if validation went south */ first_invalid.focus(); } } /** * test if node is a submit button */ function is_submit_button(node) { return ( /* must be an input or button element... */ (node.nodeName === 'INPUT' || node.nodeName === 'BUTTON') && ( /* ...and have a submitting type */ node.type === 'image' || node.type === 'submit') ); } /** * test, if the click event would trigger a submit */ function is_submitting_click(event) { return ( /* prevented default: won't trigger a submit */ !event.defaultPrevented && ( /* left button or middle button (submits in Chrome) */ !('button' in event) || event.button < 2) && /* must be a submit button... */ is_submit_button(event.target) && /* the button needs a form, that's going to be submitted */ event.target.form && /* again, if the form should not be validated, we're out of the game */ !event.target.form.hasAttribute('novalidate') ); } /** * test, if the keypress event would trigger a submit */ function is_submitting_keypress(event) { return ( /* prevented default: won't trigger a submit */ !event.defaultPrevented && ( /* ...and <Enter> was pressed... */ event.keyCode === 13 && /* ...on an <input> that is... */ event.target.nodeName === 'INPUT' && /* ...a standard text input field (not checkbox, ...) */ text_types.indexOf(event.target.type) > -1 || /* or <Enter> or <Space> was pressed... */ (event.keyCode === 13 || event.keyCode === 32) && /* ...on a submit button */ is_submit_button(event.target)) && /* there's a form... */ event.target.form && /* ...and the form allows validation */ !event.target.form.hasAttribute('novalidate') ); } /** * catch explicit submission by click on a button */ function click_handler(event) { if (is_submitting_click(event)) { event.preventDefault(); if (is_submit_button(event.target) && event.target.hasAttribute('formnovalidate')) { /* if validation should be ignored, we're not interested in any checks */ submit_form_via(event.target); } else { check(event); } } } /** * catch explicit submission by click on a button, but circumvent validation */ function ignored_click_handler(event) { if (is_submitting_click(event)) { event.preventDefault(); submit_form_via(event.target); } } /** * catch implicit submission by pressing <Enter> in some situations */ function keypress_handler(event) { if (is_submitting_keypress(event)) { var wrapper = get_wrapper(event.target.form) || { settings: {} }; if (wrapper.settings.prevent_implicit_submit) { /* user doesn't want an implicit submit. Cancel here. */ event.preventDefault(); return; } /* check, that there is no submit button in the form. Otherwise * that should be clicked. */ var el = event.target.form.elements.length; var submit; for (var i = 0; i < el; i++) { if (['image', 'submit'].indexOf(event.target.form.elements[i].type) > -1) { submit = event.target.form.elements[i]; break; } } event.preventDefault(); if (submit) { submit.click(); } else { check(event); } } } /** * catch implicit submission by pressing <Enter> in some situations, but circumvent validation */ function ignored_keypress_handler(event) { if (is_submitting_keypress(event)) { /* check, that there is no submit button in the form. Otherwise * that should be clicked. */ var el = event.target.form.elements.length; var submit; for (var i = 0; i < el; i++) { if (['image', 'submit'].indexOf(event.target.form.elements[i].type) > -1) { submit = event.target.form.elements[i]; break; } } event.preventDefault(); if (submit) { submit.click(); } else { submit_form_via(event.target); } } } /** * catch all relevant events _prior_ to a form being submitted * * @param bool ignore bypass validation, when an attempt to submit the * form is detected. */ function catch_submit(listening_node) { var ignore = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : false; if (ignore) { listening_node.addEventListener('click', ignored_click_handler); listening_node.addEventListener('keypress', ignored_keypress_handler); } else { listening_node.addEventListener('click', click_handler); listening_node.addEventListener('keypress', keypress_handler); } } /** * decommission the event listeners from catch_submit() again */ function uncatch_submit(listening_node) { listening_node.removeEventListener('click', ignored_click_handler); listening_node.removeEventListener('keypress', ignored_keypress_handler); listening_node.removeEventListener('click', click_handler); listening_node.removeEventListener('keypress', keypress_handler); } /** * remove `property` from element and restore _original_property, if present */ function uninstall_property (element, property) { delete element[property]; var original_descriptor = Object.getOwnPropertyDescriptor(element, '_original_' + property); if (original_descriptor) { Object.defineProperty(element, property, original_descriptor); } } /** * add `property` to an element * * js> installer(element, 'foo', { value: 'bar' }); * js> assert(element.foo === 'bar'); */ function install_property (element, property, descriptor) { descriptor.configurable = true; descriptor.enumerable = true; if ('value' in descriptor) { descriptor.writable = true; } var original_descriptor = Object.getOwnPropertyDescriptor(element, property); if (original_descriptor) { if (original_descriptor.configurable === false) { var wrapper = get_wrapper(element); if (wrapper && wrapper.settings.debug) { /* global console */ console.log('[hyperform] cannot install custom property ' + property); } return false; } /* we already installed that property... */ if (original_descriptor.get && original_descriptor.get.__hyperform || original_descriptor.value && original_descriptor.value.__hyperform) { return; } /* publish existing property under new name, if it's not from us */ Object.defineProperty(element, '_original_' + property, original_descriptor); } delete element[property]; Object.defineProperty(element, property, descriptor); return true; } function is_field (element) { return element instanceof window.HTMLButtonElement || element instanceof window.HTMLInputElement || element instanceof window.HTMLSelectElement || element instanceof window.HTMLTextAreaElement || element instanceof window.HTMLFieldSetElement || element === window.HTMLButtonElement.prototype || element === window.HTMLInputElement.prototype || element === window.HTMLSelectElement.prototype || element === window.HTMLTextAreaElement.prototype || element === window.HTMLFieldSetElement.prototype; } /** * set a custom validity message or delete it with an empty string */ function setCustomValidity(element, msg) { message_store.set(element, msg, true); } function sprintf (str) { for (var _len = arguments.length, args = Array(_len > 1 ? _len - 1 : 0), _key = 1; _key < _len; _key++) { args[_key - 1] = arguments[_key]; } var args_length = args.length; var global_index = 0; return str.replace(/%([0-9]+\$)?([sl])/g, function (match, position, type) { var local_index = global_index; if (position) { local_index = Number(position.replace(/\$$/, '')) - 1; } global_index += 1; var arg = ''; if (args_length > local_index) { arg = args[local_index]; } if (arg instanceof Date || typeof arg === 'number' || arg instanceof Number) { /* try getting a localized representation of dates and numbers, if the * browser supports this */ if (type === 'l') { arg = (arg.toLocaleString || arg.toString).call(arg); } else { arg = arg.toString(); } } return arg; }); } /* For a given date, get the ISO week number * * Source: http://stackoverflow.com/a/6117889/113195 * * Based on information at: * * http://www.merlyn.demon.co.uk/weekcalc.htm#WNR * * Algorithm is to find nearest thursday, it's year * is the year of the week number. Then get weeks * between that date and the first day of that year. * * Note that dates in one year can be weeks of previous * or next year, overlap is up to 3 days. * * e.g. 2014/12/29 is Monday in week 1 of 2015 * 2012/1/1 is Sunday in week 52 of 2011 */ function get_week_of_year (d) { /* Copy date so don't modify original */ d = new Date(+d); d.setUTCHours(0, 0, 0); /* Set to nearest Thursday: current date + 4 - current day number * Make Sunday's day number 7 */ d.setUTCDate(d.getUTCDate() + 4 - (d.getUTCDay() || 7)); /* Get first day of year */ var yearStart = new Date(d.getUTCFullYear(), 0, 1); /* Calculate full weeks to nearest Thursday */ var weekNo = Math.ceil(((d - yearStart) / 86400000 + 1) / 7); /* Return array of year and week number */ return [d.getUTCFullYear(), weekNo]; } function pad(num) { var size = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : 2; var s = num + ''; while (s.length < size) { s = '0' + s; } return s; } /** * calculate a string from a date according to HTML5 */ function date_to_string(date, element_type) { if (!(date instanceof Date)) { return null; } switch (element_type) { case 'datetime': return date_to_string(date, 'date') + 'T' + date_to_string(date, 'time'); case 'datetime-local': return sprintf('%s-%s-%sT%s:%s:%s.%s', date.getFullYear(), pad(date.getMonth() + 1), pad(date.getDate()), pad(date.getHours()), pad(date.getMinutes()), pad(date.getSeconds()), pad(date.getMilliseconds(), 3)).replace(/(:00)?\.000$/, ''); case 'date': return sprintf('%s-%s-%s', date.getUTCFullYear(), pad(date.getUTCMonth() + 1), pad(date.getUTCDate())); case 'month': return sprintf('%s-%s', date.getUTCFullYear(), pad(date.getUTCMonth() + 1)); case 'week': var params = get_week_of_year(date); return sprintf.call(null, '%s-W%s', params[0], pad(params[1])); case 'time': return sprintf('%s:%s:%s.%s', pad(date.getUTCHours()), pad(date.getUTCMinutes()), pad(date.getUTCSeconds()), pad(date.getUTCMilliseconds(), 3)).replace(/(:00)?\.000$/, ''); } return null; } /** * return a new Date() representing the ISO date for a week number * * @see http://stackoverflow.com/a/16591175/113195 */ function get_date_from_week (week, year) { var date = new Date(Date.UTC(year, 0, 1 + (week - 1) * 7)); if (date.getUTCDay() <= 4 /* thursday */) { date.setUTCDate(date.getUTCDate() - date.getUTCDay() + 1); } else { date.setUTCDate(date.getUTCDate() + 8 - date.getUTCDay()); } return date; } /** * calculate a date from a string according to HTML5 */ function string_to_date (string, element_type) { var date = new Date(0); var ms; switch (element_type) { case 'datetime': if (!/^([0-9]{4,})-([0-9]{2})-([0-9]{2})T([01][0-9]|2[0-3]):([0-5][0-9])(?::([0-5][0-9])(?:\.([0-9]{1,3}))?)?$/.test(string)) { return null; } ms = RegExp.$7 || '000'; while (ms.length < 3) { ms += '0'; } date.setUTCFullYear(Number(RegExp.$1)); date.setUTCMonth(Number(RegExp.$2) - 1, Number(RegExp.$3)); date.setUTCHours(Number(RegExp.$4), Number(RegExp.$5), Number(RegExp.$6 || 0), Number(ms)); return date; case 'date': if (!/^([0-9]{4,})-([0-9]{2})-([0-9]{2})$/.test(string)) { return null; } date.setUTCFullYear(Number(RegExp.$1)); date.setUTCMonth(Number(RegExp.$2) - 1, Number(RegExp.$3)); return date; case 'month': if (!/^([0-9]{4,})-([0-9]{2})$/.test(string)) { return null; } date.setUTCFullYear(Number(RegExp.$1)); date.setUTCMonth(Number(RegExp.$2) - 1, 1); return date; case 'week': if (!/^([0-9]{4,})-W(0[1-9]|[1234][0-9]|5[0-3])$/.test(string)) { return null; } return get_date_from_week(Number(RegExp.$2), Number(RegExp.$1)); case 'time': if (!/^([01][0-9]|2[0-3]):([0-5][0-9])(?::([0-5][0-9])(?:\.([0-9]{1,3}))?)?$/.test(string)) { return null; } ms = RegExp.$4 || '000'; while (ms.length < 3) { ms += '0'; } date.setUTCHours(Number(RegExp.$1), Number(RegExp.$2), Number(RegExp.$3 || 0), Number(ms)); return date; } return null; } /** * calculate a date from a string according to HTML5 */ function string_to_number (string, element_type) { var rval = string_to_date(string, element_type); if (rval !== null) { return +rval; } /* not parseFloat, because we want NaN for invalid values like "1.2xxy" */ return Number(string); } /** * get the element's type in a backwards-compatible way */ function get_type (element) { if (element instanceof window.HTMLTextAreaElement) { return 'textarea'; } else if (element instanceof window.HTMLSelectElement) { return element.hasAttribute('multiple') ? 'select-multiple' : 'select-one'; } else if (element instanceof window.HTMLButtonElement) { return (element.getAttribute('type') || 'submit').toLowerCase(); } else if (element instanceof window.HTMLInputElement) { var attr = (element.getAttribute('type') || '').toLowerCase(); if (attr && inputs.indexOf(attr) > -1) { return attr; } else { /* perhaps the DOM has in-depth knowledge. Take that before returning * 'text'. */ return element.type || 'text'; } } return ''; } /** * the following validation messages are from Firefox source, * http://mxr.mozilla.org/mozilla-central/source/dom/locales/en-US/chrome/dom/dom.properties * released under MPL license, http://mozilla.org/MPL/2.0/. */ var catalog = { en: { TextTooLong: 'Please shorten this text to %l characters or less (you are currently using %l characters).', ValueMissing: 'Please fill out this field.', CheckboxMissing: 'Please check this box if you want to proceed.', RadioMissing: 'Please select one of these options.', FileMissing: 'Please select a file.', SelectMissing: 'Please select an item in the list.', InvalidEmail: 'Please enter an email address.', InvalidURL: 'Please enter a URL.', PatternMismatch: 'Please match the requested format.', PatternMismatchWithTitle: 'Please match the requested format: %l.', NumberRangeOverflow: 'Please select a value that is no more than %l.', DateRangeOverflow: 'Please select a value that is no later than %l.', TimeRangeOverflow: 'Please select a value that is no later than %l.', NumberRangeUnderflow: 'Please select a value that is no less than %l.', DateRangeUnderflow: 'Please select a value that is no earlier than %l.', TimeRangeUnderflow: 'Please select a value that is no earlier than %l.', StepMismatch: 'Please select a valid value. The two nearest valid values are %l and %l.', StepMismatchOneValue: 'Please select a valid value. The nearest valid value is %l.', BadInputNumber: 'Please enter a number.' } }; var language = 'en'; function set_language(newlang) { language = newlang; } function add_translation(lang, new_catalog) { if (!(lang in catalog)) { catalog[lang] = {}; } for (var key in new_catalog) { if (new_catalog.hasOwnProperty(key)) { catalog[lang][key] = new_catalog[key]; } } } function _ (s) { if (language in catalog && s in catalog[language]) { return catalog[language][s]; } else if (s in catalog.en) { return catalog.en[s]; } return s; } var default_step = { 'datetime-local': 60, datetime: 60, time: 60 }; var step_scale_factor = { 'datetime-local': 1000, datetime: 1000, date: 86400000, week: 604800000, time: 1000 }; var default_step_base = { week: -259200000 }; var default_min = { range: 0 }; var default_max = { range: 100 }; /** * get previous and next valid values for a stepped input element */ function get_next_valid (element) { var n = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : 1; var type = get_type(element); var aMin = element.getAttribute('min'); var min = default_min[type] || NaN; if (aMin) { var pMin = string_to_number(aMin, type); if (!isNaN(pMin)) { min = pMin; } } var aMax = element.getAttribute('max'); var max = default_max[type] || NaN; if (aMax) { var pMax = string_to_number(aMax, type); if (!isNaN(pMax)) { max = pMax; } } var aStep = element.getAttribute('step'); var step = default_step[type] || 1; if (aStep && aStep.toLowerCase() === 'any') { /* quick return: we cannot calculate prev and next */ return [_('any value'), _('any value')]; } else if (aStep) { var pStep = string_to_number(aStep, type); if (!isNaN(pStep)) { step = pStep; } } var default_value = string_to_number(element.getAttribute('value'), type); var value = string_to_number(element.value || element.getAttribute('value'), type); if (isNaN(value)) { /* quick return: we cannot calculate without a solid base */ return [_('any valid value'), _('any valid value')]; } var step_base = !isNaN(min) ? min : !isNaN(default_value) ? default_value : default_step_base[type] || 0; var scale = step_scale_factor[type] || 1; var prev = step_base + Math.floor((value - step_base) / (step * scale)) * (step * scale) * n; var next = step_base + (Math.floor((value - step_base) / (step * scale)) + 1) * (step * scale) * n; if (prev < min) { prev = null; } else if (prev > max) { prev = max; } if (next > max) { next = null; } else if (next < min) { next = min; } /* convert to date objects, if appropriate */ if (dates.indexOf(type) > -1) { prev = date_to_string(new Date(prev), type); next = date_to_string(new Date(next), type); } return [prev, next]; } /** * implement the valueAsDate functionality * * @see https://html.spec.whatwg.org/multipage/forms.html#dom-input-valueasdate */ function valueAsDate(element) { var value = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : undefined; var type = get_type(element); if (dates.indexOf(type) > -1) { if (value !== undefined) { /* setter: value must be null or a Date() */ if (value === null) { element.value = ''; } else if (value instanceof Date) { if (isNaN(value.getTime())) { element.value = ''; } else { element.value = date_to_string(value, type); } } else { throw new window.DOMException('valueAsDate setter encountered invalid value', 'TypeError'); } return; } var value_date = string_to_date(element.value, type); return value_date instanceof Date ? value_date : null; } else if (value !== undefined) { /* trying to set a date on a not-date input fails */ throw new window.DOMException('valueAsDate setter cannot set date on this element', 'InvalidStateError'); } return null; } /** * implement the valueAsNumber functionality * * @see https://html.spec.whatwg.org/multipage/forms.html#dom-input-valueasnumber */ function valueAsNumber(element) { var value = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : undefined; var type = get_type(element); if (numbers.indexOf(type) > -1) { if (type === 'range' && element.hasAttribute('multiple')) { /* @see https://html.spec.whatwg.org/multipage/forms.html#do-not-apply */ return NaN; } if (value !== undefined) { /* setter: value must be NaN or a finite number */ if (isNaN(value)) { element.value = ''; } else if (typeof value === 'number' && window.isFinite(value)) { try { /* try setting as a date, but... */ valueAsDate(element, new Date(value)); } catch (e) { /* ... when valueAsDate is not responsible, ... */ if (!(e instanceof window.DOMException)) { throw e; } /* ... set it via Number.toString(). */ element.value = value.toString(); } } else { throw new window.DOMException('valueAsNumber setter encountered invalid value', 'TypeError'); } return; } return string_to_number(element.value, type); } else if (value !== undefined) { /* trying to set a number on a not-number input fails */ throw new window.DOMException('valueAsNumber setter cannot set number on this element', 'InvalidStateError'); } return NaN; } /** * */ function stepDown(element) { var n = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : 1; if (numbers.indexOf(get_type(element)) === -1) { throw new window.DOMException('stepDown encountered invalid type', 'InvalidStateError'); } if ((element.getAttribute('step') || '').toLowerCase() === 'any') { throw new window.DOMException('stepDown encountered step "any"', 'InvalidStateError'); } var prev = get_next_valid(element, n)[0]; if (prev !== null) { valueAsNumber(element, prev); } } /** * */ function stepUp(element) { var n = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : 1; if (numbers.indexOf(get_type(element)) === -1) { throw new window.DOMException('stepUp encountered invalid type', 'InvalidStateError'); } if ((element.getAttribute('step') || '').toLowerCase() === 'any') { throw new window.DOMException('stepUp encountered step "any"', 'InvalidStateError'); } var next = get_next_valid(element, n)[1]; if (next !== null) { valueAsNumber(element, next); } } /** * get the validation message for an element, empty string, if the element * satisfies all constraints. */ function validationMessage(element) { var msg = message_store.get(element); if (!msg) { return ''; } /* make it a primitive again, since message_store returns String(). */ return msg.toString(); } /** * check, if an element will be subject to HTML5 validation at all */ function willValidate(element) { return is_validation_candidate(element); } var gA = function gA(prop) { return function () { return do_filter('attr_get_' + prop, this.getAttribute(prop), this); }; }; var sA = function sA(prop) { return function (value) { this.setAttribute(prop, do_filter('attr_set_' + prop, value, this)); }; }; var gAb = function gAb(prop) { return function () { return do_filter('attr_get_' + prop, this.hasAttribute(prop), this); }; }; var sAb = function sAb(prop) { return function (value) { if (do_filter('attr_set_' + prop, value, this)) { this.setAttribute(prop, prop); } else { this.removeAttribute(prop); } }; }; var gAn = function gAn(prop) { return function () { return do_filter('attr_get_' + prop, Math.max(0, Number(this.getAttribute(prop))), this); }; }; var sAn = function sAn(prop) { return function (value) { value = do_filter('attr_set_' + prop, value, this); if (/^[0-9]+$/.test(value)) { this.setAttribute(prop, value); } }; }; function install_properties(element) { var _arr = ['accept', 'max', 'min', 'pattern', 'placeholder', 'step']; for (var _i = 0; _i < _arr.length; _i++) { var prop = _arr[_i]; install_property(element, prop, { get: gA(prop), set: sA(prop) }); } var _arr2 = ['multiple', 'required', 'readOnly']; for (var _i2 = 0; _i2 < _arr2.length; _i2++) { var _prop = _arr2[_i2]; install_property(element, _prop, { get: gAb(_prop.toLowerCase()), set: sAb(_prop.toLowerCase()) }); } var _arr3 = ['minLength', 'maxLength']; for (var _i3 = 0; _i3 < _arr3.length; _i3++) { var _prop2 = _arr3[_i3]; install_property(element, _prop2, { get: gAn(_prop2.toLowerCase()), set: sAn(_prop2.toLowerCase()) }); } } function uninstall_properties(element) { var _arr4 = ['accept', 'max', 'min', 'pattern', 'placeholder', 'step', 'multiple', 'required', 'readOnly', 'minLength', 'maxLength']; for (var _i4 = 0; _i4 < _arr4.length; _i4++) { var prop = _arr4[_i4]; uninstall_property(element, prop); } } var polyfills = { checkValidity: { value: mark(function () { return checkValidity(this); }) }, reportValidity: { value: mark(function () { return reportValidity(this); }) }, setCustomValidity: { value: mark(function (msg) { return setCustomValidity(this, msg); }) }, stepDown: { value: mark(function () { var n = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : 1; return stepDown(this, n); }) }, stepUp: { value: mark(function () { var n = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : 1; return stepUp(this, n); }) }, validationMessage: { get: mark(function () { return validationMessage(this); }) }, validity: { get: mark(function () { return ValidityState(this); }) }, valueAsDate: { get: mark(function () { return valueAsDate(this); }), set: mark(function (value) { valueAsDate(this, value); }) }, valueAsNumber: { get: mark(function () { return valueAsNumber(this); }), set: mark(function (value) { valueAsNumber(this, value); }) }, willValidate: { get: mark(function () { return willValidate(this); }) } }; function polyfill (element) { if (is_field(element)) { for (var prop in polyfills) { install_property(element, prop, polyfills[prop]); } install_properties(element); } else if (element instanceof window.HTMLFormElement || element === window.HTMLFormElement.prototype) { install_property(element, 'checkValidity', polyfills.checkValidity); install_property(element, 'reportValidity', polyfills.reportValidity); } } function polyunfill (element) { if (is_field(element)) { uninstall_property(element, 'checkValidity'); uninstall_property(element, 'reportValidity'); uninstall_property(element, 'setCustomValidity'); uninstall_property(element, 'stepDown'); uninstall_property(element, 'stepUp'); uninstall_property(element, 'validationMessage'); uninstall_property(element, 'validity'); uninstall_property(element, 'valueAsDate'); uninstall_property(element, 'valueAsNumber'); uninstall_property(element, 'willValidate'); uninstall_properties(element); } else if (element instanceof window.HTMLFormElement) { uninstall_property(element, 'checkValidity'); uninstall_property(element, 'reportValidity'); } } var instances = new WeakMap(); /** * wrap <form>s, window or document, that get treated with the global * hyperform() */ function Wrapper(form, settings) { /* do not allow more than one instance per form. Otherwise we'd end * up with double event handlers, polyfills re-applied, ... */ var existing = instances.get(form); if (existing) { existing.settings = settings; return existing; } this.form = form; this.settings = settings; this.revalidator = this.revalidate.bind(this); instances.set(form, this); catch_submit(form, settings.revalidate === 'never'); if (form === window || form instanceof window.HTMLDocument) { /* install on the prototypes, when called for the whole document */ this.install([window.HTMLButtonElement.prototype, window.HTMLInputElement.prototype, window.HTMLSelectElement.prototype, window.HTMLTextAreaElement.prototype, window.HTMLFieldSetElement.prototype]); polyfill(window.HTMLFormElement); } else if (form instanceof window.HTMLFormElement || form instanceof window.HTMLFieldSetElement) { this.install(form.elements); if (form instanceof window.HTMLFormElement) { polyfill(form); } } if (settings.revalidate === 'oninput' || settings.revalidate === 'hybrid') { /* in a perfect world we'd just bind to "input", but support here is * abysmal: http://caniuse.com/#feat=input-event */ form.addEventListener('keyup', this.revalidator); form.addEventListener('change', this.revalidator); } if (settings.revalidate === 'onblur' || settings.revalidate === 'hybrid') { /* useCapture=true, because `blur` doesn't bubble. See * https://developer.mozilla.org/en-US/docs/Web/Events/blur#Event_delegation * for a discussion */ form.addEventListener('blur', this.revalidator, true); } } Wrapper.prototype = { destroy: function destroy() { uncatch_submit(this.form); instances.delete(this.form); this.form.removeEventListener('keyup', this.revalidator); this.form.removeEventListener('change', this.revalidator); this.form.removeEventListener('blur', this.revalidator, true); if (this.form === window || this.form instanceof window.HTMLDocument) { this.uninstall([window.HTMLButtonElement.prototype, window.HTMLInputElement.prototype, window.HTMLSelectElement.prototype, window.HTMLTextAreaElement.prototype, window.HTMLFieldSetElement.prototype]); polyunfill(window.HTMLFormElement); } else if (this.form instanceof window.HTMLFormElement || this.form instanceof window.HTMLFieldSetElement) { this.uninstall(this.form.elements); if (this.form instanceof window.HTMLFormElement) { polyunfill(this.form); } } }, /** * revalidate an input element */ revalidate: function revalidate(event) { if (event.target instanceof window.HTMLButtonElement || event.target instanceof window.HTMLTextAreaElement || event.target instanceof window.HTMLSelectElement || event.target instanceof window.HTMLInputElement) { if (this.settings.revalidate === 'hybrid') { /* "hybrid" somewhat simulates what browsers do. See for example * Firefox's :-moz-ui-invalid pseudo-class: * https://developer.mozilla.org/en-US/docs/Web/CSS/:-moz-ui-invalid */ if (event.type === 'blur' && event.target.value !== event.target.defaultValue || ValidityState(event.target).valid) { /* on blur, update the report when the value has changed from the * default or when the element is valid (possibly removing a still * standing invalidity report). */ reportValidity(event.target); } else if (event.type === 'keyup' || event.type === 'change') { if (ValidityState(event.target).valid) { // report instantly, when an element becomes valid, // postpone report to blur event, when an element is invalid reportValidity(event.target); } } } else { reportValidity(event.target); } } }, /** * install the polyfills on each given element * * If you add elements dynamically, you have to call install() on them * yourself: * * js> var form = hyperform(document.forms[0]); * js> document.forms[0].appendChild(input); * js> form.install(input); * * You can skip this, if you called hyperform on window or document. */ install: function install(els) { if (els instanceof window.Element) { els = [els]; } var els_length = els.length; for (var i = 0; i < els_length; i++) { polyfill(els[i]); } }, uninstall: function uninstall(els) { if (els instanceof window.Element) { els = [els]; } var els_length = els.length; for (var i = 0; i < els_length; i++) { polyunfill(els[i]); } } }; /** * try to get the appropriate wrapper for a specific element by looking up * its parent chain * * @return Wrapper | undefined */ function get_wrapper(element) { var wrapped; if (element.form) { /* try a shortcut with the element's <form> */ wrapped = instances.get(element.form); } /* walk up the parent nodes until document (including) */ while (!wrapped && element) { wrapped = instances.get(element); element = element.parentNode; } if (!wrapped) { /* try the global instance, if exists. This may also be undefined. */ wrapped = instances.get(window); } return wrapped; } /** * check if an element is a candidate for constraint validation * * @see https://html.spec.whatwg.org/multipage/forms.html#barred-from-constraint-validation */ function is_validation_candidate (element) { /* allow a shortcut via filters, e.g. to validate type=hidden fields */ var filtered = do_filter('is_validation_candidate', null, element); if (filtered !== null) { return !!filtered; } /* it must be any of those elements */ if (element instanceof window.HTMLSelectElement || element instanceof window.HTMLTextAreaElement || element instanceof window.HTMLButtonElement || element instanceof window.HTMLInputElement) { var type = get_type(element); /* its type must be in the whitelist or missing (select, textarea) */ if (!type || non_inputs.indexOf(type) > -1 || validation_candidates.indexOf(type) > -1) { /* it mustn't be disabled or readonly */ if (!element.hasAttribute('disabled') && !element.hasAttribute('readonly')) { var wrapped_form = get_wrapper(element); /* it hasn't got the (non-standard) attribute 'novalidate' or its * parent form has got the strict parameter */ if (wrapped_form && wrapped_form.settings.novalidate_on_elements || !element.hasAttribute('novalidate') || !element.noValidate) { /* it isn't part of a <fieldset disabled> */ var p = element.parentNode; while (p && p.nodeType === 1) { if (p instanceof window.HTMLFieldSetElement && p.hasAttribute('disabled')) { /* quick return, if it's a child of a disabled fieldset */ return false; } else if (p.nodeName.toUpperCase() === 'DATALIST') { /* quick return, if it's a child of a datalist * Do not use HTMLDataListElement to support older browsers, * too. * @see https://html.spec.whatwg.org/multipage/forms.html#the-datalist-element:barred-from-constraint-validation */ return false; } else if (p === element.form) { /* the outer boundary. We can stop looking for relevant * fieldsets. */ break; } p = p.parentNode; } /* then it's a candidate */ return true; } } } } /* this is no HTML5 validation candidate... */ return false; } function format_date (date) { var part = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : undefined; switch (part) { case 'date': return (date.toLocaleDateString || date.toDateString).call(date); case 'time': return (date.toLocaleTimeString || date.toTimeString).call(date); case 'month': return 'toLocaleDateString' in date ? date.toLocaleDateString(undefined, { year: 'numeric', month: '2-digit' }) : date.toDateString(); // case 'week': // TODO default: return (date.toLocaleString || date.toString).call(date); } } /** * patch String.length to account for non-BMP characters * * @see https://mathiasbynens.be/notes/javascript-unicode * We do not use the simple [...str].length, because it needs a ton of * polyfills in older browsers. */ function unicode_string_length (str) { return str.match(/[\0-\uD7FF\uE000-\uFFFF]|[\uD800-\uDBFF][\uDC00-\uDFFF]|[\uD800-\uDBFF](?![\uDC00-\uDFFF])|(?:[^\uD800-\uDBFF]|^)[\uDC00-\uDFFF]/g).length; } /** * internal storage for custom error messages */ var store$1 = new WeakMap(); /** * register custom error messages per element */ var custom_messages = { set: function set(element, validator, message) { var messages = store$1.get(element) || {}; messages[validator] = message; store$1.set(element, messages); return custom_messages; }, get: function get(element, validator) { var _default = arguments.length > 2 && arguments[2] !== undefined ? arguments[2] : undefined; var messages = store$1.get(element); if (messages === undefined || !(validator in messages)) { var data_id = 'data-' + validator.replace(/[A-Z]/g, '-$&').toLowerCase(); if (element.hasAttribute(data_id)) { /* if the element has a data-validator attribute, use this as fallback. * E.g., if validator == 'valueMissing', the element can specify a * custom validation message like this: * <input data-value-missing="Oh noes!"> */ return element.getAttribute(data_id); } return _default; } return messages[validator]; }, delete: function _delete(element) { var validator = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : null; if (!validator) { return store$1.delete(element); } var messages = store$1.get(element) || {}; if (validator in messages) { delete messages[validator]; store$1.set(element, messages); return true; } return false; } }; var internal_registry = new WeakMap(); /** * A registry for custom validators * * slim wrapper around a WeakMap to ensure the values are arrays * (hence allowing > 1 validators per element) */ var custom_validator_registry = { set: function set(element, validator) { var current = internal_registry.get(element) || []; current.push(validator); internal_registry.set(element, current); return custom_validator_registry; }, get: function get(element) { return internal_registry.get(element) || []; }, delete: function _delete(element) { return internal_registry.delete(element); } }; /** * test whether the element suffers from bad input */ function test_bad_input (element) { var type = get_type(element); if (!is_validation_candidate(element) || input_checked.indexOf(type) === -1) { /* we're not interested, thanks! */ return true; } /* the browser hides some bad input from the DOM, e.g. malformed numbers, * email addresses with invalid punycode representation, ... We try to resort * to the original method here. The assumption is, that a browser hiding * bad input will hopefully also always support a proper * ValidityState.badInput */ if (!element.value) { if ('_original_validity' in element && !element._original_validity.__hyperform) { return !element._original_validity.badInput; } /* no value and no original badInput: Assume all's right. */ return true; } var result = true; switch (type) { case 'color': result = /^#[a-f0-9]{6}$/.test(element.value); break; case 'number': case 'range': result = !isNaN(Number(element.value)); break; case 'datetime': case 'date': case 'month': case 'week': case 'time': result = string_to_date(element.value, type) !== null; break; case 'datetime-local': result = /^([0-9]{4,})-(0[1-9]|1[012])-(0[1-9]|[12][0-9]|3[01])T([01][0-9]|2[0-3]):([0-5][0-9])(?::([0-5][0-9])(?:\.([0-9]{1,3}))?)?$/.test(element.value); break; case 'tel': /* spec says No! Phone numbers can have all kinds of formats, so this * is expected to be a free-text field. */ // TODO we could allow a setting 'phone_regex' to be evaluated here. break; case 'email': break; } return result; } /** * test the max attribute * * we use Number() instead of parseFloat(), because an invalid attribute * value like "123abc" should result in an error. */ function test_max (element) { var type = get_type(element); if (!is_validation_candidate(element) || !element.value || !element.hasAttribute('max')) { /* we're not responsible here */ return true; } var value = void 0, max = void 0; if (dates.indexOf(type) > -1) { value = 1 * string_to_date(element.value, type); max = 1 * (string_to_date(element.getAttribute('max'), type) || NaN); } else { value = Number(element.value); max = Number(element.getAttribute('max')); } return isNaN(max) || value <= max; } /** * test the maxlength attribute */ function test_maxlength (element) { if (!is_validation_candidate(element) || !element.value || text_types.indexOf(get_type(element)) === -1 || !element.hasAttribute('maxlength') || !element.getAttribute('maxlength') // catch maxlength="" ) { return true; } var maxlength = parseInt(element.getAttribute('maxlength'), 10); /* check, if the maxlength value is usable at all. * We allow maxlength === 0 to basically disable input (Firefox does, too). */ if (isNaN(maxlength) || maxlength < 0) { return true; } return unicode_string_length(element.value) <= maxlength; } /** * test the min attribute * * we use Number() instead of parseFloat(), because an invalid attribute * value like "123abc" should result in an error. */ function test_min (element) { var type = get_type(element); if (!is_validation_candidate(element) || !element.value || !element.hasAttribute('min')) { /* we're not responsible here */ return true; } var value = void 0, min = void 0; if (dates.indexOf(type) > -1) { value = 1 * string_to_date(element.value, type); min = 1 * (string_to_date(element.getAttribute('min'), type) || NaN); } else { value = Number(element.value); min = Number(element.getAttribute('min')); } return isNaN(min) || value >= min; } /** * test the minlength attribute */ function test_minlength (element) { if (!is_validation_candidate(element) || !element.value || text_types.indexOf(get_type(element)) === -1 || !element.hasAttribute('minlength') || !element.getAttribute('minlength') // catch minlength="" ) { return true; } var minlength = parseInt(element.getAttribute('minlength'), 10); /* check, if the minlength value is usable at all. */ if (isNaN(minlength) || minlength < 0) { return true; } return unicode_string_length(element.value) >= minlength; } /** * test the pattern attribute */ function test_pattern (element) { return !is_validation_candidate(element) || !element.value || !element.hasAttribute('pattern') || new RegExp('^(?:' + element.getAttribute('pattern') + ')$').test(element.value); } /** * test the required attribute */ function test_required (element) { if (!is_validation_candidate(element) || !element.hasAttribute('required')) { /* nothing to do */ return true; } /* we don't need get_type() for element.type, because "checkbox" and "radio" * are well supported. */ switch (element.type) { case 'checkbox': return element.checked; //break; case 'radio': /* radio inputs have "required" fulfilled, if _any_ other radio * with the same name in this form is checked. */ return !!(element.checked || element.form && Array.prototype.filter.call(document.getElementsByName(element.name), function (radio) { return radio.name === element.name && radio.form === element.form && radio.checked; }).length > 0); //break; default: return !!element.value; } } /** * test the step attribute */ function test_step (element) { var type = get_type(element); if (!is_validation_candidate(element) || !element.value || numbers.indexOf(type) === -1 || (element.getAttribute('step') || '').toLowerCase() === 'any') { /* we're not responsible here. Note: If no step attribute is given, we * need to validate against the default step as per spec. */ return true; } var step = element.getAttribute('step'); if (step) { step = string_to_number(step, type); } else { step = default_step[type] || 1; } if (step <= 0 || isNaN(step)) { /* error in specified "step". We cannot validate against it, so the value * is true. */ return true; } var scale = step_scale_factor[type] || 1; var value = string_to_number(element.value, type); var min = string_to_number(element.getAttribute('min') || element.getAttribute('value') || '', type); if (isNaN(min)) { min = default_step_base[type] || 0; } if (type === 'month') { /* type=month has month-wide steps. See * https://html.spec.whatwg.org/multipage/forms.html#month-state-%28type=month%29 */ min = new Date(min).getUTCFullYear() * 12 + new Date(min).getUTCMonth(); value = new Date(value).getUTCFullYear() * 12 + new Date(value).getUTCMonth(); } var result = Math.abs(min - value) % (step * scale); return result < 0.00000001 || /* crappy floating-point arithmetics! */ result > step * scale - 0.00000001; } var ws_on_start_or_end = /^[\s\uFEFF\xA0]+|[\s\uFEFF\xA0]+$/g; /** * trim a string of whitespace * * We don't use String.trim() to remove the need to polyfill it. */ function trim (str) { return str.replace(ws_on_start_or_end, ''); } /** * split a string on comma and trim the components * * As specified at * https://html.spec.whatwg.org/multipage/infrastructure.html#split-a-string-on-commas * plus removing empty entries. */ function comma_split (str) { return str.split(',').map(function (item) { return trim(item); }).filter(function (b) { return b; }); } /* we use a dummy <a> where we set the href to test URL validity * The definition is out of the "global" scope so that JSDOM can be instantiated * after loading Hyperform for tests. */ var url_canary; /* see https://html.spec.whatwg.org/multipage/forms.html#valid-e-mail-address */ var email_pattern = /^[a-zA-Z0-9.!#$%&'*+\/=?^_`{|}~-]+@[a-zA-Z0-9](?:[a-zA-Z0-9-]{0,61}[a-zA-Z0-9])?(?:\.[a-zA-Z0-9](?:[a-zA-Z0-9-]{0,61}[a-zA-Z0-9])?)*$/; /** * test the type-inherent syntax */ function test_type (element) { var type = get_type(element); if (!is_validation_candidate(element) || type !== 'file' && !element.value || type !== 'file' && type_checked.indexOf(type) === -1) { /* we're not responsible for this element */ return true; } var is_valid = true; switch (type) { case 'url': if (!url_canary) { url_canary = document.createElement('a'); } var value = trim(element.value); url_canary.href = value; is_valid = url_canary.href === value || url_canary.href === value + '/'; break; case 'email': if (element.hasAttribute('multiple')) { is_valid = comma_split(element.value).every(function (value) { return email_pattern.test(value); }); } else { is_valid = email_pattern.test(trim(element.value)); } break; case 'file': if ('files' in element && element.files.length && element.hasAttribute('accept')) { var patterns = comma_split(element.getAttribute('accept')).map(function (pattern) { if (/^(audio|video|image)\/\*$/.test(pattern)) { pattern = new RegExp('^' + RegExp.$1 + '/.+$'); } return pattern; }); if (!patterns.length) { break; } fileloop: for (var i = 0; i < element.files.length; i++) { /* we need to match a whitelist, so pre-set with false */ var file_valid = false; patternloop: for (var j = 0; j < patterns.length; j++) { var file = element.files[i]; var pattern = patterns[j]; var fileprop = file.type; if (typeof pattern === 'string' && pattern.substr(0, 1) === '.') { if (file.name.search('.') === -1) { /* no match with any file ending */ continue patternloop; } fileprop = file.name.substr(file.name.lastIndexOf('.')); } if (fileprop.search(pattern) === 0) { /* we found one match and can quit looking */ file_valid = true; break patternloop; } } if (!file_valid) { is_valid = false; break fileloop; } } } } return is_valid; } /** * boilerplate function for all tests but customError */ function check$1(test, react) { return function (element) { var invalid = !test(element); if (invalid) { react(element); } return invalid; }; } /** * create a common function to set error messages */ function set_msg(element, msgtype, _default) { message_store.set(element, custom_messages.get(element, msgtype, _default)); } var badInput = check$1(test_bad_input, function (element) { return set_msg(element, 'badInput', _('Please match the requested type.')); }); function customError(element) { /* check, if there are custom validators in the registry, and call * them. */ var custom_validators = custom_validator_registry.get(element); var cvl = custom_validators.length; var valid = true; if (cvl) { for (var i = 0; i < cvl; i++) { var result = custom_validators[i](element); if (result !== undefined && !result) { valid = false; /* break on first invalid response */ break; } } } /* check, if there are other validity messages already */ if (valid) { var msg = message_store.get(element); valid = !(msg.toString() && 'is_custom' in msg); } return !valid; } var patternMismatch = check$1(test_pattern, function (element) { set_msg(element, 'patternMismatch', element.title ? sprintf(_('PatternMismatchWithTitle'), element.title) : _('PatternMismatch')); }); /** * TODO: when rangeOverflow and rangeUnderflow are both called directly and * successful, the inRange and outOfRange classes won't get removed, unless * element.validityState.valid is queried, too. */ var rangeOverflow = check$1(test_max, function (element) { var type = get_type(element); var wrapper = get_wrapper(element); var outOfRangeClass = wrapper && wrapper.settings.classes.outOfRange || 'hf-out-of-range'; var inRangeClass = wrapper && wrapper.settings.classes.inRange || 'hf-in-range'; var msg = void 0; switch (type) { case 'date': case 'datetime': case 'datetime-local': msg = sprintf(_('DateRangeOverflow'), format_date(string_to_date(element.getAttribute('max'), type), type)); break; case 'time': msg = sprintf(_('TimeRangeOverflow'), format_date(string_to_date(element.getAttribute('max'), type), type)); break; // case 'number': default: msg = sprintf(_('NumberRangeOverflow'), string_to_number(element.getAttribute('max'), type)); break; } set_msg(element, 'rangeOverflow', msg); element.classList.add(outOfRangeClass); element.classList.remove(inRangeClass); }); var rangeUnderflow = check$1(test_min, function (element) { var type = get_type(element); var wrapper = get_wrapper(element); var outOfRangeClass = wrapper && wrapper.settings.classes.outOfRange || 'hf-out-of-range'; var inRangeClass = wrapper && wrapper.settings.classes.inRange || 'hf-in-range'; var msg = void 0; switch (type) { case 'date': case 'datetime': case 'datetime-local': msg = sprintf(_('DateRangeUnderflow'), format_date(string_to_date(element.getAttribute('min'), type), type)); break; case 'time': msg = sprintf(_('TimeRangeUnderflow'), format_date(string_to_date(element.getAttribute('min'), type), type)); break; // case 'number': default: msg = sprintf(_('NumberRangeUnderflow'), string_to_number(element.getAttribute('min'), type)); break; } set_msg(element, 'rangeUnderflow', msg); element.classList.add(outOfRangeClass); element.classList.remove(inRangeClass); }); var stepMismatch = check$1(test_step, function (element) { var list = get_next_valid(element); var min = list[0]; var max = list[1]; var sole = false; var msg = void 0; if (min === null) { sole = max; } else if (max === null) { sole = min; } if (sole !== false) { msg = sprintf(_('StepMismatchOneValue'), sole); } else { msg = sprintf(_('StepMismatch'), min, max); } set_msg(element, 'stepMismatch', msg); }); var tooLong = check$1(test_maxlength, function (element) { set_msg(element, 'tooLong', sprintf(_('TextTooLong'), element.getAttribute('maxlength'), unicode_string_length(element.value))); }); var tooShort = check$1(test_minlength, function (element) { set_msg(element, 'tooShort', sprintf(_('Please lengthen this text to %l characters or more (you are currently using %l characters).'), element.getAttribute('maxlength'), unicode_string_length(element.value))); }); var typeMismatch = check$1(test_type, function (element) { var msg = _('Please use the appropriate format.'); var type = get_type(element); if (type === 'email') { if (element.hasAttribute('multiple')) { msg = _('Please enter a comma separated list of email addresses.'); } else { msg = _('InvalidEmail'); } } else if (type === 'url') { msg = _('InvalidURL'); } else if (type === 'file') { msg = _('Please select a file of the correct type.'); } set_msg(element, 'typeMismatch', msg); }); var valueMissing = check$1(test_required, function (element) { var msg = _('ValueMissing'); var type = get_type(element); if (type === 'checkbox') { msg = _('CheckboxMissing'); } else if (type === 'radio') { msg = _('RadioMissing'); } else if (type === 'file') { if (element.hasAttribute('multiple')) { msg = _('Please select one or more files.'); } else { msg = _('FileMissing'); } } else if (element instanceof window.HTMLSelectElement) { msg = _('SelectMissing'); } set_msg(element, 'valueMissing', msg); }); var validity_state_checkers = { badInput: badInput, customError: customError, patternMismatch: patternMismatch, rangeOverflow: rangeOverflow, rangeUnderflow: rangeUnderflow, stepMismatch: stepMismatch, tooLong: tooLong, tooShort: tooShort, typeMismatch: typeMismatch, valueMissing: valueMissing }; /** * the validity state constructor */ var ValidityState = function ValidityState(element) { if (!(element instanceof window.HTMLElement)) { throw new Error('cannot create a ValidityState for a non-element'); } var cached = ValidityState.cache.get(element); if (cached) { return cached; } if (!(this instanceof ValidityState)) { /* working around a forgotten `new` */ return new ValidityState(element); } this.element = element; ValidityState.cache.set(element, this); }; /** * the prototype for new validityState instances */ var ValidityStatePrototype = {}; ValidityState.prototype = ValidityStatePrototype; ValidityState.cache = new WeakMap(); /** * copy functionality from the validity checkers to the ValidityState * prototype */ for (var prop in validity_state_checkers) { Object.defineProperty(ValidityStatePrototype, prop, { configurable: true, enumerable: true, get: function (func) { return function () { return func(this.element); }; }(validity_state_checkers[prop]), set: undefined }); } /** * the "valid" property calls all other validity checkers and returns true, * if all those return false. * * This is the major access point for _all_ other API methods, namely * (check|report)Validity(). */ Object.defineProperty(ValidityStatePrototype, 'valid', { configurable: true, enumerable: true, get: function get() { var wrapper = get_wrapper(this.element); var validClass = wrapper && wrapper.settings.classes.valid || 'hf-valid'; var invalidClass = wrapper && wrapper.settings.classes.invalid || 'hf-invalid'; var userInvalidClass = wrapper && wrapper.settings.classes.userInvalid || 'hf-user-invalid'; var userValidClass = wrapper && wrapper.settings.classes.userValid || 'hf-user-valid'; var inRangeClass = wrapper && wrapper.settings.classes.inRange || 'hf-in-range'; var outOfRangeClass = wrapper && wrapper.settings.classes.outOfRange || 'hf-out-of-range'; var validatedClass = wrapper && wrapper.settings.classes.validated || 'hf-validated'; this.element.classList.add(validatedClass); if (is_validation_candidate(this.element)) { for (var _prop in validity_state_checkers) { if (validity_state_checkers[_prop](this.element)) { this.element.classList.add(invalidClass); this.element.classList.remove(validClass); this.element.classList.remove(userValidClass); if (this.element.value !== this.element.defaultValue) { this.element.classList.add(userInvalidClass); } else { this.element.classList.remove(userInvalidClass); } this.element.setAttribute('aria-invalid', 'true'); return false; } } } message_store.delete(this.element); this.element.classList.remove(invalidClass, userInvalidClass, outOfRangeClass); this.element.classList.add(validClass, inRangeClass); if (this.element.value !== this.element.defaultValue) { this.element.classList.add(userValidClass); } else { this.element.classList.remove(userValidClass); } this.element.setAttribute('aria-invalid', 'false'); return true; }, set: undefined }); /** * mark the validity prototype, because that is what the client-facing * code deals with mostly, not the property descriptor thing */ mark(ValidityStatePrototype); /** * check an element's validity with respect to it's form */ var checkValidity = return_hook_or('checkValidity', function (element) { /* if this is a <form>, check validity of all child inputs */ if (element instanceof window.HTMLFormElement) { return Array.prototype.map.call(element.elements, checkValidity).every(function (b) { return b; }); } /* default is true, also for elements that are no validation candidates */ var valid = ValidityState(element).valid; if (valid) { var wrapped_form = get_wrapper(element); if (wrapped_form && wrapped_form.settings.valid_event) { trigger_event(element, 'valid'); } } else { trigger_event(element, 'invalid', { cancelable: true }); } return valid; }); var version = '0.8.11'; /** * public hyperform interface: */ function hyperform(form) { var _ref = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : {}; var _ref$debug = _ref.debug; var debug = _ref$debug === undefined ? false : _ref$debug; var _ref$strict = _ref.strict; var strict = _ref$strict === undefined ? false : _ref$strict; var _ref$prevent_implicit = _ref.prevent_implicit_submit; var prevent_implicit_submit = _ref$prevent_implicit === undefined ? false : _ref$prevent_implicit; var revalidate = _ref.revalidate; var valid_event = _ref.valid_event; var extend_fieldset = _ref.extend_fieldset; var novalidate_on_elements = _ref.novalidate_on_elements; var classes = _ref.classes; if (revalidate === undefined) { /* other recognized values: 'oninput', 'onblur', 'onsubmit' and 'never' */ revalidate = strict ? 'onsubmit' : 'hybrid'; } if (valid_event === undefined) { valid_event = !strict; } if (extend_fieldset === undefined) { extend_fieldset = !strict; } if (novalidate_on_elements === undefined) { novalidate_on_elements = !strict; } if (!classes) { classes = {}; } var settings = { debug: debug, strict: strict, prevent_implicit_submit: prevent_implicit_submit, revalidate: revalidate, valid_event: valid_event, extend_fieldset: extend_fieldset, classes: classes }; if (form instanceof window.NodeList || form instanceof window.HTMLCollection || form instanceof Array) { return Array.prototype.map.call(form, function (element) { return hyperform(element, settings); }); } return new Wrapper(form, settings); } hyperform.version = version; hyperform.checkValidity = checkValidity; hyperform.reportValidity = reportValidity; hyperform.setCustomValidity = setCustomValidity; hyperform.stepDown = stepDown; hyperform.stepUp = stepUp; hyperform.validationMessage = validationMessage; hyperform.ValidityState = ValidityState; hyperform.valueAsDate = valueAsDate; hyperform.valueAsNumber = valueAsNumber; hyperform.willValidate = willValidate; hyperform.set_language = function (lang) { set_language(lang);return hyperform; }; hyperform.add_translation = function (lang, catalog) { add_translation(lang, catalog);return hyperform; }; hyperform.set_renderer = function (renderer, action) { Renderer.set(renderer, action);return hyperform; }; hyperform.add_validator = function (element, validator) { custom_validator_registry.set(element, validator);return hyperform; }; hyperform.set_message = function (element, validator, message) { custom_messages.set(element, validator, message);return hyperform; }; hyperform.add_hook = function (hook, action, position) { add_hook(hook, action, position);return hyperform; }; hyperform.remove_hook = function (hook, action) { remove_hook(hook, action);return hyperform; }; module.exports = hyperform;
00_BootstrapJS/WebContent/bootstrap-2.3.2/js/tests/vendor/jquery.js
acelaya/angular-course
/*! jQuery v1.9.1 | (c) 2005, 2012 jQuery Foundation, Inc. | jquery.org/license //@ sourceMappingURL=jquery.min.map */(function(e,t){var n,r,i=typeof t,o=e.document,a=e.location,s=e.jQuery,u=e.$,l={},c=[],p="1.9.1",f=c.concat,d=c.push,h=c.slice,g=c.indexOf,m=l.toString,y=l.hasOwnProperty,v=p.trim,b=function(e,t){return new b.fn.init(e,t,r)},x=/[+-]?(?:\d*\.|)\d+(?:[eE][+-]?\d+|)/.source,w=/\S+/g,T=/^[\s\uFEFF\xA0]+|[\s\uFEFF\xA0]+$/g,N=/^(?:(<[\w\W]+>)[^>]*|#([\w-]*))$/,C=/^<(\w+)\s*\/?>(?:<\/\1>|)$/,k=/^[\],:{}\s]*$/,E=/(?:^|:|,)(?:\s*\[)+/g,S=/\\(?:["\\\/bfnrt]|u[\da-fA-F]{4})/g,A=/"[^"\\\r\n]*"|true|false|null|-?(?:\d+\.|)\d+(?:[eE][+-]?\d+|)/g,j=/^-ms-/,D=/-([\da-z])/gi,L=function(e,t){return t.toUpperCase()},H=function(e){(o.addEventListener||"load"===e.type||"complete"===o.readyState)&&(q(),b.ready())},q=function(){o.addEventListener?(o.removeEventListener("DOMContentLoaded",H,!1),e.removeEventListener("load",H,!1)):(o.detachEvent("onreadystatechange",H),e.detachEvent("onload",H))};b.fn=b.prototype={jquery:p,constructor:b,init:function(e,n,r){var i,a;if(!e)return this;if("string"==typeof e){if(i="<"===e.charAt(0)&&">"===e.charAt(e.length-1)&&e.length>=3?[null,e,null]:N.exec(e),!i||!i[1]&&n)return!n||n.jquery?(n||r).find(e):this.constructor(n).find(e);if(i[1]){if(n=n instanceof b?n[0]:n,b.merge(this,b.parseHTML(i[1],n&&n.nodeType?n.ownerDocument||n:o,!0)),C.test(i[1])&&b.isPlainObject(n))for(i in n)b.isFunction(this[i])?this[i](n[i]):this.attr(i,n[i]);return this}if(a=o.getElementById(i[2]),a&&a.parentNode){if(a.id!==i[2])return r.find(e);this.length=1,this[0]=a}return this.context=o,this.selector=e,this}return e.nodeType?(this.context=this[0]=e,this.length=1,this):b.isFunction(e)?r.ready(e):(e.selector!==t&&(this.selector=e.selector,this.context=e.context),b.makeArray(e,this))},selector:"",length:0,size:function(){return this.length},toArray:function(){return h.call(this)},get:function(e){return null==e?this.toArray():0>e?this[this.length+e]:this[e]},pushStack:function(e){var t=b.merge(this.constructor(),e);return t.prevObject=this,t.context=this.context,t},each:function(e,t){return b.each(this,e,t)},ready:function(e){return b.ready.promise().done(e),this},slice:function(){return this.pushStack(h.apply(this,arguments))},first:function(){return this.eq(0)},last:function(){return this.eq(-1)},eq:function(e){var t=this.length,n=+e+(0>e?t:0);return this.pushStack(n>=0&&t>n?[this[n]]:[])},map:function(e){return this.pushStack(b.map(this,function(t,n){return e.call(t,n,t)}))},end:function(){return this.prevObject||this.constructor(null)},push:d,sort:[].sort,splice:[].splice},b.fn.init.prototype=b.fn,b.extend=b.fn.extend=function(){var e,n,r,i,o,a,s=arguments[0]||{},u=1,l=arguments.length,c=!1;for("boolean"==typeof s&&(c=s,s=arguments[1]||{},u=2),"object"==typeof s||b.isFunction(s)||(s={}),l===u&&(s=this,--u);l>u;u++)if(null!=(o=arguments[u]))for(i in o)e=s[i],r=o[i],s!==r&&(c&&r&&(b.isPlainObject(r)||(n=b.isArray(r)))?(n?(n=!1,a=e&&b.isArray(e)?e:[]):a=e&&b.isPlainObject(e)?e:{},s[i]=b.extend(c,a,r)):r!==t&&(s[i]=r));return s},b.extend({noConflict:function(t){return e.$===b&&(e.$=u),t&&e.jQuery===b&&(e.jQuery=s),b},isReady:!1,readyWait:1,holdReady:function(e){e?b.readyWait++:b.ready(!0)},ready:function(e){if(e===!0?!--b.readyWait:!b.isReady){if(!o.body)return setTimeout(b.ready);b.isReady=!0,e!==!0&&--b.readyWait>0||(n.resolveWith(o,[b]),b.fn.trigger&&b(o).trigger("ready").off("ready"))}},isFunction:function(e){return"function"===b.type(e)},isArray:Array.isArray||function(e){return"array"===b.type(e)},isWindow:function(e){return null!=e&&e==e.window},isNumeric:function(e){return!isNaN(parseFloat(e))&&isFinite(e)},type:function(e){return null==e?e+"":"object"==typeof e||"function"==typeof e?l[m.call(e)]||"object":typeof e},isPlainObject:function(e){if(!e||"object"!==b.type(e)||e.nodeType||b.isWindow(e))return!1;try{if(e.constructor&&!y.call(e,"constructor")&&!y.call(e.constructor.prototype,"isPrototypeOf"))return!1}catch(n){return!1}var r;for(r in e);return r===t||y.call(e,r)},isEmptyObject:function(e){var t;for(t in e)return!1;return!0},error:function(e){throw Error(e)},parseHTML:function(e,t,n){if(!e||"string"!=typeof e)return null;"boolean"==typeof t&&(n=t,t=!1),t=t||o;var r=C.exec(e),i=!n&&[];return r?[t.createElement(r[1])]:(r=b.buildFragment([e],t,i),i&&b(i).remove(),b.merge([],r.childNodes))},parseJSON:function(n){return e.JSON&&e.JSON.parse?e.JSON.parse(n):null===n?n:"string"==typeof n&&(n=b.trim(n),n&&k.test(n.replace(S,"@").replace(A,"]").replace(E,"")))?Function("return "+n)():(b.error("Invalid JSON: "+n),t)},parseXML:function(n){var r,i;if(!n||"string"!=typeof n)return null;try{e.DOMParser?(i=new DOMParser,r=i.parseFromString(n,"text/xml")):(r=new ActiveXObject("Microsoft.XMLDOM"),r.async="false",r.loadXML(n))}catch(o){r=t}return r&&r.documentElement&&!r.getElementsByTagName("parsererror").length||b.error("Invalid XML: "+n),r},noop:function(){},globalEval:function(t){t&&b.trim(t)&&(e.execScript||function(t){e.eval.call(e,t)})(t)},camelCase:function(e){return e.replace(j,"ms-").replace(D,L)},nodeName:function(e,t){return e.nodeName&&e.nodeName.toLowerCase()===t.toLowerCase()},each:function(e,t,n){var r,i=0,o=e.length,a=M(e);if(n){if(a){for(;o>i;i++)if(r=t.apply(e[i],n),r===!1)break}else for(i in e)if(r=t.apply(e[i],n),r===!1)break}else if(a){for(;o>i;i++)if(r=t.call(e[i],i,e[i]),r===!1)break}else for(i in e)if(r=t.call(e[i],i,e[i]),r===!1)break;return e},trim:v&&!v.call("\ufeff\u00a0")?function(e){return null==e?"":v.call(e)}:function(e){return null==e?"":(e+"").replace(T,"")},makeArray:function(e,t){var n=t||[];return null!=e&&(M(Object(e))?b.merge(n,"string"==typeof e?[e]:e):d.call(n,e)),n},inArray:function(e,t,n){var r;if(t){if(g)return g.call(t,e,n);for(r=t.length,n=n?0>n?Math.max(0,r+n):n:0;r>n;n++)if(n in t&&t[n]===e)return n}return-1},merge:function(e,n){var r=n.length,i=e.length,o=0;if("number"==typeof r)for(;r>o;o++)e[i++]=n[o];else while(n[o]!==t)e[i++]=n[o++];return e.length=i,e},grep:function(e,t,n){var r,i=[],o=0,a=e.length;for(n=!!n;a>o;o++)r=!!t(e[o],o),n!==r&&i.push(e[o]);return i},map:function(e,t,n){var r,i=0,o=e.length,a=M(e),s=[];if(a)for(;o>i;i++)r=t(e[i],i,n),null!=r&&(s[s.length]=r);else for(i in e)r=t(e[i],i,n),null!=r&&(s[s.length]=r);return f.apply([],s)},guid:1,proxy:function(e,n){var r,i,o;return"string"==typeof n&&(o=e[n],n=e,e=o),b.isFunction(e)?(r=h.call(arguments,2),i=function(){return e.apply(n||this,r.concat(h.call(arguments)))},i.guid=e.guid=e.guid||b.guid++,i):t},access:function(e,n,r,i,o,a,s){var u=0,l=e.length,c=null==r;if("object"===b.type(r)){o=!0;for(u in r)b.access(e,n,u,r[u],!0,a,s)}else if(i!==t&&(o=!0,b.isFunction(i)||(s=!0),c&&(s?(n.call(e,i),n=null):(c=n,n=function(e,t,n){return c.call(b(e),n)})),n))for(;l>u;u++)n(e[u],r,s?i:i.call(e[u],u,n(e[u],r)));return o?e:c?n.call(e):l?n(e[0],r):a},now:function(){return(new Date).getTime()}}),b.ready.promise=function(t){if(!n)if(n=b.Deferred(),"complete"===o.readyState)setTimeout(b.ready);else if(o.addEventListener)o.addEventListener("DOMContentLoaded",H,!1),e.addEventListener("load",H,!1);else{o.attachEvent("onreadystatechange",H),e.attachEvent("onload",H);var r=!1;try{r=null==e.frameElement&&o.documentElement}catch(i){}r&&r.doScroll&&function a(){if(!b.isReady){try{r.doScroll("left")}catch(e){return setTimeout(a,50)}q(),b.ready()}}()}return n.promise(t)},b.each("Boolean Number String Function Array Date RegExp Object Error".split(" "),function(e,t){l["[object "+t+"]"]=t.toLowerCase()});function M(e){var t=e.length,n=b.type(e);return b.isWindow(e)?!1:1===e.nodeType&&t?!0:"array"===n||"function"!==n&&(0===t||"number"==typeof t&&t>0&&t-1 in e)}r=b(o);var _={};function F(e){var t=_[e]={};return b.each(e.match(w)||[],function(e,n){t[n]=!0}),t}b.Callbacks=function(e){e="string"==typeof e?_[e]||F(e):b.extend({},e);var n,r,i,o,a,s,u=[],l=!e.once&&[],c=function(t){for(r=e.memory&&t,i=!0,a=s||0,s=0,o=u.length,n=!0;u&&o>a;a++)if(u[a].apply(t[0],t[1])===!1&&e.stopOnFalse){r=!1;break}n=!1,u&&(l?l.length&&c(l.shift()):r?u=[]:p.disable())},p={add:function(){if(u){var t=u.length;(function i(t){b.each(t,function(t,n){var r=b.type(n);"function"===r?e.unique&&p.has(n)||u.push(n):n&&n.length&&"string"!==r&&i(n)})})(arguments),n?o=u.length:r&&(s=t,c(r))}return this},remove:function(){return u&&b.each(arguments,function(e,t){var r;while((r=b.inArray(t,u,r))>-1)u.splice(r,1),n&&(o>=r&&o--,a>=r&&a--)}),this},has:function(e){return e?b.inArray(e,u)>-1:!(!u||!u.length)},empty:function(){return u=[],this},disable:function(){return u=l=r=t,this},disabled:function(){return!u},lock:function(){return l=t,r||p.disable(),this},locked:function(){return!l},fireWith:function(e,t){return t=t||[],t=[e,t.slice?t.slice():t],!u||i&&!l||(n?l.push(t):c(t)),this},fire:function(){return p.fireWith(this,arguments),this},fired:function(){return!!i}};return p},b.extend({Deferred:function(e){var t=[["resolve","done",b.Callbacks("once memory"),"resolved"],["reject","fail",b.Callbacks("once memory"),"rejected"],["notify","progress",b.Callbacks("memory")]],n="pending",r={state:function(){return n},always:function(){return i.done(arguments).fail(arguments),this},then:function(){var e=arguments;return b.Deferred(function(n){b.each(t,function(t,o){var a=o[0],s=b.isFunction(e[t])&&e[t];i[o[1]](function(){var e=s&&s.apply(this,arguments);e&&b.isFunction(e.promise)?e.promise().done(n.resolve).fail(n.reject).progress(n.notify):n[a+"With"](this===r?n.promise():this,s?[e]:arguments)})}),e=null}).promise()},promise:function(e){return null!=e?b.extend(e,r):r}},i={};return r.pipe=r.then,b.each(t,function(e,o){var a=o[2],s=o[3];r[o[1]]=a.add,s&&a.add(function(){n=s},t[1^e][2].disable,t[2][2].lock),i[o[0]]=function(){return i[o[0]+"With"](this===i?r:this,arguments),this},i[o[0]+"With"]=a.fireWith}),r.promise(i),e&&e.call(i,i),i},when:function(e){var t=0,n=h.call(arguments),r=n.length,i=1!==r||e&&b.isFunction(e.promise)?r:0,o=1===i?e:b.Deferred(),a=function(e,t,n){return function(r){t[e]=this,n[e]=arguments.length>1?h.call(arguments):r,n===s?o.notifyWith(t,n):--i||o.resolveWith(t,n)}},s,u,l;if(r>1)for(s=Array(r),u=Array(r),l=Array(r);r>t;t++)n[t]&&b.isFunction(n[t].promise)?n[t].promise().done(a(t,l,n)).fail(o.reject).progress(a(t,u,s)):--i;return i||o.resolveWith(l,n),o.promise()}}),b.support=function(){var t,n,r,a,s,u,l,c,p,f,d=o.createElement("div");if(d.setAttribute("className","t"),d.innerHTML=" <link/><table></table><a href='/a'>a</a><input type='checkbox'/>",n=d.getElementsByTagName("*"),r=d.getElementsByTagName("a")[0],!n||!r||!n.length)return{};s=o.createElement("select"),l=s.appendChild(o.createElement("option")),a=d.getElementsByTagName("input")[0],r.style.cssText="top:1px;float:left;opacity:.5",t={getSetAttribute:"t"!==d.className,leadingWhitespace:3===d.firstChild.nodeType,tbody:!d.getElementsByTagName("tbody").length,htmlSerialize:!!d.getElementsByTagName("link").length,style:/top/.test(r.getAttribute("style")),hrefNormalized:"/a"===r.getAttribute("href"),opacity:/^0.5/.test(r.style.opacity),cssFloat:!!r.style.cssFloat,checkOn:!!a.value,optSelected:l.selected,enctype:!!o.createElement("form").enctype,html5Clone:"<:nav></:nav>"!==o.createElement("nav").cloneNode(!0).outerHTML,boxModel:"CSS1Compat"===o.compatMode,deleteExpando:!0,noCloneEvent:!0,inlineBlockNeedsLayout:!1,shrinkWrapBlocks:!1,reliableMarginRight:!0,boxSizingReliable:!0,pixelPosition:!1},a.checked=!0,t.noCloneChecked=a.cloneNode(!0).checked,s.disabled=!0,t.optDisabled=!l.disabled;try{delete d.test}catch(h){t.deleteExpando=!1}a=o.createElement("input"),a.setAttribute("value",""),t.input=""===a.getAttribute("value"),a.value="t",a.setAttribute("type","radio"),t.radioValue="t"===a.value,a.setAttribute("checked","t"),a.setAttribute("name","t"),u=o.createDocumentFragment(),u.appendChild(a),t.appendChecked=a.checked,t.checkClone=u.cloneNode(!0).cloneNode(!0).lastChild.checked,d.attachEvent&&(d.attachEvent("onclick",function(){t.noCloneEvent=!1}),d.cloneNode(!0).click());for(f in{submit:!0,change:!0,focusin:!0})d.setAttribute(c="on"+f,"t"),t[f+"Bubbles"]=c in e||d.attributes[c].expando===!1;return d.style.backgroundClip="content-box",d.cloneNode(!0).style.backgroundClip="",t.clearCloneStyle="content-box"===d.style.backgroundClip,b(function(){var n,r,a,s="padding:0;margin:0;border:0;display:block;box-sizing:content-box;-moz-box-sizing:content-box;-webkit-box-sizing:content-box;",u=o.getElementsByTagName("body")[0];u&&(n=o.createElement("div"),n.style.cssText="border:0;width:0;height:0;position:absolute;top:0;left:-9999px;margin-top:1px",u.appendChild(n).appendChild(d),d.innerHTML="<table><tr><td></td><td>t</td></tr></table>",a=d.getElementsByTagName("td"),a[0].style.cssText="padding:0;margin:0;border:0;display:none",p=0===a[0].offsetHeight,a[0].style.display="",a[1].style.display="none",t.reliableHiddenOffsets=p&&0===a[0].offsetHeight,d.innerHTML="",d.style.cssText="box-sizing:border-box;-moz-box-sizing:border-box;-webkit-box-sizing:border-box;padding:1px;border:1px;display:block;width:4px;margin-top:1%;position:absolute;top:1%;",t.boxSizing=4===d.offsetWidth,t.doesNotIncludeMarginInBodyOffset=1!==u.offsetTop,e.getComputedStyle&&(t.pixelPosition="1%"!==(e.getComputedStyle(d,null)||{}).top,t.boxSizingReliable="4px"===(e.getComputedStyle(d,null)||{width:"4px"}).width,r=d.appendChild(o.createElement("div")),r.style.cssText=d.style.cssText=s,r.style.marginRight=r.style.width="0",d.style.width="1px",t.reliableMarginRight=!parseFloat((e.getComputedStyle(r,null)||{}).marginRight)),typeof d.style.zoom!==i&&(d.innerHTML="",d.style.cssText=s+"width:1px;padding:1px;display:inline;zoom:1",t.inlineBlockNeedsLayout=3===d.offsetWidth,d.style.display="block",d.innerHTML="<div></div>",d.firstChild.style.width="5px",t.shrinkWrapBlocks=3!==d.offsetWidth,t.inlineBlockNeedsLayout&&(u.style.zoom=1)),u.removeChild(n),n=d=a=r=null)}),n=s=u=l=r=a=null,t}();var O=/(?:\{[\s\S]*\}|\[[\s\S]*\])$/,B=/([A-Z])/g;function P(e,n,r,i){if(b.acceptData(e)){var o,a,s=b.expando,u="string"==typeof n,l=e.nodeType,p=l?b.cache:e,f=l?e[s]:e[s]&&s;if(f&&p[f]&&(i||p[f].data)||!u||r!==t)return f||(l?e[s]=f=c.pop()||b.guid++:f=s),p[f]||(p[f]={},l||(p[f].toJSON=b.noop)),("object"==typeof n||"function"==typeof n)&&(i?p[f]=b.extend(p[f],n):p[f].data=b.extend(p[f].data,n)),o=p[f],i||(o.data||(o.data={}),o=o.data),r!==t&&(o[b.camelCase(n)]=r),u?(a=o[n],null==a&&(a=o[b.camelCase(n)])):a=o,a}}function R(e,t,n){if(b.acceptData(e)){var r,i,o,a=e.nodeType,s=a?b.cache:e,u=a?e[b.expando]:b.expando;if(s[u]){if(t&&(o=n?s[u]:s[u].data)){b.isArray(t)?t=t.concat(b.map(t,b.camelCase)):t in o?t=[t]:(t=b.camelCase(t),t=t in o?[t]:t.split(" "));for(r=0,i=t.length;i>r;r++)delete o[t[r]];if(!(n?$:b.isEmptyObject)(o))return}(n||(delete s[u].data,$(s[u])))&&(a?b.cleanData([e],!0):b.support.deleteExpando||s!=s.window?delete s[u]:s[u]=null)}}}b.extend({cache:{},expando:"jQuery"+(p+Math.random()).replace(/\D/g,""),noData:{embed:!0,object:"clsid:D27CDB6E-AE6D-11cf-96B8-444553540000",applet:!0},hasData:function(e){return e=e.nodeType?b.cache[e[b.expando]]:e[b.expando],!!e&&!$(e)},data:function(e,t,n){return P(e,t,n)},removeData:function(e,t){return R(e,t)},_data:function(e,t,n){return P(e,t,n,!0)},_removeData:function(e,t){return R(e,t,!0)},acceptData:function(e){if(e.nodeType&&1!==e.nodeType&&9!==e.nodeType)return!1;var t=e.nodeName&&b.noData[e.nodeName.toLowerCase()];return!t||t!==!0&&e.getAttribute("classid")===t}}),b.fn.extend({data:function(e,n){var r,i,o=this[0],a=0,s=null;if(e===t){if(this.length&&(s=b.data(o),1===o.nodeType&&!b._data(o,"parsedAttrs"))){for(r=o.attributes;r.length>a;a++)i=r[a].name,i.indexOf("data-")||(i=b.camelCase(i.slice(5)),W(o,i,s[i]));b._data(o,"parsedAttrs",!0)}return s}return"object"==typeof e?this.each(function(){b.data(this,e)}):b.access(this,function(n){return n===t?o?W(o,e,b.data(o,e)):null:(this.each(function(){b.data(this,e,n)}),t)},null,n,arguments.length>1,null,!0)},removeData:function(e){return this.each(function(){b.removeData(this,e)})}});function W(e,n,r){if(r===t&&1===e.nodeType){var i="data-"+n.replace(B,"-$1").toLowerCase();if(r=e.getAttribute(i),"string"==typeof r){try{r="true"===r?!0:"false"===r?!1:"null"===r?null:+r+""===r?+r:O.test(r)?b.parseJSON(r):r}catch(o){}b.data(e,n,r)}else r=t}return r}function $(e){var t;for(t in e)if(("data"!==t||!b.isEmptyObject(e[t]))&&"toJSON"!==t)return!1;return!0}b.extend({queue:function(e,n,r){var i;return e?(n=(n||"fx")+"queue",i=b._data(e,n),r&&(!i||b.isArray(r)?i=b._data(e,n,b.makeArray(r)):i.push(r)),i||[]):t},dequeue:function(e,t){t=t||"fx";var n=b.queue(e,t),r=n.length,i=n.shift(),o=b._queueHooks(e,t),a=function(){b.dequeue(e,t)};"inprogress"===i&&(i=n.shift(),r--),o.cur=i,i&&("fx"===t&&n.unshift("inprogress"),delete o.stop,i.call(e,a,o)),!r&&o&&o.empty.fire()},_queueHooks:function(e,t){var n=t+"queueHooks";return b._data(e,n)||b._data(e,n,{empty:b.Callbacks("once memory").add(function(){b._removeData(e,t+"queue"),b._removeData(e,n)})})}}),b.fn.extend({queue:function(e,n){var r=2;return"string"!=typeof e&&(n=e,e="fx",r--),r>arguments.length?b.queue(this[0],e):n===t?this:this.each(function(){var t=b.queue(this,e,n);b._queueHooks(this,e),"fx"===e&&"inprogress"!==t[0]&&b.dequeue(this,e)})},dequeue:function(e){return this.each(function(){b.dequeue(this,e)})},delay:function(e,t){return e=b.fx?b.fx.speeds[e]||e:e,t=t||"fx",this.queue(t,function(t,n){var r=setTimeout(t,e);n.stop=function(){clearTimeout(r)}})},clearQueue:function(e){return this.queue(e||"fx",[])},promise:function(e,n){var r,i=1,o=b.Deferred(),a=this,s=this.length,u=function(){--i||o.resolveWith(a,[a])};"string"!=typeof e&&(n=e,e=t),e=e||"fx";while(s--)r=b._data(a[s],e+"queueHooks"),r&&r.empty&&(i++,r.empty.add(u));return u(),o.promise(n)}});var I,z,X=/[\t\r\n]/g,U=/\r/g,V=/^(?:input|select|textarea|button|object)$/i,Y=/^(?:a|area)$/i,J=/^(?:checked|selected|autofocus|autoplay|async|controls|defer|disabled|hidden|loop|multiple|open|readonly|required|scoped)$/i,G=/^(?:checked|selected)$/i,Q=b.support.getSetAttribute,K=b.support.input;b.fn.extend({attr:function(e,t){return b.access(this,b.attr,e,t,arguments.length>1)},removeAttr:function(e){return this.each(function(){b.removeAttr(this,e)})},prop:function(e,t){return b.access(this,b.prop,e,t,arguments.length>1)},removeProp:function(e){return e=b.propFix[e]||e,this.each(function(){try{this[e]=t,delete this[e]}catch(n){}})},addClass:function(e){var t,n,r,i,o,a=0,s=this.length,u="string"==typeof e&&e;if(b.isFunction(e))return this.each(function(t){b(this).addClass(e.call(this,t,this.className))});if(u)for(t=(e||"").match(w)||[];s>a;a++)if(n=this[a],r=1===n.nodeType&&(n.className?(" "+n.className+" ").replace(X," "):" ")){o=0;while(i=t[o++])0>r.indexOf(" "+i+" ")&&(r+=i+" ");n.className=b.trim(r)}return this},removeClass:function(e){var t,n,r,i,o,a=0,s=this.length,u=0===arguments.length||"string"==typeof e&&e;if(b.isFunction(e))return this.each(function(t){b(this).removeClass(e.call(this,t,this.className))});if(u)for(t=(e||"").match(w)||[];s>a;a++)if(n=this[a],r=1===n.nodeType&&(n.className?(" "+n.className+" ").replace(X," "):"")){o=0;while(i=t[o++])while(r.indexOf(" "+i+" ")>=0)r=r.replace(" "+i+" "," ");n.className=e?b.trim(r):""}return this},toggleClass:function(e,t){var n=typeof e,r="boolean"==typeof t;return b.isFunction(e)?this.each(function(n){b(this).toggleClass(e.call(this,n,this.className,t),t)}):this.each(function(){if("string"===n){var o,a=0,s=b(this),u=t,l=e.match(w)||[];while(o=l[a++])u=r?u:!s.hasClass(o),s[u?"addClass":"removeClass"](o)}else(n===i||"boolean"===n)&&(this.className&&b._data(this,"__className__",this.className),this.className=this.className||e===!1?"":b._data(this,"__className__")||"")})},hasClass:function(e){var t=" "+e+" ",n=0,r=this.length;for(;r>n;n++)if(1===this[n].nodeType&&(" "+this[n].className+" ").replace(X," ").indexOf(t)>=0)return!0;return!1},val:function(e){var n,r,i,o=this[0];{if(arguments.length)return i=b.isFunction(e),this.each(function(n){var o,a=b(this);1===this.nodeType&&(o=i?e.call(this,n,a.val()):e,null==o?o="":"number"==typeof o?o+="":b.isArray(o)&&(o=b.map(o,function(e){return null==e?"":e+""})),r=b.valHooks[this.type]||b.valHooks[this.nodeName.toLowerCase()],r&&"set"in r&&r.set(this,o,"value")!==t||(this.value=o))});if(o)return r=b.valHooks[o.type]||b.valHooks[o.nodeName.toLowerCase()],r&&"get"in r&&(n=r.get(o,"value"))!==t?n:(n=o.value,"string"==typeof n?n.replace(U,""):null==n?"":n)}}}),b.extend({valHooks:{option:{get:function(e){var t=e.attributes.value;return!t||t.specified?e.value:e.text}},select:{get:function(e){var t,n,r=e.options,i=e.selectedIndex,o="select-one"===e.type||0>i,a=o?null:[],s=o?i+1:r.length,u=0>i?s:o?i:0;for(;s>u;u++)if(n=r[u],!(!n.selected&&u!==i||(b.support.optDisabled?n.disabled:null!==n.getAttribute("disabled"))||n.parentNode.disabled&&b.nodeName(n.parentNode,"optgroup"))){if(t=b(n).val(),o)return t;a.push(t)}return a},set:function(e,t){var n=b.makeArray(t);return b(e).find("option").each(function(){this.selected=b.inArray(b(this).val(),n)>=0}),n.length||(e.selectedIndex=-1),n}}},attr:function(e,n,r){var o,a,s,u=e.nodeType;if(e&&3!==u&&8!==u&&2!==u)return typeof e.getAttribute===i?b.prop(e,n,r):(a=1!==u||!b.isXMLDoc(e),a&&(n=n.toLowerCase(),o=b.attrHooks[n]||(J.test(n)?z:I)),r===t?o&&a&&"get"in o&&null!==(s=o.get(e,n))?s:(typeof e.getAttribute!==i&&(s=e.getAttribute(n)),null==s?t:s):null!==r?o&&a&&"set"in o&&(s=o.set(e,r,n))!==t?s:(e.setAttribute(n,r+""),r):(b.removeAttr(e,n),t))},removeAttr:function(e,t){var n,r,i=0,o=t&&t.match(w);if(o&&1===e.nodeType)while(n=o[i++])r=b.propFix[n]||n,J.test(n)?!Q&&G.test(n)?e[b.camelCase("default-"+n)]=e[r]=!1:e[r]=!1:b.attr(e,n,""),e.removeAttribute(Q?n:r)},attrHooks:{type:{set:function(e,t){if(!b.support.radioValue&&"radio"===t&&b.nodeName(e,"input")){var n=e.value;return e.setAttribute("type",t),n&&(e.value=n),t}}}},propFix:{tabindex:"tabIndex",readonly:"readOnly","for":"htmlFor","class":"className",maxlength:"maxLength",cellspacing:"cellSpacing",cellpadding:"cellPadding",rowspan:"rowSpan",colspan:"colSpan",usemap:"useMap",frameborder:"frameBorder",contenteditable:"contentEditable"},prop:function(e,n,r){var i,o,a,s=e.nodeType;if(e&&3!==s&&8!==s&&2!==s)return a=1!==s||!b.isXMLDoc(e),a&&(n=b.propFix[n]||n,o=b.propHooks[n]),r!==t?o&&"set"in o&&(i=o.set(e,r,n))!==t?i:e[n]=r:o&&"get"in o&&null!==(i=o.get(e,n))?i:e[n]},propHooks:{tabIndex:{get:function(e){var n=e.getAttributeNode("tabindex");return n&&n.specified?parseInt(n.value,10):V.test(e.nodeName)||Y.test(e.nodeName)&&e.href?0:t}}}}),z={get:function(e,n){var r=b.prop(e,n),i="boolean"==typeof r&&e.getAttribute(n),o="boolean"==typeof r?K&&Q?null!=i:G.test(n)?e[b.camelCase("default-"+n)]:!!i:e.getAttributeNode(n);return o&&o.value!==!1?n.toLowerCase():t},set:function(e,t,n){return t===!1?b.removeAttr(e,n):K&&Q||!G.test(n)?e.setAttribute(!Q&&b.propFix[n]||n,n):e[b.camelCase("default-"+n)]=e[n]=!0,n}},K&&Q||(b.attrHooks.value={get:function(e,n){var r=e.getAttributeNode(n);return b.nodeName(e,"input")?e.defaultValue:r&&r.specified?r.value:t},set:function(e,n,r){return b.nodeName(e,"input")?(e.defaultValue=n,t):I&&I.set(e,n,r)}}),Q||(I=b.valHooks.button={get:function(e,n){var r=e.getAttributeNode(n);return r&&("id"===n||"name"===n||"coords"===n?""!==r.value:r.specified)?r.value:t},set:function(e,n,r){var i=e.getAttributeNode(r);return i||e.setAttributeNode(i=e.ownerDocument.createAttribute(r)),i.value=n+="","value"===r||n===e.getAttribute(r)?n:t}},b.attrHooks.contenteditable={get:I.get,set:function(e,t,n){I.set(e,""===t?!1:t,n)}},b.each(["width","height"],function(e,n){b.attrHooks[n]=b.extend(b.attrHooks[n],{set:function(e,r){return""===r?(e.setAttribute(n,"auto"),r):t}})})),b.support.hrefNormalized||(b.each(["href","src","width","height"],function(e,n){b.attrHooks[n]=b.extend(b.attrHooks[n],{get:function(e){var r=e.getAttribute(n,2);return null==r?t:r}})}),b.each(["href","src"],function(e,t){b.propHooks[t]={get:function(e){return e.getAttribute(t,4)}}})),b.support.style||(b.attrHooks.style={get:function(e){return e.style.cssText||t},set:function(e,t){return e.style.cssText=t+""}}),b.support.optSelected||(b.propHooks.selected=b.extend(b.propHooks.selected,{get:function(e){var t=e.parentNode;return t&&(t.selectedIndex,t.parentNode&&t.parentNode.selectedIndex),null}})),b.support.enctype||(b.propFix.enctype="encoding"),b.support.checkOn||b.each(["radio","checkbox"],function(){b.valHooks[this]={get:function(e){return null===e.getAttribute("value")?"on":e.value}}}),b.each(["radio","checkbox"],function(){b.valHooks[this]=b.extend(b.valHooks[this],{set:function(e,n){return b.isArray(n)?e.checked=b.inArray(b(e).val(),n)>=0:t}})});var Z=/^(?:input|select|textarea)$/i,et=/^key/,tt=/^(?:mouse|contextmenu)|click/,nt=/^(?:focusinfocus|focusoutblur)$/,rt=/^([^.]*)(?:\.(.+)|)$/;function it(){return!0}function ot(){return!1}b.event={global:{},add:function(e,n,r,o,a){var s,u,l,c,p,f,d,h,g,m,y,v=b._data(e);if(v){r.handler&&(c=r,r=c.handler,a=c.selector),r.guid||(r.guid=b.guid++),(u=v.events)||(u=v.events={}),(f=v.handle)||(f=v.handle=function(e){return typeof b===i||e&&b.event.triggered===e.type?t:b.event.dispatch.apply(f.elem,arguments)},f.elem=e),n=(n||"").match(w)||[""],l=n.length;while(l--)s=rt.exec(n[l])||[],g=y=s[1],m=(s[2]||"").split(".").sort(),p=b.event.special[g]||{},g=(a?p.delegateType:p.bindType)||g,p=b.event.special[g]||{},d=b.extend({type:g,origType:y,data:o,handler:r,guid:r.guid,selector:a,needsContext:a&&b.expr.match.needsContext.test(a),namespace:m.join(".")},c),(h=u[g])||(h=u[g]=[],h.delegateCount=0,p.setup&&p.setup.call(e,o,m,f)!==!1||(e.addEventListener?e.addEventListener(g,f,!1):e.attachEvent&&e.attachEvent("on"+g,f))),p.add&&(p.add.call(e,d),d.handler.guid||(d.handler.guid=r.guid)),a?h.splice(h.delegateCount++,0,d):h.push(d),b.event.global[g]=!0;e=null}},remove:function(e,t,n,r,i){var o,a,s,u,l,c,p,f,d,h,g,m=b.hasData(e)&&b._data(e);if(m&&(c=m.events)){t=(t||"").match(w)||[""],l=t.length;while(l--)if(s=rt.exec(t[l])||[],d=g=s[1],h=(s[2]||"").split(".").sort(),d){p=b.event.special[d]||{},d=(r?p.delegateType:p.bindType)||d,f=c[d]||[],s=s[2]&&RegExp("(^|\\.)"+h.join("\\.(?:.*\\.|)")+"(\\.|$)"),u=o=f.length;while(o--)a=f[o],!i&&g!==a.origType||n&&n.guid!==a.guid||s&&!s.test(a.namespace)||r&&r!==a.selector&&("**"!==r||!a.selector)||(f.splice(o,1),a.selector&&f.delegateCount--,p.remove&&p.remove.call(e,a));u&&!f.length&&(p.teardown&&p.teardown.call(e,h,m.handle)!==!1||b.removeEvent(e,d,m.handle),delete c[d])}else for(d in c)b.event.remove(e,d+t[l],n,r,!0);b.isEmptyObject(c)&&(delete m.handle,b._removeData(e,"events"))}},trigger:function(n,r,i,a){var s,u,l,c,p,f,d,h=[i||o],g=y.call(n,"type")?n.type:n,m=y.call(n,"namespace")?n.namespace.split("."):[];if(l=f=i=i||o,3!==i.nodeType&&8!==i.nodeType&&!nt.test(g+b.event.triggered)&&(g.indexOf(".")>=0&&(m=g.split("."),g=m.shift(),m.sort()),u=0>g.indexOf(":")&&"on"+g,n=n[b.expando]?n:new b.Event(g,"object"==typeof n&&n),n.isTrigger=!0,n.namespace=m.join("."),n.namespace_re=n.namespace?RegExp("(^|\\.)"+m.join("\\.(?:.*\\.|)")+"(\\.|$)"):null,n.result=t,n.target||(n.target=i),r=null==r?[n]:b.makeArray(r,[n]),p=b.event.special[g]||{},a||!p.trigger||p.trigger.apply(i,r)!==!1)){if(!a&&!p.noBubble&&!b.isWindow(i)){for(c=p.delegateType||g,nt.test(c+g)||(l=l.parentNode);l;l=l.parentNode)h.push(l),f=l;f===(i.ownerDocument||o)&&h.push(f.defaultView||f.parentWindow||e)}d=0;while((l=h[d++])&&!n.isPropagationStopped())n.type=d>1?c:p.bindType||g,s=(b._data(l,"events")||{})[n.type]&&b._data(l,"handle"),s&&s.apply(l,r),s=u&&l[u],s&&b.acceptData(l)&&s.apply&&s.apply(l,r)===!1&&n.preventDefault();if(n.type=g,!(a||n.isDefaultPrevented()||p._default&&p._default.apply(i.ownerDocument,r)!==!1||"click"===g&&b.nodeName(i,"a")||!b.acceptData(i)||!u||!i[g]||b.isWindow(i))){f=i[u],f&&(i[u]=null),b.event.triggered=g;try{i[g]()}catch(v){}b.event.triggered=t,f&&(i[u]=f)}return n.result}},dispatch:function(e){e=b.event.fix(e);var n,r,i,o,a,s=[],u=h.call(arguments),l=(b._data(this,"events")||{})[e.type]||[],c=b.event.special[e.type]||{};if(u[0]=e,e.delegateTarget=this,!c.preDispatch||c.preDispatch.call(this,e)!==!1){s=b.event.handlers.call(this,e,l),n=0;while((o=s[n++])&&!e.isPropagationStopped()){e.currentTarget=o.elem,a=0;while((i=o.handlers[a++])&&!e.isImmediatePropagationStopped())(!e.namespace_re||e.namespace_re.test(i.namespace))&&(e.handleObj=i,e.data=i.data,r=((b.event.special[i.origType]||{}).handle||i.handler).apply(o.elem,u),r!==t&&(e.result=r)===!1&&(e.preventDefault(),e.stopPropagation()))}return c.postDispatch&&c.postDispatch.call(this,e),e.result}},handlers:function(e,n){var r,i,o,a,s=[],u=n.delegateCount,l=e.target;if(u&&l.nodeType&&(!e.button||"click"!==e.type))for(;l!=this;l=l.parentNode||this)if(1===l.nodeType&&(l.disabled!==!0||"click"!==e.type)){for(o=[],a=0;u>a;a++)i=n[a],r=i.selector+" ",o[r]===t&&(o[r]=i.needsContext?b(r,this).index(l)>=0:b.find(r,this,null,[l]).length),o[r]&&o.push(i);o.length&&s.push({elem:l,handlers:o})}return n.length>u&&s.push({elem:this,handlers:n.slice(u)}),s},fix:function(e){if(e[b.expando])return e;var t,n,r,i=e.type,a=e,s=this.fixHooks[i];s||(this.fixHooks[i]=s=tt.test(i)?this.mouseHooks:et.test(i)?this.keyHooks:{}),r=s.props?this.props.concat(s.props):this.props,e=new b.Event(a),t=r.length;while(t--)n=r[t],e[n]=a[n];return e.target||(e.target=a.srcElement||o),3===e.target.nodeType&&(e.target=e.target.parentNode),e.metaKey=!!e.metaKey,s.filter?s.filter(e,a):e},props:"altKey bubbles cancelable ctrlKey currentTarget eventPhase metaKey relatedTarget shiftKey target timeStamp view which".split(" "),fixHooks:{},keyHooks:{props:"char charCode key keyCode".split(" "),filter:function(e,t){return null==e.which&&(e.which=null!=t.charCode?t.charCode:t.keyCode),e}},mouseHooks:{props:"button buttons clientX clientY fromElement offsetX offsetY pageX pageY screenX screenY toElement".split(" "),filter:function(e,n){var r,i,a,s=n.button,u=n.fromElement;return null==e.pageX&&null!=n.clientX&&(i=e.target.ownerDocument||o,a=i.documentElement,r=i.body,e.pageX=n.clientX+(a&&a.scrollLeft||r&&r.scrollLeft||0)-(a&&a.clientLeft||r&&r.clientLeft||0),e.pageY=n.clientY+(a&&a.scrollTop||r&&r.scrollTop||0)-(a&&a.clientTop||r&&r.clientTop||0)),!e.relatedTarget&&u&&(e.relatedTarget=u===e.target?n.toElement:u),e.which||s===t||(e.which=1&s?1:2&s?3:4&s?2:0),e}},special:{load:{noBubble:!0},click:{trigger:function(){return b.nodeName(this,"input")&&"checkbox"===this.type&&this.click?(this.click(),!1):t}},focus:{trigger:function(){if(this!==o.activeElement&&this.focus)try{return this.focus(),!1}catch(e){}},delegateType:"focusin"},blur:{trigger:function(){return this===o.activeElement&&this.blur?(this.blur(),!1):t},delegateType:"focusout"},beforeunload:{postDispatch:function(e){e.result!==t&&(e.originalEvent.returnValue=e.result)}}},simulate:function(e,t,n,r){var i=b.extend(new b.Event,n,{type:e,isSimulated:!0,originalEvent:{}});r?b.event.trigger(i,null,t):b.event.dispatch.call(t,i),i.isDefaultPrevented()&&n.preventDefault()}},b.removeEvent=o.removeEventListener?function(e,t,n){e.removeEventListener&&e.removeEventListener(t,n,!1)}:function(e,t,n){var r="on"+t;e.detachEvent&&(typeof e[r]===i&&(e[r]=null),e.detachEvent(r,n))},b.Event=function(e,n){return this instanceof b.Event?(e&&e.type?(this.originalEvent=e,this.type=e.type,this.isDefaultPrevented=e.defaultPrevented||e.returnValue===!1||e.getPreventDefault&&e.getPreventDefault()?it:ot):this.type=e,n&&b.extend(this,n),this.timeStamp=e&&e.timeStamp||b.now(),this[b.expando]=!0,t):new b.Event(e,n)},b.Event.prototype={isDefaultPrevented:ot,isPropagationStopped:ot,isImmediatePropagationStopped:ot,preventDefault:function(){var e=this.originalEvent;this.isDefaultPrevented=it,e&&(e.preventDefault?e.preventDefault():e.returnValue=!1)},stopPropagation:function(){var e=this.originalEvent;this.isPropagationStopped=it,e&&(e.stopPropagation&&e.stopPropagation(),e.cancelBubble=!0)},stopImmediatePropagation:function(){this.isImmediatePropagationStopped=it,this.stopPropagation()}},b.each({mouseenter:"mouseover",mouseleave:"mouseout"},function(e,t){b.event.special[e]={delegateType:t,bindType:t,handle:function(e){var n,r=this,i=e.relatedTarget,o=e.handleObj; return(!i||i!==r&&!b.contains(r,i))&&(e.type=o.origType,n=o.handler.apply(this,arguments),e.type=t),n}}}),b.support.submitBubbles||(b.event.special.submit={setup:function(){return b.nodeName(this,"form")?!1:(b.event.add(this,"click._submit keypress._submit",function(e){var n=e.target,r=b.nodeName(n,"input")||b.nodeName(n,"button")?n.form:t;r&&!b._data(r,"submitBubbles")&&(b.event.add(r,"submit._submit",function(e){e._submit_bubble=!0}),b._data(r,"submitBubbles",!0))}),t)},postDispatch:function(e){e._submit_bubble&&(delete e._submit_bubble,this.parentNode&&!e.isTrigger&&b.event.simulate("submit",this.parentNode,e,!0))},teardown:function(){return b.nodeName(this,"form")?!1:(b.event.remove(this,"._submit"),t)}}),b.support.changeBubbles||(b.event.special.change={setup:function(){return Z.test(this.nodeName)?(("checkbox"===this.type||"radio"===this.type)&&(b.event.add(this,"propertychange._change",function(e){"checked"===e.originalEvent.propertyName&&(this._just_changed=!0)}),b.event.add(this,"click._change",function(e){this._just_changed&&!e.isTrigger&&(this._just_changed=!1),b.event.simulate("change",this,e,!0)})),!1):(b.event.add(this,"beforeactivate._change",function(e){var t=e.target;Z.test(t.nodeName)&&!b._data(t,"changeBubbles")&&(b.event.add(t,"change._change",function(e){!this.parentNode||e.isSimulated||e.isTrigger||b.event.simulate("change",this.parentNode,e,!0)}),b._data(t,"changeBubbles",!0))}),t)},handle:function(e){var n=e.target;return this!==n||e.isSimulated||e.isTrigger||"radio"!==n.type&&"checkbox"!==n.type?e.handleObj.handler.apply(this,arguments):t},teardown:function(){return b.event.remove(this,"._change"),!Z.test(this.nodeName)}}),b.support.focusinBubbles||b.each({focus:"focusin",blur:"focusout"},function(e,t){var n=0,r=function(e){b.event.simulate(t,e.target,b.event.fix(e),!0)};b.event.special[t]={setup:function(){0===n++&&o.addEventListener(e,r,!0)},teardown:function(){0===--n&&o.removeEventListener(e,r,!0)}}}),b.fn.extend({on:function(e,n,r,i,o){var a,s;if("object"==typeof e){"string"!=typeof n&&(r=r||n,n=t);for(a in e)this.on(a,n,r,e[a],o);return this}if(null==r&&null==i?(i=n,r=n=t):null==i&&("string"==typeof n?(i=r,r=t):(i=r,r=n,n=t)),i===!1)i=ot;else if(!i)return this;return 1===o&&(s=i,i=function(e){return b().off(e),s.apply(this,arguments)},i.guid=s.guid||(s.guid=b.guid++)),this.each(function(){b.event.add(this,e,i,r,n)})},one:function(e,t,n,r){return this.on(e,t,n,r,1)},off:function(e,n,r){var i,o;if(e&&e.preventDefault&&e.handleObj)return i=e.handleObj,b(e.delegateTarget).off(i.namespace?i.origType+"."+i.namespace:i.origType,i.selector,i.handler),this;if("object"==typeof e){for(o in e)this.off(o,n,e[o]);return this}return(n===!1||"function"==typeof n)&&(r=n,n=t),r===!1&&(r=ot),this.each(function(){b.event.remove(this,e,r,n)})},bind:function(e,t,n){return this.on(e,null,t,n)},unbind:function(e,t){return this.off(e,null,t)},delegate:function(e,t,n,r){return this.on(t,e,n,r)},undelegate:function(e,t,n){return 1===arguments.length?this.off(e,"**"):this.off(t,e||"**",n)},trigger:function(e,t){return this.each(function(){b.event.trigger(e,t,this)})},triggerHandler:function(e,n){var r=this[0];return r?b.event.trigger(e,n,r,!0):t}}),function(e,t){var n,r,i,o,a,s,u,l,c,p,f,d,h,g,m,y,v,x="sizzle"+-new Date,w=e.document,T={},N=0,C=0,k=it(),E=it(),S=it(),A=typeof t,j=1<<31,D=[],L=D.pop,H=D.push,q=D.slice,M=D.indexOf||function(e){var t=0,n=this.length;for(;n>t;t++)if(this[t]===e)return t;return-1},_="[\\x20\\t\\r\\n\\f]",F="(?:\\\\.|[\\w-]|[^\\x00-\\xa0])+",O=F.replace("w","w#"),B="([*^$|!~]?=)",P="\\["+_+"*("+F+")"+_+"*(?:"+B+_+"*(?:(['\"])((?:\\\\.|[^\\\\])*?)\\3|("+O+")|)|)"+_+"*\\]",R=":("+F+")(?:\\(((['\"])((?:\\\\.|[^\\\\])*?)\\3|((?:\\\\.|[^\\\\()[\\]]|"+P.replace(3,8)+")*)|.*)\\)|)",W=RegExp("^"+_+"+|((?:^|[^\\\\])(?:\\\\.)*)"+_+"+$","g"),$=RegExp("^"+_+"*,"+_+"*"),I=RegExp("^"+_+"*([\\x20\\t\\r\\n\\f>+~])"+_+"*"),z=RegExp(R),X=RegExp("^"+O+"$"),U={ID:RegExp("^#("+F+")"),CLASS:RegExp("^\\.("+F+")"),NAME:RegExp("^\\[name=['\"]?("+F+")['\"]?\\]"),TAG:RegExp("^("+F.replace("w","w*")+")"),ATTR:RegExp("^"+P),PSEUDO:RegExp("^"+R),CHILD:RegExp("^:(only|first|last|nth|nth-last)-(child|of-type)(?:\\("+_+"*(even|odd|(([+-]|)(\\d*)n|)"+_+"*(?:([+-]|)"+_+"*(\\d+)|))"+_+"*\\)|)","i"),needsContext:RegExp("^"+_+"*[>+~]|:(even|odd|eq|gt|lt|nth|first|last)(?:\\("+_+"*((?:-\\d)?\\d*)"+_+"*\\)|)(?=[^-]|$)","i")},V=/[\x20\t\r\n\f]*[+~]/,Y=/^[^{]+\{\s*\[native code/,J=/^(?:#([\w-]+)|(\w+)|\.([\w-]+))$/,G=/^(?:input|select|textarea|button)$/i,Q=/^h\d$/i,K=/'|\\/g,Z=/\=[\x20\t\r\n\f]*([^'"\]]*)[\x20\t\r\n\f]*\]/g,et=/\\([\da-fA-F]{1,6}[\x20\t\r\n\f]?|.)/g,tt=function(e,t){var n="0x"+t-65536;return n!==n?t:0>n?String.fromCharCode(n+65536):String.fromCharCode(55296|n>>10,56320|1023&n)};try{q.call(w.documentElement.childNodes,0)[0].nodeType}catch(nt){q=function(e){var t,n=[];while(t=this[e++])n.push(t);return n}}function rt(e){return Y.test(e+"")}function it(){var e,t=[];return e=function(n,r){return t.push(n+=" ")>i.cacheLength&&delete e[t.shift()],e[n]=r}}function ot(e){return e[x]=!0,e}function at(e){var t=p.createElement("div");try{return e(t)}catch(n){return!1}finally{t=null}}function st(e,t,n,r){var i,o,a,s,u,l,f,g,m,v;if((t?t.ownerDocument||t:w)!==p&&c(t),t=t||p,n=n||[],!e||"string"!=typeof e)return n;if(1!==(s=t.nodeType)&&9!==s)return[];if(!d&&!r){if(i=J.exec(e))if(a=i[1]){if(9===s){if(o=t.getElementById(a),!o||!o.parentNode)return n;if(o.id===a)return n.push(o),n}else if(t.ownerDocument&&(o=t.ownerDocument.getElementById(a))&&y(t,o)&&o.id===a)return n.push(o),n}else{if(i[2])return H.apply(n,q.call(t.getElementsByTagName(e),0)),n;if((a=i[3])&&T.getByClassName&&t.getElementsByClassName)return H.apply(n,q.call(t.getElementsByClassName(a),0)),n}if(T.qsa&&!h.test(e)){if(f=!0,g=x,m=t,v=9===s&&e,1===s&&"object"!==t.nodeName.toLowerCase()){l=ft(e),(f=t.getAttribute("id"))?g=f.replace(K,"\\$&"):t.setAttribute("id",g),g="[id='"+g+"'] ",u=l.length;while(u--)l[u]=g+dt(l[u]);m=V.test(e)&&t.parentNode||t,v=l.join(",")}if(v)try{return H.apply(n,q.call(m.querySelectorAll(v),0)),n}catch(b){}finally{f||t.removeAttribute("id")}}}return wt(e.replace(W,"$1"),t,n,r)}a=st.isXML=function(e){var t=e&&(e.ownerDocument||e).documentElement;return t?"HTML"!==t.nodeName:!1},c=st.setDocument=function(e){var n=e?e.ownerDocument||e:w;return n!==p&&9===n.nodeType&&n.documentElement?(p=n,f=n.documentElement,d=a(n),T.tagNameNoComments=at(function(e){return e.appendChild(n.createComment("")),!e.getElementsByTagName("*").length}),T.attributes=at(function(e){e.innerHTML="<select></select>";var t=typeof e.lastChild.getAttribute("multiple");return"boolean"!==t&&"string"!==t}),T.getByClassName=at(function(e){return e.innerHTML="<div class='hidden e'></div><div class='hidden'></div>",e.getElementsByClassName&&e.getElementsByClassName("e").length?(e.lastChild.className="e",2===e.getElementsByClassName("e").length):!1}),T.getByName=at(function(e){e.id=x+0,e.innerHTML="<a name='"+x+"'></a><div name='"+x+"'></div>",f.insertBefore(e,f.firstChild);var t=n.getElementsByName&&n.getElementsByName(x).length===2+n.getElementsByName(x+0).length;return T.getIdNotName=!n.getElementById(x),f.removeChild(e),t}),i.attrHandle=at(function(e){return e.innerHTML="<a href='#'></a>",e.firstChild&&typeof e.firstChild.getAttribute!==A&&"#"===e.firstChild.getAttribute("href")})?{}:{href:function(e){return e.getAttribute("href",2)},type:function(e){return e.getAttribute("type")}},T.getIdNotName?(i.find.ID=function(e,t){if(typeof t.getElementById!==A&&!d){var n=t.getElementById(e);return n&&n.parentNode?[n]:[]}},i.filter.ID=function(e){var t=e.replace(et,tt);return function(e){return e.getAttribute("id")===t}}):(i.find.ID=function(e,n){if(typeof n.getElementById!==A&&!d){var r=n.getElementById(e);return r?r.id===e||typeof r.getAttributeNode!==A&&r.getAttributeNode("id").value===e?[r]:t:[]}},i.filter.ID=function(e){var t=e.replace(et,tt);return function(e){var n=typeof e.getAttributeNode!==A&&e.getAttributeNode("id");return n&&n.value===t}}),i.find.TAG=T.tagNameNoComments?function(e,n){return typeof n.getElementsByTagName!==A?n.getElementsByTagName(e):t}:function(e,t){var n,r=[],i=0,o=t.getElementsByTagName(e);if("*"===e){while(n=o[i++])1===n.nodeType&&r.push(n);return r}return o},i.find.NAME=T.getByName&&function(e,n){return typeof n.getElementsByName!==A?n.getElementsByName(name):t},i.find.CLASS=T.getByClassName&&function(e,n){return typeof n.getElementsByClassName===A||d?t:n.getElementsByClassName(e)},g=[],h=[":focus"],(T.qsa=rt(n.querySelectorAll))&&(at(function(e){e.innerHTML="<select><option selected=''></option></select>",e.querySelectorAll("[selected]").length||h.push("\\["+_+"*(?:checked|disabled|ismap|multiple|readonly|selected|value)"),e.querySelectorAll(":checked").length||h.push(":checked")}),at(function(e){e.innerHTML="<input type='hidden' i=''/>",e.querySelectorAll("[i^='']").length&&h.push("[*^$]="+_+"*(?:\"\"|'')"),e.querySelectorAll(":enabled").length||h.push(":enabled",":disabled"),e.querySelectorAll("*,:x"),h.push(",.*:")})),(T.matchesSelector=rt(m=f.matchesSelector||f.mozMatchesSelector||f.webkitMatchesSelector||f.oMatchesSelector||f.msMatchesSelector))&&at(function(e){T.disconnectedMatch=m.call(e,"div"),m.call(e,"[s!='']:x"),g.push("!=",R)}),h=RegExp(h.join("|")),g=RegExp(g.join("|")),y=rt(f.contains)||f.compareDocumentPosition?function(e,t){var n=9===e.nodeType?e.documentElement:e,r=t&&t.parentNode;return e===r||!(!r||1!==r.nodeType||!(n.contains?n.contains(r):e.compareDocumentPosition&&16&e.compareDocumentPosition(r)))}:function(e,t){if(t)while(t=t.parentNode)if(t===e)return!0;return!1},v=f.compareDocumentPosition?function(e,t){var r;return e===t?(u=!0,0):(r=t.compareDocumentPosition&&e.compareDocumentPosition&&e.compareDocumentPosition(t))?1&r||e.parentNode&&11===e.parentNode.nodeType?e===n||y(w,e)?-1:t===n||y(w,t)?1:0:4&r?-1:1:e.compareDocumentPosition?-1:1}:function(e,t){var r,i=0,o=e.parentNode,a=t.parentNode,s=[e],l=[t];if(e===t)return u=!0,0;if(!o||!a)return e===n?-1:t===n?1:o?-1:a?1:0;if(o===a)return ut(e,t);r=e;while(r=r.parentNode)s.unshift(r);r=t;while(r=r.parentNode)l.unshift(r);while(s[i]===l[i])i++;return i?ut(s[i],l[i]):s[i]===w?-1:l[i]===w?1:0},u=!1,[0,0].sort(v),T.detectDuplicates=u,p):p},st.matches=function(e,t){return st(e,null,null,t)},st.matchesSelector=function(e,t){if((e.ownerDocument||e)!==p&&c(e),t=t.replace(Z,"='$1']"),!(!T.matchesSelector||d||g&&g.test(t)||h.test(t)))try{var n=m.call(e,t);if(n||T.disconnectedMatch||e.document&&11!==e.document.nodeType)return n}catch(r){}return st(t,p,null,[e]).length>0},st.contains=function(e,t){return(e.ownerDocument||e)!==p&&c(e),y(e,t)},st.attr=function(e,t){var n;return(e.ownerDocument||e)!==p&&c(e),d||(t=t.toLowerCase()),(n=i.attrHandle[t])?n(e):d||T.attributes?e.getAttribute(t):((n=e.getAttributeNode(t))||e.getAttribute(t))&&e[t]===!0?t:n&&n.specified?n.value:null},st.error=function(e){throw Error("Syntax error, unrecognized expression: "+e)},st.uniqueSort=function(e){var t,n=[],r=1,i=0;if(u=!T.detectDuplicates,e.sort(v),u){for(;t=e[r];r++)t===e[r-1]&&(i=n.push(r));while(i--)e.splice(n[i],1)}return e};function ut(e,t){var n=t&&e,r=n&&(~t.sourceIndex||j)-(~e.sourceIndex||j);if(r)return r;if(n)while(n=n.nextSibling)if(n===t)return-1;return e?1:-1}function lt(e){return function(t){var n=t.nodeName.toLowerCase();return"input"===n&&t.type===e}}function ct(e){return function(t){var n=t.nodeName.toLowerCase();return("input"===n||"button"===n)&&t.type===e}}function pt(e){return ot(function(t){return t=+t,ot(function(n,r){var i,o=e([],n.length,t),a=o.length;while(a--)n[i=o[a]]&&(n[i]=!(r[i]=n[i]))})})}o=st.getText=function(e){var t,n="",r=0,i=e.nodeType;if(i){if(1===i||9===i||11===i){if("string"==typeof e.textContent)return e.textContent;for(e=e.firstChild;e;e=e.nextSibling)n+=o(e)}else if(3===i||4===i)return e.nodeValue}else for(;t=e[r];r++)n+=o(t);return n},i=st.selectors={cacheLength:50,createPseudo:ot,match:U,find:{},relative:{">":{dir:"parentNode",first:!0}," ":{dir:"parentNode"},"+":{dir:"previousSibling",first:!0},"~":{dir:"previousSibling"}},preFilter:{ATTR:function(e){return e[1]=e[1].replace(et,tt),e[3]=(e[4]||e[5]||"").replace(et,tt),"~="===e[2]&&(e[3]=" "+e[3]+" "),e.slice(0,4)},CHILD:function(e){return e[1]=e[1].toLowerCase(),"nth"===e[1].slice(0,3)?(e[3]||st.error(e[0]),e[4]=+(e[4]?e[5]+(e[6]||1):2*("even"===e[3]||"odd"===e[3])),e[5]=+(e[7]+e[8]||"odd"===e[3])):e[3]&&st.error(e[0]),e},PSEUDO:function(e){var t,n=!e[5]&&e[2];return U.CHILD.test(e[0])?null:(e[4]?e[2]=e[4]:n&&z.test(n)&&(t=ft(n,!0))&&(t=n.indexOf(")",n.length-t)-n.length)&&(e[0]=e[0].slice(0,t),e[2]=n.slice(0,t)),e.slice(0,3))}},filter:{TAG:function(e){return"*"===e?function(){return!0}:(e=e.replace(et,tt).toLowerCase(),function(t){return t.nodeName&&t.nodeName.toLowerCase()===e})},CLASS:function(e){var t=k[e+" "];return t||(t=RegExp("(^|"+_+")"+e+"("+_+"|$)"))&&k(e,function(e){return t.test(e.className||typeof e.getAttribute!==A&&e.getAttribute("class")||"")})},ATTR:function(e,t,n){return function(r){var i=st.attr(r,e);return null==i?"!="===t:t?(i+="","="===t?i===n:"!="===t?i!==n:"^="===t?n&&0===i.indexOf(n):"*="===t?n&&i.indexOf(n)>-1:"$="===t?n&&i.slice(-n.length)===n:"~="===t?(" "+i+" ").indexOf(n)>-1:"|="===t?i===n||i.slice(0,n.length+1)===n+"-":!1):!0}},CHILD:function(e,t,n,r,i){var o="nth"!==e.slice(0,3),a="last"!==e.slice(-4),s="of-type"===t;return 1===r&&0===i?function(e){return!!e.parentNode}:function(t,n,u){var l,c,p,f,d,h,g=o!==a?"nextSibling":"previousSibling",m=t.parentNode,y=s&&t.nodeName.toLowerCase(),v=!u&&!s;if(m){if(o){while(g){p=t;while(p=p[g])if(s?p.nodeName.toLowerCase()===y:1===p.nodeType)return!1;h=g="only"===e&&!h&&"nextSibling"}return!0}if(h=[a?m.firstChild:m.lastChild],a&&v){c=m[x]||(m[x]={}),l=c[e]||[],d=l[0]===N&&l[1],f=l[0]===N&&l[2],p=d&&m.childNodes[d];while(p=++d&&p&&p[g]||(f=d=0)||h.pop())if(1===p.nodeType&&++f&&p===t){c[e]=[N,d,f];break}}else if(v&&(l=(t[x]||(t[x]={}))[e])&&l[0]===N)f=l[1];else while(p=++d&&p&&p[g]||(f=d=0)||h.pop())if((s?p.nodeName.toLowerCase()===y:1===p.nodeType)&&++f&&(v&&((p[x]||(p[x]={}))[e]=[N,f]),p===t))break;return f-=i,f===r||0===f%r&&f/r>=0}}},PSEUDO:function(e,t){var n,r=i.pseudos[e]||i.setFilters[e.toLowerCase()]||st.error("unsupported pseudo: "+e);return r[x]?r(t):r.length>1?(n=[e,e,"",t],i.setFilters.hasOwnProperty(e.toLowerCase())?ot(function(e,n){var i,o=r(e,t),a=o.length;while(a--)i=M.call(e,o[a]),e[i]=!(n[i]=o[a])}):function(e){return r(e,0,n)}):r}},pseudos:{not:ot(function(e){var t=[],n=[],r=s(e.replace(W,"$1"));return r[x]?ot(function(e,t,n,i){var o,a=r(e,null,i,[]),s=e.length;while(s--)(o=a[s])&&(e[s]=!(t[s]=o))}):function(e,i,o){return t[0]=e,r(t,null,o,n),!n.pop()}}),has:ot(function(e){return function(t){return st(e,t).length>0}}),contains:ot(function(e){return function(t){return(t.textContent||t.innerText||o(t)).indexOf(e)>-1}}),lang:ot(function(e){return X.test(e||"")||st.error("unsupported lang: "+e),e=e.replace(et,tt).toLowerCase(),function(t){var n;do if(n=d?t.getAttribute("xml:lang")||t.getAttribute("lang"):t.lang)return n=n.toLowerCase(),n===e||0===n.indexOf(e+"-");while((t=t.parentNode)&&1===t.nodeType);return!1}}),target:function(t){var n=e.location&&e.location.hash;return n&&n.slice(1)===t.id},root:function(e){return e===f},focus:function(e){return e===p.activeElement&&(!p.hasFocus||p.hasFocus())&&!!(e.type||e.href||~e.tabIndex)},enabled:function(e){return e.disabled===!1},disabled:function(e){return e.disabled===!0},checked:function(e){var t=e.nodeName.toLowerCase();return"input"===t&&!!e.checked||"option"===t&&!!e.selected},selected:function(e){return e.parentNode&&e.parentNode.selectedIndex,e.selected===!0},empty:function(e){for(e=e.firstChild;e;e=e.nextSibling)if(e.nodeName>"@"||3===e.nodeType||4===e.nodeType)return!1;return!0},parent:function(e){return!i.pseudos.empty(e)},header:function(e){return Q.test(e.nodeName)},input:function(e){return G.test(e.nodeName)},button:function(e){var t=e.nodeName.toLowerCase();return"input"===t&&"button"===e.type||"button"===t},text:function(e){var t;return"input"===e.nodeName.toLowerCase()&&"text"===e.type&&(null==(t=e.getAttribute("type"))||t.toLowerCase()===e.type)},first:pt(function(){return[0]}),last:pt(function(e,t){return[t-1]}),eq:pt(function(e,t,n){return[0>n?n+t:n]}),even:pt(function(e,t){var n=0;for(;t>n;n+=2)e.push(n);return e}),odd:pt(function(e,t){var n=1;for(;t>n;n+=2)e.push(n);return e}),lt:pt(function(e,t,n){var r=0>n?n+t:n;for(;--r>=0;)e.push(r);return e}),gt:pt(function(e,t,n){var r=0>n?n+t:n;for(;t>++r;)e.push(r);return e})}};for(n in{radio:!0,checkbox:!0,file:!0,password:!0,image:!0})i.pseudos[n]=lt(n);for(n in{submit:!0,reset:!0})i.pseudos[n]=ct(n);function ft(e,t){var n,r,o,a,s,u,l,c=E[e+" "];if(c)return t?0:c.slice(0);s=e,u=[],l=i.preFilter;while(s){(!n||(r=$.exec(s)))&&(r&&(s=s.slice(r[0].length)||s),u.push(o=[])),n=!1,(r=I.exec(s))&&(n=r.shift(),o.push({value:n,type:r[0].replace(W," ")}),s=s.slice(n.length));for(a in i.filter)!(r=U[a].exec(s))||l[a]&&!(r=l[a](r))||(n=r.shift(),o.push({value:n,type:a,matches:r}),s=s.slice(n.length));if(!n)break}return t?s.length:s?st.error(e):E(e,u).slice(0)}function dt(e){var t=0,n=e.length,r="";for(;n>t;t++)r+=e[t].value;return r}function ht(e,t,n){var i=t.dir,o=n&&"parentNode"===i,a=C++;return t.first?function(t,n,r){while(t=t[i])if(1===t.nodeType||o)return e(t,n,r)}:function(t,n,s){var u,l,c,p=N+" "+a;if(s){while(t=t[i])if((1===t.nodeType||o)&&e(t,n,s))return!0}else while(t=t[i])if(1===t.nodeType||o)if(c=t[x]||(t[x]={}),(l=c[i])&&l[0]===p){if((u=l[1])===!0||u===r)return u===!0}else if(l=c[i]=[p],l[1]=e(t,n,s)||r,l[1]===!0)return!0}}function gt(e){return e.length>1?function(t,n,r){var i=e.length;while(i--)if(!e[i](t,n,r))return!1;return!0}:e[0]}function mt(e,t,n,r,i){var o,a=[],s=0,u=e.length,l=null!=t;for(;u>s;s++)(o=e[s])&&(!n||n(o,r,i))&&(a.push(o),l&&t.push(s));return a}function yt(e,t,n,r,i,o){return r&&!r[x]&&(r=yt(r)),i&&!i[x]&&(i=yt(i,o)),ot(function(o,a,s,u){var l,c,p,f=[],d=[],h=a.length,g=o||xt(t||"*",s.nodeType?[s]:s,[]),m=!e||!o&&t?g:mt(g,f,e,s,u),y=n?i||(o?e:h||r)?[]:a:m;if(n&&n(m,y,s,u),r){l=mt(y,d),r(l,[],s,u),c=l.length;while(c--)(p=l[c])&&(y[d[c]]=!(m[d[c]]=p))}if(o){if(i||e){if(i){l=[],c=y.length;while(c--)(p=y[c])&&l.push(m[c]=p);i(null,y=[],l,u)}c=y.length;while(c--)(p=y[c])&&(l=i?M.call(o,p):f[c])>-1&&(o[l]=!(a[l]=p))}}else y=mt(y===a?y.splice(h,y.length):y),i?i(null,a,y,u):H.apply(a,y)})}function vt(e){var t,n,r,o=e.length,a=i.relative[e[0].type],s=a||i.relative[" "],u=a?1:0,c=ht(function(e){return e===t},s,!0),p=ht(function(e){return M.call(t,e)>-1},s,!0),f=[function(e,n,r){return!a&&(r||n!==l)||((t=n).nodeType?c(e,n,r):p(e,n,r))}];for(;o>u;u++)if(n=i.relative[e[u].type])f=[ht(gt(f),n)];else{if(n=i.filter[e[u].type].apply(null,e[u].matches),n[x]){for(r=++u;o>r;r++)if(i.relative[e[r].type])break;return yt(u>1&&gt(f),u>1&&dt(e.slice(0,u-1)).replace(W,"$1"),n,r>u&&vt(e.slice(u,r)),o>r&&vt(e=e.slice(r)),o>r&&dt(e))}f.push(n)}return gt(f)}function bt(e,t){var n=0,o=t.length>0,a=e.length>0,s=function(s,u,c,f,d){var h,g,m,y=[],v=0,b="0",x=s&&[],w=null!=d,T=l,C=s||a&&i.find.TAG("*",d&&u.parentNode||u),k=N+=null==T?1:Math.random()||.1;for(w&&(l=u!==p&&u,r=n);null!=(h=C[b]);b++){if(a&&h){g=0;while(m=e[g++])if(m(h,u,c)){f.push(h);break}w&&(N=k,r=++n)}o&&((h=!m&&h)&&v--,s&&x.push(h))}if(v+=b,o&&b!==v){g=0;while(m=t[g++])m(x,y,u,c);if(s){if(v>0)while(b--)x[b]||y[b]||(y[b]=L.call(f));y=mt(y)}H.apply(f,y),w&&!s&&y.length>0&&v+t.length>1&&st.uniqueSort(f)}return w&&(N=k,l=T),x};return o?ot(s):s}s=st.compile=function(e,t){var n,r=[],i=[],o=S[e+" "];if(!o){t||(t=ft(e)),n=t.length;while(n--)o=vt(t[n]),o[x]?r.push(o):i.push(o);o=S(e,bt(i,r))}return o};function xt(e,t,n){var r=0,i=t.length;for(;i>r;r++)st(e,t[r],n);return n}function wt(e,t,n,r){var o,a,u,l,c,p=ft(e);if(!r&&1===p.length){if(a=p[0]=p[0].slice(0),a.length>2&&"ID"===(u=a[0]).type&&9===t.nodeType&&!d&&i.relative[a[1].type]){if(t=i.find.ID(u.matches[0].replace(et,tt),t)[0],!t)return n;e=e.slice(a.shift().value.length)}o=U.needsContext.test(e)?0:a.length;while(o--){if(u=a[o],i.relative[l=u.type])break;if((c=i.find[l])&&(r=c(u.matches[0].replace(et,tt),V.test(a[0].type)&&t.parentNode||t))){if(a.splice(o,1),e=r.length&&dt(a),!e)return H.apply(n,q.call(r,0)),n;break}}}return s(e,p)(r,t,d,n,V.test(e)),n}i.pseudos.nth=i.pseudos.eq;function Tt(){}i.filters=Tt.prototype=i.pseudos,i.setFilters=new Tt,c(),st.attr=b.attr,b.find=st,b.expr=st.selectors,b.expr[":"]=b.expr.pseudos,b.unique=st.uniqueSort,b.text=st.getText,b.isXMLDoc=st.isXML,b.contains=st.contains}(e);var at=/Until$/,st=/^(?:parents|prev(?:Until|All))/,ut=/^.[^:#\[\.,]*$/,lt=b.expr.match.needsContext,ct={children:!0,contents:!0,next:!0,prev:!0};b.fn.extend({find:function(e){var t,n,r,i=this.length;if("string"!=typeof e)return r=this,this.pushStack(b(e).filter(function(){for(t=0;i>t;t++)if(b.contains(r[t],this))return!0}));for(n=[],t=0;i>t;t++)b.find(e,this[t],n);return n=this.pushStack(i>1?b.unique(n):n),n.selector=(this.selector?this.selector+" ":"")+e,n},has:function(e){var t,n=b(e,this),r=n.length;return this.filter(function(){for(t=0;r>t;t++)if(b.contains(this,n[t]))return!0})},not:function(e){return this.pushStack(ft(this,e,!1))},filter:function(e){return this.pushStack(ft(this,e,!0))},is:function(e){return!!e&&("string"==typeof e?lt.test(e)?b(e,this.context).index(this[0])>=0:b.filter(e,this).length>0:this.filter(e).length>0)},closest:function(e,t){var n,r=0,i=this.length,o=[],a=lt.test(e)||"string"!=typeof e?b(e,t||this.context):0;for(;i>r;r++){n=this[r];while(n&&n.ownerDocument&&n!==t&&11!==n.nodeType){if(a?a.index(n)>-1:b.find.matchesSelector(n,e)){o.push(n);break}n=n.parentNode}}return this.pushStack(o.length>1?b.unique(o):o)},index:function(e){return e?"string"==typeof e?b.inArray(this[0],b(e)):b.inArray(e.jquery?e[0]:e,this):this[0]&&this[0].parentNode?this.first().prevAll().length:-1},add:function(e,t){var n="string"==typeof e?b(e,t):b.makeArray(e&&e.nodeType?[e]:e),r=b.merge(this.get(),n);return this.pushStack(b.unique(r))},addBack:function(e){return this.add(null==e?this.prevObject:this.prevObject.filter(e))}}),b.fn.andSelf=b.fn.addBack;function pt(e,t){do e=e[t];while(e&&1!==e.nodeType);return e}b.each({parent:function(e){var t=e.parentNode;return t&&11!==t.nodeType?t:null},parents:function(e){return b.dir(e,"parentNode")},parentsUntil:function(e,t,n){return b.dir(e,"parentNode",n)},next:function(e){return pt(e,"nextSibling")},prev:function(e){return pt(e,"previousSibling")},nextAll:function(e){return b.dir(e,"nextSibling")},prevAll:function(e){return b.dir(e,"previousSibling")},nextUntil:function(e,t,n){return b.dir(e,"nextSibling",n)},prevUntil:function(e,t,n){return b.dir(e,"previousSibling",n)},siblings:function(e){return b.sibling((e.parentNode||{}).firstChild,e)},children:function(e){return b.sibling(e.firstChild)},contents:function(e){return b.nodeName(e,"iframe")?e.contentDocument||e.contentWindow.document:b.merge([],e.childNodes)}},function(e,t){b.fn[e]=function(n,r){var i=b.map(this,t,n);return at.test(e)||(r=n),r&&"string"==typeof r&&(i=b.filter(r,i)),i=this.length>1&&!ct[e]?b.unique(i):i,this.length>1&&st.test(e)&&(i=i.reverse()),this.pushStack(i)}}),b.extend({filter:function(e,t,n){return n&&(e=":not("+e+")"),1===t.length?b.find.matchesSelector(t[0],e)?[t[0]]:[]:b.find.matches(e,t)},dir:function(e,n,r){var i=[],o=e[n];while(o&&9!==o.nodeType&&(r===t||1!==o.nodeType||!b(o).is(r)))1===o.nodeType&&i.push(o),o=o[n];return i},sibling:function(e,t){var n=[];for(;e;e=e.nextSibling)1===e.nodeType&&e!==t&&n.push(e);return n}});function ft(e,t,n){if(t=t||0,b.isFunction(t))return b.grep(e,function(e,r){var i=!!t.call(e,r,e);return i===n});if(t.nodeType)return b.grep(e,function(e){return e===t===n});if("string"==typeof t){var r=b.grep(e,function(e){return 1===e.nodeType});if(ut.test(t))return b.filter(t,r,!n);t=b.filter(t,r)}return b.grep(e,function(e){return b.inArray(e,t)>=0===n})}function dt(e){var t=ht.split("|"),n=e.createDocumentFragment();if(n.createElement)while(t.length)n.createElement(t.pop());return n}var ht="abbr|article|aside|audio|bdi|canvas|data|datalist|details|figcaption|figure|footer|header|hgroup|mark|meter|nav|output|progress|section|summary|time|video",gt=/ jQuery\d+="(?:null|\d+)"/g,mt=RegExp("<(?:"+ht+")[\\s/>]","i"),yt=/^\s+/,vt=/<(?!area|br|col|embed|hr|img|input|link|meta|param)(([\w:]+)[^>]*)\/>/gi,bt=/<([\w:]+)/,xt=/<tbody/i,wt=/<|&#?\w+;/,Tt=/<(?:script|style|link)/i,Nt=/^(?:checkbox|radio)$/i,Ct=/checked\s*(?:[^=]|=\s*.checked.)/i,kt=/^$|\/(?:java|ecma)script/i,Et=/^true\/(.*)/,St=/^\s*<!(?:\[CDATA\[|--)|(?:\]\]|--)>\s*$/g,At={option:[1,"<select multiple='multiple'>","</select>"],legend:[1,"<fieldset>","</fieldset>"],area:[1,"<map>","</map>"],param:[1,"<object>","</object>"],thead:[1,"<table>","</table>"],tr:[2,"<table><tbody>","</tbody></table>"],col:[2,"<table><tbody></tbody><colgroup>","</colgroup></table>"],td:[3,"<table><tbody><tr>","</tr></tbody></table>"],_default:b.support.htmlSerialize?[0,"",""]:[1,"X<div>","</div>"]},jt=dt(o),Dt=jt.appendChild(o.createElement("div"));At.optgroup=At.option,At.tbody=At.tfoot=At.colgroup=At.caption=At.thead,At.th=At.td,b.fn.extend({text:function(e){return b.access(this,function(e){return e===t?b.text(this):this.empty().append((this[0]&&this[0].ownerDocument||o).createTextNode(e))},null,e,arguments.length)},wrapAll:function(e){if(b.isFunction(e))return this.each(function(t){b(this).wrapAll(e.call(this,t))});if(this[0]){var t=b(e,this[0].ownerDocument).eq(0).clone(!0);this[0].parentNode&&t.insertBefore(this[0]),t.map(function(){var e=this;while(e.firstChild&&1===e.firstChild.nodeType)e=e.firstChild;return e}).append(this)}return this},wrapInner:function(e){return b.isFunction(e)?this.each(function(t){b(this).wrapInner(e.call(this,t))}):this.each(function(){var t=b(this),n=t.contents();n.length?n.wrapAll(e):t.append(e)})},wrap:function(e){var t=b.isFunction(e);return this.each(function(n){b(this).wrapAll(t?e.call(this,n):e)})},unwrap:function(){return this.parent().each(function(){b.nodeName(this,"body")||b(this).replaceWith(this.childNodes)}).end()},append:function(){return this.domManip(arguments,!0,function(e){(1===this.nodeType||11===this.nodeType||9===this.nodeType)&&this.appendChild(e)})},prepend:function(){return this.domManip(arguments,!0,function(e){(1===this.nodeType||11===this.nodeType||9===this.nodeType)&&this.insertBefore(e,this.firstChild)})},before:function(){return this.domManip(arguments,!1,function(e){this.parentNode&&this.parentNode.insertBefore(e,this)})},after:function(){return this.domManip(arguments,!1,function(e){this.parentNode&&this.parentNode.insertBefore(e,this.nextSibling)})},remove:function(e,t){var n,r=0;for(;null!=(n=this[r]);r++)(!e||b.filter(e,[n]).length>0)&&(t||1!==n.nodeType||b.cleanData(Ot(n)),n.parentNode&&(t&&b.contains(n.ownerDocument,n)&&Mt(Ot(n,"script")),n.parentNode.removeChild(n)));return this},empty:function(){var e,t=0;for(;null!=(e=this[t]);t++){1===e.nodeType&&b.cleanData(Ot(e,!1));while(e.firstChild)e.removeChild(e.firstChild);e.options&&b.nodeName(e,"select")&&(e.options.length=0)}return this},clone:function(e,t){return e=null==e?!1:e,t=null==t?e:t,this.map(function(){return b.clone(this,e,t)})},html:function(e){return b.access(this,function(e){var n=this[0]||{},r=0,i=this.length;if(e===t)return 1===n.nodeType?n.innerHTML.replace(gt,""):t;if(!("string"!=typeof e||Tt.test(e)||!b.support.htmlSerialize&&mt.test(e)||!b.support.leadingWhitespace&&yt.test(e)||At[(bt.exec(e)||["",""])[1].toLowerCase()])){e=e.replace(vt,"<$1></$2>");try{for(;i>r;r++)n=this[r]||{},1===n.nodeType&&(b.cleanData(Ot(n,!1)),n.innerHTML=e);n=0}catch(o){}}n&&this.empty().append(e)},null,e,arguments.length)},replaceWith:function(e){var t=b.isFunction(e);return t||"string"==typeof e||(e=b(e).not(this).detach()),this.domManip([e],!0,function(e){var t=this.nextSibling,n=this.parentNode;n&&(b(this).remove(),n.insertBefore(e,t))})},detach:function(e){return this.remove(e,!0)},domManip:function(e,n,r){e=f.apply([],e);var i,o,a,s,u,l,c=0,p=this.length,d=this,h=p-1,g=e[0],m=b.isFunction(g);if(m||!(1>=p||"string"!=typeof g||b.support.checkClone)&&Ct.test(g))return this.each(function(i){var o=d.eq(i);m&&(e[0]=g.call(this,i,n?o.html():t)),o.domManip(e,n,r)});if(p&&(l=b.buildFragment(e,this[0].ownerDocument,!1,this),i=l.firstChild,1===l.childNodes.length&&(l=i),i)){for(n=n&&b.nodeName(i,"tr"),s=b.map(Ot(l,"script"),Ht),a=s.length;p>c;c++)o=l,c!==h&&(o=b.clone(o,!0,!0),a&&b.merge(s,Ot(o,"script"))),r.call(n&&b.nodeName(this[c],"table")?Lt(this[c],"tbody"):this[c],o,c);if(a)for(u=s[s.length-1].ownerDocument,b.map(s,qt),c=0;a>c;c++)o=s[c],kt.test(o.type||"")&&!b._data(o,"globalEval")&&b.contains(u,o)&&(o.src?b.ajax({url:o.src,type:"GET",dataType:"script",async:!1,global:!1,"throws":!0}):b.globalEval((o.text||o.textContent||o.innerHTML||"").replace(St,"")));l=i=null}return this}});function Lt(e,t){return e.getElementsByTagName(t)[0]||e.appendChild(e.ownerDocument.createElement(t))}function Ht(e){var t=e.getAttributeNode("type");return e.type=(t&&t.specified)+"/"+e.type,e}function qt(e){var t=Et.exec(e.type);return t?e.type=t[1]:e.removeAttribute("type"),e}function Mt(e,t){var n,r=0;for(;null!=(n=e[r]);r++)b._data(n,"globalEval",!t||b._data(t[r],"globalEval"))}function _t(e,t){if(1===t.nodeType&&b.hasData(e)){var n,r,i,o=b._data(e),a=b._data(t,o),s=o.events;if(s){delete a.handle,a.events={};for(n in s)for(r=0,i=s[n].length;i>r;r++)b.event.add(t,n,s[n][r])}a.data&&(a.data=b.extend({},a.data))}}function Ft(e,t){var n,r,i;if(1===t.nodeType){if(n=t.nodeName.toLowerCase(),!b.support.noCloneEvent&&t[b.expando]){i=b._data(t);for(r in i.events)b.removeEvent(t,r,i.handle);t.removeAttribute(b.expando)}"script"===n&&t.text!==e.text?(Ht(t).text=e.text,qt(t)):"object"===n?(t.parentNode&&(t.outerHTML=e.outerHTML),b.support.html5Clone&&e.innerHTML&&!b.trim(t.innerHTML)&&(t.innerHTML=e.innerHTML)):"input"===n&&Nt.test(e.type)?(t.defaultChecked=t.checked=e.checked,t.value!==e.value&&(t.value=e.value)):"option"===n?t.defaultSelected=t.selected=e.defaultSelected:("input"===n||"textarea"===n)&&(t.defaultValue=e.defaultValue)}}b.each({appendTo:"append",prependTo:"prepend",insertBefore:"before",insertAfter:"after",replaceAll:"replaceWith"},function(e,t){b.fn[e]=function(e){var n,r=0,i=[],o=b(e),a=o.length-1;for(;a>=r;r++)n=r===a?this:this.clone(!0),b(o[r])[t](n),d.apply(i,n.get());return this.pushStack(i)}});function Ot(e,n){var r,o,a=0,s=typeof e.getElementsByTagName!==i?e.getElementsByTagName(n||"*"):typeof e.querySelectorAll!==i?e.querySelectorAll(n||"*"):t;if(!s)for(s=[],r=e.childNodes||e;null!=(o=r[a]);a++)!n||b.nodeName(o,n)?s.push(o):b.merge(s,Ot(o,n));return n===t||n&&b.nodeName(e,n)?b.merge([e],s):s}function Bt(e){Nt.test(e.type)&&(e.defaultChecked=e.checked)}b.extend({clone:function(e,t,n){var r,i,o,a,s,u=b.contains(e.ownerDocument,e);if(b.support.html5Clone||b.isXMLDoc(e)||!mt.test("<"+e.nodeName+">")?o=e.cloneNode(!0):(Dt.innerHTML=e.outerHTML,Dt.removeChild(o=Dt.firstChild)),!(b.support.noCloneEvent&&b.support.noCloneChecked||1!==e.nodeType&&11!==e.nodeType||b.isXMLDoc(e)))for(r=Ot(o),s=Ot(e),a=0;null!=(i=s[a]);++a)r[a]&&Ft(i,r[a]);if(t)if(n)for(s=s||Ot(e),r=r||Ot(o),a=0;null!=(i=s[a]);a++)_t(i,r[a]);else _t(e,o);return r=Ot(o,"script"),r.length>0&&Mt(r,!u&&Ot(e,"script")),r=s=i=null,o},buildFragment:function(e,t,n,r){var i,o,a,s,u,l,c,p=e.length,f=dt(t),d=[],h=0;for(;p>h;h++)if(o=e[h],o||0===o)if("object"===b.type(o))b.merge(d,o.nodeType?[o]:o);else if(wt.test(o)){s=s||f.appendChild(t.createElement("div")),u=(bt.exec(o)||["",""])[1].toLowerCase(),c=At[u]||At._default,s.innerHTML=c[1]+o.replace(vt,"<$1></$2>")+c[2],i=c[0];while(i--)s=s.lastChild;if(!b.support.leadingWhitespace&&yt.test(o)&&d.push(t.createTextNode(yt.exec(o)[0])),!b.support.tbody){o="table"!==u||xt.test(o)?"<table>"!==c[1]||xt.test(o)?0:s:s.firstChild,i=o&&o.childNodes.length;while(i--)b.nodeName(l=o.childNodes[i],"tbody")&&!l.childNodes.length&&o.removeChild(l) }b.merge(d,s.childNodes),s.textContent="";while(s.firstChild)s.removeChild(s.firstChild);s=f.lastChild}else d.push(t.createTextNode(o));s&&f.removeChild(s),b.support.appendChecked||b.grep(Ot(d,"input"),Bt),h=0;while(o=d[h++])if((!r||-1===b.inArray(o,r))&&(a=b.contains(o.ownerDocument,o),s=Ot(f.appendChild(o),"script"),a&&Mt(s),n)){i=0;while(o=s[i++])kt.test(o.type||"")&&n.push(o)}return s=null,f},cleanData:function(e,t){var n,r,o,a,s=0,u=b.expando,l=b.cache,p=b.support.deleteExpando,f=b.event.special;for(;null!=(n=e[s]);s++)if((t||b.acceptData(n))&&(o=n[u],a=o&&l[o])){if(a.events)for(r in a.events)f[r]?b.event.remove(n,r):b.removeEvent(n,r,a.handle);l[o]&&(delete l[o],p?delete n[u]:typeof n.removeAttribute!==i?n.removeAttribute(u):n[u]=null,c.push(o))}}});var Pt,Rt,Wt,$t=/alpha\([^)]*\)/i,It=/opacity\s*=\s*([^)]*)/,zt=/^(top|right|bottom|left)$/,Xt=/^(none|table(?!-c[ea]).+)/,Ut=/^margin/,Vt=RegExp("^("+x+")(.*)$","i"),Yt=RegExp("^("+x+")(?!px)[a-z%]+$","i"),Jt=RegExp("^([+-])=("+x+")","i"),Gt={BODY:"block"},Qt={position:"absolute",visibility:"hidden",display:"block"},Kt={letterSpacing:0,fontWeight:400},Zt=["Top","Right","Bottom","Left"],en=["Webkit","O","Moz","ms"];function tn(e,t){if(t in e)return t;var n=t.charAt(0).toUpperCase()+t.slice(1),r=t,i=en.length;while(i--)if(t=en[i]+n,t in e)return t;return r}function nn(e,t){return e=t||e,"none"===b.css(e,"display")||!b.contains(e.ownerDocument,e)}function rn(e,t){var n,r,i,o=[],a=0,s=e.length;for(;s>a;a++)r=e[a],r.style&&(o[a]=b._data(r,"olddisplay"),n=r.style.display,t?(o[a]||"none"!==n||(r.style.display=""),""===r.style.display&&nn(r)&&(o[a]=b._data(r,"olddisplay",un(r.nodeName)))):o[a]||(i=nn(r),(n&&"none"!==n||!i)&&b._data(r,"olddisplay",i?n:b.css(r,"display"))));for(a=0;s>a;a++)r=e[a],r.style&&(t&&"none"!==r.style.display&&""!==r.style.display||(r.style.display=t?o[a]||"":"none"));return e}b.fn.extend({css:function(e,n){return b.access(this,function(e,n,r){var i,o,a={},s=0;if(b.isArray(n)){for(o=Rt(e),i=n.length;i>s;s++)a[n[s]]=b.css(e,n[s],!1,o);return a}return r!==t?b.style(e,n,r):b.css(e,n)},e,n,arguments.length>1)},show:function(){return rn(this,!0)},hide:function(){return rn(this)},toggle:function(e){var t="boolean"==typeof e;return this.each(function(){(t?e:nn(this))?b(this).show():b(this).hide()})}}),b.extend({cssHooks:{opacity:{get:function(e,t){if(t){var n=Wt(e,"opacity");return""===n?"1":n}}}},cssNumber:{columnCount:!0,fillOpacity:!0,fontWeight:!0,lineHeight:!0,opacity:!0,orphans:!0,widows:!0,zIndex:!0,zoom:!0},cssProps:{"float":b.support.cssFloat?"cssFloat":"styleFloat"},style:function(e,n,r,i){if(e&&3!==e.nodeType&&8!==e.nodeType&&e.style){var o,a,s,u=b.camelCase(n),l=e.style;if(n=b.cssProps[u]||(b.cssProps[u]=tn(l,u)),s=b.cssHooks[n]||b.cssHooks[u],r===t)return s&&"get"in s&&(o=s.get(e,!1,i))!==t?o:l[n];if(a=typeof r,"string"===a&&(o=Jt.exec(r))&&(r=(o[1]+1)*o[2]+parseFloat(b.css(e,n)),a="number"),!(null==r||"number"===a&&isNaN(r)||("number"!==a||b.cssNumber[u]||(r+="px"),b.support.clearCloneStyle||""!==r||0!==n.indexOf("background")||(l[n]="inherit"),s&&"set"in s&&(r=s.set(e,r,i))===t)))try{l[n]=r}catch(c){}}},css:function(e,n,r,i){var o,a,s,u=b.camelCase(n);return n=b.cssProps[u]||(b.cssProps[u]=tn(e.style,u)),s=b.cssHooks[n]||b.cssHooks[u],s&&"get"in s&&(a=s.get(e,!0,r)),a===t&&(a=Wt(e,n,i)),"normal"===a&&n in Kt&&(a=Kt[n]),""===r||r?(o=parseFloat(a),r===!0||b.isNumeric(o)?o||0:a):a},swap:function(e,t,n,r){var i,o,a={};for(o in t)a[o]=e.style[o],e.style[o]=t[o];i=n.apply(e,r||[]);for(o in t)e.style[o]=a[o];return i}}),e.getComputedStyle?(Rt=function(t){return e.getComputedStyle(t,null)},Wt=function(e,n,r){var i,o,a,s=r||Rt(e),u=s?s.getPropertyValue(n)||s[n]:t,l=e.style;return s&&(""!==u||b.contains(e.ownerDocument,e)||(u=b.style(e,n)),Yt.test(u)&&Ut.test(n)&&(i=l.width,o=l.minWidth,a=l.maxWidth,l.minWidth=l.maxWidth=l.width=u,u=s.width,l.width=i,l.minWidth=o,l.maxWidth=a)),u}):o.documentElement.currentStyle&&(Rt=function(e){return e.currentStyle},Wt=function(e,n,r){var i,o,a,s=r||Rt(e),u=s?s[n]:t,l=e.style;return null==u&&l&&l[n]&&(u=l[n]),Yt.test(u)&&!zt.test(n)&&(i=l.left,o=e.runtimeStyle,a=o&&o.left,a&&(o.left=e.currentStyle.left),l.left="fontSize"===n?"1em":u,u=l.pixelLeft+"px",l.left=i,a&&(o.left=a)),""===u?"auto":u});function on(e,t,n){var r=Vt.exec(t);return r?Math.max(0,r[1]-(n||0))+(r[2]||"px"):t}function an(e,t,n,r,i){var o=n===(r?"border":"content")?4:"width"===t?1:0,a=0;for(;4>o;o+=2)"margin"===n&&(a+=b.css(e,n+Zt[o],!0,i)),r?("content"===n&&(a-=b.css(e,"padding"+Zt[o],!0,i)),"margin"!==n&&(a-=b.css(e,"border"+Zt[o]+"Width",!0,i))):(a+=b.css(e,"padding"+Zt[o],!0,i),"padding"!==n&&(a+=b.css(e,"border"+Zt[o]+"Width",!0,i)));return a}function sn(e,t,n){var r=!0,i="width"===t?e.offsetWidth:e.offsetHeight,o=Rt(e),a=b.support.boxSizing&&"border-box"===b.css(e,"boxSizing",!1,o);if(0>=i||null==i){if(i=Wt(e,t,o),(0>i||null==i)&&(i=e.style[t]),Yt.test(i))return i;r=a&&(b.support.boxSizingReliable||i===e.style[t]),i=parseFloat(i)||0}return i+an(e,t,n||(a?"border":"content"),r,o)+"px"}function un(e){var t=o,n=Gt[e];return n||(n=ln(e,t),"none"!==n&&n||(Pt=(Pt||b("<iframe frameborder='0' width='0' height='0'/>").css("cssText","display:block !important")).appendTo(t.documentElement),t=(Pt[0].contentWindow||Pt[0].contentDocument).document,t.write("<!doctype html><html><body>"),t.close(),n=ln(e,t),Pt.detach()),Gt[e]=n),n}function ln(e,t){var n=b(t.createElement(e)).appendTo(t.body),r=b.css(n[0],"display");return n.remove(),r}b.each(["height","width"],function(e,n){b.cssHooks[n]={get:function(e,r,i){return r?0===e.offsetWidth&&Xt.test(b.css(e,"display"))?b.swap(e,Qt,function(){return sn(e,n,i)}):sn(e,n,i):t},set:function(e,t,r){var i=r&&Rt(e);return on(e,t,r?an(e,n,r,b.support.boxSizing&&"border-box"===b.css(e,"boxSizing",!1,i),i):0)}}}),b.support.opacity||(b.cssHooks.opacity={get:function(e,t){return It.test((t&&e.currentStyle?e.currentStyle.filter:e.style.filter)||"")?.01*parseFloat(RegExp.$1)+"":t?"1":""},set:function(e,t){var n=e.style,r=e.currentStyle,i=b.isNumeric(t)?"alpha(opacity="+100*t+")":"",o=r&&r.filter||n.filter||"";n.zoom=1,(t>=1||""===t)&&""===b.trim(o.replace($t,""))&&n.removeAttribute&&(n.removeAttribute("filter"),""===t||r&&!r.filter)||(n.filter=$t.test(o)?o.replace($t,i):o+" "+i)}}),b(function(){b.support.reliableMarginRight||(b.cssHooks.marginRight={get:function(e,n){return n?b.swap(e,{display:"inline-block"},Wt,[e,"marginRight"]):t}}),!b.support.pixelPosition&&b.fn.position&&b.each(["top","left"],function(e,n){b.cssHooks[n]={get:function(e,r){return r?(r=Wt(e,n),Yt.test(r)?b(e).position()[n]+"px":r):t}}})}),b.expr&&b.expr.filters&&(b.expr.filters.hidden=function(e){return 0>=e.offsetWidth&&0>=e.offsetHeight||!b.support.reliableHiddenOffsets&&"none"===(e.style&&e.style.display||b.css(e,"display"))},b.expr.filters.visible=function(e){return!b.expr.filters.hidden(e)}),b.each({margin:"",padding:"",border:"Width"},function(e,t){b.cssHooks[e+t]={expand:function(n){var r=0,i={},o="string"==typeof n?n.split(" "):[n];for(;4>r;r++)i[e+Zt[r]+t]=o[r]||o[r-2]||o[0];return i}},Ut.test(e)||(b.cssHooks[e+t].set=on)});var cn=/%20/g,pn=/\[\]$/,fn=/\r?\n/g,dn=/^(?:submit|button|image|reset|file)$/i,hn=/^(?:input|select|textarea|keygen)/i;b.fn.extend({serialize:function(){return b.param(this.serializeArray())},serializeArray:function(){return this.map(function(){var e=b.prop(this,"elements");return e?b.makeArray(e):this}).filter(function(){var e=this.type;return this.name&&!b(this).is(":disabled")&&hn.test(this.nodeName)&&!dn.test(e)&&(this.checked||!Nt.test(e))}).map(function(e,t){var n=b(this).val();return null==n?null:b.isArray(n)?b.map(n,function(e){return{name:t.name,value:e.replace(fn,"\r\n")}}):{name:t.name,value:n.replace(fn,"\r\n")}}).get()}}),b.param=function(e,n){var r,i=[],o=function(e,t){t=b.isFunction(t)?t():null==t?"":t,i[i.length]=encodeURIComponent(e)+"="+encodeURIComponent(t)};if(n===t&&(n=b.ajaxSettings&&b.ajaxSettings.traditional),b.isArray(e)||e.jquery&&!b.isPlainObject(e))b.each(e,function(){o(this.name,this.value)});else for(r in e)gn(r,e[r],n,o);return i.join("&").replace(cn,"+")};function gn(e,t,n,r){var i;if(b.isArray(t))b.each(t,function(t,i){n||pn.test(e)?r(e,i):gn(e+"["+("object"==typeof i?t:"")+"]",i,n,r)});else if(n||"object"!==b.type(t))r(e,t);else for(i in t)gn(e+"["+i+"]",t[i],n,r)}b.each("blur focus focusin focusout load resize scroll unload click dblclick mousedown mouseup mousemove mouseover mouseout mouseenter mouseleave change select submit keydown keypress keyup error contextmenu".split(" "),function(e,t){b.fn[t]=function(e,n){return arguments.length>0?this.on(t,null,e,n):this.trigger(t)}}),b.fn.hover=function(e,t){return this.mouseenter(e).mouseleave(t||e)};var mn,yn,vn=b.now(),bn=/\?/,xn=/#.*$/,wn=/([?&])_=[^&]*/,Tn=/^(.*?):[ \t]*([^\r\n]*)\r?$/gm,Nn=/^(?:about|app|app-storage|.+-extension|file|res|widget):$/,Cn=/^(?:GET|HEAD)$/,kn=/^\/\//,En=/^([\w.+-]+:)(?:\/\/([^\/?#:]*)(?::(\d+)|)|)/,Sn=b.fn.load,An={},jn={},Dn="*/".concat("*");try{yn=a.href}catch(Ln){yn=o.createElement("a"),yn.href="",yn=yn.href}mn=En.exec(yn.toLowerCase())||[];function Hn(e){return function(t,n){"string"!=typeof t&&(n=t,t="*");var r,i=0,o=t.toLowerCase().match(w)||[];if(b.isFunction(n))while(r=o[i++])"+"===r[0]?(r=r.slice(1)||"*",(e[r]=e[r]||[]).unshift(n)):(e[r]=e[r]||[]).push(n)}}function qn(e,n,r,i){var o={},a=e===jn;function s(u){var l;return o[u]=!0,b.each(e[u]||[],function(e,u){var c=u(n,r,i);return"string"!=typeof c||a||o[c]?a?!(l=c):t:(n.dataTypes.unshift(c),s(c),!1)}),l}return s(n.dataTypes[0])||!o["*"]&&s("*")}function Mn(e,n){var r,i,o=b.ajaxSettings.flatOptions||{};for(i in n)n[i]!==t&&((o[i]?e:r||(r={}))[i]=n[i]);return r&&b.extend(!0,e,r),e}b.fn.load=function(e,n,r){if("string"!=typeof e&&Sn)return Sn.apply(this,arguments);var i,o,a,s=this,u=e.indexOf(" ");return u>=0&&(i=e.slice(u,e.length),e=e.slice(0,u)),b.isFunction(n)?(r=n,n=t):n&&"object"==typeof n&&(a="POST"),s.length>0&&b.ajax({url:e,type:a,dataType:"html",data:n}).done(function(e){o=arguments,s.html(i?b("<div>").append(b.parseHTML(e)).find(i):e)}).complete(r&&function(e,t){s.each(r,o||[e.responseText,t,e])}),this},b.each(["ajaxStart","ajaxStop","ajaxComplete","ajaxError","ajaxSuccess","ajaxSend"],function(e,t){b.fn[t]=function(e){return this.on(t,e)}}),b.each(["get","post"],function(e,n){b[n]=function(e,r,i,o){return b.isFunction(r)&&(o=o||i,i=r,r=t),b.ajax({url:e,type:n,dataType:o,data:r,success:i})}}),b.extend({active:0,lastModified:{},etag:{},ajaxSettings:{url:yn,type:"GET",isLocal:Nn.test(mn[1]),global:!0,processData:!0,async:!0,contentType:"application/x-www-form-urlencoded; charset=UTF-8",accepts:{"*":Dn,text:"text/plain",html:"text/html",xml:"application/xml, text/xml",json:"application/json, text/javascript"},contents:{xml:/xml/,html:/html/,json:/json/},responseFields:{xml:"responseXML",text:"responseText"},converters:{"* text":e.String,"text html":!0,"text json":b.parseJSON,"text xml":b.parseXML},flatOptions:{url:!0,context:!0}},ajaxSetup:function(e,t){return t?Mn(Mn(e,b.ajaxSettings),t):Mn(b.ajaxSettings,e)},ajaxPrefilter:Hn(An),ajaxTransport:Hn(jn),ajax:function(e,n){"object"==typeof e&&(n=e,e=t),n=n||{};var r,i,o,a,s,u,l,c,p=b.ajaxSetup({},n),f=p.context||p,d=p.context&&(f.nodeType||f.jquery)?b(f):b.event,h=b.Deferred(),g=b.Callbacks("once memory"),m=p.statusCode||{},y={},v={},x=0,T="canceled",N={readyState:0,getResponseHeader:function(e){var t;if(2===x){if(!c){c={};while(t=Tn.exec(a))c[t[1].toLowerCase()]=t[2]}t=c[e.toLowerCase()]}return null==t?null:t},getAllResponseHeaders:function(){return 2===x?a:null},setRequestHeader:function(e,t){var n=e.toLowerCase();return x||(e=v[n]=v[n]||e,y[e]=t),this},overrideMimeType:function(e){return x||(p.mimeType=e),this},statusCode:function(e){var t;if(e)if(2>x)for(t in e)m[t]=[m[t],e[t]];else N.always(e[N.status]);return this},abort:function(e){var t=e||T;return l&&l.abort(t),k(0,t),this}};if(h.promise(N).complete=g.add,N.success=N.done,N.error=N.fail,p.url=((e||p.url||yn)+"").replace(xn,"").replace(kn,mn[1]+"//"),p.type=n.method||n.type||p.method||p.type,p.dataTypes=b.trim(p.dataType||"*").toLowerCase().match(w)||[""],null==p.crossDomain&&(r=En.exec(p.url.toLowerCase()),p.crossDomain=!(!r||r[1]===mn[1]&&r[2]===mn[2]&&(r[3]||("http:"===r[1]?80:443))==(mn[3]||("http:"===mn[1]?80:443)))),p.data&&p.processData&&"string"!=typeof p.data&&(p.data=b.param(p.data,p.traditional)),qn(An,p,n,N),2===x)return N;u=p.global,u&&0===b.active++&&b.event.trigger("ajaxStart"),p.type=p.type.toUpperCase(),p.hasContent=!Cn.test(p.type),o=p.url,p.hasContent||(p.data&&(o=p.url+=(bn.test(o)?"&":"?")+p.data,delete p.data),p.cache===!1&&(p.url=wn.test(o)?o.replace(wn,"$1_="+vn++):o+(bn.test(o)?"&":"?")+"_="+vn++)),p.ifModified&&(b.lastModified[o]&&N.setRequestHeader("If-Modified-Since",b.lastModified[o]),b.etag[o]&&N.setRequestHeader("If-None-Match",b.etag[o])),(p.data&&p.hasContent&&p.contentType!==!1||n.contentType)&&N.setRequestHeader("Content-Type",p.contentType),N.setRequestHeader("Accept",p.dataTypes[0]&&p.accepts[p.dataTypes[0]]?p.accepts[p.dataTypes[0]]+("*"!==p.dataTypes[0]?", "+Dn+"; q=0.01":""):p.accepts["*"]);for(i in p.headers)N.setRequestHeader(i,p.headers[i]);if(p.beforeSend&&(p.beforeSend.call(f,N,p)===!1||2===x))return N.abort();T="abort";for(i in{success:1,error:1,complete:1})N[i](p[i]);if(l=qn(jn,p,n,N)){N.readyState=1,u&&d.trigger("ajaxSend",[N,p]),p.async&&p.timeout>0&&(s=setTimeout(function(){N.abort("timeout")},p.timeout));try{x=1,l.send(y,k)}catch(C){if(!(2>x))throw C;k(-1,C)}}else k(-1,"No Transport");function k(e,n,r,i){var c,y,v,w,T,C=n;2!==x&&(x=2,s&&clearTimeout(s),l=t,a=i||"",N.readyState=e>0?4:0,r&&(w=_n(p,N,r)),e>=200&&300>e||304===e?(p.ifModified&&(T=N.getResponseHeader("Last-Modified"),T&&(b.lastModified[o]=T),T=N.getResponseHeader("etag"),T&&(b.etag[o]=T)),204===e?(c=!0,C="nocontent"):304===e?(c=!0,C="notmodified"):(c=Fn(p,w),C=c.state,y=c.data,v=c.error,c=!v)):(v=C,(e||!C)&&(C="error",0>e&&(e=0))),N.status=e,N.statusText=(n||C)+"",c?h.resolveWith(f,[y,C,N]):h.rejectWith(f,[N,C,v]),N.statusCode(m),m=t,u&&d.trigger(c?"ajaxSuccess":"ajaxError",[N,p,c?y:v]),g.fireWith(f,[N,C]),u&&(d.trigger("ajaxComplete",[N,p]),--b.active||b.event.trigger("ajaxStop")))}return N},getScript:function(e,n){return b.get(e,t,n,"script")},getJSON:function(e,t,n){return b.get(e,t,n,"json")}});function _n(e,n,r){var i,o,a,s,u=e.contents,l=e.dataTypes,c=e.responseFields;for(s in c)s in r&&(n[c[s]]=r[s]);while("*"===l[0])l.shift(),o===t&&(o=e.mimeType||n.getResponseHeader("Content-Type"));if(o)for(s in u)if(u[s]&&u[s].test(o)){l.unshift(s);break}if(l[0]in r)a=l[0];else{for(s in r){if(!l[0]||e.converters[s+" "+l[0]]){a=s;break}i||(i=s)}a=a||i}return a?(a!==l[0]&&l.unshift(a),r[a]):t}function Fn(e,t){var n,r,i,o,a={},s=0,u=e.dataTypes.slice(),l=u[0];if(e.dataFilter&&(t=e.dataFilter(t,e.dataType)),u[1])for(i in e.converters)a[i.toLowerCase()]=e.converters[i];for(;r=u[++s];)if("*"!==r){if("*"!==l&&l!==r){if(i=a[l+" "+r]||a["* "+r],!i)for(n in a)if(o=n.split(" "),o[1]===r&&(i=a[l+" "+o[0]]||a["* "+o[0]])){i===!0?i=a[n]:a[n]!==!0&&(r=o[0],u.splice(s--,0,r));break}if(i!==!0)if(i&&e["throws"])t=i(t);else try{t=i(t)}catch(c){return{state:"parsererror",error:i?c:"No conversion from "+l+" to "+r}}}l=r}return{state:"success",data:t}}b.ajaxSetup({accepts:{script:"text/javascript, application/javascript, application/ecmascript, application/x-ecmascript"},contents:{script:/(?:java|ecma)script/},converters:{"text script":function(e){return b.globalEval(e),e}}}),b.ajaxPrefilter("script",function(e){e.cache===t&&(e.cache=!1),e.crossDomain&&(e.type="GET",e.global=!1)}),b.ajaxTransport("script",function(e){if(e.crossDomain){var n,r=o.head||b("head")[0]||o.documentElement;return{send:function(t,i){n=o.createElement("script"),n.async=!0,e.scriptCharset&&(n.charset=e.scriptCharset),n.src=e.url,n.onload=n.onreadystatechange=function(e,t){(t||!n.readyState||/loaded|complete/.test(n.readyState))&&(n.onload=n.onreadystatechange=null,n.parentNode&&n.parentNode.removeChild(n),n=null,t||i(200,"success"))},r.insertBefore(n,r.firstChild)},abort:function(){n&&n.onload(t,!0)}}}});var On=[],Bn=/(=)\?(?=&|$)|\?\?/;b.ajaxSetup({jsonp:"callback",jsonpCallback:function(){var e=On.pop()||b.expando+"_"+vn++;return this[e]=!0,e}}),b.ajaxPrefilter("json jsonp",function(n,r,i){var o,a,s,u=n.jsonp!==!1&&(Bn.test(n.url)?"url":"string"==typeof n.data&&!(n.contentType||"").indexOf("application/x-www-form-urlencoded")&&Bn.test(n.data)&&"data");return u||"jsonp"===n.dataTypes[0]?(o=n.jsonpCallback=b.isFunction(n.jsonpCallback)?n.jsonpCallback():n.jsonpCallback,u?n[u]=n[u].replace(Bn,"$1"+o):n.jsonp!==!1&&(n.url+=(bn.test(n.url)?"&":"?")+n.jsonp+"="+o),n.converters["script json"]=function(){return s||b.error(o+" was not called"),s[0]},n.dataTypes[0]="json",a=e[o],e[o]=function(){s=arguments},i.always(function(){e[o]=a,n[o]&&(n.jsonpCallback=r.jsonpCallback,On.push(o)),s&&b.isFunction(a)&&a(s[0]),s=a=t}),"script"):t});var Pn,Rn,Wn=0,$n=e.ActiveXObject&&function(){var e;for(e in Pn)Pn[e](t,!0)};function In(){try{return new e.XMLHttpRequest}catch(t){}}function zn(){try{return new e.ActiveXObject("Microsoft.XMLHTTP")}catch(t){}}b.ajaxSettings.xhr=e.ActiveXObject?function(){return!this.isLocal&&In()||zn()}:In,Rn=b.ajaxSettings.xhr(),b.support.cors=!!Rn&&"withCredentials"in Rn,Rn=b.support.ajax=!!Rn,Rn&&b.ajaxTransport(function(n){if(!n.crossDomain||b.support.cors){var r;return{send:function(i,o){var a,s,u=n.xhr();if(n.username?u.open(n.type,n.url,n.async,n.username,n.password):u.open(n.type,n.url,n.async),n.xhrFields)for(s in n.xhrFields)u[s]=n.xhrFields[s];n.mimeType&&u.overrideMimeType&&u.overrideMimeType(n.mimeType),n.crossDomain||i["X-Requested-With"]||(i["X-Requested-With"]="XMLHttpRequest");try{for(s in i)u.setRequestHeader(s,i[s])}catch(l){}u.send(n.hasContent&&n.data||null),r=function(e,i){var s,l,c,p;try{if(r&&(i||4===u.readyState))if(r=t,a&&(u.onreadystatechange=b.noop,$n&&delete Pn[a]),i)4!==u.readyState&&u.abort();else{p={},s=u.status,l=u.getAllResponseHeaders(),"string"==typeof u.responseText&&(p.text=u.responseText);try{c=u.statusText}catch(f){c=""}s||!n.isLocal||n.crossDomain?1223===s&&(s=204):s=p.text?200:404}}catch(d){i||o(-1,d)}p&&o(s,c,p,l)},n.async?4===u.readyState?setTimeout(r):(a=++Wn,$n&&(Pn||(Pn={},b(e).unload($n)),Pn[a]=r),u.onreadystatechange=r):r()},abort:function(){r&&r(t,!0)}}}});var Xn,Un,Vn=/^(?:toggle|show|hide)$/,Yn=RegExp("^(?:([+-])=|)("+x+")([a-z%]*)$","i"),Jn=/queueHooks$/,Gn=[nr],Qn={"*":[function(e,t){var n,r,i=this.createTween(e,t),o=Yn.exec(t),a=i.cur(),s=+a||0,u=1,l=20;if(o){if(n=+o[2],r=o[3]||(b.cssNumber[e]?"":"px"),"px"!==r&&s){s=b.css(i.elem,e,!0)||n||1;do u=u||".5",s/=u,b.style(i.elem,e,s+r);while(u!==(u=i.cur()/a)&&1!==u&&--l)}i.unit=r,i.start=s,i.end=o[1]?s+(o[1]+1)*n:n}return i}]};function Kn(){return setTimeout(function(){Xn=t}),Xn=b.now()}function Zn(e,t){b.each(t,function(t,n){var r=(Qn[t]||[]).concat(Qn["*"]),i=0,o=r.length;for(;o>i;i++)if(r[i].call(e,t,n))return})}function er(e,t,n){var r,i,o=0,a=Gn.length,s=b.Deferred().always(function(){delete u.elem}),u=function(){if(i)return!1;var t=Xn||Kn(),n=Math.max(0,l.startTime+l.duration-t),r=n/l.duration||0,o=1-r,a=0,u=l.tweens.length;for(;u>a;a++)l.tweens[a].run(o);return s.notifyWith(e,[l,o,n]),1>o&&u?n:(s.resolveWith(e,[l]),!1)},l=s.promise({elem:e,props:b.extend({},t),opts:b.extend(!0,{specialEasing:{}},n),originalProperties:t,originalOptions:n,startTime:Xn||Kn(),duration:n.duration,tweens:[],createTween:function(t,n){var r=b.Tween(e,l.opts,t,n,l.opts.specialEasing[t]||l.opts.easing);return l.tweens.push(r),r},stop:function(t){var n=0,r=t?l.tweens.length:0;if(i)return this;for(i=!0;r>n;n++)l.tweens[n].run(1);return t?s.resolveWith(e,[l,t]):s.rejectWith(e,[l,t]),this}}),c=l.props;for(tr(c,l.opts.specialEasing);a>o;o++)if(r=Gn[o].call(l,e,c,l.opts))return r;return Zn(l,c),b.isFunction(l.opts.start)&&l.opts.start.call(e,l),b.fx.timer(b.extend(u,{elem:e,anim:l,queue:l.opts.queue})),l.progress(l.opts.progress).done(l.opts.done,l.opts.complete).fail(l.opts.fail).always(l.opts.always)}function tr(e,t){var n,r,i,o,a;for(i in e)if(r=b.camelCase(i),o=t[r],n=e[i],b.isArray(n)&&(o=n[1],n=e[i]=n[0]),i!==r&&(e[r]=n,delete e[i]),a=b.cssHooks[r],a&&"expand"in a){n=a.expand(n),delete e[r];for(i in n)i in e||(e[i]=n[i],t[i]=o)}else t[r]=o}b.Animation=b.extend(er,{tweener:function(e,t){b.isFunction(e)?(t=e,e=["*"]):e=e.split(" ");var n,r=0,i=e.length;for(;i>r;r++)n=e[r],Qn[n]=Qn[n]||[],Qn[n].unshift(t)},prefilter:function(e,t){t?Gn.unshift(e):Gn.push(e)}});function nr(e,t,n){var r,i,o,a,s,u,l,c,p,f=this,d=e.style,h={},g=[],m=e.nodeType&&nn(e);n.queue||(c=b._queueHooks(e,"fx"),null==c.unqueued&&(c.unqueued=0,p=c.empty.fire,c.empty.fire=function(){c.unqueued||p()}),c.unqueued++,f.always(function(){f.always(function(){c.unqueued--,b.queue(e,"fx").length||c.empty.fire()})})),1===e.nodeType&&("height"in t||"width"in t)&&(n.overflow=[d.overflow,d.overflowX,d.overflowY],"inline"===b.css(e,"display")&&"none"===b.css(e,"float")&&(b.support.inlineBlockNeedsLayout&&"inline"!==un(e.nodeName)?d.zoom=1:d.display="inline-block")),n.overflow&&(d.overflow="hidden",b.support.shrinkWrapBlocks||f.always(function(){d.overflow=n.overflow[0],d.overflowX=n.overflow[1],d.overflowY=n.overflow[2]}));for(i in t)if(a=t[i],Vn.exec(a)){if(delete t[i],u=u||"toggle"===a,a===(m?"hide":"show"))continue;g.push(i)}if(o=g.length){s=b._data(e,"fxshow")||b._data(e,"fxshow",{}),"hidden"in s&&(m=s.hidden),u&&(s.hidden=!m),m?b(e).show():f.done(function(){b(e).hide()}),f.done(function(){var t;b._removeData(e,"fxshow");for(t in h)b.style(e,t,h[t])});for(i=0;o>i;i++)r=g[i],l=f.createTween(r,m?s[r]:0),h[r]=s[r]||b.style(e,r),r in s||(s[r]=l.start,m&&(l.end=l.start,l.start="width"===r||"height"===r?1:0))}}function rr(e,t,n,r,i){return new rr.prototype.init(e,t,n,r,i)}b.Tween=rr,rr.prototype={constructor:rr,init:function(e,t,n,r,i,o){this.elem=e,this.prop=n,this.easing=i||"swing",this.options=t,this.start=this.now=this.cur(),this.end=r,this.unit=o||(b.cssNumber[n]?"":"px")},cur:function(){var e=rr.propHooks[this.prop];return e&&e.get?e.get(this):rr.propHooks._default.get(this)},run:function(e){var t,n=rr.propHooks[this.prop];return this.pos=t=this.options.duration?b.easing[this.easing](e,this.options.duration*e,0,1,this.options.duration):e,this.now=(this.end-this.start)*t+this.start,this.options.step&&this.options.step.call(this.elem,this.now,this),n&&n.set?n.set(this):rr.propHooks._default.set(this),this}},rr.prototype.init.prototype=rr.prototype,rr.propHooks={_default:{get:function(e){var t;return null==e.elem[e.prop]||e.elem.style&&null!=e.elem.style[e.prop]?(t=b.css(e.elem,e.prop,""),t&&"auto"!==t?t:0):e.elem[e.prop]},set:function(e){b.fx.step[e.prop]?b.fx.step[e.prop](e):e.elem.style&&(null!=e.elem.style[b.cssProps[e.prop]]||b.cssHooks[e.prop])?b.style(e.elem,e.prop,e.now+e.unit):e.elem[e.prop]=e.now}}},rr.propHooks.scrollTop=rr.propHooks.scrollLeft={set:function(e){e.elem.nodeType&&e.elem.parentNode&&(e.elem[e.prop]=e.now)}},b.each(["toggle","show","hide"],function(e,t){var n=b.fn[t];b.fn[t]=function(e,r,i){return null==e||"boolean"==typeof e?n.apply(this,arguments):this.animate(ir(t,!0),e,r,i)}}),b.fn.extend({fadeTo:function(e,t,n,r){return this.filter(nn).css("opacity",0).show().end().animate({opacity:t},e,n,r)},animate:function(e,t,n,r){var i=b.isEmptyObject(e),o=b.speed(t,n,r),a=function(){var t=er(this,b.extend({},e),o);a.finish=function(){t.stop(!0)},(i||b._data(this,"finish"))&&t.stop(!0)};return a.finish=a,i||o.queue===!1?this.each(a):this.queue(o.queue,a)},stop:function(e,n,r){var i=function(e){var t=e.stop;delete e.stop,t(r)};return"string"!=typeof e&&(r=n,n=e,e=t),n&&e!==!1&&this.queue(e||"fx",[]),this.each(function(){var t=!0,n=null!=e&&e+"queueHooks",o=b.timers,a=b._data(this);if(n)a[n]&&a[n].stop&&i(a[n]);else for(n in a)a[n]&&a[n].stop&&Jn.test(n)&&i(a[n]);for(n=o.length;n--;)o[n].elem!==this||null!=e&&o[n].queue!==e||(o[n].anim.stop(r),t=!1,o.splice(n,1));(t||!r)&&b.dequeue(this,e)})},finish:function(e){return e!==!1&&(e=e||"fx"),this.each(function(){var t,n=b._data(this),r=n[e+"queue"],i=n[e+"queueHooks"],o=b.timers,a=r?r.length:0;for(n.finish=!0,b.queue(this,e,[]),i&&i.cur&&i.cur.finish&&i.cur.finish.call(this),t=o.length;t--;)o[t].elem===this&&o[t].queue===e&&(o[t].anim.stop(!0),o.splice(t,1));for(t=0;a>t;t++)r[t]&&r[t].finish&&r[t].finish.call(this);delete n.finish})}});function ir(e,t){var n,r={height:e},i=0;for(t=t?1:0;4>i;i+=2-t)n=Zt[i],r["margin"+n]=r["padding"+n]=e;return t&&(r.opacity=r.width=e),r}b.each({slideDown:ir("show"),slideUp:ir("hide"),slideToggle:ir("toggle"),fadeIn:{opacity:"show"},fadeOut:{opacity:"hide"},fadeToggle:{opacity:"toggle"}},function(e,t){b.fn[e]=function(e,n,r){return this.animate(t,e,n,r)}}),b.speed=function(e,t,n){var r=e&&"object"==typeof e?b.extend({},e):{complete:n||!n&&t||b.isFunction(e)&&e,duration:e,easing:n&&t||t&&!b.isFunction(t)&&t};return r.duration=b.fx.off?0:"number"==typeof r.duration?r.duration:r.duration in b.fx.speeds?b.fx.speeds[r.duration]:b.fx.speeds._default,(null==r.queue||r.queue===!0)&&(r.queue="fx"),r.old=r.complete,r.complete=function(){b.isFunction(r.old)&&r.old.call(this),r.queue&&b.dequeue(this,r.queue)},r},b.easing={linear:function(e){return e},swing:function(e){return.5-Math.cos(e*Math.PI)/2}},b.timers=[],b.fx=rr.prototype.init,b.fx.tick=function(){var e,n=b.timers,r=0;for(Xn=b.now();n.length>r;r++)e=n[r],e()||n[r]!==e||n.splice(r--,1);n.length||b.fx.stop(),Xn=t},b.fx.timer=function(e){e()&&b.timers.push(e)&&b.fx.start()},b.fx.interval=13,b.fx.start=function(){Un||(Un=setInterval(b.fx.tick,b.fx.interval))},b.fx.stop=function(){clearInterval(Un),Un=null},b.fx.speeds={slow:600,fast:200,_default:400},b.fx.step={},b.expr&&b.expr.filters&&(b.expr.filters.animated=function(e){return b.grep(b.timers,function(t){return e===t.elem}).length}),b.fn.offset=function(e){if(arguments.length)return e===t?this:this.each(function(t){b.offset.setOffset(this,e,t)});var n,r,o={top:0,left:0},a=this[0],s=a&&a.ownerDocument;if(s)return n=s.documentElement,b.contains(n,a)?(typeof a.getBoundingClientRect!==i&&(o=a.getBoundingClientRect()),r=or(s),{top:o.top+(r.pageYOffset||n.scrollTop)-(n.clientTop||0),left:o.left+(r.pageXOffset||n.scrollLeft)-(n.clientLeft||0)}):o},b.offset={setOffset:function(e,t,n){var r=b.css(e,"position");"static"===r&&(e.style.position="relative");var i=b(e),o=i.offset(),a=b.css(e,"top"),s=b.css(e,"left"),u=("absolute"===r||"fixed"===r)&&b.inArray("auto",[a,s])>-1,l={},c={},p,f;u?(c=i.position(),p=c.top,f=c.left):(p=parseFloat(a)||0,f=parseFloat(s)||0),b.isFunction(t)&&(t=t.call(e,n,o)),null!=t.top&&(l.top=t.top-o.top+p),null!=t.left&&(l.left=t.left-o.left+f),"using"in t?t.using.call(e,l):i.css(l)}},b.fn.extend({position:function(){if(this[0]){var e,t,n={top:0,left:0},r=this[0];return"fixed"===b.css(r,"position")?t=r.getBoundingClientRect():(e=this.offsetParent(),t=this.offset(),b.nodeName(e[0],"html")||(n=e.offset()),n.top+=b.css(e[0],"borderTopWidth",!0),n.left+=b.css(e[0],"borderLeftWidth",!0)),{top:t.top-n.top-b.css(r,"marginTop",!0),left:t.left-n.left-b.css(r,"marginLeft",!0)}}},offsetParent:function(){return this.map(function(){var e=this.offsetParent||o.documentElement;while(e&&!b.nodeName(e,"html")&&"static"===b.css(e,"position"))e=e.offsetParent;return e||o.documentElement})}}),b.each({scrollLeft:"pageXOffset",scrollTop:"pageYOffset"},function(e,n){var r=/Y/.test(n);b.fn[e]=function(i){return b.access(this,function(e,i,o){var a=or(e);return o===t?a?n in a?a[n]:a.document.documentElement[i]:e[i]:(a?a.scrollTo(r?b(a).scrollLeft():o,r?o:b(a).scrollTop()):e[i]=o,t)},e,i,arguments.length,null)}});function or(e){return b.isWindow(e)?e:9===e.nodeType?e.defaultView||e.parentWindow:!1}b.each({Height:"height",Width:"width"},function(e,n){b.each({padding:"inner"+e,content:n,"":"outer"+e},function(r,i){b.fn[i]=function(i,o){var a=arguments.length&&(r||"boolean"!=typeof i),s=r||(i===!0||o===!0?"margin":"border");return b.access(this,function(n,r,i){var o;return b.isWindow(n)?n.document.documentElement["client"+e]:9===n.nodeType?(o=n.documentElement,Math.max(n.body["scroll"+e],o["scroll"+e],n.body["offset"+e],o["offset"+e],o["client"+e])):i===t?b.css(n,r,s):b.style(n,r,i,s)},n,a?i:t,a,null)}})}),e.jQuery=e.$=b,"function"==typeof define&&define.amd&&define.amd.jQuery&&define("jquery",[],function(){return b})})(window);
app/javascript/mastodon/containers/account_container.js
yi0713/mastodon
import React from 'react'; import { connect } from 'react-redux'; import { defineMessages, injectIntl, FormattedMessage } from 'react-intl'; import { makeGetAccount } from '../selectors'; import Account from '../components/account'; import { followAccount, unfollowAccount, blockAccount, unblockAccount, muteAccount, unmuteAccount, } from '../actions/accounts'; import { openModal } from '../actions/modal'; import { initMuteModal } from '../actions/mutes'; import { unfollowModal } from '../initial_state'; const messages = defineMessages({ unfollowConfirm: { id: 'confirmations.unfollow.confirm', defaultMessage: 'Unfollow' }, }); const makeMapStateToProps = () => { const getAccount = makeGetAccount(); const mapStateToProps = (state, props) => ({ account: getAccount(state, props.id), }); return mapStateToProps; }; const mapDispatchToProps = (dispatch, { intl }) => ({ onFollow (account) { if (account.getIn(['relationship', 'following']) || account.getIn(['relationship', 'requested'])) { if (unfollowModal) { dispatch(openModal('CONFIRM', { message: <FormattedMessage id='confirmations.unfollow.message' defaultMessage='Are you sure you want to unfollow {name}?' values={{ name: <strong>@{account.get('acct')}</strong> }} />, confirm: intl.formatMessage(messages.unfollowConfirm), onConfirm: () => dispatch(unfollowAccount(account.get('id'))), })); } else { dispatch(unfollowAccount(account.get('id'))); } } else { dispatch(followAccount(account.get('id'))); } }, onBlock (account) { if (account.getIn(['relationship', 'blocking'])) { dispatch(unblockAccount(account.get('id'))); } else { dispatch(blockAccount(account.get('id'))); } }, onMute (account) { if (account.getIn(['relationship', 'muting'])) { dispatch(unmuteAccount(account.get('id'))); } else { dispatch(initMuteModal(account)); } }, onMuteNotifications (account, notifications) { dispatch(muteAccount(account.get('id'), notifications)); }, }); export default injectIntl(connect(makeMapStateToProps, mapDispatchToProps)(Account));
app/components/BurgerMenu.js
Krbz/react-native-maps-application
import React from 'react'; import { TouchableOpacity, View } from "react-native"; import Icon from 'react-native-vector-icons/FontAwesome'; const BurgerMenuButton = ({onPress, }) => { return ( <TouchableOpacity style={styles.burgerMenuContainer} onPress={onPress}> <Icon name="bars" size={20} color="#000" /> </TouchableOpacity> ); }; const styles = { burgerMenuContainer: { padding: 20, position: 'absolute', zIndex: 2, } }; export default BurgerMenuButton;
Pods/React/node_modules/react-tools/src/renderers/shared/reconciler/__tests__/ReactCompositeComponentDOMMinimalism-test.js
WPDreamMelody/HelloRN
/** * Copyright 2013-2015, Facebook, Inc. * All rights reserved. * * This source code is licensed under the BSD-style license found in the * LICENSE file in the root directory of this source tree. An additional grant * of patent rights can be found in the PATENTS file in the same directory. * * @emails react-core */ 'use strict'; // Requires var React; var ReactTestUtils; var reactComponentExpect; // Test components var LowerLevelComposite; var MyCompositeComponent; var expectSingleChildlessDiv; /** * Integration test, testing the combination of JSX with our unit of * abstraction, `ReactCompositeComponent` does not ever add superfluous DOM * nodes. */ describe('ReactCompositeComponentDOMMinimalism', function() { beforeEach(function() { reactComponentExpect = require('reactComponentExpect'); React = require('React'); ReactTestUtils = require('ReactTestUtils'); LowerLevelComposite = React.createClass({ render: function() { return ( <div> {this.props.children} </div> ); }, }); MyCompositeComponent = React.createClass({ render: function() { return ( <LowerLevelComposite> {this.props.children} </LowerLevelComposite> ); }, }); expectSingleChildlessDiv = function(instance) { reactComponentExpect(instance) .expectRenderedChild() .toBeCompositeComponentWithType(LowerLevelComposite) .expectRenderedChild() .toBeDOMComponentWithTag('div') .toBeDOMComponentWithNoChildren(); }; }); it('should not render extra nodes for non-interpolated text', function() { var instance = ( <MyCompositeComponent> A string child </MyCompositeComponent> ); instance = ReactTestUtils.renderIntoDocument(instance); expectSingleChildlessDiv(instance); }); it('should not render extra nodes for non-interpolated text', function() { var instance = ( <MyCompositeComponent> {'Interpolated String Child'} </MyCompositeComponent> ); instance = ReactTestUtils.renderIntoDocument(instance); expectSingleChildlessDiv(instance); }); it('should not render extra nodes for non-interpolated text', function() { var instance = ( <MyCompositeComponent> <ul> This text causes no children in ul, just innerHTML </ul> </MyCompositeComponent> ); instance = ReactTestUtils.renderIntoDocument(instance); reactComponentExpect(instance) .expectRenderedChild() .toBeCompositeComponentWithType(LowerLevelComposite) .expectRenderedChild() .toBeDOMComponentWithTag('div') .toBeDOMComponentWithChildCount(1) .expectRenderedChildAt(0) .toBeDOMComponentWithTag('ul') .toBeDOMComponentWithNoChildren(); }); });
src/Parser/Druid/Balance/CHANGELOG.js
enragednuke/WoWAnalyzer
import React from 'react'; import { Iskalla, Gebuz } from 'MAINTAINERS'; import Wrapper from 'common/Wrapper'; import ItemLink from 'common/ItemLink'; import ITEMS from 'common/ITEMS'; import SPELLS from 'common/SPELLS'; import SpellLink from 'common/SpellLink'; export default [ { date: new Date('2018-1-6'), changes: <Wrapper>Added tier 21.</Wrapper>, contributors: [Gebuz], }, { date: new Date('2018-1-5'), changes: <Wrapper>Added the following legendaries: <ItemLink id={ITEMS.IMPECCABLE_FEL_ESSENCE.id} icon />, <ItemLink id={ITEMS.ONETHS_INTUITION.id} icon />, <ItemLink id={ITEMS.LADY_AND_THE_CHILD.id} icon />, <ItemLink id={ITEMS.PROMISE_OF_ELUNE.id} icon />, and <ItemLink id={ITEMS.SOUL_OF_THE_ARCHDRUID.id} icon /> and updated <ItemLink id={ITEMS.THE_EMERALD_DREAMCATCHER.id} icon />.</Wrapper>, contributors: [Gebuz], }, { date: new Date('2018-1-2'), changes: <Wrapper>Added Astral Power usage tab.</Wrapper>, contributors: [Gebuz], }, { date: new Date('2017-12-29'), changes: <Wrapper>Added Checklist.</Wrapper>, contributors: [Gebuz], }, { date: new Date('2017-12-29'), changes: <Wrapper>Added all spells to Cast efficiency.</Wrapper>, contributors: [Gebuz], }, { date: new Date('2017-12-28'), changes: <Wrapper>Added cooldown thoughtput tracker.</Wrapper>, contributors: [Gebuz], }, { date: new Date('2017-9-28'), changes: <Wrapper>Added a tracker module for <ItemLink id={ITEMS.THE_EMERALD_DREAMCATCHER.id} icon />.</Wrapper>, contributors: [Iskalla], }, { date: new Date('2017-9-22'), changes: <Wrapper>Added Overcapped Lunar and Solar empowerments modules.</Wrapper>, contributors: [Iskalla], }, { date: new Date('2017-9-20'), changes: <Wrapper>Minor fixes to Unempowered <SpellLink id={SPELLS.LUNAR_STRIKE.id} icon /> module.</Wrapper>, contributors: [Iskalla], }, { date: new Date('2017-9-12'), changes: <Wrapper>Added a module to track Unempowered <SpellLink id={SPELLS.LUNAR_STRIKE.id} icon /> casts.</Wrapper>, contributors: [Iskalla], }, { date: new Date('2017-9-12'), changes: <Wrapper>Added the Damage module and Reorder of Stat boxes.</Wrapper>, contributors: [Iskalla], }, { date: new Date('2017-9-12'), changes: <Wrapper>Minor text fixes.</Wrapper>, contributors: [Iskalla], }, { date: new Date('2017-9-07'), changes: <Wrapper>Fixed stackable buffs - Now the ABC module should be more reliable.</Wrapper>, contributors: [Iskalla], }, { date: new Date('2017-9-05'), changes: <Wrapper>Added Moon spells casted module.</Wrapper>, contributors: [Iskalla], }, { date: new Date('2017-9-04'), changes: <Wrapper>Added wasted Astral Power module.</Wrapper>, contributors: [Iskalla], }, { date: new Date('2017-9-02'), changes: <Wrapper>Added <SpellLink id={SPELLS.MOONFIRE_BEAR.id} icon /> and <SpellLink id={SPELLS.SUNFIRE.id} icon /> uptime modules.</Wrapper>, contributors: [Iskalla], }, { date: new Date('2017-8-30'), changes: <Wrapper>Added support.</Wrapper>, contributors: [Iskalla], }, ];
src/redux/utils/createDevToolsWindow.js
E-HERO-ZZ/tomatoTime
import React from 'react' import ReactDOM from 'react-dom' import { Provider } from 'react-redux' import DevTools from 'containers/DevToolsWindow' export default function createDevToolsWindow (store) { const win = window.open( null, 'redux-devtools', // give it a name so it reuses the same window `width=400,height=${window.outerHeight},menubar=no,location=no,resizable=yes,scrollbars=no,status=no` ) // reload in case it's reusing the same window with the old content win.location.reload() // wait a little bit for it to reload, then render setTimeout(() => { // Wait for the reload to prevent: // "Uncaught Error: Invariant Violation: _registerComponent(...): Target container is not a DOM element." win.document.write('<div id="react-devtools-root"></div>') win.document.body.style.margin = '0' ReactDOM.render( <Provider store={store}> <DevTools /> </Provider> , win.document.getElementById('react-devtools-root') ) }, 10) }
ajax/libs/rxjs/2.4.10/rx.js
sitic/cdnjs
// Copyright (c) Microsoft Open Technologies, Inc. All rights reserved. See License.txt in the project root for license information. ;(function (undefined) { var objectTypes = { 'boolean': false, 'function': true, 'object': true, 'number': false, 'string': false, 'undefined': false }; var root = (objectTypes[typeof window] && window) || this, freeExports = objectTypes[typeof exports] && exports && !exports.nodeType && exports, freeModule = objectTypes[typeof module] && module && !module.nodeType && module, moduleExports = freeModule && freeModule.exports === freeExports && freeExports, freeGlobal = objectTypes[typeof global] && global; if (freeGlobal && (freeGlobal.global === freeGlobal || freeGlobal.window === freeGlobal)) { root = freeGlobal; } var Rx = { internals: {}, config: { Promise: root.Promise }, helpers: { } }; // Defaults var noop = Rx.helpers.noop = function () { }, notDefined = Rx.helpers.notDefined = function (x) { return typeof x === 'undefined'; }, isScheduler = Rx.helpers.isScheduler = function (x) { return x instanceof Rx.Scheduler; }, identity = Rx.helpers.identity = function (x) { return x; }, pluck = Rx.helpers.pluck = function (property) { return function (x) { return x[property]; }; }, just = Rx.helpers.just = function (value) { return function () { return value; }; }, defaultNow = Rx.helpers.defaultNow = Date.now, defaultComparer = Rx.helpers.defaultComparer = function (x, y) { return isEqual(x, y); }, defaultSubComparer = Rx.helpers.defaultSubComparer = function (x, y) { return x > y ? 1 : (x < y ? -1 : 0); }, defaultKeySerializer = Rx.helpers.defaultKeySerializer = function (x) { return x.toString(); }, defaultError = Rx.helpers.defaultError = function (err) { throw err; }, isPromise = Rx.helpers.isPromise = function (p) { return !!p && typeof p.then === 'function'; }, asArray = Rx.helpers.asArray = function () { return Array.prototype.slice.call(arguments); }, not = Rx.helpers.not = function (a) { return !a; }, isFunction = Rx.helpers.isFunction = (function () { var isFn = function (value) { return typeof value == 'function' || false; } // fallback for older versions of Chrome and Safari if (isFn(/x/)) { isFn = function(value) { return typeof value == 'function' && toString.call(value) == '[object Function]'; }; } return isFn; }()); function cloneArray(arr) { for(var a = [], i = 0, len = arr.length; i < len; i++) { a.push(arr[i]); } return a;} Rx.config.longStackSupport = false; var hasStacks = false; try { throw new Error(); } catch (e) { hasStacks = !!e.stack; } // All code after this point will be filtered from stack traces reported by RxJS var rStartingLine = captureLine(), rFileName; var STACK_JUMP_SEPARATOR = "From previous event:"; function makeStackTraceLong(error, observable) { // If possible, transform the error stack trace by removing Node and RxJS // cruft, then concatenating with the stack trace of `observable`. if (hasStacks && observable.stack && typeof error === "object" && error !== null && error.stack && error.stack.indexOf(STACK_JUMP_SEPARATOR) === -1 ) { var stacks = []; for (var o = observable; !!o; o = o.source) { if (o.stack) { stacks.unshift(o.stack); } } stacks.unshift(error.stack); var concatedStacks = stacks.join("\n" + STACK_JUMP_SEPARATOR + "\n"); error.stack = filterStackString(concatedStacks); } } function filterStackString(stackString) { var lines = stackString.split("\n"), desiredLines = []; for (var i = 0, len = lines.length; i < len; i++) { var line = lines[i]; if (!isInternalFrame(line) && !isNodeFrame(line) && line) { desiredLines.push(line); } } return desiredLines.join("\n"); } function isInternalFrame(stackLine) { var fileNameAndLineNumber = getFileNameAndLineNumber(stackLine); if (!fileNameAndLineNumber) { return false; } var fileName = fileNameAndLineNumber[0], lineNumber = fileNameAndLineNumber[1]; return fileName === rFileName && lineNumber >= rStartingLine && lineNumber <= rEndingLine; } function isNodeFrame(stackLine) { return stackLine.indexOf("(module.js:") !== -1 || stackLine.indexOf("(node.js:") !== -1; } function captureLine() { if (!hasStacks) { return; } try { throw new Error(); } catch (e) { var lines = e.stack.split("\n"); var firstLine = lines[0].indexOf("@") > 0 ? lines[1] : lines[2]; var fileNameAndLineNumber = getFileNameAndLineNumber(firstLine); if (!fileNameAndLineNumber) { return; } rFileName = fileNameAndLineNumber[0]; return fileNameAndLineNumber[1]; } } function getFileNameAndLineNumber(stackLine) { // Named functions: "at functionName (filename:lineNumber:columnNumber)" var attempt1 = /at .+ \((.+):(\d+):(?:\d+)\)$/.exec(stackLine); if (attempt1) { return [attempt1[1], Number(attempt1[2])]; } // Anonymous functions: "at filename:lineNumber:columnNumber" var attempt2 = /at ([^ ]+):(\d+):(?:\d+)$/.exec(stackLine); if (attempt2) { return [attempt2[1], Number(attempt2[2])]; } // Firefox style: "function@filename:lineNumber or @filename:lineNumber" var attempt3 = /.*@(.+):(\d+)$/.exec(stackLine); if (attempt3) { return [attempt3[1], Number(attempt3[2])]; } } var EmptyError = Rx.EmptyError = function() { this.message = 'Sequence contains no elements.'; Error.call(this); }; EmptyError.prototype = Error.prototype; var ObjectDisposedError = Rx.ObjectDisposedError = function() { this.message = 'Object has been disposed'; Error.call(this); }; ObjectDisposedError.prototype = Error.prototype; var ArgumentOutOfRangeError = Rx.ArgumentOutOfRangeError = function () { this.message = 'Argument out of range'; Error.call(this); }; ArgumentOutOfRangeError.prototype = Error.prototype; var NotSupportedError = Rx.NotSupportedError = function (message) { this.message = message || 'This operation is not supported'; Error.call(this); }; NotSupportedError.prototype = Error.prototype; var NotImplementedError = Rx.NotImplementedError = function (message) { this.message = message || 'This operation is not implemented'; Error.call(this); }; NotImplementedError.prototype = Error.prototype; var notImplemented = Rx.helpers.notImplemented = function () { throw new NotImplementedError(); }; var notSupported = Rx.helpers.notSupported = function () { throw new NotSupportedError(); }; // Shim in iterator support var $iterator$ = (typeof Symbol === 'function' && Symbol.iterator) || '_es6shim_iterator_'; // Bug for mozilla version if (root.Set && typeof new root.Set()['@@iterator'] === 'function') { $iterator$ = '@@iterator'; } var doneEnumerator = Rx.doneEnumerator = { done: true, value: undefined }; var isIterable = Rx.helpers.isIterable = function (o) { return o[$iterator$] !== undefined; } var isArrayLike = Rx.helpers.isArrayLike = function (o) { return o && o.length !== undefined; } Rx.helpers.iterator = $iterator$; var bindCallback = Rx.internals.bindCallback = function (func, thisArg, argCount) { if (typeof thisArg === 'undefined') { return func; } switch(argCount) { case 0: return function() { return func.call(thisArg) }; case 1: return function(arg) { return func.call(thisArg, arg); } case 2: return function(value, index) { return func.call(thisArg, value, index); }; case 3: return function(value, index, collection) { return func.call(thisArg, value, index, collection); }; } return function() { return func.apply(thisArg, arguments); }; }; /** Used to determine if values are of the language type Object */ var dontEnums = ['toString', 'toLocaleString', 'valueOf', 'hasOwnProperty', 'isPrototypeOf', 'propertyIsEnumerable', 'constructor'], dontEnumsLength = dontEnums.length; /** `Object#toString` result shortcuts */ var argsClass = '[object Arguments]', arrayClass = '[object Array]', boolClass = '[object Boolean]', dateClass = '[object Date]', errorClass = '[object Error]', funcClass = '[object Function]', numberClass = '[object Number]', objectClass = '[object Object]', regexpClass = '[object RegExp]', stringClass = '[object String]'; var toString = Object.prototype.toString, hasOwnProperty = Object.prototype.hasOwnProperty, supportsArgsClass = toString.call(arguments) == argsClass, // For less <IE9 && FF<4 supportNodeClass, errorProto = Error.prototype, objectProto = Object.prototype, stringProto = String.prototype, propertyIsEnumerable = objectProto.propertyIsEnumerable; try { supportNodeClass = !(toString.call(document) == objectClass && !({ 'toString': 0 } + '')); } catch (e) { supportNodeClass = true; } var nonEnumProps = {}; nonEnumProps[arrayClass] = nonEnumProps[dateClass] = nonEnumProps[numberClass] = { 'constructor': true, 'toLocaleString': true, 'toString': true, 'valueOf': true }; nonEnumProps[boolClass] = nonEnumProps[stringClass] = { 'constructor': true, 'toString': true, 'valueOf': true }; nonEnumProps[errorClass] = nonEnumProps[funcClass] = nonEnumProps[regexpClass] = { 'constructor': true, 'toString': true }; nonEnumProps[objectClass] = { 'constructor': true }; var support = {}; (function () { var ctor = function() { this.x = 1; }, props = []; ctor.prototype = { 'valueOf': 1, 'y': 1 }; for (var key in new ctor) { props.push(key); } for (key in arguments) { } // Detect if `name` or `message` properties of `Error.prototype` are enumerable by default. support.enumErrorProps = propertyIsEnumerable.call(errorProto, 'message') || propertyIsEnumerable.call(errorProto, 'name'); // Detect if `prototype` properties are enumerable by default. support.enumPrototypes = propertyIsEnumerable.call(ctor, 'prototype'); // Detect if `arguments` object indexes are non-enumerable support.nonEnumArgs = key != 0; // Detect if properties shadowing those on `Object.prototype` are non-enumerable. support.nonEnumShadows = !/valueOf/.test(props); }(1)); var isObject = Rx.internals.isObject = function(value) { var type = typeof value; return value && (type == 'function' || type == 'object') || false; }; function keysIn(object) { var result = []; if (!isObject(object)) { return result; } if (support.nonEnumArgs && object.length && isArguments(object)) { object = slice.call(object); } var skipProto = support.enumPrototypes && typeof object == 'function', skipErrorProps = support.enumErrorProps && (object === errorProto || object instanceof Error); for (var key in object) { if (!(skipProto && key == 'prototype') && !(skipErrorProps && (key == 'message' || key == 'name'))) { result.push(key); } } if (support.nonEnumShadows && object !== objectProto) { var ctor = object.constructor, index = -1, length = dontEnumsLength; if (object === (ctor && ctor.prototype)) { var className = object === stringProto ? stringClass : object === errorProto ? errorClass : toString.call(object), nonEnum = nonEnumProps[className]; } while (++index < length) { key = dontEnums[index]; if (!(nonEnum && nonEnum[key]) && hasOwnProperty.call(object, key)) { result.push(key); } } } return result; } function internalFor(object, callback, keysFunc) { var index = -1, props = keysFunc(object), length = props.length; while (++index < length) { var key = props[index]; if (callback(object[key], key, object) === false) { break; } } return object; } function internalForIn(object, callback) { return internalFor(object, callback, keysIn); } function isNode(value) { // IE < 9 presents DOM nodes as `Object` objects except they have `toString` // methods that are `typeof` "string" and still can coerce nodes to strings return typeof value.toString != 'function' && typeof (value + '') == 'string'; } var isArguments = function(value) { return (value && typeof value == 'object') ? toString.call(value) == argsClass : false; } // fallback for browsers that can't detect `arguments` objects by [[Class]] if (!supportsArgsClass) { isArguments = function(value) { return (value && typeof value == 'object') ? hasOwnProperty.call(value, 'callee') : false; }; } var isEqual = Rx.internals.isEqual = function (x, y) { return deepEquals(x, y, [], []); }; /** @private * Used for deep comparison **/ function deepEquals(a, b, stackA, stackB) { // exit early for identical values if (a === b) { // treat `+0` vs. `-0` as not equal return a !== 0 || (1 / a == 1 / b); } var type = typeof a, otherType = typeof b; // exit early for unlike primitive values if (a === a && (a == null || b == null || (type != 'function' && type != 'object' && otherType != 'function' && otherType != 'object'))) { return false; } // compare [[Class]] names var className = toString.call(a), otherClass = toString.call(b); if (className == argsClass) { className = objectClass; } if (otherClass == argsClass) { otherClass = objectClass; } if (className != otherClass) { return false; } switch (className) { case boolClass: case dateClass: // coerce dates and booleans to numbers, dates to milliseconds and booleans // to `1` or `0` treating invalid dates coerced to `NaN` as not equal return +a == +b; case numberClass: // treat `NaN` vs. `NaN` as equal return (a != +a) ? b != +b : // but treat `-0` vs. `+0` as not equal (a == 0 ? (1 / a == 1 / b) : a == +b); case regexpClass: case stringClass: // coerce regexes to strings (http://es5.github.io/#x15.10.6.4) // treat string primitives and their corresponding object instances as equal return a == String(b); } var isArr = className == arrayClass; if (!isArr) { // exit for functions and DOM nodes if (className != objectClass || (!support.nodeClass && (isNode(a) || isNode(b)))) { return false; } // in older versions of Opera, `arguments` objects have `Array` constructors var ctorA = !support.argsObject && isArguments(a) ? Object : a.constructor, ctorB = !support.argsObject && isArguments(b) ? Object : b.constructor; // non `Object` object instances with different constructors are not equal if (ctorA != ctorB && !(hasOwnProperty.call(a, 'constructor') && hasOwnProperty.call(b, 'constructor')) && !(isFunction(ctorA) && ctorA instanceof ctorA && isFunction(ctorB) && ctorB instanceof ctorB) && ('constructor' in a && 'constructor' in b) ) { return false; } } // assume cyclic structures are equal // the algorithm for detecting cyclic structures is adapted from ES 5.1 // section 15.12.3, abstract operation `JO` (http://es5.github.io/#x15.12.3) var initedStack = !stackA; stackA || (stackA = []); stackB || (stackB = []); var length = stackA.length; while (length--) { if (stackA[length] == a) { return stackB[length] == b; } } var size = 0; var result = true; // add `a` and `b` to the stack of traversed objects stackA.push(a); stackB.push(b); // recursively compare objects and arrays (susceptible to call stack limits) if (isArr) { // compare lengths to determine if a deep comparison is necessary length = a.length; size = b.length; result = size == length; if (result) { // deep compare the contents, ignoring non-numeric properties while (size--) { var index = length, value = b[size]; if (!(result = deepEquals(a[size], value, stackA, stackB))) { break; } } } } else { // deep compare objects using `forIn`, instead of `forOwn`, to avoid `Object.keys` // which, in this case, is more costly internalForIn(b, function(value, key, b) { if (hasOwnProperty.call(b, key)) { // count the number of properties. size++; // deep compare each property value. return (result = hasOwnProperty.call(a, key) && deepEquals(a[key], value, stackA, stackB)); } }); if (result) { // ensure both objects have the same number of properties internalForIn(a, function(value, key, a) { if (hasOwnProperty.call(a, key)) { // `size` will be `-1` if `a` has more properties than `b` return (result = --size > -1); } }); } } stackA.pop(); stackB.pop(); return result; } var hasProp = {}.hasOwnProperty, slice = Array.prototype.slice; var inherits = this.inherits = Rx.internals.inherits = function (child, parent) { function __() { this.constructor = child; } __.prototype = parent.prototype; child.prototype = new __(); }; var addProperties = Rx.internals.addProperties = function (obj) { for(var sources = [], i = 1, len = arguments.length; i < len; i++) { sources.push(arguments[i]); } for (var idx = 0, ln = sources.length; idx < ln; idx++) { var source = sources[idx]; for (var prop in source) { obj[prop] = source[prop]; } } }; // Rx Utils var addRef = Rx.internals.addRef = function (xs, r) { return new AnonymousObservable(function (observer) { return new CompositeDisposable(r.getDisposable(), xs.subscribe(observer)); }); }; function arrayInitialize(count, factory) { var a = new Array(count); for (var i = 0; i < count; i++) { a[i] = factory(); } return a; } var errorObj = {e: {}}; var tryCatchTarget; function tryCatcher() { try { return tryCatchTarget.apply(this, arguments); } catch (e) { errorObj.e = e; return errorObj; } } function tryCatch(fn) { if (!isFunction(fn)) { throw new TypeError('fn must be a function'); } tryCatchTarget = fn; return tryCatcher; } function thrower(e) { throw e; } // Collections function IndexedItem(id, value) { this.id = id; this.value = value; } IndexedItem.prototype.compareTo = function (other) { var c = this.value.compareTo(other.value); c === 0 && (c = this.id - other.id); return c; }; // Priority Queue for Scheduling var PriorityQueue = Rx.internals.PriorityQueue = function (capacity) { this.items = new Array(capacity); this.length = 0; }; var priorityProto = PriorityQueue.prototype; priorityProto.isHigherPriority = function (left, right) { return this.items[left].compareTo(this.items[right]) < 0; }; priorityProto.percolate = function (index) { if (index >= this.length || index < 0) { return; } var parent = index - 1 >> 1; if (parent < 0 || parent === index) { return; } if (this.isHigherPriority(index, parent)) { var temp = this.items[index]; this.items[index] = this.items[parent]; this.items[parent] = temp; this.percolate(parent); } }; priorityProto.heapify = function (index) { +index || (index = 0); if (index >= this.length || index < 0) { return; } var left = 2 * index + 1, right = 2 * index + 2, first = index; if (left < this.length && this.isHigherPriority(left, first)) { first = left; } if (right < this.length && this.isHigherPriority(right, first)) { first = right; } if (first !== index) { var temp = this.items[index]; this.items[index] = this.items[first]; this.items[first] = temp; this.heapify(first); } }; priorityProto.peek = function () { return this.items[0].value; }; priorityProto.removeAt = function (index) { this.items[index] = this.items[--this.length]; this.items[this.length] = undefined; this.heapify(); }; priorityProto.dequeue = function () { var result = this.peek(); this.removeAt(0); return result; }; priorityProto.enqueue = function (item) { var index = this.length++; this.items[index] = new IndexedItem(PriorityQueue.count++, item); this.percolate(index); }; priorityProto.remove = function (item) { for (var i = 0; i < this.length; i++) { if (this.items[i].value === item) { this.removeAt(i); return true; } } return false; }; PriorityQueue.count = 0; /** * Represents a group of disposable resources that are disposed together. * @constructor */ var CompositeDisposable = Rx.CompositeDisposable = function () { var args = [], i, len; if (Array.isArray(arguments[0])) { args = arguments[0]; len = args.length; } else { len = arguments.length; args = new Array(len); for(i = 0; i < len; i++) { args[i] = arguments[i]; } } for(i = 0; i < len; i++) { if (!isDisposable(args[i])) { throw new TypeError('Not a disposable'); } } this.disposables = args; this.isDisposed = false; this.length = args.length; }; var CompositeDisposablePrototype = CompositeDisposable.prototype; /** * Adds a disposable to the CompositeDisposable or disposes the disposable if the CompositeDisposable is disposed. * @param {Mixed} item Disposable to add. */ CompositeDisposablePrototype.add = function (item) { if (this.isDisposed) { item.dispose(); } else { this.disposables.push(item); this.length++; } }; /** * Removes and disposes the first occurrence of a disposable from the CompositeDisposable. * @param {Mixed} item Disposable to remove. * @returns {Boolean} true if found; false otherwise. */ CompositeDisposablePrototype.remove = function (item) { var shouldDispose = false; if (!this.isDisposed) { var idx = this.disposables.indexOf(item); if (idx !== -1) { shouldDispose = true; this.disposables.splice(idx, 1); this.length--; item.dispose(); } } return shouldDispose; }; /** * Disposes all disposables in the group and removes them from the group. */ CompositeDisposablePrototype.dispose = function () { if (!this.isDisposed) { this.isDisposed = true; var len = this.disposables.length, currentDisposables = new Array(len); for(var i = 0; i < len; i++) { currentDisposables[i] = this.disposables[i]; } this.disposables = []; this.length = 0; for (i = 0; i < len; i++) { currentDisposables[i].dispose(); } } }; /** * Provides a set of static methods for creating Disposables. * @param {Function} dispose Action to run during the first call to dispose. The action is guaranteed to be run at most once. */ var Disposable = Rx.Disposable = function (action) { this.isDisposed = false; this.action = action || noop; }; /** Performs the task of cleaning up resources. */ Disposable.prototype.dispose = function () { if (!this.isDisposed) { this.action(); this.isDisposed = true; } }; /** * Creates a disposable object that invokes the specified action when disposed. * @param {Function} dispose Action to run during the first call to dispose. The action is guaranteed to be run at most once. * @return {Disposable} The disposable object that runs the given action upon disposal. */ var disposableCreate = Disposable.create = function (action) { return new Disposable(action); }; /** * Gets the disposable that does nothing when disposed. */ var disposableEmpty = Disposable.empty = { dispose: noop }; /** * Validates whether the given object is a disposable * @param {Object} Object to test whether it has a dispose method * @returns {Boolean} true if a disposable object, else false. */ var isDisposable = Disposable.isDisposable = function (d) { return d && isFunction(d.dispose); }; var checkDisposed = Disposable.checkDisposed = function (disposable) { if (disposable.isDisposed) { throw new ObjectDisposedError(); } }; var SingleAssignmentDisposable = Rx.SingleAssignmentDisposable = (function () { function BooleanDisposable () { this.isDisposed = false; this.current = null; } var booleanDisposablePrototype = BooleanDisposable.prototype; /** * Gets the underlying disposable. * @return The underlying disposable. */ booleanDisposablePrototype.getDisposable = function () { return this.current; }; /** * Sets the underlying disposable. * @param {Disposable} value The new underlying disposable. */ booleanDisposablePrototype.setDisposable = function (value) { var shouldDispose = this.isDisposed; if (!shouldDispose) { var old = this.current; this.current = value; } old && old.dispose(); shouldDispose && value && value.dispose(); }; /** * Disposes the underlying disposable as well as all future replacements. */ booleanDisposablePrototype.dispose = function () { if (!this.isDisposed) { this.isDisposed = true; var old = this.current; this.current = null; } old && old.dispose(); }; return BooleanDisposable; }()); var SerialDisposable = Rx.SerialDisposable = SingleAssignmentDisposable; /** * Represents a disposable resource that only disposes its underlying disposable resource when all dependent disposable objects have been disposed. */ var RefCountDisposable = Rx.RefCountDisposable = (function () { function InnerDisposable(disposable) { this.disposable = disposable; this.disposable.count++; this.isInnerDisposed = false; } InnerDisposable.prototype.dispose = function () { if (!this.disposable.isDisposed && !this.isInnerDisposed) { this.isInnerDisposed = true; this.disposable.count--; if (this.disposable.count === 0 && this.disposable.isPrimaryDisposed) { this.disposable.isDisposed = true; this.disposable.underlyingDisposable.dispose(); } } }; /** * Initializes a new instance of the RefCountDisposable with the specified disposable. * @constructor * @param {Disposable} disposable Underlying disposable. */ function RefCountDisposable(disposable) { this.underlyingDisposable = disposable; this.isDisposed = false; this.isPrimaryDisposed = false; this.count = 0; } /** * Disposes the underlying disposable only when all dependent disposables have been disposed */ RefCountDisposable.prototype.dispose = function () { if (!this.isDisposed && !this.isPrimaryDisposed) { this.isPrimaryDisposed = true; if (this.count === 0) { this.isDisposed = true; this.underlyingDisposable.dispose(); } } }; /** * Returns a dependent disposable that when disposed decreases the refcount on the underlying disposable. * @returns {Disposable} A dependent disposable contributing to the reference count that manages the underlying disposable's lifetime. */ RefCountDisposable.prototype.getDisposable = function () { return this.isDisposed ? disposableEmpty : new InnerDisposable(this); }; return RefCountDisposable; })(); function ScheduledDisposable(scheduler, disposable) { this.scheduler = scheduler; this.disposable = disposable; this.isDisposed = false; } function scheduleItem(s, self) { if (!self.isDisposed) { self.isDisposed = true; self.disposable.dispose(); } } ScheduledDisposable.prototype.dispose = function () { this.scheduler.scheduleWithState(this, scheduleItem); }; var ScheduledItem = Rx.internals.ScheduledItem = function (scheduler, state, action, dueTime, comparer) { this.scheduler = scheduler; this.state = state; this.action = action; this.dueTime = dueTime; this.comparer = comparer || defaultSubComparer; this.disposable = new SingleAssignmentDisposable(); } ScheduledItem.prototype.invoke = function () { this.disposable.setDisposable(this.invokeCore()); }; ScheduledItem.prototype.compareTo = function (other) { return this.comparer(this.dueTime, other.dueTime); }; ScheduledItem.prototype.isCancelled = function () { return this.disposable.isDisposed; }; ScheduledItem.prototype.invokeCore = function () { return this.action(this.scheduler, this.state); }; /** Provides a set of static properties to access commonly used schedulers. */ var Scheduler = Rx.Scheduler = (function () { function Scheduler(now, schedule, scheduleRelative, scheduleAbsolute) { this.now = now; this._schedule = schedule; this._scheduleRelative = scheduleRelative; this._scheduleAbsolute = scheduleAbsolute; } function invokeAction(scheduler, action) { action(); return disposableEmpty; } var schedulerProto = Scheduler.prototype; /** * Schedules an action to be executed. * @param {Function} action Action to execute. * @returns {Disposable} The disposable object used to cancel the scheduled action (best effort). */ schedulerProto.schedule = function (action) { return this._schedule(action, invokeAction); }; /** * Schedules an action to be executed. * @param state State passed to the action to be executed. * @param {Function} action Action to be executed. * @returns {Disposable} The disposable object used to cancel the scheduled action (best effort). */ schedulerProto.scheduleWithState = function (state, action) { return this._schedule(state, action); }; /** * Schedules an action to be executed after the specified relative due time. * @param {Function} action Action to execute. * @param {Number} dueTime Relative time after which to execute the action. * @returns {Disposable} The disposable object used to cancel the scheduled action (best effort). */ schedulerProto.scheduleWithRelative = function (dueTime, action) { return this._scheduleRelative(action, dueTime, invokeAction); }; /** * Schedules an action to be executed after dueTime. * @param state State passed to the action to be executed. * @param {Function} action Action to be executed. * @param {Number} dueTime Relative time after which to execute the action. * @returns {Disposable} The disposable object used to cancel the scheduled action (best effort). */ schedulerProto.scheduleWithRelativeAndState = function (state, dueTime, action) { return this._scheduleRelative(state, dueTime, action); }; /** * Schedules an action to be executed at the specified absolute due time. * @param {Function} action Action to execute. * @param {Number} dueTime Absolute time at which to execute the action. * @returns {Disposable} The disposable object used to cancel the scheduled action (best effort). */ schedulerProto.scheduleWithAbsolute = function (dueTime, action) { return this._scheduleAbsolute(action, dueTime, invokeAction); }; /** * Schedules an action to be executed at dueTime. * @param {Mixed} state State passed to the action to be executed. * @param {Function} action Action to be executed. * @param {Number}dueTime Absolute time at which to execute the action. * @returns {Disposable} The disposable object used to cancel the scheduled action (best effort). */ schedulerProto.scheduleWithAbsoluteAndState = function (state, dueTime, action) { return this._scheduleAbsolute(state, dueTime, action); }; /** Gets the current time according to the local machine's system clock. */ Scheduler.now = defaultNow; /** * Normalizes the specified TimeSpan value to a positive value. * @param {Number} timeSpan The time span value to normalize. * @returns {Number} The specified TimeSpan value if it is zero or positive; otherwise, 0 */ Scheduler.normalize = function (timeSpan) { timeSpan < 0 && (timeSpan = 0); return timeSpan; }; return Scheduler; }()); var normalizeTime = Scheduler.normalize; (function (schedulerProto) { function invokeRecImmediate(scheduler, pair) { var state = pair[0], action = pair[1], group = new CompositeDisposable(); function recursiveAction(state1) { action(state1, function (state2) { var isAdded = false, isDone = false, d = scheduler.scheduleWithState(state2, function (scheduler1, state3) { if (isAdded) { group.remove(d); } else { isDone = true; } recursiveAction(state3); return disposableEmpty; }); if (!isDone) { group.add(d); isAdded = true; } }); } recursiveAction(state); return group; } function invokeRecDate(scheduler, pair, method) { var state = pair[0], action = pair[1], group = new CompositeDisposable(); function recursiveAction(state1) { action(state1, function (state2, dueTime1) { var isAdded = false, isDone = false, d = scheduler[method](state2, dueTime1, function (scheduler1, state3) { if (isAdded) { group.remove(d); } else { isDone = true; } recursiveAction(state3); return disposableEmpty; }); if (!isDone) { group.add(d); isAdded = true; } }); }; recursiveAction(state); return group; } function scheduleInnerRecursive(action, self) { action(function(dt) { self(action, dt); }); } /** * Schedules an action to be executed recursively. * @param {Function} action Action to execute recursively. The parameter passed to the action is used to trigger recursive scheduling of the action. * @returns {Disposable} The disposable object used to cancel the scheduled action (best effort). */ schedulerProto.scheduleRecursive = function (action) { return this.scheduleRecursiveWithState(action, function (_action, self) { _action(function () { self(_action); }); }); }; /** * Schedules an action to be executed recursively. * @param {Mixed} state State passed to the action to be executed. * @param {Function} action Action to execute recursively. The last parameter passed to the action is used to trigger recursive scheduling of the action, passing in recursive invocation state. * @returns {Disposable} The disposable object used to cancel the scheduled action (best effort). */ schedulerProto.scheduleRecursiveWithState = function (state, action) { return this.scheduleWithState([state, action], invokeRecImmediate); }; /** * Schedules an action to be executed recursively after a specified relative due time. * @param {Function} action Action to execute recursively. The parameter passed to the action is used to trigger recursive scheduling of the action at the specified relative time. * @param {Number}dueTime Relative time after which to execute the action for the first time. * @returns {Disposable} The disposable object used to cancel the scheduled action (best effort). */ schedulerProto.scheduleRecursiveWithRelative = function (dueTime, action) { return this.scheduleRecursiveWithRelativeAndState(action, dueTime, scheduleInnerRecursive); }; /** * Schedules an action to be executed recursively after a specified relative due time. * @param {Mixed} state State passed to the action to be executed. * @param {Function} action Action to execute recursively. The last parameter passed to the action is used to trigger recursive scheduling of the action, passing in the recursive due time and invocation state. * @param {Number}dueTime Relative time after which to execute the action for the first time. * @returns {Disposable} The disposable object used to cancel the scheduled action (best effort). */ schedulerProto.scheduleRecursiveWithRelativeAndState = function (state, dueTime, action) { return this._scheduleRelative([state, action], dueTime, function (s, p) { return invokeRecDate(s, p, 'scheduleWithRelativeAndState'); }); }; /** * Schedules an action to be executed recursively at a specified absolute due time. * @param {Function} action Action to execute recursively. The parameter passed to the action is used to trigger recursive scheduling of the action at the specified absolute time. * @param {Number}dueTime Absolute time at which to execute the action for the first time. * @returns {Disposable} The disposable object used to cancel the scheduled action (best effort). */ schedulerProto.scheduleRecursiveWithAbsolute = function (dueTime, action) { return this.scheduleRecursiveWithAbsoluteAndState(action, dueTime, scheduleInnerRecursive); }; /** * Schedules an action to be executed recursively at a specified absolute due time. * @param {Mixed} state State passed to the action to be executed. * @param {Function} action Action to execute recursively. The last parameter passed to the action is used to trigger recursive scheduling of the action, passing in the recursive due time and invocation state. * @param {Number}dueTime Absolute time at which to execute the action for the first time. * @returns {Disposable} The disposable object used to cancel the scheduled action (best effort). */ schedulerProto.scheduleRecursiveWithAbsoluteAndState = function (state, dueTime, action) { return this._scheduleAbsolute([state, action], dueTime, function (s, p) { return invokeRecDate(s, p, 'scheduleWithAbsoluteAndState'); }); }; }(Scheduler.prototype)); (function (schedulerProto) { /** * Schedules a periodic piece of work by dynamically discovering the scheduler's capabilities. The periodic task will be scheduled using window.setInterval for the base implementation. * @param {Number} period Period for running the work periodically. * @param {Function} action Action to be executed. * @returns {Disposable} The disposable object used to cancel the scheduled recurring action (best effort). */ Scheduler.prototype.schedulePeriodic = function (period, action) { return this.schedulePeriodicWithState(null, period, action); }; /** * Schedules a periodic piece of work by dynamically discovering the scheduler's capabilities. The periodic task will be scheduled using window.setInterval for the base implementation. * @param {Mixed} state Initial state passed to the action upon the first iteration. * @param {Number} period Period for running the work periodically. * @param {Function} action Action to be executed, potentially updating the state. * @returns {Disposable} The disposable object used to cancel the scheduled recurring action (best effort). */ Scheduler.prototype.schedulePeriodicWithState = function(state, period, action) { if (typeof root.setInterval === 'undefined') { throw new NotSupportedError(); } period = normalizeTime(period); var s = state, id = root.setInterval(function () { s = action(s); }, period); return disposableCreate(function () { root.clearInterval(id); }); }; }(Scheduler.prototype)); (function (schedulerProto) { /** * Returns a scheduler that wraps the original scheduler, adding exception handling for scheduled actions. * @param {Function} handler Handler that's run if an exception is caught. The exception will be rethrown if the handler returns false. * @returns {Scheduler} Wrapper around the original scheduler, enforcing exception handling. */ schedulerProto.catchError = schedulerProto['catch'] = function (handler) { return new CatchScheduler(this, handler); }; }(Scheduler.prototype)); var SchedulePeriodicRecursive = Rx.internals.SchedulePeriodicRecursive = (function () { function tick(command, recurse) { recurse(0, this._period); try { this._state = this._action(this._state); } catch (e) { this._cancel.dispose(); throw e; } } function SchedulePeriodicRecursive(scheduler, state, period, action) { this._scheduler = scheduler; this._state = state; this._period = period; this._action = action; } SchedulePeriodicRecursive.prototype.start = function () { var d = new SingleAssignmentDisposable(); this._cancel = d; d.setDisposable(this._scheduler.scheduleRecursiveWithRelativeAndState(0, this._period, tick.bind(this))); return d; }; return SchedulePeriodicRecursive; }()); /** Gets a scheduler that schedules work immediately on the current thread. */ var immediateScheduler = Scheduler.immediate = (function () { function scheduleNow(state, action) { return action(this, state); } return new Scheduler(defaultNow, scheduleNow, notSupported, notSupported); }()); /** * Gets a scheduler that schedules work as soon as possible on the current thread. */ var currentThreadScheduler = Scheduler.currentThread = (function () { var queue; function runTrampoline () { while (queue.length > 0) { var item = queue.dequeue(); !item.isCancelled() && item.invoke(); } } function scheduleNow(state, action) { var si = new ScheduledItem(this, state, action, this.now()); if (!queue) { queue = new PriorityQueue(4); queue.enqueue(si); var result = tryCatch(runTrampoline)(); queue = null; if (result === errorObj) { return thrower(result.e); } } else { queue.enqueue(si); } return si.disposable; } var currentScheduler = new Scheduler(defaultNow, scheduleNow, notSupported, notSupported); currentScheduler.scheduleRequired = function () { return !queue; }; return currentScheduler; }()); var scheduleMethod, clearMethod; var localTimer = (function () { var localSetTimeout, localClearTimeout = noop; if (!!root.WScript) { localSetTimeout = function (fn, time) { root.WScript.Sleep(time); fn(); }; } else if (!!root.setTimeout) { localSetTimeout = root.setTimeout; localClearTimeout = root.clearTimeout; } else { throw new NotSupportedError(); } return { setTimeout: localSetTimeout, clearTimeout: localClearTimeout }; }()); var localSetTimeout = localTimer.setTimeout, localClearTimeout = localTimer.clearTimeout; (function () { var nextHandle = 1, tasksByHandle = {}, currentlyRunning = false; clearMethod = function (handle) { delete tasksByHandle[handle]; }; function runTask(handle) { if (currentlyRunning) { localSetTimeout(function () { runTask(handle) }, 0); } else { var task = tasksByHandle[handle]; if (task) { currentlyRunning = true; var result = tryCatch(task)(); clearMethod(handle); currentlyRunning = false; if (result === errorObj) { return thrower(result.e); } } } } var reNative = RegExp('^' + String(toString) .replace(/[.*+?^${}()|[\]\\]/g, '\\$&') .replace(/toString| for [^\]]+/g, '.*?') + '$' ); var setImmediate = typeof (setImmediate = freeGlobal && moduleExports && freeGlobal.setImmediate) == 'function' && !reNative.test(setImmediate) && setImmediate; function postMessageSupported () { // Ensure not in a worker if (!root.postMessage || root.importScripts) { return false; } var isAsync = false, oldHandler = root.onmessage; // Test for async root.onmessage = function () { isAsync = true; }; root.postMessage('', '*'); root.onmessage = oldHandler; return isAsync; } // Use in order, setImmediate, nextTick, postMessage, MessageChannel, script readystatechanged, setTimeout if (isFunction(setImmediate)) { scheduleMethod = function (action) { var id = nextHandle++; tasksByHandle[id] = action; setImmediate(function () { runTask(id); }); return id; }; } else if (typeof process !== 'undefined' && {}.toString.call(process) === '[object process]') { scheduleMethod = function (action) { var id = nextHandle++; tasksByHandle[id] = action; process.nextTick(function () { runTask(id); }); return id; }; } else if (postMessageSupported()) { var MSG_PREFIX = 'ms.rx.schedule' + Math.random(); function onGlobalPostMessage(event) { // Only if we're a match to avoid any other global events if (typeof event.data === 'string' && event.data.substring(0, MSG_PREFIX.length) === MSG_PREFIX) { runTask(event.data.substring(MSG_PREFIX.length)); } } if (root.addEventListener) { root.addEventListener('message', onGlobalPostMessage, false); } else { root.attachEvent('onmessage', onGlobalPostMessage, false); } scheduleMethod = function (action) { var id = nextHandle++; tasksByHandle[id] = action; root.postMessage(MSG_PREFIX + currentId, '*'); return id; }; } else if (!!root.MessageChannel) { var channel = new root.MessageChannel(); channel.port1.onmessage = function (e) { runTask(e.data); }; scheduleMethod = function (action) { var id = nextHandle++; tasksByHandle[id] = action; channel.port2.postMessage(id); return id; }; } else if ('document' in root && 'onreadystatechange' in root.document.createElement('script')) { scheduleMethod = function (action) { var scriptElement = root.document.createElement('script'); var id = nextHandle++; tasksByHandle[id] = action; scriptElement.onreadystatechange = function () { runTask(id); scriptElement.onreadystatechange = null; scriptElement.parentNode.removeChild(scriptElement); scriptElement = null; }; root.document.documentElement.appendChild(scriptElement); return id; }; } else { scheduleMethod = function (action) { var id = nextHandle++; tasksByHandle[id] = action; localSetTimeout(function () { runTask(id); }, 0); return id; }; } }()); /** * Gets a scheduler that schedules work via a timed callback based upon platform. */ var timeoutScheduler = Scheduler.timeout = Scheduler.default = (function () { function scheduleNow(state, action) { var scheduler = this, disposable = new SingleAssignmentDisposable(); var id = scheduleMethod(function () { if (!disposable.isDisposed) { disposable.setDisposable(action(scheduler, state)); } }); return new CompositeDisposable(disposable, disposableCreate(function () { clearMethod(id); })); } function scheduleRelative(state, dueTime, action) { var scheduler = this, dt = Scheduler.normalize(dueTime); if (dt === 0) { return scheduler.scheduleWithState(state, action); } var disposable = new SingleAssignmentDisposable(); var id = localSetTimeout(function () { if (!disposable.isDisposed) { disposable.setDisposable(action(scheduler, state)); } }, dt); return new CompositeDisposable(disposable, disposableCreate(function () { localClearTimeout(id); })); } function scheduleAbsolute(state, dueTime, action) { return this.scheduleWithRelativeAndState(state, dueTime - this.now(), action); } return new Scheduler(defaultNow, scheduleNow, scheduleRelative, scheduleAbsolute); })(); var CatchScheduler = (function (__super__) { function scheduleNow(state, action) { return this._scheduler.scheduleWithState(state, this._wrap(action)); } function scheduleRelative(state, dueTime, action) { return this._scheduler.scheduleWithRelativeAndState(state, dueTime, this._wrap(action)); } function scheduleAbsolute(state, dueTime, action) { return this._scheduler.scheduleWithAbsoluteAndState(state, dueTime, this._wrap(action)); } inherits(CatchScheduler, __super__); function CatchScheduler(scheduler, handler) { this._scheduler = scheduler; this._handler = handler; this._recursiveOriginal = null; this._recursiveWrapper = null; __super__.call(this, this._scheduler.now.bind(this._scheduler), scheduleNow, scheduleRelative, scheduleAbsolute); } CatchScheduler.prototype._clone = function (scheduler) { return new CatchScheduler(scheduler, this._handler); }; CatchScheduler.prototype._wrap = function (action) { var parent = this; return function (self, state) { try { return action(parent._getRecursiveWrapper(self), state); } catch (e) { if (!parent._handler(e)) { throw e; } return disposableEmpty; } }; }; CatchScheduler.prototype._getRecursiveWrapper = function (scheduler) { if (this._recursiveOriginal !== scheduler) { this._recursiveOriginal = scheduler; var wrapper = this._clone(scheduler); wrapper._recursiveOriginal = scheduler; wrapper._recursiveWrapper = wrapper; this._recursiveWrapper = wrapper; } return this._recursiveWrapper; }; CatchScheduler.prototype.schedulePeriodicWithState = function (state, period, action) { var self = this, failed = false, d = new SingleAssignmentDisposable(); d.setDisposable(this._scheduler.schedulePeriodicWithState(state, period, function (state1) { if (failed) { return null; } try { return action(state1); } catch (e) { failed = true; if (!self._handler(e)) { throw e; } d.dispose(); return null; } })); return d; }; return CatchScheduler; }(Scheduler)); /** * Represents a notification to an observer. */ var Notification = Rx.Notification = (function () { function Notification(kind, value, exception, accept, acceptObservable, toString) { this.kind = kind; this.value = value; this.exception = exception; this._accept = accept; this._acceptObservable = acceptObservable; this.toString = toString; } /** * Invokes the delegate corresponding to the notification or the observer's method corresponding to the notification and returns the produced result. * * @memberOf Notification * @param {Any} observerOrOnNext Delegate to invoke for an OnNext notification or Observer to invoke the notification on.. * @param {Function} onError Delegate to invoke for an OnError notification. * @param {Function} onCompleted Delegate to invoke for an OnCompleted notification. * @returns {Any} Result produced by the observation. */ Notification.prototype.accept = function (observerOrOnNext, onError, onCompleted) { return observerOrOnNext && typeof observerOrOnNext === 'object' ? this._acceptObservable(observerOrOnNext) : this._accept(observerOrOnNext, onError, onCompleted); }; /** * Returns an observable sequence with a single notification. * * @memberOf Notifications * @param {Scheduler} [scheduler] Scheduler to send out the notification calls on. * @returns {Observable} The observable sequence that surfaces the behavior of the notification upon subscription. */ Notification.prototype.toObservable = function (scheduler) { var self = this; isScheduler(scheduler) || (scheduler = immediateScheduler); return new AnonymousObservable(function (observer) { return scheduler.scheduleWithState(self, function (_, notification) { notification._acceptObservable(observer); notification.kind === 'N' && observer.onCompleted(); }); }); }; return Notification; })(); /** * Creates an object that represents an OnNext notification to an observer. * @param {Any} value The value contained in the notification. * @returns {Notification} The OnNext notification containing the value. */ var notificationCreateOnNext = Notification.createOnNext = (function () { function _accept(onNext) { return onNext(this.value); } function _acceptObservable(observer) { return observer.onNext(this.value); } function toString() { return 'OnNext(' + this.value + ')'; } return function (value) { return new Notification('N', value, null, _accept, _acceptObservable, toString); }; }()); /** * Creates an object that represents an OnError notification to an observer. * @param {Any} error The exception contained in the notification. * @returns {Notification} The OnError notification containing the exception. */ var notificationCreateOnError = Notification.createOnError = (function () { function _accept (onNext, onError) { return onError(this.exception); } function _acceptObservable(observer) { return observer.onError(this.exception); } function toString () { return 'OnError(' + this.exception + ')'; } return function (e) { return new Notification('E', null, e, _accept, _acceptObservable, toString); }; }()); /** * Creates an object that represents an OnCompleted notification to an observer. * @returns {Notification} The OnCompleted notification. */ var notificationCreateOnCompleted = Notification.createOnCompleted = (function () { function _accept (onNext, onError, onCompleted) { return onCompleted(); } function _acceptObservable(observer) { return observer.onCompleted(); } function toString () { return 'OnCompleted()'; } return function () { return new Notification('C', null, null, _accept, _acceptObservable, toString); }; }()); var Enumerator = Rx.internals.Enumerator = function (next) { this._next = next; }; Enumerator.prototype.next = function () { return this._next(); }; Enumerator.prototype[$iterator$] = function () { return this; } var Enumerable = Rx.internals.Enumerable = function (iterator) { this._iterator = iterator; }; Enumerable.prototype[$iterator$] = function () { return this._iterator(); }; Enumerable.prototype.concat = function () { var sources = this; return new AnonymousObservable(function (o) { var e = sources[$iterator$](); var isDisposed, subscription = new SerialDisposable(); var cancelable = immediateScheduler.scheduleRecursive(function (self) { if (isDisposed) { return; } try { var currentItem = e.next(); } catch (ex) { return o.onError(ex); } if (currentItem.done) { return o.onCompleted(); } // Check if promise var currentValue = currentItem.value; isPromise(currentValue) && (currentValue = observableFromPromise(currentValue)); var d = new SingleAssignmentDisposable(); subscription.setDisposable(d); d.setDisposable(currentValue.subscribe( function(x) { o.onNext(x); }, function(err) { o.onError(err); }, self) ); }); return new CompositeDisposable(subscription, cancelable, disposableCreate(function () { isDisposed = true; })); }); }; Enumerable.prototype.catchError = function () { var sources = this; return new AnonymousObservable(function (o) { var e = sources[$iterator$](); var isDisposed, subscription = new SerialDisposable(); var cancelable = immediateScheduler.scheduleRecursiveWithState(null, function (lastException, self) { if (isDisposed) { return; } try { var currentItem = e.next(); } catch (ex) { return observer.onError(ex); } if (currentItem.done) { if (lastException !== null) { o.onError(lastException); } else { o.onCompleted(); } return; } // Check if promise var currentValue = currentItem.value; isPromise(currentValue) && (currentValue = observableFromPromise(currentValue)); var d = new SingleAssignmentDisposable(); subscription.setDisposable(d); d.setDisposable(currentValue.subscribe( function(x) { o.onNext(x); }, self, function() { o.onCompleted(); })); }); return new CompositeDisposable(subscription, cancelable, disposableCreate(function () { isDisposed = true; })); }); }; Enumerable.prototype.catchErrorWhen = function (notificationHandler) { var sources = this; return new AnonymousObservable(function (o) { var exceptions = new Subject(), notifier = new Subject(), handled = notificationHandler(exceptions), notificationDisposable = handled.subscribe(notifier); var e = sources[$iterator$](); var isDisposed, lastException, subscription = new SerialDisposable(); var cancelable = immediateScheduler.scheduleRecursive(function (self) { if (isDisposed) { return; } try { var currentItem = e.next(); } catch (ex) { return o.onError(ex); } if (currentItem.done) { if (lastException) { o.onError(lastException); } else { o.onCompleted(); } return; } // Check if promise var currentValue = currentItem.value; isPromise(currentValue) && (currentValue = observableFromPromise(currentValue)); var outer = new SingleAssignmentDisposable(); var inner = new SingleAssignmentDisposable(); subscription.setDisposable(new CompositeDisposable(inner, outer)); outer.setDisposable(currentValue.subscribe( function(x) { o.onNext(x); }, function (exn) { inner.setDisposable(notifier.subscribe(self, function(ex) { o.onError(ex); }, function() { o.onCompleted(); })); exceptions.onNext(exn); }, function() { o.onCompleted(); })); }); return new CompositeDisposable(notificationDisposable, subscription, cancelable, disposableCreate(function () { isDisposed = true; })); }); }; var enumerableRepeat = Enumerable.repeat = function (value, repeatCount) { if (repeatCount == null) { repeatCount = -1; } return new Enumerable(function () { var left = repeatCount; return new Enumerator(function () { if (left === 0) { return doneEnumerator; } if (left > 0) { left--; } return { done: false, value: value }; }); }); }; var enumerableOf = Enumerable.of = function (source, selector, thisArg) { if (selector) { var selectorFn = bindCallback(selector, thisArg, 3); } return new Enumerable(function () { var index = -1; return new Enumerator( function () { return ++index < source.length ? { done: false, value: !selector ? source[index] : selectorFn(source[index], index, source) } : doneEnumerator; }); }); }; /** * Supports push-style iteration over an observable sequence. */ var Observer = Rx.Observer = function () { }; /** * Creates a notification callback from an observer. * @returns The action that forwards its input notification to the underlying observer. */ Observer.prototype.toNotifier = function () { var observer = this; return function (n) { return n.accept(observer); }; }; /** * Hides the identity of an observer. * @returns An observer that hides the identity of the specified observer. */ Observer.prototype.asObserver = function () { return new AnonymousObserver(this.onNext.bind(this), this.onError.bind(this), this.onCompleted.bind(this)); }; /** * Checks access to the observer for grammar violations. This includes checking for multiple OnError or OnCompleted calls, as well as reentrancy in any of the observer methods. * If a violation is detected, an Error is thrown from the offending observer method call. * @returns An observer that checks callbacks invocations against the observer grammar and, if the checks pass, forwards those to the specified observer. */ Observer.prototype.checked = function () { return new CheckedObserver(this); }; /** * Creates an observer from the specified OnNext, along with optional OnError, and OnCompleted actions. * @param {Function} [onNext] Observer's OnNext action implementation. * @param {Function} [onError] Observer's OnError action implementation. * @param {Function} [onCompleted] Observer's OnCompleted action implementation. * @returns {Observer} The observer object implemented using the given actions. */ var observerCreate = Observer.create = function (onNext, onError, onCompleted) { onNext || (onNext = noop); onError || (onError = defaultError); onCompleted || (onCompleted = noop); return new AnonymousObserver(onNext, onError, onCompleted); }; /** * Creates an observer from a notification callback. * * @static * @memberOf Observer * @param {Function} handler Action that handles a notification. * @returns The observer object that invokes the specified handler using a notification corresponding to each message it receives. */ Observer.fromNotifier = function (handler, thisArg) { return new AnonymousObserver(function (x) { return handler.call(thisArg, notificationCreateOnNext(x)); }, function (e) { return handler.call(thisArg, notificationCreateOnError(e)); }, function () { return handler.call(thisArg, notificationCreateOnCompleted()); }); }; /** * Schedules the invocation of observer methods on the given scheduler. * @param {Scheduler} scheduler Scheduler to schedule observer messages on. * @returns {Observer} Observer whose messages are scheduled on the given scheduler. */ Observer.prototype.notifyOn = function (scheduler) { return new ObserveOnObserver(scheduler, this); }; Observer.prototype.makeSafe = function(disposable) { return new AnonymousSafeObserver(this._onNext, this._onError, this._onCompleted, disposable); }; /** * Abstract base class for implementations of the Observer class. * This base class enforces the grammar of observers where OnError and OnCompleted are terminal messages. */ var AbstractObserver = Rx.internals.AbstractObserver = (function (__super__) { inherits(AbstractObserver, __super__); /** * Creates a new observer in a non-stopped state. */ function AbstractObserver() { this.isStopped = false; __super__.call(this); } // Must be implemented by other observers AbstractObserver.prototype.next = notImplemented; AbstractObserver.prototype.error = notImplemented; AbstractObserver.prototype.completed = notImplemented; /** * Notifies the observer of a new element in the sequence. * @param {Any} value Next element in the sequence. */ AbstractObserver.prototype.onNext = function (value) { if (!this.isStopped) { this.next(value); } }; /** * Notifies the observer that an exception has occurred. * @param {Any} error The error that has occurred. */ AbstractObserver.prototype.onError = function (error) { if (!this.isStopped) { this.isStopped = true; this.error(error); } }; /** * Notifies the observer of the end of the sequence. */ AbstractObserver.prototype.onCompleted = function () { if (!this.isStopped) { this.isStopped = true; this.completed(); } }; /** * Disposes the observer, causing it to transition to the stopped state. */ AbstractObserver.prototype.dispose = function () { this.isStopped = true; }; AbstractObserver.prototype.fail = function (e) { if (!this.isStopped) { this.isStopped = true; this.error(e); return true; } return false; }; return AbstractObserver; }(Observer)); /** * Class to create an Observer instance from delegate-based implementations of the on* methods. */ var AnonymousObserver = Rx.AnonymousObserver = (function (__super__) { inherits(AnonymousObserver, __super__); /** * Creates an observer from the specified OnNext, OnError, and OnCompleted actions. * @param {Any} onNext Observer's OnNext action implementation. * @param {Any} onError Observer's OnError action implementation. * @param {Any} onCompleted Observer's OnCompleted action implementation. */ function AnonymousObserver(onNext, onError, onCompleted) { __super__.call(this); this._onNext = onNext; this._onError = onError; this._onCompleted = onCompleted; } /** * Calls the onNext action. * @param {Any} value Next element in the sequence. */ AnonymousObserver.prototype.next = function (value) { this._onNext(value); }; /** * Calls the onError action. * @param {Any} error The error that has occurred. */ AnonymousObserver.prototype.error = function (error) { this._onError(error); }; /** * Calls the onCompleted action. */ AnonymousObserver.prototype.completed = function () { this._onCompleted(); }; return AnonymousObserver; }(AbstractObserver)); var CheckedObserver = (function (__super__) { inherits(CheckedObserver, __super__); function CheckedObserver(observer) { __super__.call(this); this._observer = observer; this._state = 0; // 0 - idle, 1 - busy, 2 - done } var CheckedObserverPrototype = CheckedObserver.prototype; CheckedObserverPrototype.onNext = function (value) { this.checkAccess(); var res = tryCatch(this._observer.onNext).call(this._observer, value); this._state = 0; res === errorObj && thrower(res.e); }; CheckedObserverPrototype.onError = function (err) { this.checkAccess(); var res = tryCatch(this._observer.onError).call(this._observer, err); this._state = 2; res === errorObj && thrower(res.e); }; CheckedObserverPrototype.onCompleted = function () { this.checkAccess(); var res = tryCatch(this._observer.onCompleted).call(this._observer); this._state = 2; res === errorObj && thrower(res.e); }; CheckedObserverPrototype.checkAccess = function () { if (this._state === 1) { throw new Error('Re-entrancy detected'); } if (this._state === 2) { throw new Error('Observer completed'); } if (this._state === 0) { this._state = 1; } }; return CheckedObserver; }(Observer)); var ScheduledObserver = Rx.internals.ScheduledObserver = (function (__super__) { inherits(ScheduledObserver, __super__); function ScheduledObserver(scheduler, observer) { __super__.call(this); this.scheduler = scheduler; this.observer = observer; this.isAcquired = false; this.hasFaulted = false; this.queue = []; this.disposable = new SerialDisposable(); } ScheduledObserver.prototype.next = function (value) { var self = this; this.queue.push(function () { self.observer.onNext(value); }); }; ScheduledObserver.prototype.error = function (e) { var self = this; this.queue.push(function () { self.observer.onError(e); }); }; ScheduledObserver.prototype.completed = function () { var self = this; this.queue.push(function () { self.observer.onCompleted(); }); }; ScheduledObserver.prototype.ensureActive = function () { var isOwner = false, parent = this; if (!this.hasFaulted && this.queue.length > 0) { isOwner = !this.isAcquired; this.isAcquired = true; } if (isOwner) { this.disposable.setDisposable(this.scheduler.scheduleRecursive(function (self) { var work; if (parent.queue.length > 0) { work = parent.queue.shift(); } else { parent.isAcquired = false; return; } try { work(); } catch (ex) { parent.queue = []; parent.hasFaulted = true; throw ex; } self(); })); } }; ScheduledObserver.prototype.dispose = function () { __super__.prototype.dispose.call(this); this.disposable.dispose(); }; return ScheduledObserver; }(AbstractObserver)); var ObserveOnObserver = (function (__super__) { inherits(ObserveOnObserver, __super__); function ObserveOnObserver(scheduler, observer, cancel) { __super__.call(this, scheduler, observer); this._cancel = cancel; } ObserveOnObserver.prototype.next = function (value) { __super__.prototype.next.call(this, value); this.ensureActive(); }; ObserveOnObserver.prototype.error = function (e) { __super__.prototype.error.call(this, e); this.ensureActive(); }; ObserveOnObserver.prototype.completed = function () { __super__.prototype.completed.call(this); this.ensureActive(); }; ObserveOnObserver.prototype.dispose = function () { __super__.prototype.dispose.call(this); this._cancel && this._cancel.dispose(); this._cancel = null; }; return ObserveOnObserver; })(ScheduledObserver); var observableProto; /** * Represents a push-style collection. */ var Observable = Rx.Observable = (function () { function Observable(subscribe) { if (Rx.config.longStackSupport && hasStacks) { try { throw new Error(); } catch (e) { this.stack = e.stack.substring(e.stack.indexOf("\n") + 1); } var self = this; this._subscribe = function (observer) { var oldOnError = observer.onError.bind(observer); observer.onError = function (err) { makeStackTraceLong(err, self); oldOnError(err); }; return subscribe.call(self, observer); }; } else { this._subscribe = subscribe; } } observableProto = Observable.prototype; /** * Subscribes an observer to the observable sequence. * @param {Mixed} [observerOrOnNext] The object that is to receive notifications or an action to invoke for each element in the observable sequence. * @param {Function} [onError] Action to invoke upon exceptional termination of the observable sequence. * @param {Function} [onCompleted] Action to invoke upon graceful termination of the observable sequence. * @returns {Diposable} A disposable handling the subscriptions and unsubscriptions. */ observableProto.subscribe = observableProto.forEach = function (observerOrOnNext, onError, onCompleted) { return this._subscribe(typeof observerOrOnNext === 'object' ? observerOrOnNext : observerCreate(observerOrOnNext, onError, onCompleted)); }; /** * Subscribes to the next value in the sequence with an optional "this" argument. * @param {Function} onNext The function to invoke on each element in the observable sequence. * @param {Any} [thisArg] Object to use as this when executing callback. * @returns {Disposable} A disposable handling the subscriptions and unsubscriptions. */ observableProto.subscribeOnNext = function (onNext, thisArg) { return this._subscribe(observerCreate(typeof thisArg !== 'undefined' ? function(x) { onNext.call(thisArg, x); } : onNext)); }; /** * Subscribes to an exceptional condition in the sequence with an optional "this" argument. * @param {Function} onError The function to invoke upon exceptional termination of the observable sequence. * @param {Any} [thisArg] Object to use as this when executing callback. * @returns {Disposable} A disposable handling the subscriptions and unsubscriptions. */ observableProto.subscribeOnError = function (onError, thisArg) { return this._subscribe(observerCreate(null, typeof thisArg !== 'undefined' ? function(e) { onError.call(thisArg, e); } : onError)); }; /** * Subscribes to the next value in the sequence with an optional "this" argument. * @param {Function} onCompleted The function to invoke upon graceful termination of the observable sequence. * @param {Any} [thisArg] Object to use as this when executing callback. * @returns {Disposable} A disposable handling the subscriptions and unsubscriptions. */ observableProto.subscribeOnCompleted = function (onCompleted, thisArg) { return this._subscribe(observerCreate(null, null, typeof thisArg !== 'undefined' ? function() { onCompleted.call(thisArg); } : onCompleted)); }; return Observable; })(); var ObservableBase = Rx.ObservableBase = (function (__super__) { inherits(ObservableBase, __super__); function fixSubscriber(subscriber) { return subscriber && isFunction(subscriber.dispose) ? subscriber : isFunction(subscriber) ? disposableCreate(subscriber) : disposableEmpty; } function setDisposable(s, state) { var ado = state[0], self = state[1]; var sub = tryCatch(self.subscribeCore).call(self, ado); if (sub === errorObj) { if(!ado.fail(errorObj.e)) { return thrower(errorObj.e); } } ado.setDisposable(fixSubscriber(sub)); } function subscribe(observer) { var ado = new AutoDetachObserver(observer), state = [ado, this]; if (currentThreadScheduler.scheduleRequired()) { currentThreadScheduler.scheduleWithState(state, setDisposable); } else { setDisposable(null, state); } return ado; } function ObservableBase() { __super__.call(this, subscribe); } ObservableBase.prototype.subscribeCore = notImplemented; return ObservableBase; }(Observable)); /** * Wraps the source sequence in order to run its observer callbacks on the specified scheduler. * * This only invokes observer callbacks on a scheduler. In case the subscription and/or unsubscription actions have side-effects * that require to be run on a scheduler, use subscribeOn. * * @param {Scheduler} scheduler Scheduler to notify observers on. * @returns {Observable} The source sequence whose observations happen on the specified scheduler. */ observableProto.observeOn = function (scheduler) { var source = this; return new AnonymousObservable(function (observer) { return source.subscribe(new ObserveOnObserver(scheduler, observer)); }, source); }; /** * Wraps the source sequence in order to run its subscription and unsubscription logic on the specified scheduler. This operation is not commonly used; * see the remarks section for more information on the distinction between subscribeOn and observeOn. * This only performs the side-effects of subscription and unsubscription on the specified scheduler. In order to invoke observer * callbacks on a scheduler, use observeOn. * @param {Scheduler} scheduler Scheduler to perform subscription and unsubscription actions on. * @returns {Observable} The source sequence whose subscriptions and unsubscriptions happen on the specified scheduler. */ observableProto.subscribeOn = function (scheduler) { var source = this; return new AnonymousObservable(function (observer) { var m = new SingleAssignmentDisposable(), d = new SerialDisposable(); d.setDisposable(m); m.setDisposable(scheduler.schedule(function () { d.setDisposable(new ScheduledDisposable(scheduler, source.subscribe(observer))); })); return d; }, source); }; /** * Converts a Promise to an Observable sequence * @param {Promise} An ES6 Compliant promise. * @returns {Observable} An Observable sequence which wraps the existing promise success and failure. */ var observableFromPromise = Observable.fromPromise = function (promise) { return observableDefer(function () { var subject = new Rx.AsyncSubject(); promise.then( function (value) { subject.onNext(value); subject.onCompleted(); }, subject.onError.bind(subject)); return subject; }); }; /* * Converts an existing observable sequence to an ES6 Compatible Promise * @example * var promise = Rx.Observable.return(42).toPromise(RSVP.Promise); * * // With config * Rx.config.Promise = RSVP.Promise; * var promise = Rx.Observable.return(42).toPromise(); * @param {Function} [promiseCtor] The constructor of the promise. If not provided, it looks for it in Rx.config.Promise. * @returns {Promise} An ES6 compatible promise with the last value from the observable sequence. */ observableProto.toPromise = function (promiseCtor) { promiseCtor || (promiseCtor = Rx.config.Promise); if (!promiseCtor) { throw new NotSupportedError('Promise type not provided nor in Rx.config.Promise'); } var source = this; return new promiseCtor(function (resolve, reject) { // No cancellation can be done var value, hasValue = false; source.subscribe(function (v) { value = v; hasValue = true; }, reject, function () { hasValue && resolve(value); }); }); }; var ToArrayObservable = (function(__super__) { inherits(ToArrayObservable, __super__); function ToArrayObservable(source) { this.source = source; __super__.call(this); } ToArrayObservable.prototype.subscribeCore = function(observer) { return this.source.subscribe(new ToArrayObserver(observer)); }; return ToArrayObservable; }(ObservableBase)); function ToArrayObserver(observer) { this.observer = observer; this.a = []; this.isStopped = false; } ToArrayObserver.prototype.onNext = function (x) { if(!this.isStopped) { this.a.push(x); } }; ToArrayObserver.prototype.onError = function (e) { if (!this.isStopped) { this.isStopped = true; this.observer.onError(e); } }; ToArrayObserver.prototype.onCompleted = function () { if (!this.isStopped) { this.isStopped = true; this.observer.onNext(this.a); this.observer.onCompleted(); } }; ToArrayObserver.prototype.dispose = function () { this.isStopped = true; } ToArrayObserver.prototype.fail = function (e) { if (!this.isStopped) { this.isStopped = true; this.observer.onError(e); return true; } return false; }; /** * Creates an array from an observable sequence. * @returns {Observable} An observable sequence containing a single element with a list containing all the elements of the source sequence. */ observableProto.toArray = function () { return new ToArrayObservable(this); }; /** * Creates an observable sequence from a specified subscribe method implementation. * @example * var res = Rx.Observable.create(function (observer) { return function () { } ); * var res = Rx.Observable.create(function (observer) { return Rx.Disposable.empty; } ); * var res = Rx.Observable.create(function (observer) { } ); * @param {Function} subscribe Implementation of the resulting observable sequence's subscribe method, returning a function that will be wrapped in a Disposable. * @returns {Observable} The observable sequence with the specified implementation for the Subscribe method. */ Observable.create = Observable.createWithDisposable = function (subscribe, parent) { return new AnonymousObservable(subscribe, parent); }; /** * Returns an observable sequence that invokes the specified factory function whenever a new observer subscribes. * * @example * var res = Rx.Observable.defer(function () { return Rx.Observable.fromArray([1,2,3]); }); * @param {Function} observableFactory Observable factory function to invoke for each observer that subscribes to the resulting sequence or Promise. * @returns {Observable} An observable sequence whose observers trigger an invocation of the given observable factory function. */ var observableDefer = Observable.defer = function (observableFactory) { return new AnonymousObservable(function (observer) { var result; try { result = observableFactory(); } catch (e) { return observableThrow(e).subscribe(observer); } isPromise(result) && (result = observableFromPromise(result)); return result.subscribe(observer); }); }; /** * Returns an empty observable sequence, using the specified scheduler to send out the single OnCompleted message. * * @example * var res = Rx.Observable.empty(); * var res = Rx.Observable.empty(Rx.Scheduler.timeout); * @param {Scheduler} [scheduler] Scheduler to send the termination call on. * @returns {Observable} An observable sequence with no elements. */ var observableEmpty = Observable.empty = function (scheduler) { isScheduler(scheduler) || (scheduler = immediateScheduler); return new AnonymousObservable(function (observer) { return scheduler.scheduleWithState(null, function () { observer.onCompleted(); }); }); }; var FromObservable = (function(__super__) { inherits(FromObservable, __super__); function FromObservable(iterable, mapper, scheduler) { this.iterable = iterable; this.mapper = mapper; this.scheduler = scheduler; __super__.call(this); } FromObservable.prototype.subscribeCore = function (observer) { var sink = new FromSink(observer, this); return sink.run(); }; return FromObservable; }(ObservableBase)); var FromSink = (function () { function FromSink(observer, parent) { this.observer = observer; this.parent = parent; } FromSink.prototype.run = function () { var list = Object(this.parent.iterable), it = getIterable(list), observer = this.observer, mapper = this.parent.mapper; function loopRecursive(i, recurse) { try { var next = it.next(); } catch (e) { return observer.onError(e); } if (next.done) { return observer.onCompleted(); } var result = next.value; if (mapper) { try { result = mapper(result, i); } catch (e) { return observer.onError(e); } } observer.onNext(result); recurse(i + 1); } return this.parent.scheduler.scheduleRecursiveWithState(0, loopRecursive); }; return FromSink; }()); var maxSafeInteger = Math.pow(2, 53) - 1; function StringIterable(str) { this._s = s; } StringIterable.prototype[$iterator$] = function () { return new StringIterator(this._s); }; function StringIterator(str) { this._s = s; this._l = s.length; this._i = 0; } StringIterator.prototype[$iterator$] = function () { return this; }; StringIterator.prototype.next = function () { return this._i < this._l ? { done: false, value: this._s.charAt(this._i++) } : doneEnumerator; }; function ArrayIterable(a) { this._a = a; } ArrayIterable.prototype[$iterator$] = function () { return new ArrayIterator(this._a); }; function ArrayIterator(a) { this._a = a; this._l = toLength(a); this._i = 0; } ArrayIterator.prototype[$iterator$] = function () { return this; }; ArrayIterator.prototype.next = function () { return this._i < this._l ? { done: false, value: this._a[this._i++] } : doneEnumerator; }; function numberIsFinite(value) { return typeof value === 'number' && root.isFinite(value); } function isNan(n) { return n !== n; } function getIterable(o) { var i = o[$iterator$], it; if (!i && typeof o === 'string') { it = new StringIterable(o); return it[$iterator$](); } if (!i && o.length !== undefined) { it = new ArrayIterable(o); return it[$iterator$](); } if (!i) { throw new TypeError('Object is not iterable'); } return o[$iterator$](); } function sign(value) { var number = +value; if (number === 0) { return number; } if (isNaN(number)) { return number; } return number < 0 ? -1 : 1; } function toLength(o) { var len = +o.length; if (isNaN(len)) { return 0; } if (len === 0 || !numberIsFinite(len)) { return len; } len = sign(len) * Math.floor(Math.abs(len)); if (len <= 0) { return 0; } if (len > maxSafeInteger) { return maxSafeInteger; } return len; } /** * This method creates a new Observable sequence from an array-like or iterable object. * @param {Any} arrayLike An array-like or iterable object to convert to an Observable sequence. * @param {Function} [mapFn] Map function to call on every element of the array. * @param {Any} [thisArg] The context to use calling the mapFn if provided. * @param {Scheduler} [scheduler] Optional scheduler to use for scheduling. If not provided, defaults to Scheduler.currentThread. */ var observableFrom = Observable.from = function (iterable, mapFn, thisArg, scheduler) { if (iterable == null) { throw new Error('iterable cannot be null.') } if (mapFn && !isFunction(mapFn)) { throw new Error('mapFn when provided must be a function'); } if (mapFn) { var mapper = bindCallback(mapFn, thisArg, 2); } isScheduler(scheduler) || (scheduler = currentThreadScheduler); return new FromObservable(iterable, mapper, scheduler); } var FromArrayObservable = (function(__super__) { inherits(FromArrayObservable, __super__); function FromArrayObservable(args, scheduler) { this.args = args; this.scheduler = scheduler; __super__.call(this); } FromArrayObservable.prototype.subscribeCore = function (observer) { var sink = new FromArraySink(observer, this); return sink.run(); }; return FromArrayObservable; }(ObservableBase)); function FromArraySink(observer, parent) { this.observer = observer; this.parent = parent; } FromArraySink.prototype.run = function () { var observer = this.observer, args = this.parent.args, len = args.length; function loopRecursive(i, recurse) { if (i < len) { observer.onNext(args[i]); recurse(i + 1); } else { observer.onCompleted(); } } return this.parent.scheduler.scheduleRecursiveWithState(0, loopRecursive); }; /** * Converts an array to an observable sequence, using an optional scheduler to enumerate the array. * @deprecated use Observable.from or Observable.of * @param {Scheduler} [scheduler] Scheduler to run the enumeration of the input sequence on. * @returns {Observable} The observable sequence whose elements are pulled from the given enumerable sequence. */ var observableFromArray = Observable.fromArray = function (array, scheduler) { isScheduler(scheduler) || (scheduler = currentThreadScheduler); return new FromArrayObservable(array, scheduler) }; /** * Generates an observable sequence by running a state-driven loop producing the sequence's elements, using the specified scheduler to send out observer messages. * * @example * var res = Rx.Observable.generate(0, function (x) { return x < 10; }, function (x) { return x + 1; }, function (x) { return x; }); * var res = Rx.Observable.generate(0, function (x) { return x < 10; }, function (x) { return x + 1; }, function (x) { return x; }, Rx.Scheduler.timeout); * @param {Mixed} initialState Initial state. * @param {Function} condition Condition to terminate generation (upon returning false). * @param {Function} iterate Iteration step function. * @param {Function} resultSelector Selector function for results produced in the sequence. * @param {Scheduler} [scheduler] Scheduler on which to run the generator loop. If not provided, defaults to Scheduler.currentThread. * @returns {Observable} The generated sequence. */ Observable.generate = function (initialState, condition, iterate, resultSelector, scheduler) { isScheduler(scheduler) || (scheduler = currentThreadScheduler); return new AnonymousObservable(function (o) { var first = true; return scheduler.scheduleRecursiveWithState(initialState, function (state, self) { var hasResult, result; try { if (first) { first = false; } else { state = iterate(state); } hasResult = condition(state); hasResult && (result = resultSelector(state)); } catch (e) { o.onError(e); return; } if (hasResult) { o.onNext(result); self(state); } else { o.onCompleted(); } }); }); }; /** * Returns a non-terminating observable sequence, which can be used to denote an infinite duration (e.g. when using reactive joins). * @returns {Observable} An observable sequence whose observers will never get called. */ var observableNever = Observable.never = function () { return new AnonymousObservable(function () { return disposableEmpty; }); }; function observableOf (scheduler, array) { isScheduler(scheduler) || (scheduler = currentThreadScheduler); return new FromArrayObservable(array, scheduler); } /** * This method creates a new Observable instance with a variable number of arguments, regardless of number or type of the arguments. * @returns {Observable} The observable sequence whose elements are pulled from the given arguments. */ Observable.of = function () { var len = arguments.length, args = new Array(len); for(var i = 0; i < len; i++) { args[i] = arguments[i]; } return new FromArrayObservable(args, currentThreadScheduler); }; /** * This method creates a new Observable instance with a variable number of arguments, regardless of number or type of the arguments. * @param {Scheduler} scheduler A scheduler to use for scheduling the arguments. * @returns {Observable} The observable sequence whose elements are pulled from the given arguments. */ Observable.ofWithScheduler = function (scheduler) { var len = arguments.length, args = new Array(len - 1); for(var i = 1; i < len; i++) { args[i - 1] = arguments[i]; } return new FromArrayObservable(args, scheduler); }; /** * Convert an object into an observable sequence of [key, value] pairs. * @param {Object} obj The object to inspect. * @param {Scheduler} [scheduler] Scheduler to run the enumeration of the input sequence on. * @returns {Observable} An observable sequence of [key, value] pairs from the object. */ Observable.pairs = function (obj, scheduler) { scheduler || (scheduler = Rx.Scheduler.currentThread); return new AnonymousObservable(function (observer) { var keys = Object.keys(obj), len = keys.length; return scheduler.scheduleRecursiveWithState(0, function (idx, self) { if (idx < len) { var key = keys[idx]; observer.onNext([key, obj[key]]); self(idx + 1); } else { observer.onCompleted(); } }); }); }; var RangeObservable = (function(__super__) { inherits(RangeObservable, __super__); function RangeObservable(start, count, scheduler) { this.start = start; this.count = count; this.scheduler = scheduler; __super__.call(this); } RangeObservable.prototype.subscribeCore = function (observer) { var sink = new RangeSink(observer, this); return sink.run(); }; return RangeObservable; }(ObservableBase)); var RangeSink = (function () { function RangeSink(observer, parent) { this.observer = observer; this.parent = parent; } RangeSink.prototype.run = function () { var start = this.parent.start, count = this.parent.count, observer = this.observer; function loopRecursive(i, recurse) { if (i < count) { observer.onNext(start + i); recurse(i + 1); } else { observer.onCompleted(); } } return this.parent.scheduler.scheduleRecursiveWithState(0, loopRecursive); }; return RangeSink; }()); /** * Generates an observable sequence of integral numbers within a specified range, using the specified scheduler to send out observer messages. * @param {Number} start The value of the first integer in the sequence. * @param {Number} count The number of sequential integers to generate. * @param {Scheduler} [scheduler] Scheduler to run the generator loop on. If not specified, defaults to Scheduler.currentThread. * @returns {Observable} An observable sequence that contains a range of sequential integral numbers. */ Observable.range = function (start, count, scheduler) { isScheduler(scheduler) || (scheduler = currentThreadScheduler); return new RangeObservable(start, count, scheduler); }; /** * Generates an observable sequence that repeats the given element the specified number of times, using the specified scheduler to send out observer messages. * * @example * var res = Rx.Observable.repeat(42); * var res = Rx.Observable.repeat(42, 4); * 3 - res = Rx.Observable.repeat(42, 4, Rx.Scheduler.timeout); * 4 - res = Rx.Observable.repeat(42, null, Rx.Scheduler.timeout); * @param {Mixed} value Element to repeat. * @param {Number} repeatCount [Optiona] Number of times to repeat the element. If not specified, repeats indefinitely. * @param {Scheduler} scheduler Scheduler to run the producer loop on. If not specified, defaults to Scheduler.immediate. * @returns {Observable} An observable sequence that repeats the given element the specified number of times. */ Observable.repeat = function (value, repeatCount, scheduler) { isScheduler(scheduler) || (scheduler = currentThreadScheduler); return observableReturn(value, scheduler).repeat(repeatCount == null ? -1 : repeatCount); }; /** * Returns an observable sequence that contains a single element, using the specified scheduler to send out observer messages. * There is an alias called 'just' or browsers <IE9. * @param {Mixed} value Single element in the resulting observable sequence. * @param {Scheduler} scheduler Scheduler to send the single element on. If not specified, defaults to Scheduler.immediate. * @returns {Observable} An observable sequence containing the single specified element. */ var observableReturn = Observable['return'] = Observable.just = Observable.returnValue = function (value, scheduler) { isScheduler(scheduler) || (scheduler = immediateScheduler); return new AnonymousObservable(function (observer) { return scheduler.scheduleWithState(value, function (_, v) { observer.onNext(v); observer.onCompleted(); }); }); }; /** * Returns an observable sequence that terminates with an exception, using the specified scheduler to send out the single onError message. * There is an alias to this method called 'throwError' for browsers <IE9. * @param {Mixed} error An object used for the sequence's termination. * @param {Scheduler} scheduler Scheduler to send the exceptional termination call on. If not specified, defaults to Scheduler.immediate. * @returns {Observable} The observable sequence that terminates exceptionally with the specified exception object. */ var observableThrow = Observable['throw'] = Observable.throwError = function (error, scheduler) { isScheduler(scheduler) || (scheduler = immediateScheduler); return new AnonymousObservable(function (observer) { return scheduler.schedule(function () { observer.onError(error); }); }); }; /** @deprecated use #some instead */ Observable.throwException = function () { //deprecate('throwException', 'throwError'); return Observable.throwError.apply(null, arguments); }; /** * Constructs an observable sequence that depends on a resource object, whose lifetime is tied to the resulting observable sequence's lifetime. * @param {Function} resourceFactory Factory function to obtain a resource object. * @param {Function} observableFactory Factory function to obtain an observable sequence that depends on the obtained resource. * @returns {Observable} An observable sequence whose lifetime controls the lifetime of the dependent resource object. */ Observable.using = function (resourceFactory, observableFactory) { return new AnonymousObservable(function (observer) { var disposable = disposableEmpty, resource, source; try { resource = resourceFactory(); resource && (disposable = resource); source = observableFactory(resource); } catch (exception) { return new CompositeDisposable(observableThrow(exception).subscribe(observer), disposable); } return new CompositeDisposable(source.subscribe(observer), disposable); }); }; /** * Propagates the observable sequence or Promise that reacts first. * @param {Observable} rightSource Second observable sequence or Promise. * @returns {Observable} {Observable} An observable sequence that surfaces either of the given sequences, whichever reacted first. */ observableProto.amb = function (rightSource) { var leftSource = this; return new AnonymousObservable(function (observer) { var choice, leftChoice = 'L', rightChoice = 'R', leftSubscription = new SingleAssignmentDisposable(), rightSubscription = new SingleAssignmentDisposable(); isPromise(rightSource) && (rightSource = observableFromPromise(rightSource)); function choiceL() { if (!choice) { choice = leftChoice; rightSubscription.dispose(); } } function choiceR() { if (!choice) { choice = rightChoice; leftSubscription.dispose(); } } leftSubscription.setDisposable(leftSource.subscribe(function (left) { choiceL(); if (choice === leftChoice) { observer.onNext(left); } }, function (err) { choiceL(); if (choice === leftChoice) { observer.onError(err); } }, function () { choiceL(); if (choice === leftChoice) { observer.onCompleted(); } })); rightSubscription.setDisposable(rightSource.subscribe(function (right) { choiceR(); if (choice === rightChoice) { observer.onNext(right); } }, function (err) { choiceR(); if (choice === rightChoice) { observer.onError(err); } }, function () { choiceR(); if (choice === rightChoice) { observer.onCompleted(); } })); return new CompositeDisposable(leftSubscription, rightSubscription); }); }; /** * Propagates the observable sequence or Promise that reacts first. * * @example * var = Rx.Observable.amb(xs, ys, zs); * @returns {Observable} An observable sequence that surfaces any of the given sequences, whichever reacted first. */ Observable.amb = function () { var acc = observableNever(), items = []; if (Array.isArray(arguments[0])) { items = arguments[0]; } else { for(var i = 0, len = arguments.length; i < len; i++) { items.push(arguments[i]); } } function func(previous, current) { return previous.amb(current); } for (var i = 0, len = items.length; i < len; i++) { acc = func(acc, items[i]); } return acc; }; function observableCatchHandler(source, handler) { return new AnonymousObservable(function (o) { var d1 = new SingleAssignmentDisposable(), subscription = new SerialDisposable(); subscription.setDisposable(d1); d1.setDisposable(source.subscribe(function (x) { o.onNext(x); }, function (e) { try { var result = handler(e); } catch (ex) { return o.onError(ex); } isPromise(result) && (result = observableFromPromise(result)); var d = new SingleAssignmentDisposable(); subscription.setDisposable(d); d.setDisposable(result.subscribe(o)); }, function (x) { o.onCompleted(x); })); return subscription; }, source); } /** * Continues an observable sequence that is terminated by an exception with the next observable sequence. * @example * 1 - xs.catchException(ys) * 2 - xs.catchException(function (ex) { return ys(ex); }) * @param {Mixed} handlerOrSecond Exception handler function that returns an observable sequence given the error that occurred in the first sequence, or a second observable sequence used to produce results when an error occurred in the first sequence. * @returns {Observable} An observable sequence containing the first sequence's elements, followed by the elements of the handler sequence in case an exception occurred. */ observableProto['catch'] = observableProto.catchError = observableProto.catchException = function (handlerOrSecond) { return typeof handlerOrSecond === 'function' ? observableCatchHandler(this, handlerOrSecond) : observableCatch([this, handlerOrSecond]); }; /** * Continues an observable sequence that is terminated by an exception with the next observable sequence. * @param {Array | Arguments} args Arguments or an array to use as the next sequence if an error occurs. * @returns {Observable} An observable sequence containing elements from consecutive source sequences until a source sequence terminates successfully. */ var observableCatch = Observable.catchError = Observable['catch'] = Observable.catchException = function () { var items = []; if (Array.isArray(arguments[0])) { items = arguments[0]; } else { for(var i = 0, len = arguments.length; i < len; i++) { items.push(arguments[i]); } } return enumerableOf(items).catchError(); }; /** * Merges the specified observable sequences into one observable sequence by using the selector function whenever any of the observable sequences or Promises produces an element. * This can be in the form of an argument list of observables or an array. * * @example * 1 - obs = observable.combineLatest(obs1, obs2, obs3, function (o1, o2, o3) { return o1 + o2 + o3; }); * 2 - obs = observable.combineLatest([obs1, obs2, obs3], function (o1, o2, o3) { return o1 + o2 + o3; }); * @returns {Observable} An observable sequence containing the result of combining elements of the sources using the specified result selector function. */ observableProto.combineLatest = function () { var len = arguments.length, args = new Array(len); for(var i = 0; i < len; i++) { args[i] = arguments[i]; } if (Array.isArray(args[0])) { args[0].unshift(this); } else { args.unshift(this); } return combineLatest.apply(this, args); }; /** * Merges the specified observable sequences into one observable sequence by using the selector function whenever any of the observable sequences or Promises produces an element. * * @example * 1 - obs = Rx.Observable.combineLatest(obs1, obs2, obs3, function (o1, o2, o3) { return o1 + o2 + o3; }); * 2 - obs = Rx.Observable.combineLatest([obs1, obs2, obs3], function (o1, o2, o3) { return o1 + o2 + o3; }); * @returns {Observable} An observable sequence containing the result of combining elements of the sources using the specified result selector function. */ var combineLatest = Observable.combineLatest = function () { var len = arguments.length, args = new Array(len); for(var i = 0; i < len; i++) { args[i] = arguments[i]; } var resultSelector = args.pop(); Array.isArray(args[0]) && (args = args[0]); return new AnonymousObservable(function (o) { var n = args.length, falseFactory = function () { return false; }, hasValue = arrayInitialize(n, falseFactory), hasValueAll = false, isDone = arrayInitialize(n, falseFactory), values = new Array(n); function next(i) { hasValue[i] = true; if (hasValueAll || (hasValueAll = hasValue.every(identity))) { try { var res = resultSelector.apply(null, values); } catch (e) { return o.onError(e); } o.onNext(res); } else if (isDone.filter(function (x, j) { return j !== i; }).every(identity)) { o.onCompleted(); } } function done (i) { isDone[i] = true; isDone.every(identity) && o.onCompleted(); } var subscriptions = new Array(n); for (var idx = 0; idx < n; idx++) { (function (i) { var source = args[i], sad = new SingleAssignmentDisposable(); isPromise(source) && (source = observableFromPromise(source)); sad.setDisposable(source.subscribe(function (x) { values[i] = x; next(i); }, function(e) { o.onError(e); }, function () { done(i); } )); subscriptions[i] = sad; }(idx)); } return new CompositeDisposable(subscriptions); }, this); }; /** * Concatenates all the observable sequences. This takes in either an array or variable arguments to concatenate. * @returns {Observable} An observable sequence that contains the elements of each given sequence, in sequential order. */ observableProto.concat = function () { for(var args = [], i = 0, len = arguments.length; i < len; i++) { args.push(arguments[i]); } args.unshift(this); return observableConcat.apply(null, args); }; /** * Concatenates all the observable sequences. * @param {Array | Arguments} args Arguments or an array to concat to the observable sequence. * @returns {Observable} An observable sequence that contains the elements of each given sequence, in sequential order. */ var observableConcat = Observable.concat = function () { var args; if (Array.isArray(arguments[0])) { args = arguments[0]; } else { args = new Array(arguments.length); for(var i = 0, len = arguments.length; i < len; i++) { args[i] = arguments[i]; } } return enumerableOf(args).concat(); }; /** * Concatenates an observable sequence of observable sequences. * @returns {Observable} An observable sequence that contains the elements of each observed inner sequence, in sequential order. */ observableProto.concatAll = observableProto.concatObservable = function () { return this.merge(1); }; var MergeObservable = (function (__super__) { inherits(MergeObservable, __super__); function MergeObservable(source, maxConcurrent) { this.source = source; this.maxConcurrent = maxConcurrent; __super__.call(this); } MergeObservable.prototype.subscribeCore = function(observer) { var g = new CompositeDisposable(); g.add(this.source.subscribe(new MergeObserver(observer, this.maxConcurrent, g))); return g; }; return MergeObservable; }(ObservableBase)); var MergeObserver = (function () { function MergeObserver(o, max, g) { this.o = o; this.max = max; this.g = g; this.done = false; this.q = []; this.activeCount = 0; this.isStopped = false; } MergeObserver.prototype.handleSubscribe = function (xs) { var sad = new SingleAssignmentDisposable(); this.g.add(sad); isPromise(xs) && (xs = observableFromPromise(xs)); sad.setDisposable(xs.subscribe(new InnerObserver(this, sad))); }; MergeObserver.prototype.onNext = function (innerSource) { if (this.isStopped) { return; } if(this.activeCount < this.max) { this.activeCount++; this.handleSubscribe(innerSource); } else { this.q.push(innerSource); } }; MergeObserver.prototype.onError = function (e) { if (!this.isStopped) { this.isStopped = true; this.o.onError(e); } }; MergeObserver.prototype.onCompleted = function () { if (!this.isStopped) { this.isStopped = true; this.done = true; this.activeCount === 0 && this.o.onCompleted(); } }; MergeObserver.prototype.dispose = function() { this.isStopped = true; }; MergeObserver.prototype.fail = function (e) { if (!this.isStopped) { this.isStopped = true; this.o.onError(e); return true; } return false; }; function InnerObserver(parent, sad) { this.parent = parent; this.sad = sad; this.isStopped = false; } InnerObserver.prototype.onNext = function (x) { if(!this.isStopped) { this.parent.o.onNext(x); } }; InnerObserver.prototype.onError = function (e) { if (!this.isStopped) { this.isStopped = true; this.parent.o.onError(e); } }; InnerObserver.prototype.onCompleted = function () { if(!this.isStopped) { this.isStopped = true; var parent = this.parent; parent.g.remove(this.sad); if (parent.q.length > 0) { parent.handleSubscribe(parent.q.shift()); } else { parent.activeCount--; parent.done && parent.activeCount === 0 && parent.o.onCompleted(); } } }; InnerObserver.prototype.dispose = function() { this.isStopped = true; }; InnerObserver.prototype.fail = function (e) { if (!this.isStopped) { this.isStopped = true; this.parent.o.onError(e); return true; } return false; }; return MergeObserver; }()); /** * Merges an observable sequence of observable sequences into an observable sequence, limiting the number of concurrent subscriptions to inner sequences. * Or merges two observable sequences into a single observable sequence. * * @example * 1 - merged = sources.merge(1); * 2 - merged = source.merge(otherSource); * @param {Mixed} [maxConcurrentOrOther] Maximum number of inner observable sequences being subscribed to concurrently or the second observable sequence. * @returns {Observable} The observable sequence that merges the elements of the inner sequences. */ observableProto.merge = function (maxConcurrentOrOther) { return typeof maxConcurrentOrOther !== 'number' ? observableMerge(this, maxConcurrentOrOther) : new MergeObservable(this, maxConcurrentOrOther); }; /** * Merges all the observable sequences into a single observable sequence. * The scheduler is optional and if not specified, the immediate scheduler is used. * @returns {Observable} The observable sequence that merges the elements of the observable sequences. */ var observableMerge = Observable.merge = function () { var scheduler, sources = [], i, len = arguments.length; if (!arguments[0]) { scheduler = immediateScheduler; for(i = 1; i < len; i++) { sources.push(arguments[i]); } } else if (isScheduler(arguments[0])) { scheduler = arguments[0]; for(i = 1; i < len; i++) { sources.push(arguments[i]); } } else { scheduler = immediateScheduler; for(i = 0; i < len; i++) { sources.push(arguments[i]); } } if (Array.isArray(sources[0])) { sources = sources[0]; } return observableOf(scheduler, sources).mergeAll(); }; var CompositeError = Rx.CompositeError = function(errors) { this.name = "NotImplementedError"; this.innerErrors = errors; this.message = 'This contains multiple errors. Check the innerErrors'; Error.call(this); } CompositeError.prototype = Error.prototype; /** * Flattens an Observable that emits Observables into one Observable, in a way that allows an Observer to * receive all successfully emitted items from all of the source Observables without being interrupted by * an error notification from one of them. * * This behaves like Observable.prototype.mergeAll except that if any of the merged Observables notify of an * error via the Observer's onError, mergeDelayError will refrain from propagating that * error notification until all of the merged Observables have finished emitting items. * @param {Array | Arguments} args Arguments or an array to merge. * @returns {Observable} an Observable that emits all of the items emitted by the Observables emitted by the Observable */ Observable.mergeDelayError = function() { var args; if (Array.isArray(arguments[0])) { args = arguments[0]; } else { var len = arguments.length; args = new Array(len); for(var i = 0; i < len; i++) { args[i] = arguments[i]; } } var source = observableOf(null, args); return new AnonymousObservable(function (o) { var group = new CompositeDisposable(), m = new SingleAssignmentDisposable(), isStopped = false, errors = []; function setCompletion() { if (errors.length === 0) { o.onCompleted(); } else if (errors.length === 1) { o.onError(errors[0]); } else { o.onError(new CompositeError(errors)); } } group.add(m); m.setDisposable(source.subscribe( function (innerSource) { var innerSubscription = new SingleAssignmentDisposable(); group.add(innerSubscription); // Check for promises support isPromise(innerSource) && (innerSource = observableFromPromise(innerSource)); innerSubscription.setDisposable(innerSource.subscribe( function (x) { o.onNext(x); }, function (e) { errors.push(e); group.remove(innerSubscription); isStopped && group.length === 1 && setCompletion(); }, function () { group.remove(innerSubscription); isStopped && group.length === 1 && setCompletion(); })); }, function (e) { errors.push(e); isStopped = true; group.length === 1 && setCompletion(); }, function () { isStopped = true; group.length === 1 && setCompletion(); })); return group; }); }; var MergeAllObservable = (function (__super__) { inherits(MergeAllObservable, __super__); function MergeAllObservable(source) { this.source = source; __super__.call(this); } MergeAllObservable.prototype.subscribeCore = function (observer) { var g = new CompositeDisposable(), m = new SingleAssignmentDisposable(); g.add(m); m.setDisposable(this.source.subscribe(new MergeAllObserver(observer, g))); return g; }; return MergeAllObservable; }(ObservableBase)); var MergeAllObserver = (function() { function MergeAllObserver(o, g) { this.o = o; this.g = g; this.isStopped = false; this.done = false; } MergeAllObserver.prototype.onNext = function(innerSource) { if(this.isStopped) { return; } var sad = new SingleAssignmentDisposable(); this.g.add(sad); isPromise(innerSource) && (innerSource = observableFromPromise(innerSource)); sad.setDisposable(innerSource.subscribe(new InnerObserver(this, this.g, sad))); }; MergeAllObserver.prototype.onError = function (e) { if(!this.isStopped) { this.isStopped = true; this.o.onError(e); } }; MergeAllObserver.prototype.onCompleted = function () { if(!this.isStopped) { this.isStopped = true; this.done = true; this.g.length === 1 && this.o.onCompleted(); } }; MergeAllObserver.prototype.dispose = function() { this.isStopped = true; }; MergeAllObserver.prototype.fail = function (e) { if (!this.isStopped) { this.isStopped = true; this.o.onError(e); return true; } return false; }; function InnerObserver(parent, g, sad) { this.parent = parent; this.g = g; this.sad = sad; this.isStopped = false; } InnerObserver.prototype.onNext = function (x) { if (!this.isStopped) { this.parent.o.onNext(x); } }; InnerObserver.prototype.onError = function (e) { if(!this.isStopped) { this.isStopped = true; this.parent.o.onError(e); } }; InnerObserver.prototype.onCompleted = function () { if(!this.isStopped) { var parent = this.parent; this.isStopped = true; parent.g.remove(this.sad); parent.done && parent.g.length === 1 && parent.o.onCompleted(); } }; InnerObserver.prototype.dispose = function() { this.isStopped = true; }; InnerObserver.prototype.fail = function (e) { if (!this.isStopped) { this.isStopped = true; this.parent.o.onError(e); return true; } return false; }; return MergeAllObserver; }()); /** * Merges an observable sequence of observable sequences into an observable sequence. * @returns {Observable} The observable sequence that merges the elements of the inner sequences. */ observableProto.mergeAll = observableProto.mergeObservable = function () { return new MergeAllObservable(this); }; /** * Continues an observable sequence that is terminated normally or by an exception with the next observable sequence. * @param {Observable} second Second observable sequence used to produce results after the first sequence terminates. * @returns {Observable} An observable sequence that concatenates the first and second sequence, even if the first sequence terminates exceptionally. */ observableProto.onErrorResumeNext = function (second) { if (!second) { throw new Error('Second observable is required'); } return onErrorResumeNext([this, second]); }; /** * Continues an observable sequence that is terminated normally or by an exception with the next observable sequence. * * @example * 1 - res = Rx.Observable.onErrorResumeNext(xs, ys, zs); * 1 - res = Rx.Observable.onErrorResumeNext([xs, ys, zs]); * @returns {Observable} An observable sequence that concatenates the source sequences, even if a sequence terminates exceptionally. */ var onErrorResumeNext = Observable.onErrorResumeNext = function () { var sources = []; if (Array.isArray(arguments[0])) { sources = arguments[0]; } else { for(var i = 0, len = arguments.length; i < len; i++) { sources.push(arguments[i]); } } return new AnonymousObservable(function (observer) { var pos = 0, subscription = new SerialDisposable(), cancelable = immediateScheduler.scheduleRecursive(function (self) { var current, d; if (pos < sources.length) { current = sources[pos++]; isPromise(current) && (current = observableFromPromise(current)); d = new SingleAssignmentDisposable(); subscription.setDisposable(d); d.setDisposable(current.subscribe(observer.onNext.bind(observer), self, self)); } else { observer.onCompleted(); } }); return new CompositeDisposable(subscription, cancelable); }); }; /** * Returns the values from the source observable sequence only after the other observable sequence produces a value. * @param {Observable | Promise} other The observable sequence or Promise that triggers propagation of elements of the source sequence. * @returns {Observable} An observable sequence containing the elements of the source sequence starting from the point the other sequence triggered propagation. */ observableProto.skipUntil = function (other) { var source = this; return new AnonymousObservable(function (o) { var isOpen = false; var disposables = new CompositeDisposable(source.subscribe(function (left) { isOpen && o.onNext(left); }, function (e) { o.onError(e); }, function () { isOpen && o.onCompleted(); })); isPromise(other) && (other = observableFromPromise(other)); var rightSubscription = new SingleAssignmentDisposable(); disposables.add(rightSubscription); rightSubscription.setDisposable(other.subscribe(function () { isOpen = true; rightSubscription.dispose(); }, function (e) { o.onError(e); }, function () { rightSubscription.dispose(); })); return disposables; }, source); }; /** * Transforms an observable sequence of observable sequences into an observable sequence producing values only from the most recent observable sequence. * @returns {Observable} The observable sequence that at any point in time produces the elements of the most recent inner observable sequence that has been received. */ observableProto['switch'] = observableProto.switchLatest = function () { var sources = this; return new AnonymousObservable(function (observer) { var hasLatest = false, innerSubscription = new SerialDisposable(), isStopped = false, latest = 0, subscription = sources.subscribe( function (innerSource) { var d = new SingleAssignmentDisposable(), id = ++latest; hasLatest = true; innerSubscription.setDisposable(d); // Check if Promise or Observable isPromise(innerSource) && (innerSource = observableFromPromise(innerSource)); d.setDisposable(innerSource.subscribe( function (x) { latest === id && observer.onNext(x); }, function (e) { latest === id && observer.onError(e); }, function () { if (latest === id) { hasLatest = false; isStopped && observer.onCompleted(); } })); }, function (e) { observer.onError(e); }, function () { isStopped = true; !hasLatest && observer.onCompleted(); }); return new CompositeDisposable(subscription, innerSubscription); }, sources); }; /** * Returns the values from the source observable sequence until the other observable sequence produces a value. * @param {Observable | Promise} other Observable sequence or Promise that terminates propagation of elements of the source sequence. * @returns {Observable} An observable sequence containing the elements of the source sequence up to the point the other sequence interrupted further propagation. */ observableProto.takeUntil = function (other) { var source = this; return new AnonymousObservable(function (o) { isPromise(other) && (other = observableFromPromise(other)); return new CompositeDisposable( source.subscribe(o), other.subscribe(function () { o.onCompleted(); }, function (e) { o.onError(e); }, noop) ); }, source); }; /** * Merges the specified observable sequences into one observable sequence by using the selector function only when the (first) source observable sequence produces an element. * * @example * 1 - obs = obs1.withLatestFrom(obs2, obs3, function (o1, o2, o3) { return o1 + o2 + o3; }); * 2 - obs = obs1.withLatestFrom([obs2, obs3], function (o1, o2, o3) { return o1 + o2 + o3; }); * @returns {Observable} An observable sequence containing the result of combining elements of the sources using the specified result selector function. */ observableProto.withLatestFrom = function () { var len = arguments.length, args = new Array(len) for(var i = 0; i < len; i++) { args[i] = arguments[i]; } var resultSelector = args.pop(), source = this; if (typeof source === 'undefined') { throw new Error('Source observable not found for withLatestFrom().'); } if (typeof resultSelector !== 'function') { throw new Error('withLatestFrom() expects a resultSelector function.'); } if (Array.isArray(args[0])) { args = args[0]; } return new AnonymousObservable(function (observer) { var falseFactory = function () { return false; }, n = args.length, hasValue = arrayInitialize(n, falseFactory), hasValueAll = false, values = new Array(n); var subscriptions = new Array(n + 1); for (var idx = 0; idx < n; idx++) { (function (i) { var other = args[i], sad = new SingleAssignmentDisposable(); isPromise(other) && (other = observableFromPromise(other)); sad.setDisposable(other.subscribe(function (x) { values[i] = x; hasValue[i] = true; hasValueAll = hasValue.every(identity); }, observer.onError.bind(observer), function () {})); subscriptions[i] = sad; }(idx)); } var sad = new SingleAssignmentDisposable(); sad.setDisposable(source.subscribe(function (x) { var res; var allValues = [x].concat(values); if (!hasValueAll) return; try { res = resultSelector.apply(null, allValues); } catch (ex) { observer.onError(ex); return; } observer.onNext(res); }, observer.onError.bind(observer), function () { observer.onCompleted(); })); subscriptions[n] = sad; return new CompositeDisposable(subscriptions); }, this); }; function zipArray(second, resultSelector) { var first = this; return new AnonymousObservable(function (observer) { var index = 0, len = second.length; return first.subscribe(function (left) { if (index < len) { var right = second[index++], result; try { result = resultSelector(left, right); } catch (e) { return observer.onError(e); } observer.onNext(result); } else { observer.onCompleted(); } }, function (e) { observer.onError(e); }, function () { observer.onCompleted(); }); }, first); } function falseFactory() { return false; } function emptyArrayFactory() { return []; } /** * Merges the specified observable sequences into one observable sequence by using the selector function whenever all of the observable sequences or an array have produced an element at a corresponding index. * The last element in the arguments must be a function to invoke for each series of elements at corresponding indexes in the args. * * @example * 1 - res = obs1.zip(obs2, fn); * 1 - res = x1.zip([1,2,3], fn); * @returns {Observable} An observable sequence containing the result of combining elements of the args using the specified result selector function. */ observableProto.zip = function () { if (Array.isArray(arguments[0])) { return zipArray.apply(this, arguments); } var len = arguments.length, args = new Array(len); for(var i = 0; i < len; i++) { args[i] = arguments[i]; } var parent = this, resultSelector = args.pop(); args.unshift(parent); return new AnonymousObservable(function (observer) { var n = args.length, queues = arrayInitialize(n, emptyArrayFactory), isDone = arrayInitialize(n, falseFactory); function next(i) { var res, queuedValues; if (queues.every(function (x) { return x.length > 0; })) { try { queuedValues = queues.map(function (x) { return x.shift(); }); res = resultSelector.apply(parent, queuedValues); } catch (ex) { observer.onError(ex); return; } observer.onNext(res); } else if (isDone.filter(function (x, j) { return j !== i; }).every(identity)) { observer.onCompleted(); } }; function done(i) { isDone[i] = true; if (isDone.every(function (x) { return x; })) { observer.onCompleted(); } } var subscriptions = new Array(n); for (var idx = 0; idx < n; idx++) { (function (i) { var source = args[i], sad = new SingleAssignmentDisposable(); isPromise(source) && (source = observableFromPromise(source)); sad.setDisposable(source.subscribe(function (x) { queues[i].push(x); next(i); }, function (e) { observer.onError(e); }, function () { done(i); })); subscriptions[i] = sad; })(idx); } return new CompositeDisposable(subscriptions); }, parent); }; /** * Merges the specified observable sequences into one observable sequence by using the selector function whenever all of the observable sequences have produced an element at a corresponding index. * @param arguments Observable sources. * @param {Function} resultSelector Function to invoke for each series of elements at corresponding indexes in the sources. * @returns {Observable} An observable sequence containing the result of combining elements of the sources using the specified result selector function. */ Observable.zip = function () { var len = arguments.length, args = new Array(len); for(var i = 0; i < len; i++) { args[i] = arguments[i]; } var first = args.shift(); return first.zip.apply(first, args); }; /** * Merges the specified observable sequences into one observable sequence by emitting a list with the elements of the observable sequences at corresponding indexes. * @param arguments Observable sources. * @returns {Observable} An observable sequence containing lists of elements at corresponding indexes. */ Observable.zipArray = function () { var sources; if (Array.isArray(arguments[0])) { sources = arguments[0]; } else { var len = arguments.length; sources = new Array(len); for(var i = 0; i < len; i++) { sources[i] = arguments[i]; } } return new AnonymousObservable(function (observer) { var n = sources.length, queues = arrayInitialize(n, function () { return []; }), isDone = arrayInitialize(n, function () { return false; }); function next(i) { if (queues.every(function (x) { return x.length > 0; })) { var res = queues.map(function (x) { return x.shift(); }); observer.onNext(res); } else if (isDone.filter(function (x, j) { return j !== i; }).every(identity)) { observer.onCompleted(); return; } }; function done(i) { isDone[i] = true; if (isDone.every(identity)) { observer.onCompleted(); return; } } var subscriptions = new Array(n); for (var idx = 0; idx < n; idx++) { (function (i) { subscriptions[i] = new SingleAssignmentDisposable(); subscriptions[i].setDisposable(sources[i].subscribe(function (x) { queues[i].push(x); next(i); }, function (e) { observer.onError(e); }, function () { done(i); })); })(idx); } return new CompositeDisposable(subscriptions); }); }; /** * Hides the identity of an observable sequence. * @returns {Observable} An observable sequence that hides the identity of the source sequence. */ observableProto.asObservable = function () { var source = this; return new AnonymousObservable(function (o) { return source.subscribe(o); }, this); }; /** * Projects each element of an observable sequence into zero or more buffers which are produced based on element count information. * * @example * var res = xs.bufferWithCount(10); * var res = xs.bufferWithCount(10, 1); * @param {Number} count Length of each buffer. * @param {Number} [skip] Number of elements to skip between creation of consecutive buffers. If not provided, defaults to the count. * @returns {Observable} An observable sequence of buffers. */ observableProto.bufferWithCount = function (count, skip) { if (typeof skip !== 'number') { skip = count; } return this.windowWithCount(count, skip).selectMany(function (x) { return x.toArray(); }).where(function (x) { return x.length > 0; }); }; /** * Dematerializes the explicit notification values of an observable sequence as implicit notifications. * @returns {Observable} An observable sequence exhibiting the behavior corresponding to the source sequence's notification values. */ observableProto.dematerialize = function () { var source = this; return new AnonymousObservable(function (o) { return source.subscribe(function (x) { return x.accept(o); }, function(e) { o.onError(e); }, function () { o.onCompleted(); }); }, this); }; /** * Returns an observable sequence that contains only distinct contiguous elements according to the keySelector and the comparer. * * var obs = observable.distinctUntilChanged(); * var obs = observable.distinctUntilChanged(function (x) { return x.id; }); * var obs = observable.distinctUntilChanged(function (x) { return x.id; }, function (x, y) { return x === y; }); * * @param {Function} [keySelector] A function to compute the comparison key for each element. If not provided, it projects the value. * @param {Function} [comparer] Equality comparer for computed key values. If not provided, defaults to an equality comparer function. * @returns {Observable} An observable sequence only containing the distinct contiguous elements, based on a computed key value, from the source sequence. */ observableProto.distinctUntilChanged = function (keySelector, comparer) { var source = this; comparer || (comparer = defaultComparer); return new AnonymousObservable(function (o) { var hasCurrentKey = false, currentKey; return source.subscribe(function (value) { var key = value; if (keySelector) { try { key = keySelector(value); } catch (e) { o.onError(e); return; } } if (hasCurrentKey) { try { var comparerEquals = comparer(currentKey, key); } catch (e) { o.onError(e); return; } } if (!hasCurrentKey || !comparerEquals) { hasCurrentKey = true; currentKey = key; o.onNext(value); } }, function (e) { o.onError(e); }, function () { o.onCompleted(); }); }, this); }; /** * Invokes an action for each element in the observable sequence and invokes an action upon graceful or exceptional termination of the observable sequence. * This method can be used for debugging, logging, etc. of query behavior by intercepting the message stream to run arbitrary actions for messages on the pipeline. * @param {Function | Observer} observerOrOnNext Action to invoke for each element in the observable sequence or an observer. * @param {Function} [onError] Action to invoke upon exceptional termination of the observable sequence. Used if only the observerOrOnNext parameter is also a function. * @param {Function} [onCompleted] Action to invoke upon graceful termination of the observable sequence. Used if only the observerOrOnNext parameter is also a function. * @returns {Observable} The source sequence with the side-effecting behavior applied. */ observableProto['do'] = observableProto.tap = observableProto.doAction = function (observerOrOnNext, onError, onCompleted) { var source = this; return new AnonymousObservable(function (observer) { var tapObserver = !observerOrOnNext || isFunction(observerOrOnNext) ? observerCreate(observerOrOnNext || noop, onError || noop, onCompleted || noop) : observerOrOnNext; return source.subscribe(function (x) { try { tapObserver.onNext(x); } catch (e) { observer.onError(e); } observer.onNext(x); }, function (err) { try { tapObserver.onError(err); } catch (e) { observer.onError(e); } observer.onError(err); }, function () { try { tapObserver.onCompleted(); } catch (e) { observer.onError(e); } observer.onCompleted(); }); }, this); }; /** * Invokes an action for each element in the observable sequence. * This method can be used for debugging, logging, etc. of query behavior by intercepting the message stream to run arbitrary actions for messages on the pipeline. * @param {Function} onNext Action to invoke for each element in the observable sequence. * @param {Any} [thisArg] Object to use as this when executing callback. * @returns {Observable} The source sequence with the side-effecting behavior applied. */ observableProto.doOnNext = observableProto.tapOnNext = function (onNext, thisArg) { return this.tap(typeof thisArg !== 'undefined' ? function (x) { onNext.call(thisArg, x); } : onNext); }; /** * Invokes an action upon exceptional termination of the observable sequence. * This method can be used for debugging, logging, etc. of query behavior by intercepting the message stream to run arbitrary actions for messages on the pipeline. * @param {Function} onError Action to invoke upon exceptional termination of the observable sequence. * @param {Any} [thisArg] Object to use as this when executing callback. * @returns {Observable} The source sequence with the side-effecting behavior applied. */ observableProto.doOnError = observableProto.tapOnError = function (onError, thisArg) { return this.tap(noop, typeof thisArg !== 'undefined' ? function (e) { onError.call(thisArg, e); } : onError); }; /** * Invokes an action upon graceful termination of the observable sequence. * This method can be used for debugging, logging, etc. of query behavior by intercepting the message stream to run arbitrary actions for messages on the pipeline. * @param {Function} onCompleted Action to invoke upon graceful termination of the observable sequence. * @param {Any} [thisArg] Object to use as this when executing callback. * @returns {Observable} The source sequence with the side-effecting behavior applied. */ observableProto.doOnCompleted = observableProto.tapOnCompleted = function (onCompleted, thisArg) { return this.tap(noop, null, typeof thisArg !== 'undefined' ? function () { onCompleted.call(thisArg); } : onCompleted); }; /** * Invokes a specified action after the source observable sequence terminates gracefully or exceptionally. * @param {Function} finallyAction Action to invoke after the source observable sequence terminates. * @returns {Observable} Source sequence with the action-invoking termination behavior applied. */ observableProto['finally'] = observableProto.ensure = function (action) { var source = this; return new AnonymousObservable(function (observer) { var subscription; try { subscription = source.subscribe(observer); } catch (e) { action(); throw e; } return disposableCreate(function () { try { subscription.dispose(); } catch (e) { throw e; } finally { action(); } }); }, this); }; /** * @deprecated use #finally or #ensure instead. */ observableProto.finallyAction = function (action) { //deprecate('finallyAction', 'finally or ensure'); return this.ensure(action); }; /** * Ignores all elements in an observable sequence leaving only the termination messages. * @returns {Observable} An empty observable sequence that signals termination, successful or exceptional, of the source sequence. */ observableProto.ignoreElements = function () { var source = this; return new AnonymousObservable(function (o) { return source.subscribe(noop, function (e) { o.onError(e); }, function () { o.onCompleted(); }); }, source); }; /** * Materializes the implicit notifications of an observable sequence as explicit notification values. * @returns {Observable} An observable sequence containing the materialized notification values from the source sequence. */ observableProto.materialize = function () { var source = this; return new AnonymousObservable(function (observer) { return source.subscribe(function (value) { observer.onNext(notificationCreateOnNext(value)); }, function (e) { observer.onNext(notificationCreateOnError(e)); observer.onCompleted(); }, function () { observer.onNext(notificationCreateOnCompleted()); observer.onCompleted(); }); }, source); }; /** * Repeats the observable sequence a specified number of times. If the repeat count is not specified, the sequence repeats indefinitely. * @param {Number} [repeatCount] Number of times to repeat the sequence. If not provided, repeats the sequence indefinitely. * @returns {Observable} The observable sequence producing the elements of the given sequence repeatedly. */ observableProto.repeat = function (repeatCount) { return enumerableRepeat(this, repeatCount).concat(); }; /** * Repeats the source observable sequence the specified number of times or until it successfully terminates. If the retry count is not specified, it retries indefinitely. * Note if you encounter an error and want it to retry once, then you must use .retry(2); * * @example * var res = retried = retry.repeat(); * var res = retried = retry.repeat(2); * @param {Number} [retryCount] Number of times to retry the sequence. If not provided, retry the sequence indefinitely. * @returns {Observable} An observable sequence producing the elements of the given sequence repeatedly until it terminates successfully. */ observableProto.retry = function (retryCount) { return enumerableRepeat(this, retryCount).catchError(); }; /** * Repeats the source observable sequence upon error each time the notifier emits or until it successfully terminates. * if the notifier completes, the observable sequence completes. * * @example * var timer = Observable.timer(500); * var source = observable.retryWhen(timer); * @param {Observable} [notifier] An observable that triggers the retries or completes the observable with onNext or onCompleted respectively. * @returns {Observable} An observable sequence producing the elements of the given sequence repeatedly until it terminates successfully. */ observableProto.retryWhen = function (notifier) { return enumerableRepeat(this).catchErrorWhen(notifier); }; /** * Applies an accumulator function over an observable sequence and returns each intermediate result. The optional seed value is used as the initial accumulator value. * For aggregation behavior with no intermediate results, see Observable.aggregate. * @example * var res = source.scan(function (acc, x) { return acc + x; }); * var res = source.scan(0, function (acc, x) { return acc + x; }); * @param {Mixed} [seed] The initial accumulator value. * @param {Function} accumulator An accumulator function to be invoked on each element. * @returns {Observable} An observable sequence containing the accumulated values. */ observableProto.scan = function () { var hasSeed = false, seed, accumulator, source = this; if (arguments.length === 2) { hasSeed = true; seed = arguments[0]; accumulator = arguments[1]; } else { accumulator = arguments[0]; } return new AnonymousObservable(function (o) { var hasAccumulation, accumulation, hasValue; return source.subscribe ( function (x) { !hasValue && (hasValue = true); try { if (hasAccumulation) { accumulation = accumulator(accumulation, x); } else { accumulation = hasSeed ? accumulator(seed, x) : x; hasAccumulation = true; } } catch (e) { o.onError(e); return; } o.onNext(accumulation); }, function (e) { o.onError(e); }, function () { !hasValue && hasSeed && o.onNext(seed); o.onCompleted(); } ); }, source); }; /** * Bypasses a specified number of elements at the end of an observable sequence. * @description * This operator accumulates a queue with a length enough to store the first `count` elements. As more elements are * received, elements are taken from the front of the queue and produced on the result sequence. This causes elements to be delayed. * @param count Number of elements to bypass at the end of the source sequence. * @returns {Observable} An observable sequence containing the source sequence elements except for the bypassed ones at the end. */ observableProto.skipLast = function (count) { if (count < 0) { throw new ArgumentOutOfRangeError(); } var source = this; return new AnonymousObservable(function (o) { var q = []; return source.subscribe(function (x) { q.push(x); q.length > count && o.onNext(q.shift()); }, function (e) { o.onError(e); }, function () { o.onCompleted(); }); }, source); }; /** * Prepends a sequence of values to an observable sequence with an optional scheduler and an argument list of values to prepend. * @example * var res = source.startWith(1, 2, 3); * var res = source.startWith(Rx.Scheduler.timeout, 1, 2, 3); * @param {Arguments} args The specified values to prepend to the observable sequence * @returns {Observable} The source sequence prepended with the specified values. */ observableProto.startWith = function () { var values, scheduler, start = 0; if (!!arguments.length && isScheduler(arguments[0])) { scheduler = arguments[0]; start = 1; } else { scheduler = immediateScheduler; } for(var args = [], i = start, len = arguments.length; i < len; i++) { args.push(arguments[i]); } return enumerableOf([observableFromArray(args, scheduler), this]).concat(); }; /** * Returns a specified number of contiguous elements from the end of an observable sequence. * @description * This operator accumulates a buffer with a length enough to store elements count elements. Upon completion of * the source sequence, this buffer is drained on the result sequence. This causes the elements to be delayed. * @param {Number} count Number of elements to take from the end of the source sequence. * @returns {Observable} An observable sequence containing the specified number of elements from the end of the source sequence. */ observableProto.takeLast = function (count) { if (count < 0) { throw new ArgumentOutOfRangeError(); } var source = this; return new AnonymousObservable(function (o) { var q = []; return source.subscribe(function (x) { q.push(x); q.length > count && q.shift(); }, function (e) { o.onError(e); }, function () { while (q.length > 0) { o.onNext(q.shift()); } o.onCompleted(); }); }, source); }; /** * Returns an array with the specified number of contiguous elements from the end of an observable sequence. * * @description * This operator accumulates a buffer with a length enough to store count elements. Upon completion of the * source sequence, this buffer is produced on the result sequence. * @param {Number} count Number of elements to take from the end of the source sequence. * @returns {Observable} An observable sequence containing a single array with the specified number of elements from the end of the source sequence. */ observableProto.takeLastBuffer = function (count) { var source = this; return new AnonymousObservable(function (o) { var q = []; return source.subscribe(function (x) { q.push(x); q.length > count && q.shift(); }, function (e) { o.onError(e); }, function () { o.onNext(q); o.onCompleted(); }); }, source); }; /** * Projects each element of an observable sequence into zero or more windows which are produced based on element count information. * * var res = xs.windowWithCount(10); * var res = xs.windowWithCount(10, 1); * @param {Number} count Length of each window. * @param {Number} [skip] Number of elements to skip between creation of consecutive windows. If not specified, defaults to the count. * @returns {Observable} An observable sequence of windows. */ observableProto.windowWithCount = function (count, skip) { var source = this; +count || (count = 0); Math.abs(count) === Infinity && (count = 0); if (count <= 0) { throw new ArgumentOutOfRangeError(); } skip == null && (skip = count); +skip || (skip = 0); Math.abs(skip) === Infinity && (skip = 0); if (skip <= 0) { throw new ArgumentOutOfRangeError(); } return new AnonymousObservable(function (observer) { var m = new SingleAssignmentDisposable(), refCountDisposable = new RefCountDisposable(m), n = 0, q = []; function createWindow () { var s = new Subject(); q.push(s); observer.onNext(addRef(s, refCountDisposable)); } createWindow(); m.setDisposable(source.subscribe( function (x) { for (var i = 0, len = q.length; i < len; i++) { q[i].onNext(x); } var c = n - count + 1; c >= 0 && c % skip === 0 && q.shift().onCompleted(); ++n % skip === 0 && createWindow(); }, function (e) { while (q.length > 0) { q.shift().onError(e); } observer.onError(e); }, function () { while (q.length > 0) { q.shift().onCompleted(); } observer.onCompleted(); } )); return refCountDisposable; }, source); }; function concatMap(source, selector, thisArg) { var selectorFunc = bindCallback(selector, thisArg, 3); return source.map(function (x, i) { var result = selectorFunc(x, i, source); isPromise(result) && (result = observableFromPromise(result)); (isArrayLike(result) || isIterable(result)) && (result = observableFrom(result)); return result; }).concatAll(); } /** * One of the Following: * Projects each element of an observable sequence to an observable sequence and merges the resulting observable sequences into one observable sequence. * * @example * var res = source.concatMap(function (x) { return Rx.Observable.range(0, x); }); * Or: * Projects each element of an observable sequence to an observable sequence, invokes the result selector for the source element and each of the corresponding inner sequence's elements, and merges the results into one observable sequence. * * var res = source.concatMap(function (x) { return Rx.Observable.range(0, x); }, function (x, y) { return x + y; }); * Or: * Projects each element of the source observable sequence to the other observable sequence and merges the resulting observable sequences into one observable sequence. * * var res = source.concatMap(Rx.Observable.fromArray([1,2,3])); * @param {Function} selector A transform function to apply to each element or an observable sequence to project each element from the * source sequence onto which could be either an observable or Promise. * @param {Function} [resultSelector] A transform function to apply to each element of the intermediate sequence. * @returns {Observable} An observable sequence whose elements are the result of invoking the one-to-many transform function collectionSelector on each element of the input sequence and then mapping each of those sequence elements and their corresponding source element to a result element. */ observableProto.selectConcat = observableProto.concatMap = function (selector, resultSelector, thisArg) { if (isFunction(selector) && isFunction(resultSelector)) { return this.concatMap(function (x, i) { var selectorResult = selector(x, i); isPromise(selectorResult) && (selectorResult = observableFromPromise(selectorResult)); (isArrayLike(selectorResult) || isIterable(selectorResult)) && (selectorResult = observableFrom(selectorResult)); return selectorResult.map(function (y, i2) { return resultSelector(x, y, i, i2); }); }); } return isFunction(selector) ? concatMap(this, selector, thisArg) : concatMap(this, function () { return selector; }); }; /** * Projects each notification of an observable sequence to an observable sequence and concats the resulting observable sequences into one observable sequence. * @param {Function} onNext A transform function to apply to each element; the second parameter of the function represents the index of the source element. * @param {Function} onError A transform function to apply when an error occurs in the source sequence. * @param {Function} onCompleted A transform function to apply when the end of the source sequence is reached. * @param {Any} [thisArg] An optional "this" to use to invoke each transform. * @returns {Observable} An observable sequence whose elements are the result of invoking the one-to-many transform function corresponding to each notification in the input sequence. */ observableProto.concatMapObserver = observableProto.selectConcatObserver = function(onNext, onError, onCompleted, thisArg) { var source = this, onNextFunc = bindCallback(onNext, thisArg, 2), onErrorFunc = bindCallback(onError, thisArg, 1), onCompletedFunc = bindCallback(onCompleted, thisArg, 0); return new AnonymousObservable(function (observer) { var index = 0; return source.subscribe( function (x) { var result; try { result = onNextFunc(x, index++); } catch (e) { observer.onError(e); return; } isPromise(result) && (result = observableFromPromise(result)); observer.onNext(result); }, function (err) { var result; try { result = onErrorFunc(err); } catch (e) { observer.onError(e); return; } isPromise(result) && (result = observableFromPromise(result)); observer.onNext(result); observer.onCompleted(); }, function () { var result; try { result = onCompletedFunc(); } catch (e) { observer.onError(e); return; } isPromise(result) && (result = observableFromPromise(result)); observer.onNext(result); observer.onCompleted(); }); }, this).concatAll(); }; /** * Returns the elements of the specified sequence or the specified value in a singleton sequence if the sequence is empty. * * var res = obs = xs.defaultIfEmpty(); * 2 - obs = xs.defaultIfEmpty(false); * * @memberOf Observable# * @param defaultValue The value to return if the sequence is empty. If not provided, this defaults to null. * @returns {Observable} An observable sequence that contains the specified default value if the source is empty; otherwise, the elements of the source itself. */ observableProto.defaultIfEmpty = function (defaultValue) { var source = this; defaultValue === undefined && (defaultValue = null); return new AnonymousObservable(function (observer) { var found = false; return source.subscribe(function (x) { found = true; observer.onNext(x); }, function (e) { observer.onError(e); }, function () { !found && observer.onNext(defaultValue); observer.onCompleted(); }); }, source); }; // Swap out for Array.findIndex function arrayIndexOfComparer(array, item, comparer) { for (var i = 0, len = array.length; i < len; i++) { if (comparer(array[i], item)) { return i; } } return -1; } function HashSet(comparer) { this.comparer = comparer; this.set = []; } HashSet.prototype.push = function(value) { var retValue = arrayIndexOfComparer(this.set, value, this.comparer) === -1; retValue && this.set.push(value); return retValue; }; /** * Returns an observable sequence that contains only distinct elements according to the keySelector and the comparer. * Usage of this operator should be considered carefully due to the maintenance of an internal lookup structure which can grow large. * * @example * var res = obs = xs.distinct(); * 2 - obs = xs.distinct(function (x) { return x.id; }); * 2 - obs = xs.distinct(function (x) { return x.id; }, function (a,b) { return a === b; }); * @param {Function} [keySelector] A function to compute the comparison key for each element. * @param {Function} [comparer] Used to compare items in the collection. * @returns {Observable} An observable sequence only containing the distinct elements, based on a computed key value, from the source sequence. */ observableProto.distinct = function (keySelector, comparer) { var source = this; comparer || (comparer = defaultComparer); return new AnonymousObservable(function (o) { var hashSet = new HashSet(comparer); return source.subscribe(function (x) { var key = x; if (keySelector) { try { key = keySelector(x); } catch (e) { o.onError(e); return; } } hashSet.push(key) && o.onNext(x); }, function (e) { o.onError(e); }, function () { o.onCompleted(); }); }, this); }; var MapObservable = (function (__super__) { inherits(MapObservable, __super__); function MapObservable(source, selector, thisArg) { this.source = source; this.selector = bindCallback(selector, thisArg, 3); __super__.call(this); } MapObservable.prototype.internalMap = function (selector, thisArg) { var self = this; return new MapObservable(this.source, function (x, i, o) { return selector.call(this, self.selector(x, i, o), i, o); }, thisArg) }; MapObservable.prototype.subscribeCore = function (observer) { return this.source.subscribe(new MapObserver(observer, this.selector, this)); }; return MapObservable; }(ObservableBase)); function MapObserver(observer, selector, source) { this.observer = observer; this.selector = selector; this.source = source; this.i = 0; this.isStopped = false; } MapObserver.prototype.onNext = function(x) { if (this.isStopped) { return; } var result = tryCatch(this.selector).call(this, x, this.i++, this.source); if (result === errorObj) { return this.observer.onError(result.e); } this.observer.onNext(result); }; MapObserver.prototype.onError = function (e) { if(!this.isStopped) { this.isStopped = true; this.observer.onError(e); } }; MapObserver.prototype.onCompleted = function () { if(!this.isStopped) { this.isStopped = true; this.observer.onCompleted(); } }; MapObserver.prototype.dispose = function() { this.isStopped = true; }; MapObserver.prototype.fail = function (e) { if (!this.isStopped) { this.isStopped = true; this.observer.onError(e); return true; } return false; }; /** * Projects each element of an observable sequence into a new form by incorporating the element's index. * @param {Function} selector A transform function to apply to each source element; the second parameter of the function represents the index of the source element. * @param {Any} [thisArg] Object to use as this when executing callback. * @returns {Observable} An observable sequence whose elements are the result of invoking the transform function on each element of source. */ observableProto.map = observableProto.select = function (selector, thisArg) { var selectorFn = typeof selector === 'function' ? selector : function () { return selector; }; return this instanceof MapObservable ? this.internalMap(selectorFn, thisArg) : new MapObservable(this, selectorFn, thisArg); }; /** * Retrieves the value of a specified nested property from all elements in * the Observable sequence. * @param {Arguments} arguments The nested properties to pluck. * @returns {Observable} Returns a new Observable sequence of property values. */ observableProto.pluck = function () { var args = arguments, len = arguments.length; if (len === 0) { throw new Error('List of properties cannot be empty.'); } return this.map(function (x) { var currentProp = x; for (var i = 0; i < len; i++) { var p = currentProp[args[i]]; if (typeof p !== 'undefined') { currentProp = p; } else { return undefined; } } return currentProp; }); }; /** * Projects each notification of an observable sequence to an observable sequence and merges the resulting observable sequences into one observable sequence. * @param {Function} onNext A transform function to apply to each element; the second parameter of the function represents the index of the source element. * @param {Function} onError A transform function to apply when an error occurs in the source sequence. * @param {Function} onCompleted A transform function to apply when the end of the source sequence is reached. * @param {Any} [thisArg] An optional "this" to use to invoke each transform. * @returns {Observable} An observable sequence whose elements are the result of invoking the one-to-many transform function corresponding to each notification in the input sequence. */ observableProto.flatMapObserver = observableProto.selectManyObserver = function (onNext, onError, onCompleted, thisArg) { var source = this; return new AnonymousObservable(function (observer) { var index = 0; return source.subscribe( function (x) { var result; try { result = onNext.call(thisArg, x, index++); } catch (e) { observer.onError(e); return; } isPromise(result) && (result = observableFromPromise(result)); observer.onNext(result); }, function (err) { var result; try { result = onError.call(thisArg, err); } catch (e) { observer.onError(e); return; } isPromise(result) && (result = observableFromPromise(result)); observer.onNext(result); observer.onCompleted(); }, function () { var result; try { result = onCompleted.call(thisArg); } catch (e) { observer.onError(e); return; } isPromise(result) && (result = observableFromPromise(result)); observer.onNext(result); observer.onCompleted(); }); }, source).mergeAll(); }; function flatMap(source, selector, thisArg) { var selectorFunc = bindCallback(selector, thisArg, 3); return source.map(function (x, i) { var result = selectorFunc(x, i, source); isPromise(result) && (result = observableFromPromise(result)); (isArrayLike(result) || isIterable(result)) && (result = observableFrom(result)); return result; }).mergeAll(); } /** * One of the Following: * Projects each element of an observable sequence to an observable sequence and merges the resulting observable sequences into one observable sequence. * * @example * var res = source.selectMany(function (x) { return Rx.Observable.range(0, x); }); * Or: * Projects each element of an observable sequence to an observable sequence, invokes the result selector for the source element and each of the corresponding inner sequence's elements, and merges the results into one observable sequence. * * var res = source.selectMany(function (x) { return Rx.Observable.range(0, x); }, function (x, y) { return x + y; }); * Or: * Projects each element of the source observable sequence to the other observable sequence and merges the resulting observable sequences into one observable sequence. * * var res = source.selectMany(Rx.Observable.fromArray([1,2,3])); * @param {Function} selector A transform function to apply to each element or an observable sequence to project each element from the source sequence onto which could be either an observable or Promise. * @param {Function} [resultSelector] A transform function to apply to each element of the intermediate sequence. * @param {Any} [thisArg] Object to use as this when executing callback. * @returns {Observable} An observable sequence whose elements are the result of invoking the one-to-many transform function collectionSelector on each element of the input sequence and then mapping each of those sequence elements and their corresponding source element to a result element. */ observableProto.selectMany = observableProto.flatMap = function (selector, resultSelector, thisArg) { if (isFunction(selector) && isFunction(resultSelector)) { return this.flatMap(function (x, i) { var selectorResult = selector(x, i); isPromise(selectorResult) && (selectorResult = observableFromPromise(selectorResult)); (isArrayLike(selectorResult) || isIterable(selectorResult)) && (selectorResult = observableFrom(selectorResult)); return selectorResult.map(function (y, i2) { return resultSelector(x, y, i, i2); }); }, thisArg); } return isFunction(selector) ? flatMap(this, selector, thisArg) : flatMap(this, function () { return selector; }); }; /** * Projects each element of an observable sequence into a new sequence of observable sequences by incorporating the element's index and then * transforms an observable sequence of observable sequences into an observable sequence producing values only from the most recent observable sequence. * @param {Function} selector A transform function to apply to each source element; the second parameter of the function represents the index of the source element. * @param {Any} [thisArg] Object to use as this when executing callback. * @returns {Observable} An observable sequence whose elements are the result of invoking the transform function on each element of source producing an Observable of Observable sequences * and that at any point in time produces the elements of the most recent inner observable sequence that has been received. */ observableProto.selectSwitch = observableProto.flatMapLatest = observableProto.switchMap = function (selector, thisArg) { return this.select(selector, thisArg).switchLatest(); }; /** * Bypasses a specified number of elements in an observable sequence and then returns the remaining elements. * @param {Number} count The number of elements to skip before returning the remaining elements. * @returns {Observable} An observable sequence that contains the elements that occur after the specified index in the input sequence. */ observableProto.skip = function (count) { if (count < 0) { throw new ArgumentOutOfRangeError(); } var source = this; return new AnonymousObservable(function (o) { var remaining = count; return source.subscribe(function (x) { if (remaining <= 0) { o.onNext(x); } else { remaining--; } }, function (e) { o.onError(e); }, function () { o.onCompleted(); }); }, source); }; /** * Bypasses elements in an observable sequence as long as a specified condition is true and then returns the remaining elements. * The element's index is used in the logic of the predicate function. * * var res = source.skipWhile(function (value) { return value < 10; }); * var res = source.skipWhile(function (value, index) { return value < 10 || index < 10; }); * @param {Function} predicate A function to test each element for a condition; the second parameter of the function represents the index of the source element. * @param {Any} [thisArg] Object to use as this when executing callback. * @returns {Observable} An observable sequence that contains the elements from the input sequence starting at the first element in the linear series that does not pass the test specified by predicate. */ observableProto.skipWhile = function (predicate, thisArg) { var source = this, callback = bindCallback(predicate, thisArg, 3); return new AnonymousObservable(function (o) { var i = 0, running = false; return source.subscribe(function (x) { if (!running) { try { running = !callback(x, i++, source); } catch (e) { o.onError(e); return; } } running && o.onNext(x); }, function (e) { o.onError(e); }, function () { o.onCompleted(); }); }, source); }; /** * Returns a specified number of contiguous elements from the start of an observable sequence, using the specified scheduler for the edge case of take(0). * * var res = source.take(5); * var res = source.take(0, Rx.Scheduler.timeout); * @param {Number} count The number of elements to return. * @param {Scheduler} [scheduler] Scheduler used to produce an OnCompleted message in case <paramref name="count count</paramref> is set to 0. * @returns {Observable} An observable sequence that contains the specified number of elements from the start of the input sequence. */ observableProto.take = function (count, scheduler) { if (count < 0) { throw new ArgumentOutOfRangeError(); } if (count === 0) { return observableEmpty(scheduler); } var source = this; return new AnonymousObservable(function (o) { var remaining = count; return source.subscribe(function (x) { if (remaining-- > 0) { o.onNext(x); remaining === 0 && o.onCompleted(); } }, function (e) { o.onError(e); }, function () { o.onCompleted(); }); }, source); }; /** * Returns elements from an observable sequence as long as a specified condition is true. * The element's index is used in the logic of the predicate function. * @param {Function} predicate A function to test each element for a condition; the second parameter of the function represents the index of the source element. * @param {Any} [thisArg] Object to use as this when executing callback. * @returns {Observable} An observable sequence that contains the elements from the input sequence that occur before the element at which the test no longer passes. */ observableProto.takeWhile = function (predicate, thisArg) { var source = this, callback = bindCallback(predicate, thisArg, 3); return new AnonymousObservable(function (o) { var i = 0, running = true; return source.subscribe(function (x) { if (running) { try { running = callback(x, i++, source); } catch (e) { o.onError(e); return; } if (running) { o.onNext(x); } else { o.onCompleted(); } } }, function (e) { o.onError(e); }, function () { o.onCompleted(); }); }, source); }; var FilterObservable = (function (__super__) { inherits(FilterObservable, __super__); function FilterObservable(source, predicate, thisArg) { this.source = source; this.predicate = bindCallback(predicate, thisArg, 3); __super__.call(this); } FilterObservable.prototype.subscribeCore = function (observer) { return this.source.subscribe(new FilterObserver(observer, this.predicate, this)); }; FilterObservable.prototype.internalFilter = function(predicate, thisArg) { var self = this; return new FilterObservable(this.source, function(x, i, o) { return self.predicate(x, i, o) && predicate.call(this, x, i, o); }, thisArg); }; return FilterObservable; }(ObservableBase)); function FilterObserver(observer, predicate, source) { this.observer = observer; this.predicate = predicate; this.source = source; this.i = 0; this.isStopped = false; } FilterObserver.prototype.onNext = function(x) { if (this.isStopped) { return; } var shouldYield = tryCatch(this.predicate).call(this, x, this.i++, this.source); if (shouldYield === errorObj) { return this.observer.onError(shouldYield.e); } shouldYield && this.observer.onNext(x); }; FilterObserver.prototype.onError = function (e) { if(!this.isStopped) { this.isStopped = true; this.observer.onError(e); } }; FilterObserver.prototype.onCompleted = function () { if(!this.isStopped) { this.isStopped = true; this.observer.onCompleted(); } }; FilterObserver.prototype.dispose = function() { this.isStopped = true; }; FilterObserver.prototype.fail = function (e) { if (!this.isStopped) { this.isStopped = true; this.observer.onError(e); return true; } return false; }; /** * Filters the elements of an observable sequence based on a predicate by incorporating the element's index. * @param {Function} predicate A function to test each source element for a condition; the second parameter of the function represents the index of the source element. * @param {Any} [thisArg] Object to use as this when executing callback. * @returns {Observable} An observable sequence that contains elements from the input sequence that satisfy the condition. */ observableProto.filter = observableProto.where = function (predicate, thisArg) { return this instanceof FilterObservable ? this.internalFilter(predicate, thisArg) : new FilterObservable(this, predicate, thisArg); }; /** * Executes a transducer to transform the observable sequence * @param {Transducer} transducer A transducer to execute * @returns {Observable} An Observable sequence containing the results from the transducer. */ observableProto.transduce = function(transducer) { var source = this; function transformForObserver(observer) { return { init: function() { return observer; }, step: function(obs, input) { return obs.onNext(input); }, result: function(obs) { return obs.onCompleted(); } }; } return new AnonymousObservable(function(observer) { var xform = transducer(transformForObserver(observer)); return source.subscribe( function(v) { try { xform.step(observer, v); } catch (e) { observer.onError(e); } }, observer.onError.bind(observer), function() { xform.result(observer); } ); }, source); }; var AnonymousObservable = Rx.AnonymousObservable = (function (__super__) { inherits(AnonymousObservable, __super__); // Fix subscriber to check for undefined or function returned to decorate as Disposable function fixSubscriber(subscriber) { return subscriber && isFunction(subscriber.dispose) ? subscriber : isFunction(subscriber) ? disposableCreate(subscriber) : disposableEmpty; } function setDisposable(s, state) { var ado = state[0], subscribe = state[1]; var sub = tryCatch(subscribe)(ado); if (sub === errorObj) { if(!ado.fail(errorObj.e)) { return thrower(errorObj.e); } } ado.setDisposable(fixSubscriber(sub)); } function AnonymousObservable(subscribe, parent) { this.source = parent; function s(observer) { var ado = new AutoDetachObserver(observer), state = [ado, subscribe]; if (currentThreadScheduler.scheduleRequired()) { currentThreadScheduler.scheduleWithState(state, setDisposable); } else { setDisposable(null, state); } return ado; } __super__.call(this, s); } return AnonymousObservable; }(Observable)); var AutoDetachObserver = (function (__super__) { inherits(AutoDetachObserver, __super__); function AutoDetachObserver(observer) { __super__.call(this); this.observer = observer; this.m = new SingleAssignmentDisposable(); } var AutoDetachObserverPrototype = AutoDetachObserver.prototype; AutoDetachObserverPrototype.next = function (value) { var result = tryCatch(this.observer.onNext).call(this.observer, value); if (result === errorObj) { this.dispose(); thrower(result.e); } }; AutoDetachObserverPrototype.error = function (err) { var result = tryCatch(this.observer.onError).call(this.observer, err); this.dispose(); result === errorObj && thrower(result.e); }; AutoDetachObserverPrototype.completed = function () { var result = tryCatch(this.observer.onCompleted).call(this.observer); this.dispose(); result === errorObj && thrower(result.e); }; AutoDetachObserverPrototype.setDisposable = function (value) { this.m.setDisposable(value); }; AutoDetachObserverPrototype.getDisposable = function () { return this.m.getDisposable(); }; AutoDetachObserverPrototype.dispose = function () { __super__.prototype.dispose.call(this); this.m.dispose(); }; return AutoDetachObserver; }(AbstractObserver)); var InnerSubscription = function (subject, observer) { this.subject = subject; this.observer = observer; }; InnerSubscription.prototype.dispose = function () { if (!this.subject.isDisposed && this.observer !== null) { var idx = this.subject.observers.indexOf(this.observer); this.subject.observers.splice(idx, 1); this.observer = null; } }; /** * Represents an object that is both an observable sequence as well as an observer. * Each notification is broadcasted to all subscribed observers. */ var Subject = Rx.Subject = (function (__super__) { function subscribe(observer) { checkDisposed(this); if (!this.isStopped) { this.observers.push(observer); return new InnerSubscription(this, observer); } if (this.hasError) { observer.onError(this.error); return disposableEmpty; } observer.onCompleted(); return disposableEmpty; } inherits(Subject, __super__); /** * Creates a subject. */ function Subject() { __super__.call(this, subscribe); this.isDisposed = false, this.isStopped = false, this.observers = []; this.hasError = false; } addProperties(Subject.prototype, Observer.prototype, { /** * Indicates whether the subject has observers subscribed to it. * @returns {Boolean} Indicates whether the subject has observers subscribed to it. */ hasObservers: function () { return this.observers.length > 0; }, /** * Notifies all subscribed observers about the end of the sequence. */ onCompleted: function () { checkDisposed(this); if (!this.isStopped) { this.isStopped = true; for (var i = 0, os = cloneArray(this.observers), len = os.length; i < len; i++) { os[i].onCompleted(); } this.observers.length = 0; } }, /** * Notifies all subscribed observers about the exception. * @param {Mixed} error The exception to send to all observers. */ onError: function (error) { checkDisposed(this); if (!this.isStopped) { this.isStopped = true; this.error = error; this.hasError = true; for (var i = 0, os = cloneArray(this.observers), len = os.length; i < len; i++) { os[i].onError(error); } this.observers.length = 0; } }, /** * Notifies all subscribed observers about the arrival of the specified element in the sequence. * @param {Mixed} value The value to send to all observers. */ onNext: function (value) { checkDisposed(this); if (!this.isStopped) { for (var i = 0, os = cloneArray(this.observers), len = os.length; i < len; i++) { os[i].onNext(value); } } }, /** * Unsubscribe all observers and release resources. */ dispose: function () { this.isDisposed = true; this.observers = null; } }); /** * Creates a subject from the specified observer and observable. * @param {Observer} observer The observer used to send messages to the subject. * @param {Observable} observable The observable used to subscribe to messages sent from the subject. * @returns {Subject} Subject implemented using the given observer and observable. */ Subject.create = function (observer, observable) { return new AnonymousSubject(observer, observable); }; return Subject; }(Observable)); /** * Represents the result of an asynchronous operation. * The last value before the OnCompleted notification, or the error received through OnError, is sent to all subscribed observers. */ var AsyncSubject = Rx.AsyncSubject = (function (__super__) { function subscribe(observer) { checkDisposed(this); if (!this.isStopped) { this.observers.push(observer); return new InnerSubscription(this, observer); } if (this.hasError) { observer.onError(this.error); } else if (this.hasValue) { observer.onNext(this.value); observer.onCompleted(); } else { observer.onCompleted(); } return disposableEmpty; } inherits(AsyncSubject, __super__); /** * Creates a subject that can only receive one value and that value is cached for all future observations. * @constructor */ function AsyncSubject() { __super__.call(this, subscribe); this.isDisposed = false; this.isStopped = false; this.hasValue = false; this.observers = []; this.hasError = false; } addProperties(AsyncSubject.prototype, Observer, { /** * Indicates whether the subject has observers subscribed to it. * @returns {Boolean} Indicates whether the subject has observers subscribed to it. */ hasObservers: function () { checkDisposed(this); return this.observers.length > 0; }, /** * Notifies all subscribed observers about the end of the sequence, also causing the last received value to be sent out (if any). */ onCompleted: function () { var i, len; checkDisposed(this); if (!this.isStopped) { this.isStopped = true; var os = cloneArray(this.observers), len = os.length; if (this.hasValue) { for (i = 0; i < len; i++) { var o = os[i]; o.onNext(this.value); o.onCompleted(); } } else { for (i = 0; i < len; i++) { os[i].onCompleted(); } } this.observers.length = 0; } }, /** * Notifies all subscribed observers about the error. * @param {Mixed} error The Error to send to all observers. */ onError: function (error) { checkDisposed(this); if (!this.isStopped) { this.isStopped = true; this.hasError = true; this.error = error; for (var i = 0, os = cloneArray(this.observers), len = os.length; i < len; i++) { os[i].onError(error); } this.observers.length = 0; } }, /** * Sends a value to the subject. The last value received before successful termination will be sent to all subscribed and future observers. * @param {Mixed} value The value to store in the subject. */ onNext: function (value) { checkDisposed(this); if (this.isStopped) { return; } this.value = value; this.hasValue = true; }, /** * Unsubscribe all observers and release resources. */ dispose: function () { this.isDisposed = true; this.observers = null; this.exception = null; this.value = null; } }); return AsyncSubject; }(Observable)); var AnonymousSubject = Rx.AnonymousSubject = (function (__super__) { inherits(AnonymousSubject, __super__); function subscribe(observer) { return this.observable.subscribe(observer); } function AnonymousSubject(observer, observable) { this.observer = observer; this.observable = observable; __super__.call(this, subscribe); } addProperties(AnonymousSubject.prototype, Observer.prototype, { onCompleted: function () { this.observer.onCompleted(); }, onError: function (error) { this.observer.onError(error); }, onNext: function (value) { this.observer.onNext(value); } }); return AnonymousSubject; }(Observable)); if (typeof define == 'function' && typeof define.amd == 'object' && define.amd) { root.Rx = Rx; define(function() { return Rx; }); } else if (freeExports && freeModule) { // in Node.js or RingoJS if (moduleExports) { (freeModule.exports = Rx).Rx = Rx; } else { freeExports.Rx = Rx; } } else { // in a browser or Rhino root.Rx = Rx; } // All code before this point will be filtered from stack traces. var rEndingLine = captureLine(); }.call(this));
ajax/libs/winjs/4.2.0/js/ui.min.js
LeaYeh/cdnjs
/*! Copyright (c) Microsoft Corporation. All Rights Reserved. Licensed under the MIT License. See License.txt in the project root for license information. */ !function(){var a="undefined"!=typeof window?window:"undefined"!=typeof self?self:"undefined"!=typeof global?global:{};!function(b){"function"==typeof define&&define.amd?define(["./base"],b):(a.msWriteProfilerMark&&msWriteProfilerMark("WinJS.4.2 4.2.0.winjs.2015.8.17 ui.js,StartTM"),b("undefined"!=typeof module?require("./base"):a.WinJS),a.msWriteProfilerMark&&msWriteProfilerMark("WinJS.4.2 4.2.0.winjs.2015.8.17 ui.js,StopTM"))}(function(b){var c=b.Utilities._require,d=b.Utilities._define;d("WinJS/VirtualizedDataSource/_VirtualizedDataSourceImpl",["exports","../Core/_Global","../Core/_Base","../Core/_BaseUtils","../Core/_ErrorFromName","../Core/_Events","../Core/_Log","../Core/_Resources","../Core/_WriteProfilerMark","../Promise","../Scheduler","../_Signal","../Utilities/_UI"],function(a,b,c,d,e,f,g,h,i,j,k,l,m){"use strict";c.Namespace._moduleDefine(a,"WinJS.UI",{VirtualizedDataSource:c.Namespace._lazy(function(){function a(a,c){function f(a){var b="WinJS.UI.VirtualizedDataSource:"+pe+":"+a+",StartTM";i(b),g.log&&g.log(b,"winjs vds","perf")}function u(a){var b="WinJS.UI.VirtualizedDataSource:"+pe+":"+a+",StopTM";i(b),g.log&&g.log(b,"winjs vds","perf")}function v(a){return"number"==typeof a&&a>=0}function w(a){return v(a)&&a===Math.floor(a)}function x(a){if(null===a)a=void 0;else if(void 0!==a&&!w(a))throw new e("WinJS.UI.ListDataSource.InvalidIndexReturned",s.invalidIndexReturned);return a}function y(a){if(null===a)a=void 0;else if(void 0!==a&&!w(a)&&a!==p.unknown)throw new e("WinJS.UI.ListDataSource.InvalidCountReturned",s.invalidCountReturned);return a}function z(){var a=(nd++).toString(),b={handle:a,item:null,itemNew:null,fetchListeners:null,cursorCount:0,bindingMap:null};return Nd[a]=b,b}function A(){return z()}function B(a,b){a.prev=b.prev,a.next=b,a.prev.next=a,b.prev=a}function C(a){a.lastInSequence&&(delete a.lastInSequence,a.prev.lastInSequence=!0),a.firstInSequence&&(delete a.firstInSequence,a.next.firstInSequence=!0),a.prev.next=a.next,a.next.prev=a.prev}function D(a){for(;!a.firstInSequence;)a=a.prev;return a}function E(a){for(;!a.lastInSequence;)a=a.next;return a}function F(a,b,c){return b.prev.next=c.next,c.next.prev=b.prev,b.prev=a.prev,c.next=a,b.prev.next=b,a.prev=c,!0}function G(a,b,c){return b.prev.next=c.next,c.next.prev=b.prev,b.prev=a,c.next=a.next,a.next=b,c.next.prev=c,!0}function H(a){delete a.lastInSequence,delete a.next.firstInSequence}function I(a){var b=a.next;a.lastInSequence=!0,b.firstInSequence=!0,b===Ld&&nb(Ld,void 0)}function J(a,b,c,d){B(a,b);var e=a.prev;e.lastInSequence&&(c?delete e.lastInSequence:a.firstInSequence=!0,d?delete b.firstInSequence:a.lastInSequence=!0)}function K(a,b){a.key=b,Od[a.key]=a}function L(a,b,c){+b===b&&(a.index=b,c[b]=a,Ad||(a.firstInSequence&&a.prev&&a.prev.index===b-1&&H(a.prev),a.lastInSequence&&a.next&&a.next.index===b+1&&H(a)))}function M(a,b){var c=b===Pd?A():z();return B(c,a),c}function N(a,b,c){var d=M(a,c);return d.firstInSequence=!0,d.lastInSequence=!0,L(d,b,c),d}function O(a,b){return N(a,b,Pd)}function P(a,b){var c=M(a,b);return delete a.firstInSequence,c.prev.index===c.index-1?delete c.prev.lastInSequence:c.firstInSequence=!0,L(c,a.index-1,b),c}function Q(a,b){var c=M(a.next,b);return delete a.lastInSequence,c.next.index===c.index+1?delete c.next.firstInSequence:c.lastInSequence=!0,L(c,a.index+1,b),c}function R(a,b,c,d){J(a,b,c,d),Od[a.key]=a,void 0!==a.index&&(Pd[a.index]=a)}function S(a){C(a),a.key&&delete Od[a.key],void 0!==a.index&&Pd[a.index]===a&&delete Pd[a.index];var b=a.bindingMap;for(var c in b){var d=b[c].handle;d&&Nd[d]===a&&delete Nd[d]}Nd[a.handle]===a&&delete Nd[a.handle]}function T(a){return!Nd[a.handle]}function U(a,b,c,d,e){var f=e?null:b[a-1];if(f&&(f.next!==d||d.firstInSequence))f=f.next;else if(f=b[a+1],!f){f=c.next;for(var g;;){if(f.firstInSequence&&(g=f),!(a>=f.index)||f===d)break;f=f.next}f!==d||d.firstInSequence||(f=g&&void 0===g.index?g:void 0)}return f}function V(a){return!a.item&&!a.itemNew&&a!==Ld}function W(a,b){Object.defineProperty(a,"handle",{value:b,writable:!1,enumerable:!1,configurable:!0})}function X(a,b,c){W(a,c),Object.defineProperty(a,"index",{get:function(){for(;b.slotMergedWith;)b=b.slotMergedWith;return b.index},enumerable:!1,configurable:!0})}function Y(a){if(void 0===a)return a;var b=JSON.stringify(a);if(void 0===b)throw new e("WinJS.UI.ListDataSource.ObjectIsNotValidJson",s.objectIsNotValidJson);return b}function Z(b){return a.itemSignature?a.itemSignature(b.data):Y(b.data)}function $(b){var c=b.itemNew;b.itemNew=null,c&&(c=Object.create(c),X(c,b,b.handle),a.compareByIdentity||(b.signature=Z(c))),b.item=c,delete b.indexRequested,delete b.keyRequested}function _(a){return a.bindingMap||a.cursorCount>0}function ab(a){return _(a)||a.fetchListeners||a.directFetchListeners}function bb(a){return ab(a)||!a.firstInSequence&&_(a.prev)||!a.lastInSequence&&_(a.next)||!ie&&(!a.firstInSequence&&a.prev!==Kd&&!(a.prev.item||a.prev.itemNew))|(!a.lastInSequence&&a.next!==Ld&&!(a.next.item||a.next.itemNew))}function cb(a){I(a),S(a)}function db(){if(!vd){(!Rd||T(Rd))&&(Rd=Ld.prev);for(var a=Rd.prev,b=Rd.next,c=0,d=function(a){a===Ld||bb(a)||(hd>=c?c++:cb(a))};a||b;){if(a){var e=a;a=e.prev,e!==Kd&&d(e)}if(b){var f=b;b=f.next,f!==Md&&d(f)}}Qd=0}}function eb(a){ab(a)||(Qd++,vd||Ud||(Rd=a,Qd>hd&&!Sd&&(Sd=!0,k.schedule(function(){Sd=!1,db()},k.Priority.idle,null,"WinJS.UI.VirtualizedDataSource.releaseSlotIfUnrequested"))))}function fb(a){for(var b in ld)a(ld[b])}function gb(a,b){for(var c in a.bindingMap)b(a.bindingMap[c].bindingRecord,c)}function hb(a){return a.notificationsSent||(a.notificationsSent=!0,a.notificationHandler.beginNotifications&&a.notificationHandler.beginNotifications()),a.notificationHandler}function ib(){sd||yd||fb(function(a){a.notificationsSent&&(a.notificationsSent=!1,a.notificationHandler.endNotifications&&a.notificationHandler.endNotifications())})}function jb(a,b){var c=a.bindingMap;if(c){var d=c[b];if(d){var e=d.handle;if(e)return e}}return a.handle}function kb(a,b){return a&&a.handle!==b&&(a=Object.create(a),W(a,b)),a}function lb(a){var b=Jd;Jd=a,fb(function(a){a.notificationHandler&&a.notificationHandler.countChanged&&hb(a).countChanged(Jd,b)})}function mb(a,b){gb(a,function(c,d){c.notificationHandler.indexChanged&&hb(c).indexChanged(jb(a,d),a.index,b)})}function nb(a,b){var c=a.index;if(void 0!==c&&Pd[c]===a&&delete Pd[c],+b===b)L(a,b,Pd);else{if(+c!==c)return;delete a.index}mb(a,c)}function ob(a,b,c,d,e){var f={};if(!(!d&&b.lastInSequence||!e&&c.firstInSequence))if(b===Kd)if(c===Ld)for(var g in ld)f[g]=ld[g];else for(var g in c.bindingMap)f[g]=ld[g];else if(c===Ld||c.bindingMap)for(var g in b.bindingMap)(c===Ld||c.bindingMap[g])&&(f[g]=ld[g]);for(var g in a.bindingMap)f[g]=ld[g];return f}function pb(a){var b,c=a.prev,d=a.next,e=ob(a,c,d);for(b in e){var f=e[b];f.notificationHandler&&hb(f).inserted(f.itemPromiseFromKnownSlot(a),c.lastInSequence||c===Kd?null:jb(c,b),d.firstInSequence||d===Ld?null:jb(d,b))}}function qb(a){var b=a.item;$(a),gb(a,function(c,d){var e=jb(a,d);hb(c).changed(kb(a.item,e),kb(b,e))})}function rb(a,b,c,d,e){var f,g=b.prev;if(b===a){if(!a.firstInSequence||!c)return;b=a.next}else if(g===a){if(!a.lastInSequence||!d)return;g=a.prev}if(!e){var h=ob(a,g,b,c,d);for(f in h){var i=h[f];hb(i).moved(i.itemPromiseFromKnownSlot(a),(g.lastInSequence||g===a.prev)&&!c||g===Kd?null:jb(g,f),(b.firstInSequence||b===a.next)&&!d||b===Ld?null:jb(b,f))}fb(function(b){b.adjustCurrentSlot(a)})}C(a),J(a,b,c,d)}function sb(a,b){Bb(a,!0),gb(a,function(c,d){hb(c).removed(jb(a,d),b)}),fb(function(b){b.adjustCurrentSlot(a)}),S(a)}function tb(a){for(;!a.firstInSequence;)a=a.prev;var b;do{b=a.lastInSequence;var c=a.next;sb(a,!0),a=c}while(!b)}function ub(a){var b;if(!a)return b;for(var c=0;!a.firstInSequence;)c++,a=a.prev;return"number"==typeof a.indexNew?a.indexNew+c:"number"==typeof a.index?a.index+c:b}function vb(a,b){for(a=a.next;a;a=a.next)if(a.firstInSequence){var c=void 0!==a.indexNew?a.indexNew:a.index;void 0!==c&&(a.indexNew=c+b)}zd+=b,Ad=!0,Ud?wc():Cd++}function wb(a,b){if(a.firstInSequence){var c;if(0>b)c=a.indexNew,void 0!==c?delete a.indexNew:c=a.index,a.lastInSequence||(a=a.next,void 0!==c&&(a.indexNew=c));else if(!a.lastInSequence){var d=a.next;c=d.indexNew,void 0!==c?delete d.indexNew:c=d.index,void 0!==c&&(a.indexNew=c)}}vb(a,b)}function xb(a,b){for(var c=Kd;c!==Ld;c=c.next){var d=c.indexNew;if(void 0!==d&&d>=a){vb(c,b);break}}}function yb(){var a,b,c;for(a=Kd;;a=a.next){if(a.firstInSequence){if(b=a,void 0!==a.indexNew){if(c=a.indexNew,delete a.indexNew,isNaN(c))break}else c=a.index;a!==Kd&&a.prev.index===c-1&&H(a.prev)}if(a.lastInSequence)for(var d=c,e=b;e!==a.next;e=e.next)d!==e.index&&nb(e,d),+d===d&&d++;if(a===Ld)break}for(;a!==Md;a=a.next)void 0!==a.index&&a!==Ld&&nb(a,void 0);Ad=!1,zd&&+Jd===Jd&&(pd?pd.reset():lb(Jd+zd),zd=0)}function zb(a,b,c,d,e){if(a.item)return new j(function(b){e?e(b,a.item):b(a.item)});var f={listBindingID:d,retained:!1};return a[b]||(a[b]={}),a[b][c]=f,f.promise=new j(function(a,b){f.complete=e?function(b){e(a,b)}:a,f.error=b},function(){for(;a.slotMergedWith;)a=a.slotMergedWith;var d=a[b];if(d){if(delete d[c],Object.keys(d).length>0)return;delete a[b]}eb(a)}),f.promise}function Ab(a,b){for(var c in b)b[c].complete(a)}function Bb(a,b){var c=a.fetchListeners,d=a.directFetchListeners;if(c||d){$(a);var e=a.item,f=function(a){b?Ab(e,a):Gd.push(function(){Ab(e,a)})};d&&(a.directFetchListeners=null,f(d)),c&&(a.fetchListeners=null,f(c)),eb(a)}}function Cb(){var a=Gd;Gd=[];for(var b=0,c=a.length;c>b;b++)a[b]()}function Db(a,b){var c=a.directFetchListeners;if(c){a.directFetchListeners=null;for(var d in c)c[d].error(b);eb(a)}}function Eb(a){return a.firstInSequence&&P(a,Pd),a.lastInSequence&&Q(a,Pd),a.itemNew&&$(a),ac(),a}function Fb(a){if(!a.firstInSequence){var b=a.prev;return b===Kd?null:Eb(b)}return Eb(P(a,Pd))}function Gb(a){if(!a.lastInSequence){var b=a.next;return b===Ld?null:Eb(b)}return Eb(Q(a,Pd))}function Hb(a){return a?zb(a,"directFetchListeners",(od++).toString()):j.wrap(null)}function Ib(a){if("string"!=typeof a||!a)throw new e("WinJS.UI.ListDataSource.KeyIsInvalid",s.keyIsInvalid)}function Jb(a){var b=O(Md);return K(b,a),b.keyRequested=!0,b}function Kb(a,b){Ib(a);var c=Od[a];return c||(c=Jb(a),c.hints=b),Eb(c)}function Lb(a){if("number"!=typeof a||0>a)throw new e("WinJS.UI.ListDataSource.IndexIsInvalid",s.indexIsInvalid);if(Ld.index<=a)return null;var b=Pd[a];if(!b){var c=U(a,Pd,Kd,Ld);if(!c)return null;c===Ld&&a>=Ld&&nb(Ld,void 0),b=c.prev.index===a-1?Q(c.prev,Pd):c.index===a+1?P(c,Pd):O(c,a)}return b.item||(b.indexRequested=!0),Eb(b)}function Mb(a){var b=O(Md);return b.description=a,Eb(b)}function Nb(a){if(jd=a,id!==jd){var c=function(){kd=!1,id!==jd&&(id=jd,qe.dispatchEvent(t,id))};jd===o.failure?c():kd||(kd=!0,b.setTimeout(c,40))}}function Ob(a){var b=a.fetchID;return b&&Fd[b]}function Pb(a,b){a.fetchID=b}function Qb(){var a=Ed;return Ed++,Fd[a]=!0,a}function Rb(a,b,c){var d=Qb();Pb(a,d);for(var e=a;!e.firstInSequence&&b>0;)e=e.prev,b--,Pb(e,d);for(var f=a;!f.lastInSequence&&c>0;)f=f.next,c--,Pb(f,d);return d}function Sb(a){var b=a.items,c=a.offset,d=a.totalCount,e=a.absoluteIndex,f=a.atStart,g=a.atEnd;if(v(e)){if(v(d)){var h=b.length;e-c+h===d&&(g=!0)}c===e&&(f=!0)}f&&(b.unshift(Hd),a.offset++),g&&b.push(Id)}function Tb(a,b,c){return delete Fd[c],b!==Cd||T(a)?(ac(),!1):!0}function Ub(a,b,c,d){var g=Cd;c.then(function(c){if(!c.items||!c.items.length)return j.wrapError(new e(q.doesNotExist));var h="itemsFetched id="+b+" count="+c.items.length;f(h),Tb(a,g,b)&&(+d===d&&(c.absoluteIndex=d),Sb(c),qc(a,c.items,c.offset,c.totalCount,c.absoluteIndex)),u(h)}).then(null,function(c){Tb(a,g,b)&&rc(a,c)})}function Vb(a,b,c,d){var g=Cd;d.then(function(d){if(!d.items||!d.items.length)return j.wrapError(new e(q.doesNotExist));var h="itemsFetched id="+c+" count="+d.items.length;f(h),Tb(b,g,c)&&(d.absoluteIndex=a,Sb(d),sc(a,b,d.items,d.offset,d.totalCount,d.absoluteIndex)),u(h)}).then(null,function(){Tb(b,g,c)&&tc(a,b,g)})}function Wb(a,b){var c=Rb(a,0,b-1);je?Ub(a,c,je(c,b),0):Ub(a,c,ie(c,0,0,b-1),0)}function Xb(a,b){var c=Rb(a,b-1,0);Ub(a,c,ke(c,b))}function Yb(a,b,c){var d=Rb(a,b,c);Ub(a,d,he(d,a.key,b,c,a.hints))}function Zb(a,b,c){var d=a.index;if(b>d&&(b=d),ie){var e=Rb(a,b,c);Ub(a,e,ie(e,d,b,c),d)}else if(a.key)Yb(a,b,c);else{var f,g,h=Kd,i=d+1;for(f=a.prev;f!==Kd;f=f.prev)if(void 0!==f.index&&f.key){g=d-f.index,i>g&&(i=g,h=f);break}for(f=a.next;f!==Ld;f=f.next)if(void 0!==f.index&&f.key){g=f.index-d,i>g&&(i=g,h=f);break}if(h===Kd){var e=Rb(a,0,d+1);Vb(0,a,e,je(e,d+1))}else{var j=Math.max(h.index-d,0),k=Math.max(d-h.index,0),e=Rb(h,j,k);Vb(h.index,a,e,he(e,h.key,j,k,a.hints))}}}function $b(a,b,c){var d=Rb(a,b,c);Ub(a,d,le(d,a.description,b,c))}function _b(){if(!Ud){for(var a,b,c,d,e,f,g,h,i=!1,j=!1,k=Kd.next;k!==Md;){var l=k.next;if(k!==Ld&&V(k)&&(j=!0,a?b++:(a=k,b=1),Ob(k)&&(i=!0),k.keyRequested&&!c&&(c=k,d=b-1),void 0===k.description||e||(e=k,f=b-1),k.indexRequested&&!g&&(g=k,h=b-1),k.lastInSequence||l===Md||!V(l))){if(i)i=!1;else{if(qd=!1,!a.firstInSequence&&a.prev.key&&he?Yb(a.prev,0,b):!k.lastInSequence&&l.key&&he?Yb(l,b,0):a.prev!==Kd||a.firstInSequence||!je&&!ie?l===Ld&&!k.lastInSequence&&ke?Xb(k,b):c?Yb(c,d,b-1-d):e?$b(e,f,b-1-f):g?Zb(g,h,b-1-h):"number"==typeof a.index?Zb(a,b-1,0):tb(a):Wb(a,b),qd)return void ac();if(Ud)return}a=g=c=null}k=l}Nb(j?o.waiting:o.ready)}}function ac(){Dd||(Dd=!0,k.schedule(function(){Dd=!1,_b(),ib()},k.Priority.max,null,"WinJS.UI.ListDataSource._fetch"))}function bc(b){var c=b.itemNew;if(!c)return!1;var d=b.item;for(var e in d)switch(e){case"data":break;default:if(d[e]!==c[e])return!0}return a.compareByIdentity?d.data!==c.data:b.signature!==Z(c)}function cc(a){ab(a)?bc(a)?qb(a):a.itemNew=null:a.item=null}function dc(a){a.item?cc(a):Bb(a)}function ec(a,b){a.key||K(a,b.key),a.itemNew=b,dc(a)}function fc(a,b,c){var d=b.bindingMap;if(d)for(var e in c)if(d[e]){var f=b.fetchListeners;for(var g in f){var h=f[g];h.listBindingID===e&&h.retained&&(delete f[g],h.complete(null))}var i=d[e].bindingRecord;hb(i).removed(jb(b,e),!0,jb(a,e)),b.bindingMap&&delete b.bindingMap[e]}}function gc(a,b){if(a.index!==b.index){var c=b.index;b.index=a.index,mb(b,c)}b.slotMergedWith=a;var d=b.bindingMap;for(var e in d){a.bindingMap||(a.bindingMap={});var f=d[e];f.handle||(f.handle=b.handle),Nd[f.handle]=a,a.bindingMap[e]=f}fb(function(c){c.adjustCurrentSlot(b,a)});var g=b.itemNew||b.item;if(g&&(g=Object.create(g),X(g,a,a.handle),ec(a,g)),a.item)b.directFetchListeners&&Gd.push(function(){Ab(a.item,b.directFetchListeners)}),b.fetchListeners&&Gd.push(function(){Ab(a.item,b.fetchListeners)});else{var h;for(h in b.directFetchListeners)a.directFetchListeners||(a.directFetchListeners={}),a.directFetchListeners[h]=b.directFetchListeners[h];for(h in b.fetchListeners)a.fetchListeners||(a.fetchListeners={}),a.fetchListeners[h]=b.fetchListeners[h]}a.itemNew&&Bb(a),b.handle=(nd++).toString(),I(b),S(b)}function hc(a,b,c){b&&b.key&&(c||(c=b.itemNew||b.item),delete b.key,delete Od[c.key],b.itemNew=null,b.item=null),c&&ec(a,c),b&&gc(a,b)}function ic(a){if("object"!=typeof a)throw new e("WinJS.UI.ListDataSource.InvalidItemReturned",s.invalidItemReturned);if(a===Hd)return Kd;if(a===Id)return Ld;if(a.key)return d.validation&&Ib(a.key),Od[a.key];throw new e("WinJS.UI.ListDataSource.InvalidKeyReturned",s.invalidKeyReturned)}function jc(a,b){var c=ic(b);c===a&&(c=null),c&&fc(a,c,a.bindingMap),hc(a,c,b)}function kc(a,b,c,d){if(b&&a.key&&a.key!==b.key)return wc(),!1;var e=Pd[c];if(e)if(e===a)e=null;else{if(e.key&&(a.key||b&&e.key!==b.key))return wc(),!1;if(!a.key&&e.bindingMap)return!1}var f;if(b)if(f=Od[b.key],f===a)f=null;else if(f&&f.bindingMap)return!1;return e?(fc(a,e,a.bindingMap),delete Pd[c],nb(a,c),a.prev.index===c-1&&H(a.prev),a.next.index===c+1&&H(a),d.slotNext=e.slotNext,b||(b=e.itemNew||e.item,b&&(f=Od[b.key]))):nb(a,c),f&&e!==f&&fc(a,f,a.bindingMap),hc(a,f,b),e&&e!==f&&gc(a,e),!0}function lc(a,b,c){if(b.key&&a.key&&b.key!==a.key)return wc(),!1;for(var d in a.bindingMap)c[d]=!0;return fc(a,b,c),hc(a,b),!0}function mc(a,b){for(var c={};a;){var d=a.firstInSequence?null:a.prev;if(b.firstInSequence||b.prev!==Kd){if(b=b.firstInSequence?P(b,Pd):b.prev,!lc(b,a,c))return}else sb(a,!0);a=d}}function nc(a,b){for(var c={};a;){var d=a.lastInSequence?null:a.next;if(b.lastInSequence||b.next!==Ld){if(b=b.lastInSequence?Q(b,Pd):b.next,!lc(b,a,c))return}else sb(a,!0);a=d}}function oc(a){for(var b=0;b<a.length;b++){var c=a[b];mc(c.slotBeforeSequence,c.slotFirstInSequence),nc(c.slotAfterSequence,c.slotLastInSequence)}}function pc(a,b){function c(b){for(var c=Ld.prev;!(c.index<a)&&c!==b;){var e=c.prev;void 0!==c.index&&sb(c,!0),c=e}d=0}for(var d=0,e=Ld.prev;!(e.index<a)||d>0;){var f=e.prev;if(e===Kd){c(Kd);break}if(e.key){if(e.index>=a)return wc(),!1;if(!(e.index>=b))return he?Yb(e,0,d):Zb(e,0,d),!1;c(e)}else e.indexRequested||e.firstInSequence?c(f):d++;e=f}return!0}function qc(a,b,c,d,e){var g="WinJS.UI.ListDataSource.processResults";return f(g),e=x(e),d=y(d),vd?void u(g):(Ad&&yb(),!v(d)&&d!==p.unknown||d===Jd||Ld.firstInSequence?(qd=!0,function(){var f,g,h,i,j=b.length;if("number"!=typeof e)for(f=0;j>f;f++)if(h=ic(b[f]),h&&void 0!==h.index){e=h.index+c-f;break}"number"==typeof e&&b[j-1]===Id?d=e-c+j-1:!v(d)||void 0!==e&&null!==e||(e=d-(j-1)+c),v(d)&&!pc(d,e-c)&&(d=void 0);var k=new Array(j);for(f=0;j>f;f++){var l=null;if(h=ic(b[f])){if(f>0&&!h.firstInSequence&&h.prev.key&&h.prev.key!==b[f-1].key||"number"==typeof e&&void 0!==h.index&&h.index!==e-c+f)return void wc();(h===Kd||h===Ld||h.bindingMap)&&(l=h)}if("number"==typeof e&&(h=Pd[e-c+f])){if(h.key&&h.key!==b[f].key)return void wc();!l&&h.bindingMap&&(l=h)}if(f===c){if(a.key&&a.key!==b[f].key||"number"==typeof a.index&&"number"==typeof e&&a.index!==e)return void wc();l||(l=a)}k[f]=l}for(f=0;j>f;f++)h=k[f],h&&void 0!==h.index&&h!==Kd&&h!==Ld&&jc(h,b[f]);var m,n,o=[],p=!0;for(f=0;j>f;f++)if(h=k[f],h&&h!==Ld){var q=f;if(void 0===h.index){var r={};kc(h,b[f],e-c+f,r);var s,t=h,u=h;for(g=f-1;!t.firstInSequence&&(s=b[g],s!==Hd);g--){var w=e-c+g;if(0>w)break;if(!kc(t.prev,s,w,r))break;t=t.prev,g>=0&&(k[g]=t)}for(g=f+1;!u.lastInSequence&&(s=b[g],s!==Id&&g!==d||u.next===Ld)&&(u.next===Ld||kc(u.next,s,e-c+g,r))&&(u=u.next,j>g&&(k[g]=u),q=g,u!==Ld);g++);if(m=t.firstInSequence?null:t.prev,n=u.lastInSequence?null:u.next,m&&I(m),n&&I(u),"number"==typeof e){if(u===Ld)m&&G(Ld,D(m),m);else{var x=r.slotNext;x||(x=U(u.index,Pd,Kd,Ld,!0)),F(x,t,u)}t.prev.index===t.index-1&&H(t.prev),u.next.index===u.index+1&&H(u)}else p||(i=k[f-1],i&&(t.prev!==i&&(u===Ld?(m&&G(Ld,D(m),m),F(t,D(i),i)):G(i,t,u)),H(i)));if(p=!1,Td)return;o.push({slotBeforeSequence:m,slotFirstInSequence:t,slotLastInSequence:u,slotAfterSequence:n})}f!==c||h===a||T(a)||(m=a.firstInSequence?null:a.prev,n=a.lastInSequence?null:a.next,fc(h,a,h.bindingMap),gc(h,a),o.push({slotBeforeSequence:m,slotFirstInSequence:h,slotLastInSequence:h,slotAfterSequence:n})),f=q}for(v(d)&&Ld.index!==d&&nb(Ld,d),oc(o),f=0;j>f;f++)if(h=k[f]){for(g=f-1;g>=0;g--){var y=k[g+1];jc(k[g]=y.firstInSequence?P(k[g+1],Pd):y.prev,b[g])}for(g=f+1;j>g;g++)i=k[g-1],h=k[g],h?h.firstInSequence&&(h.prev!==i&&G(i,h,E(h)),H(i)):jc(k[g]=i.lastInSequence?Q(i,Pd):i.next,b[g]);break}delete a.description}(),Td||(void 0!==d&&d!==Jd&&lb(d),ac()),ib(),Cb(),void u(g)):(wc(),void u(g)))}function rc(a,b){switch(b.name){case q.noResponse:Nb(o.failure),Db(a,b);break;case q.doesNotExist:a.indexRequested?pc(a.index):(a.keyRequested||a.description)&&tb(a),ib(),wc()}}function sc(a,b,c,d,f,g){g=x(g),f=y(f);var h=a-d,i=c.length;if(b.index>=h&&b.index<h+i)qc(b,c,b.index-h,f,b.index);else if(d===i-1&&a<b.index||v(f)&&f<=b.index)rc(b,new e(q.doesNotExist));else if(b.index<h){var j=Rb(b,0,h-b.index);Vb(h,b,j,he(j,c[0].key,h-b.index,0))}else{var k=h+i-1,j=Rb(b,b.index-k,0);Vb(k,b,j,he(j,c[i-1].key,0,b.index-k))}}function tc(a,b,c){switch(c.name){case q.doesNotExist:a===Kd.index?(pc(0),rc(b,c)):wc();break;default:rc(b,c)}}function uc(){for(var a=0;a<ne.length&&"beginRefresh"!==ne[a].kind;a++);for(var b=a;b<ne.length&&"beginRefresh"!==ne[b].kind;b++);if(b>a&&b+(b-a)<ne.length){for(var c=!0,d=b-a,e=0;d>e;e++)if(ne[a+e].kind!==ne[b+e].kind){c=!1;break}if(c&&g.log){g.log(s.refreshCycleIdentified,"winjs vds","error");for(var e=a;b>e;e++)g.log(""+(e-a)+": "+JSON.stringify(ne[e]),"winjs vds","error")}return c}}function vc(){return++me>h&&uc()?void Nb(o.failure):(ne[++oe%ne.length]={kind:"beginRefresh"},Zd={firstInSequence:!0,lastInSequence:!0,index:-1},$d={firstInSequence:!0,lastInSequence:!0},Zd.next=$d,$d.prev=Zd,Xd=!1,Yd=void 0,_d={},ae={},be={},be[-1]=Zd,void(ce={}))}function wc(){if(!Td){if(Td=!0,Nb(o.waiting),xd)return xd=!1,void Zc();if(!vd){var a=++Cd;Ud=!0,Wd=0,k.schedule(function(){if(Cd===a){Td=!1,vc();for(var b=Kd.next;b!==Md;){var c=b.next;bb(b)||b===Ld||cb(b),b=c}Ec()}},k.Priority.high,null,"WinJS.VirtualizedDataSource.beginRefresh")}}}function xc(){return Vd=Vd||new l,wc(),Vd.promise}function yc(a,b){return delete Fd[b],a!==Cd?!1:(Wd--,!0)}function zc(a,b,c,d,g){var h=Cd;Wd++,d.then(function(b){if(!b.items||!b.items.length)return j.wrapError(new e(q.doesNotExist));var d="itemsFetched id="+c+" count="+b.items.length;f(d),yc(h,c)&&(Sb(b),Kc(a,b.items,b.offset,b.totalCount,"number"==typeof g?g:b.absoluteIndex)),u(d)}).then(null,function(d){yc(h,c)&&Lc(a,b,d)})}function Ac(a,b,c,d){if(he)zc(a.key,!1,b,he(b,a.key,c,d,a.hints));else{var e=10,f=a.index;be[f]&&be[f].firstInSequence?zc(a.key,!1,b,ie(b,f-1,Math.min(c+e,f)-1,d+1+e),f-1):be[f]&&be[f].lastInSequence?zc(a.key,!1,b,ie(b,f+1,Math.min(c+e,f)+1,d-1+e),f+1):zc(a.key,!1,b,ie(b,f,Math.min(c+e,f),d+e),f)}}function Bc(a){je?zc(null,!0,a,je(a,1),0):ie&&zc(null,!0,a,ie(a,0,0,0),0)}function Cc(a){return Fd[_d[a]]}function Dc(a,b){for(var c,d,e,f=3,g=Cd,h=0,i=a;i!==Md;i=i.next){if(!c&&i.key&&!ce[i.key]&&!Cc(i.key)){var j=ae[i.key];(!j||j.firstInSequence||j.lastInSequence)&&(c=i,d=j,e=Qb())}if(c){var k=Cc(i.key);if(ce[i.key]||ae[i.key]||k||(i.key&&(_d[i.key]=e),h++),i.lastInSequence||i.next===Ld||k){if(Ac(c,e,!d||d.firstInSequence?f:0,h-1+f),!b)break;c=null,h=0}}else i.key&&V(i)&&!ce[i.key]&&(ae[i.key]||(e=Qb(),zc(i.key,!1,e,he(e,i.key,1,1,i.hints))))}0!==Wd||Xd||Cd!==g||Bc(Qb())}function Ec(){var a=Cd;do de=!1,ee=!0,Dc(Kd.next,!0),ee=!1;while(0===Wd&&de&&Cd===a&&Ud);0===Wd&&Cd===a&&Uc()}function Fc(a){var b=Cd;if(a){var c=Od[a];c||(c=Kd.next);do fe=!1,ge=!0,Dc(c,!1),ge=!1;while(fe&&Cd===b&&Ud)}ee?de=!0:0===Wd&&Cd===b&&Ec()}function Gc(a){if("object"==typeof a&&a){if(a===Hd)return Zd;if(a===Id)return $d;if(a.key)return ae[a.key];throw new e("WinJS.UI.ListDataSource.InvalidKeyReturned",s.invalidKeyReturned)}throw new e("WinJS.UI.ListDataSource.InvalidItemReturned",s.invalidItemReturned)}function Hc(a,b){for(;void 0===a.index;){if(L(a,b,be),a.firstInSequence)return!0;a=a.prev,b--}return a.index!==b?(wc(),!1):!0}function Ic(a,b){a.key=b.key,ae[a.key]=a,a.item=b}function Jc(){for(var a=$d;!a.firstInSequence;)if(a=a.prev,a===Zd)return null;return a}function Kc(a,b,c,d,e){e=x(e),d=y(d);var f=!1;Xd=!0;var g=e-c,h=b[0];h.key===a&&(f=!0);var i=Gc(h);if(i){if(+g===g&&!Hc(i,g))return}else{if(be[g])return void wc();var j;if(void 0!==e&&(j=be[g-1])){if(!j.lastInSequence)return void wc();i=Q(j,be)}else{var k=+g===g?U(g,be,Zd,$d):Jc(Zd,$d);if(!k)return void wc();i=N(k,g,be)}Ic(i,b[0])}for(var l=b.length,m=1;l>m;m++){h=b[m],h.key===a&&(f=!0);var n=Gc(h);if(n){if(void 0!==i.index&&!Hc(n,i.index+1))return;if(n!==i.next){if(!i.lastInSequence||!n.firstInSequence)return void wc();var o=E(n);if(o!==$d)G(i,n,o);else{var q=D(i);if(q===Zd)return void wc();F(n,q,i)}H(i)}else i.lastInSequence&&H(i)}else{if(!i.lastInSequence)return void wc();n=Q(i,be),Ic(n,h)}i=n}if(f||(ce[a]=!0),!v(d)&&!$d.firstInSequence){var r=$d.prev.index;void 0!==r&&(d=r+1)}if(v(d)||d===p.unknown){if(v(Yd)){if(d!==Yd)return void wc()}else Yd=d;v(Yd)&&!be[Yd]&&L($d,Yd,be)}ge?fe=!0:Fc(a)}function Lc(a,b,c){switch(c.name){case q.noResponse:Nb(o.failure);break;case q.doesNotExist:b?(L($d,0,be),Yd=0,Uc()):(ce[a]=!0,ge?fe=!0:Fc(a))}}function Mc(a){return a===Zd?Kd:a===$d?Ld:Od[a.key]}function Nc(a){return a===Kd?Zd:a===Ld?$d:ae[a.key]}function Oc(a){H(a),a.next.mergedForRefresh=!0}function Pc(a,b){K(b,a.key),b.itemNew=a.item}function Qc(a,b,c){var d=A();Pc(a,d),J(d,b,c,!c);var e=a.index;return+e!==e&&(e=c?d.prev.index+1:b.next.index-1),L(d,e,Pd),d}function Rc(a,b,c){a?(fc(a,b,a.bindingMap),hc(a,b,c.item)):(Pc(c,b),b.indexRequested&&dc(b))}function Sc(a,b,c){return b.key?!1:(a?(c.mergeWithPrev=!b.firstInSequence,c.mergeWithNext=!b.lastInSequence):c.stationary=!0,Rc(a,b,c),!0)}function Tc(a){var b;if(a.indexRequested)b=a.index;else{var c=Nc(a);c&&(b=c.index)}return b}function Uc(){me=0,ne=new Array(100),oe=-1,Ad=!0,_d={};var a,b,c,d,e,f,g,h,i,j,k,l,m,n,o,p,q,r,s=[],t=[];for(o=0,h=Zd;h;h=h.next)h.sequenceNumber=o,h.firstInSequence&&(j=h),h.lastInSequence&&(t[o]={first:j,last:h,matchingItems:0},o++);for(Rd=null,Qd=0,c=Kd.next;c!==Md;)h=ae[c.key],e=c.next,c!==Ld&&(bb(c)?c.key&&!h?sb(c,!1):0===Yd||c.indexRequested&&c.index>=Yd?sb(c,!0):c.item||c.keyRequested?c.itemNew=h.item:c.key&&(c.keyRequested||(delete Od[c.key],delete c.key),c.itemNew=null):cb(c)),c=e;for(c=Kd.next;c!==Ld;)e=c.next,c.indexRequested&&(h=be[c.index],h&&Rc(Mc(h),c,h)),c=e;var u,v,w,x,y,z=0,A=[];for(k=0,c=Kd;c!==Md;c=c.next){if(c.firstInSequence)for(j=c,w=null,a=0;o>a;a++)A[a]=0;if(c.indexRequested&&(w=c),h=Nc(c),h&&A[h.sequenceNumber]++,c.lastInSequence){for(v=0,a=z;o>a;a++)v<A[a]&&(v=A[a],u=a);l={first:j,last:c,sequenceNew:v>0?t[u]:void 0,matchingItems:v},w&&(l.indexRequested=!0,l.stationarySlot=w),s[k]=l,c===Ld&&(x=k,y=l),k++,void 0!==t[u].first.index&&(z=u)}}s[0].sequenceNew!==t[0]&&(I(Kd),s[0].first=Kd.next,s.unshift({first:Kd,last:Kd,sequenceNew:t[0],matchingItems:1}),x++,k++);var B=!Ld.firstInSequence;for(y.sequenceNew!==t[o-1]&&(I(Ld.prev),y.last=Ld.prev,x++,s.splice(x,0,{first:Ld,last:Ld,sequenceNew:t[o-1],matchingItems:1}),k++,y=s[x]),a=0;k>a;a++)p=s[a].sequenceNew,p&&p.matchingItems<s[a].matchingItems&&(p.matchingItems=s[a].matchingItems,p.sequenceOld=s[a]);for(t[o-1].sequenceOld=y,y.stationarySlot=Ld,t[0].sequenceOld=s[0],s[0].stationarySlot=Kd,a=0;x>=a;a++)l=s[a],l.sequenceNew&&(n=l.sequenceNew.sequenceOld)===m&&m.last!==Ld?(Oc(n.last),n.last=l.last,delete s[a]):m=l;for(m=null,a=x;a>=0;a--)l=s[a],l&&(l.sequenceNew&&(n=l.sequenceNew.sequenceOld)===m&&l.last!==Ld?(Oc(l.last),n.first=l.first,delete s[a]):m=l);B&&delete Ld.mergedForRefresh;var C=[];for(a=x+1;k>a;a++)if(l=s[a],l&&(!l.sequenceNew||l.sequenceNew.sequenceOld!==l)){var D=!0,E=null,J=null,K=0;for(h=Nc(l.first),h&&(E=J=h,K=1),c=l.first;c!==l.last;c=c.next){var L=Nc(c.next);if(h&&L&&(h.lastInSequence||h.next!==L)){D=!1;break}h&&!E&&(E=J=h),L&&E&&(J=L,K++),h=L}if(D&&E&&void 0!==E.index){var M;E.firstInSequence||(f=Mc(E.prev),f&&(M=f.index));var N;if(J.lastInSequence||(g=Mc(J.next),g&&(N=g.index)),(!g||g.lastInSequence||g.mergedForRefresh)&&(void 0===M||void 0===N||N-M-1>=K)){for(l.locationJustDetermined=!0,h=E;h.locationJustDetermined=!0,h!==J;h=h.next);var j=Mc(E),O=Mc(J);C.push({slotBeforeSequence:j.firstInSequence?null:j.prev,slotFirstInSequence:j,slotLastInSequence:O,slotAfterSequence:O.lastInSequence?null:O.next})}}}for(a=0;k>a;a++)if(l=s[a],!(!l||l.indexRequested||l.locationJustDetermined||l.sequenceNew&&l.sequenceNew.sequenceOld===l)){l.sequenceNew=null,c=l.first;var P;do{if(P=c===l.last,e=c.next,c!==Kd&&c!==Ld&&c!==Md&&!c.item&&!c.keyRequested)if(sb(c,!0),l.first===c){if(l.last===c){delete s[a];break}l.first=c.next}else l.last===c&&(l.last=c.prev);c=e}while(!P)}for(a=0;o>a;a++){for(p=t[a],h=p.first;!Mc(h)&&!h.lastInSequence;h=h.next);if(h.lastInSequence&&!Mc(h))p.firstInner=p.lastInner=null;else{for(p.firstInner=h,h=p.last;!Mc(h);h=h.prev);p.lastInner=h}}for(a=0;o>a;a++)if(p=t[a],p&&p.firstInner&&(l=p.sequenceOld)){var Q=0;for(c=l.first;!0&&(h=Nc(c),h&&h.sequenceNumber===p.firstInner.sequenceNumber&&(h.ordinal=Q),!c.lastInSequence);c=c.next,Q++);var R=[];for(h=p.firstInner;!0;h=h.next){if(Q=h.ordinal,void 0!==Q){for(var S=0,T=R.length-1;T>=S;){var U=Math.floor(.5*(S+T));R[U].ordinal<Q?S=U+1:T=U-1}R[S]=h,S>0&&(h.predecessor=R[S-1])}if(h===p.lastInner)break}var W=[],X=R.length;for(h=R[X-1],b=X;b--;)h.stationary=!0,W[b]=h,h=h.predecessor;l.stationarySlot=Mc(W[0]),h=W[0],c=Mc(h),d=c.prev;for(var Y=c.firstInSequence;!h.firstInSequence;)if(h=h.prev,i=Mc(h),!i||h.locationJustDetermined)for(;!Y&&d!==Kd&&(c=d,d=c.prev,Y=c.firstInSequence,!Sc(i,c,h)););for(b=0;X-1>b;b++){h=W[b],c=Mc(h);var i,Z=W[b+1],_=null,ab=Mc(Z);for(e=c.next,h=h.next;h!==Z&&!_&&c!==ab;h=h.next)if(i=Mc(h),!i||h.locationJustDetermined)for(;e!==ab;){if(e.mergedForRefresh){_=h.prev;break}if(c=e,e=c.next,Sc(i,c,h))break}if(_)for(d=ab.prev,h=Z.prev;h!==_&&ab!==c;h=h.prev)if(i=Mc(h),!i||h.locationJustDetermined)for(;d!==c&&(ab=d,d=ab.prev,!Sc(i,ab,h)););for(;e!==ab;)c=e,e=c.next,c!==Kd&&V(c)&&!c.keyRequested&&sb(c)}for(h=W[X-1],c=Mc(h),e=c.next,Y=c.lastInSequence;!h.lastInSequence;)if(h=h.next,i=Mc(h),!i||h.locationJustDetermined)for(;!Y&&e!==Ld&&(c=e,e=c.next,Y=c.lastInSequence,!Sc(i,c,h)););}for(a=0;o>a;a++)if(p=t[a],p.firstInner)for(d=null,h=p.firstInner;!0;h=h.next){if(c=Mc(h)){if(!h.stationary){var db,eb=!1,fb=!1;if(d)db=d.next,eb=!0;else{var gb;for(gb=p.firstInner;!gb.stationary&&gb!==p.lastInner;gb=gb.next);if(gb.stationary)db=Mc(gb),fb=!0;else if(q=h.index,0===q)db=Kd.next,eb=!0;else if(void 0===q)db=Md;else{db=Kd.next;for(var hb=null;;){if(db.firstInSequence&&(hb=db),q<db.index&&hb||db===Ld)break;db=db.next}!db.firstInSequence&&hb&&(db=hb)}}c.mergedForRefresh&&(delete c.mergedForRefresh,c.lastInSequence||(c.next.mergedForRefresh=!0)),eb=eb||h.mergeWithPrev,fb=fb||h.mergeWithNext;var jb=h.locationJustDetermined;rb(c,db,eb,fb,jb),jb&&fb&&(db.mergedForRefresh=!0)}d=c}if(h===p.lastInner)break}for(a=0;o>a;a++)if(p=t[a],p.firstInner)for(d=null,h=p.firstInner;!0;h=h.next){if(c=Mc(h),!c){var kb;if(d)kb=d.next;else{var mb;for(mb=p.firstInner;!Mc(mb);mb=mb.next);kb=Mc(mb)}c=Qc(h,kb,!!d);var L=Nc(kb);kb.mergedForRefresh||L&&L.locationJustDetermined||($(c),pb(c))}if(d=c,h===p.lastInner)break}Pd=[];var ob=-1;for(c=Kd,r=0;c!==Md;r++){var e=c.next;if(c.firstInSequence&&(j=c,r=0),void 0===ob){var qb=Tc(c);void 0!==qb&&(ob=qb-r)}if(void 0!==ob&&!c.lastInSequence){var tb=Tc(c.next);if(void 0!==tb&&tb!==ob+r+1){I(c);for(var ub=!0,vb=c.next,wb=!1;!wb&&vb!==Ld;){var xb=vb.next;wb=vb.lastInSequence,rb(vb,xb,!ub,!1),ub=!1,vb=xb}}}if(c.lastInSequence){q=ob;for(var yb=j;yb!==e;){var zb=yb.next;if(q>=Yd&&yb!==Ld)sb(yb,!0);else{var Ab=Pd[q];q!==yb.index?(delete Pd[q],nb(yb,q)):+q===q&&Pd[q]!==yb&&(Pd[q]=yb),yb.itemNew&&dc(yb),Ab&&(yb.key?(fc(yb,Ab,yb.bindingMap),gc(yb,Ab),+q===q&&(Pd[q]=yb)):(fc(Ab,yb,Ab.bindingMap),gc(Ab,yb),+q===q&&(Pd[q]=Ab))),+q===q&&q++}yb=zb}ob=void 0}c=e}var Bb,Db=-2;for(c=Kd,r=0;c!==Md;r++){var e=c.next;if(c.firstInSequence&&(j=c,r=0),delete c.mergedForRefresh,c.lastInSequence)if(void 0===j.index){f=j.prev;var Eb;f&&(Eb=Nc(f))&&!Eb.lastInSequence&&(h=Nc(c))&&h.prev===Eb?(G(f,j,c),H(f)):c===Ld||Bb||F(Md,j,c)}else{if(Db<c.index&&!Bb)Db=c.index;else{for(g=Kd.next;g.index<c.index;g=g.next);for(var vb=j;vb!==e;){var xb=vb.next;h=Nc(vb),rb(vb,g,g.prev.index===vb.index-1,g.index===vb.index+1,h&&h.locationJustDetermined),vb=xb}}f=j.prev,f&&f.index===j.index-1&&H(f)}c===Ld&&(Bb=!0),c=e}Ad=!1,oc(C),void 0!==Yd&&Yd!==Jd&&lb(Yd),ib();var Fb=[];for(a=0;o>a;a++){p=t[a];var Gb=[];c=null,r=0;var Hb;for(h=p.first;!0&&(h===Zd?Gb.push(Hd):h===$d?Gb.push(Id):(Gb.push(h.item),c||(c=Mc(h),Hb=r)),!h.lastInSequence);h=h.next,r++);c&&Fb.push({slot:c,results:Gb,offset:Hb})}for(vc(),Ud=!1,Cb(),a=0;a<Fb.length;a++){var Ib=Fb[a];qc(Ib.slot,Ib.results,Ib.offset,Jd,Ib.slot.index)}if(Vd){var Jb=Vd;Vd=null,Jb.complete()}ac()}function Vc(a,b,c,d,e,f,g){var h=ud.prev,i={prev:h,next:ud,applyEdit:a,editType:b,complete:c,error:d,keyUpdate:e};h.next=i,ud.prev=i,vd=!0,(Td||Ud)&&(Cd++,Ud=!1,Td=!0),ud.next===i&&Zc(),i.failed||(f(),i.undo=g),sd||$c()}function Wc(){td=!1;var a=ud.next.next; ud.next=a,a.prev=ud}function Xc(){for(;ud.prev!==ud;){var a=ud.prev;a.error&&a.error(new e(r.canceled)),a.undo&&!Td&&a.undo(),ud.prev=a.prev}ud.next=ud,sd=!1,$c()}function Yc(b){function c(){xd||(f?wd=!0:Zc())}function d(a){if(a){var d;if(g&&g.key!==a.key){var e=a.key;if(b.undo){if(d=g.slot){var h=d.key;h&&delete Od[h],K(d,e),d.itemNew=a,d.item?(qb(d),ib()):Bb(d)}}else g.key=e}else b.editType===re.change&&(d.itemNew=a,f||cc(d))}Wc(),b.complete&&b.complete(a),c()}function e(a){switch(a.Name){case r.noResponse:return Nb(o.failure),xd=!0,void(td=!1);case r.notPermitted:break;case r.noLongerMeaningful:wc()}b.failed=!0,Wc(),Xc(),b.error&&b.error(a),c()}if(!td){var f=!0,g=b.keyUpdate;a.beginEdits&&!rd&&(rd=!0,a.beginEdits()),td=!0,b.applyEdit().then(d,e),f=!1}}function Zc(){for(;ud.next!==ud;)if(wd=!1,Yc(ud.next),!wd)return;_c()}function $c(){yb(),ib(),Cb(),ud.next===ud&&_c()}function _c(){vd=!1,a.endEdits&&rd&&!sd&&(rd=!1,a.endEdits()),Td?(Td=!1,wc()):ac()}function ad(a){return Ib(a),Od[a]||Jb(a)}function bd(a,b,c,d,e){var f=A();return J(f,c,d,e),a&&K(f,a),f.itemNew=b,wb(f,1),sd||yd||(f.firstInSequence||"number"!=typeof f.prev.index?f.lastInSequence||"number"!=typeof f.next.index||L(f,f.next.index-1,Pd):L(f,f.prev.index+1,Pd)),$(f),pb(f),f}function cd(a,b,c,d,e){var f={key:a};return new j(function(a,g){Vc(e,re.insert,a,g,f,function(){if(c){var a={key:f.key,data:b};f.slot=bd(f.key,a,c,d,!d)}},function(){var a=f.slot;a&&(wb(a,-1),sb(a,!1))})})}function dd(a,b,c,d){return new j(function(e,f){var g,h,i,j;Vc(d,re.move,e,f,null,function(){h=a.next,i=a.firstInSequence,j=a.lastInSequence;var d=a.prev;g=!("number"==typeof a.index||!i&&d.item||!j&&h.item),wb(a,-1),rb(a,b,c,!c),wb(a,1),g&&(I(d),i||mc(d,a),j||nc(h,a))},function(){g?wc():(wb(a,-1),rb(a,h,!i,!j),wb(a,1))})})}function ed(){function a(){yd||(yb(),ib(),Cb())}this.invalidateAll=function(){return 0===Jd?(this.reload(),j.wrap()):xc()},this.reload=function(){pd&&pd.cancel(),Vd&&Vd.cancel();for(var a=Kd.next;a!==Md;a=a.next){var b=a.fetchListeners;for(var c in b)b[c].promise.cancel();var d=a.directFetchListeners;for(var c in d)d[c].promise.cancel()}fd(),fb(function(a){a.notificationHandler&&a.notificationHandler.reload()})},this.beginNotifications=function(){yd=!0},this.inserted=function(b,c,d,e){if(vd)wc();else{var f=b.key,g=Od[c],h=Od[d],i="string"==typeof c,j="string"==typeof d;if(i?h&&!h.firstInSequence&&(g=h.prev):j&&g&&!g.lastInSequence&&(h=g.next),(i||j)&&!g&&!h&&Kd.next===Ld)return void wc();if(Od[f])return void wc();if(g&&h&&(g.next!==h||g.lastInSequence||h.firstInSequence))return void wc();if(g&&(g.keyRequested||g.indexRequested)||h&&(h.keyRequested||h.indexRequested))return void wc();if(g||h)bd(f,b,h?h:g.next,!!g,!!h);else if(Kd.next===Ld)bd(f,b,Kd.next,!0,!0);else{if(void 0===e)return void wc();xb(e,1)}a()}},this.changed=function(b){if(vd)wc();else{var c=b.key,d=Od[c];d&&(d.keyRequested?wc():(d.itemNew=b,d.item&&(qb(d),a())))}},this.moved=function(b,c,d,e,f){if(vd)wc();else{var g=b.key,h=Od[g],i=Od[c],j=Od[d];h&&h.keyRequested||i&&i.keyRequested||j&&j.keyRequested?wc():h?i&&j&&(i.next!==j||i.lastInSequence||j.firstInSequence)?wc():i||j?(wb(h,-1),rb(h,j?j:i.next,!!i,!!j),wb(h,1),a()):(wb(h,-1),sb(h,!1),void 0!==e&&(f>e&&f--,xb(f,1)),a()):i||j?(void 0!==e&&(xb(e,-1),f>e&&f--),this.inserted(b,c,d,f)):void 0!==e&&(xb(e,-1),f>e&&f--,xb(f,1),a())}},this.removed=function(b,c){if(vd)wc();else{var d;d="string"==typeof b?Od[b]:Pd[c],d?d.keyRequested?wc():(wb(d,-1),sb(d,!1),a()):void 0!==c&&(xb(c,-1),a())}},this.endNotifications=function(){yd=!1,a()}}function fd(){Nb(o.ready),pd=null,rd=!1,sd=!1,td=!1,ud={},ud.next=ud,ud.prev=ud,vd=!1,xd=!1,zd=0,Ad=!1,Bd=0,Fd={},Gd=[],Jd=p.unknown,Kd={firstInSequence:!0,lastInSequence:!0,index:-1},Ld={firstInSequence:!0,lastInSequence:!0},Md={firstInSequence:!0,lastInSequence:!0},Kd.next=Ld,Ld.prev=Kd,Ld.next=Md,Md.prev=Ld,Nd={},Od={},Pd={},Pd[-1]=Kd,Qd=0,Rd=null,Sd=!1,Td=!1,Ud=!1,Vd=null}var gd,hd,id,jd,kd,ld,md,nd,od,pd,qd,rd,sd,td,ud,vd,wd,xd,yd,zd,Ad,Bd,Cd,Dd,Ed,Fd,Gd,Hd,Id,Jd,Kd,Ld,Md,Nd,Od,Pd,Qd,Rd,Sd,Td,Ud,Vd,Wd,Xd,Yd,Zd,$d,_d,ae,be,ce,de,ee,fe,ge,he,ie,je,ke,le,me=0,ne=new Array(100),oe=-1;a.itemsFromKey&&(he=function(b,c,d,e,g){var h="fetchItemsFromKey id="+b+" key="+c+" countBefore="+d+" countAfter="+e;f(h),ne[++oe%ne.length]={kind:"itemsFromKey",key:c,countBefore:d,countAfter:e};var i=a.itemsFromKey(c,d,e,g);return u(h),i}),a.itemsFromIndex&&(ie=function(b,c,d,e){var g="fetchItemsFromIndex id="+b+" index="+c+" countBefore="+d+" countAfter="+e;f(g),ne[++oe%ne.length]={kind:"itemsFromIndex",index:c,countBefore:d,countAfter:e};var h=a.itemsFromIndex(c,d,e);return u(g),h}),a.itemsFromStart&&(je=function(b,c){var d="fetchItemsFromStart id="+b+" count="+c;f(d),ne[++oe%ne.length]={kind:"itemsFromStart",count:c};var e=a.itemsFromStart(c);return u(d),e}),a.itemsFromEnd&&(ke=function(b,c){var d="fetchItemsFromEnd id="+b+" count="+c;f(d),ne[++oe%ne.length]={kind:"itemsFromEnd",count:c};var e=a.itemsFromEnd(c);return u(d),e}),a.itemsFromDescription&&(le=function(b,c,d,e){var g="fetchItemsFromDescription id="+b+" desc="+c+" countBefore="+d+" countAfter="+e;f(g),ne[++oe%ne.length]={kind:"itemsFromDescription",description:c,countBefore:d,countAfter:e};var h=a.itemsFromDescription(c,d,e);return u(g),h});var pe=++n,qe=this,re={insert:"insert",change:"change",move:"move",remove:"remove"};if(!a)throw new e("WinJS.UI.ListDataSource.ListDataAdapterIsInvalid",s.listDataAdapterIsInvalid);hd=a.compareByIdentity?0:200,c&&"number"==typeof c.cacheSize&&(hd=c.cacheSize),a.setNotificationHandler&&(gd=new ed,a.setNotificationHandler(gd)),id=o.ready,kd=!1,ld={},md=0,nd=1,od=0,Cd=0,Dd=!1,Ed=1,Hd={},Id={},fd(),this.createListBinding=function(a){function b(a){a&&a.cursorCount++}function c(a){a&&0===--a.cursorCount&&eb(a)}function d(a){b(a),c(m),m=a}function e(a,b){a===m&&(b||(b=!m||m.lastInSequence||m.next===Ld?null:m.next),d(b))}function f(a){var b=a.bindingMap,c=b[l].handle;delete a.bindingMap[l];var d=!0,e=!0;for(var f in b)if(d=!1,c&&b[f].handle===c){e=!1;break}c&&e&&delete Nd[c],d&&(a.bindingMap=null,eb(a))}function g(a,b){a.bindingMap||(a.bindingMap={});var c=a.bindingMap[l];if(c?c.count++:a.bindingMap[l]={bindingRecord:ld[l],count:1},a.fetchListeners){var d=a.fetchListeners[b];d&&(d.retained=!0)}}function h(a){var b=Nd[a];if(b){var c=b.bindingMap[l];if(0===--c.count){var d=b.fetchListeners;for(var e in d){var g=d[e];g.listBindingID===l&&(g.retained=!1)}f(b)}}}function i(b){var c=jb(b,l),d=(od++).toString(),e=zb(b,"fetchListeners",d,l,function(a,b){a(kb(b,c))});return X(e,b,c),a&&(e.retain=function(){return o._retainItem(b,d),e},e.release=function(){o._releaseItem(c)}),e}function k(b){var c;return!n&&b?c=i(b):(n?(c=new j(function(){}),c.cancel()):c=j.wrap(null),W(c,null),a&&(c.retain=function(){return c},c.release=function(){})),d(b),c}var l=(md++).toString(),m=null,n=!1;ld[l]={notificationHandler:a,notificationsSent:!1,adjustCurrentSlot:e,itemPromiseFromKnownSlot:i};var o={_retainItem:function(a,b){g(a,b)},_releaseItem:function(a){h(a)},jumpToItem:function(a){return k(a?Nd[a.handle]:null)},current:function(){return k(m)},previous:function(){return k(m?Fb(m):null)},next:function(){return k(m?Gb(m):null)},releaseItem:function(a){this._releaseItem(a.handle)},release:function(){n=!0,c(m),m=null;for(var a=Kd.next;a!==Md;){var b=a.next,d=a.fetchListeners;for(var e in d){var g=d[e];g.listBindingID===l&&(g.promise.cancel(),delete d[e])}a.bindingMap&&a.bindingMap[l]&&f(a),a=b}delete ld[l]}};return(je||ie)&&(o.first=function(){return k(Gb(Kd))}),ke&&(o.last=function(){return k(Fb(Ld))}),he&&(o.fromKey=function(a,b){return k(Kb(a,b))}),(ie||je&&he)&&(o.fromIndex=function(a){return k(Lb(a))}),le&&(o.fromDescription=function(a){return k(Mb(a))}),o},this.invalidateAll=function(){return xc()};var se=function(a,b){var c=new l;a.then(function(a){c.complete(a)},function(a){c.error(a)});var d=c.promise.then(null,function(c){return"WinJS.UI.VirtualizedDataSource.resetCount"===c.name?(pd=null,a=b.getCount()):j.wrapError(c)}),f=0,g={get:function(){return f++,new j(function(a,b){d.then(a,b)},function(){0===--f&&(c.promise.cancel(),a.cancel(),g===pd&&(pd=null))})},reset:function(){c.error(new e("WinJS.UI.VirtualizedDataSource.resetCount"))},cancel:function(){c.promise.cancel(),a.cancel(),g===pd&&(pd=null)}};return g};this.getCount=function(){if(a.getCount){var b=this;return j.wrap().then(function(){if(sd||vd)return Jd;var c;if(!pd){var d;c=a.getCount();var e;c.then(function(){pd===d&&(pd=null),e=!0},function(){pd===d&&(pd=null),e=!0}),zd=0,e||(d=pd=se(c,b))}return pd?pd.get():c}).then(function(a){if(!w(a)&&void 0!==a)throw new e("WinJS.UI.ListDataSource.InvalidRequestedCountReturned",s.invalidRequestedCountReturned);return a!==Jd&&(Jd===p.unknown?Jd=a:(lb(a),ib())),0===a&&(Kd.next!==Ld||Ld.next!==Md?wc():Kd.lastInSequence&&(H(Kd),Ld.index=0)),a}).then(null,function(a){return a.name===m.CountError.noResponse?(Nb(o.failure),Jd):j.wrapError(a)})}return j.wrap(Jd)},he&&(this.itemFromKey=function(a,b){return Hb(Kb(a,b))}),(ie||je&&he)&&(this.itemFromIndex=function(a){return Hb(Lb(a))}),le&&(this.itemFromDescription=function(a){return Hb(Mb(a))}),this.beginEdits=function(){sd=!0},a.insertAtStart&&(this.insertAtStart=function(b,c){return cd(b,c,Kd.lastInSequence?null:Kd.next,!0,function(){return a.insertAtStart(b,c)})}),a.insertBefore&&(this.insertBefore=function(b,c,d){var e=ad(d);return cd(b,c,e,!1,function(){return a.insertBefore(b,c,d,ub(e))})}),a.insertAfter&&(this.insertAfter=function(b,c,d){var e=ad(d);return cd(b,c,e?e.next:null,!0,function(){return a.insertAfter(b,c,d,ub(e))})}),a.insertAtEnd&&(this.insertAtEnd=function(b,c){return cd(b,c,Ld.firstInSequence?null:Ld,!1,function(){return a.insertAtEnd(b,c)})}),a.change&&(this.change=function(b,c){var d=ad(b);return new j(function(e,f){var g;Vc(function(){return a.change(b,c,ub(d))},re.change,e,f,null,function(){g=d.item,d.itemNew={key:b,data:c},g?qb(d):Bb(d)},function(){g?(d.itemNew=g,qb(d)):wc()})})}),a.moveToStart&&(this.moveToStart=function(b){var c=ad(b);return dd(c,Kd.next,!0,function(){return a.moveToStart(b,ub(c))})}),a.moveBefore&&(this.moveBefore=function(b,c){var d=ad(b),e=ad(c);return dd(d,e,!1,function(){return a.moveBefore(b,c,ub(d),ub(e))})}),a.moveAfter&&(this.moveAfter=function(b,c){var d=ad(b),e=ad(c);return dd(d,e.next,!0,function(){return a.moveAfter(b,c,ub(d),ub(e))})}),a.moveToEnd&&(this.moveToEnd=function(b){var c=ad(b);return dd(c,Ld,!1,function(){return a.moveToEnd(b,ub(c))})}),a.remove&&(this.remove=function(b){Ib(b);var c=Od[b];return new j(function(d,e){var f,g,h;Vc(function(){return a.remove(b,ub(c))},re.remove,d,e,null,function(){c&&(f=c.next,g=c.firstInSequence,h=c.lastInSequence,wb(c,-1),sb(c,!1))},function(){c&&(R(c,f,!g,!h),wb(c,1),pb(c))})})}),this.endEdits=function(){sd=!1,$c()}}var h=100,n=1,o=m.DataSourceStatus,p=m.CountResult,q=m.FetchError,r=m.EditError,s={get listDataAdapterIsInvalid(){return"Invalid argument: listDataAdapter must be an object or an array."},get indexIsInvalid(){return"Invalid argument: index must be a non-negative integer."},get keyIsInvalid(){return"Invalid argument: key must be a string."},get invalidItemReturned(){return"Error: data adapter returned item that is not an object."},get invalidKeyReturned(){return"Error: data adapter returned item with undefined or null key."},get invalidIndexReturned(){return"Error: data adapter should return undefined, null or a non-negative integer for the index."},get invalidCountReturned(){return"Error: data adapter should return undefined, null, CountResult.unknown, or a non-negative integer for the count."},get invalidRequestedCountReturned(){return"Error: data adapter should return CountResult.unknown, CountResult.failure, or a non-negative integer for the count."},get refreshCycleIdentified(){return"refresh cycle found, likely data inconsistency"}},t="statuschanged",u=c.Class.define(function(){},{_baseDataSourceConstructor:a,_isVirtualizedDataSource:!0},{supportedForProcessing:!1});return c.Class.mix(u,f.eventMixin),u})})}),d("WinJS/VirtualizedDataSource/_GroupDataSource",["exports","../Core/_Base","../Core/_ErrorFromName","../Promise","../Scheduler","../Utilities/_UI","./_VirtualizedDataSourceImpl"],function(a,b,c,d,e,f,g){"use strict";b.Namespace._moduleDefine(a,"WinJS.UI",{_GroupDataSource:b.Namespace._lazy(function(){function a(){return new c(f.FetchError.doesNotExist)}function h(a){return a&&a.firstReached&&a.lastReached}var i=101,j=b.Class.define(function(a){this._groupDataAdapter=a},{beginNotifications:function(){},inserted:function(a,b,c){this._groupDataAdapter._inserted(a,b,c)},changed:function(a,b){this._groupDataAdapter._changed(a,b)},moved:function(a,b,c){this._groupDataAdapter._moved(a,b,c)},removed:function(a,b){this._groupDataAdapter._removed(a,b)},countChanged:function(a,b){0===a&&0!==b&&this._groupDataAdapter.invalidateGroups()},indexChanged:function(a,b,c){this._groupDataAdapter._indexChanged(a,b,c)},endNotifications:function(){this._groupDataAdapter._endNotifications()},reload:function(){this._groupDataAdapter._reload()}},{supportedForProcessing:!1}),k=b.Class.define(function(a,b,c,d){this._listBinding=a.createListBinding(new j(this)),this._groupKey=b,this._groupData=c,this._initializeState(),this._batchSize=i,this._count=null,d&&("number"==typeof d.groupCountEstimate&&(this._count=d.groupCountEstimate<0?null:Math.max(d.groupCountEstimate,1)),"number"==typeof d.batchSize&&(this._batchSize=d.batchSize+1)),this._listBinding.last&&(this.itemsFromEnd=function(a){var b=this;return this._fetchItems(function(){return b._lastGroup},function(a){if(a)return!1;var c=b._count;return+c!==c?!0:c>0?!0:void 0},function(){b._fetchBatch(b._listBinding.last(),b._batchSize-1,0)},a-1,0)})},{setNotificationHandler:function(a){this._listDataNotificationHandler=a},compareByIdentity:!0,itemsFromKey:function(a,b,c,d){var e=this;return this._fetchItems(function(){return e._keyMap[a]},function(){var a=e._lastGroup;return a?+a.index!==a.index?!0:void 0:!0},function(){d=d||{};var a="string"==typeof d.groupMemberKey&&e._listBinding.fromKey?e._listBinding.fromKey(d.groupMemberKey):"number"==typeof d.groupMemberIndex&&e._listBinding.fromIndex?e._listBinding.fromIndex(d.groupMemberIndex):void 0!==d.groupMemberDescription&&e._listBinding.fromDescription?e._listBinding.fromDescription(d.groupMemberDescription):e._listBinding.first(),b=Math.floor(.5*(e._batchSize-1));e._fetchBatch(a,b,e._batchSize-1-b)},b,c)},itemsFromIndex:function(a,b,c){var d=this;return this._fetchItems(function(){return d._indexMap[a]},function(){var b=d._lastGroup;return b?+b.index!==b.index?!0:a<=b.index?!0:void 0:!0},function(){d._fetchNextIndex()},b,c)},getCount:function(){if(this._lastGroup&&"number"==typeof this._lastGroup.index)return d.wrap(this._count);var a=this,b=new d(function(b){var c={initialBatch:function(){a._fetchNextIndex()},getGroup:function(){return null},countBefore:0,countAfter:0,complete:function(c){c&&(a._count=0);var d=a._count;return"number"==typeof d?(b(d),!0):!1}};a._fetchQueue.push(c),a._itemBatch||a._continueFetch(c)});return"number"==typeof this._count?d.wrap(this._count):b},invalidateGroups:function(){this._beginRefresh(),this._initializeState()},_initializeState:function(){this._count=null,this._indexMax=null,this._keyMap={},this._indexMap={},this._lastGroup=null,this._handleMap={},this._fetchQueue=[],this._itemBatch=null,this._itemsToFetch=0,this._indicesChanged=!1},_releaseItem:function(a){delete this._handleMap[a.handle],this._listBinding.releaseItem(a)},_processBatch:function(){for(var a=null,b=null,c=null,d=0,f=!0,g=0;g<this._batchSize;g++){var h=this._itemBatch[g],i=h?this._groupKey(h):null;if(h&&(f=!1),b&&null!==i&&i===b.key)d++,b.lastItem===a?(b.lastItem.handle!==b.firstItem.handle&&this._releaseItem(b.lastItem),b.lastItem=h,this._handleMap[h.handle]=b,b.size++):b.firstItem===h&&(b.firstItem.handle!==b.lastItem.handle&&this._releaseItem(b.firstItem),b.firstItem=c,this._handleMap[c.handle]=b,b.size+=d);else{var j=null;if(b&&(b.lastReached=!0,"number"==typeof b.index&&(j=b.index+1)),h){var k=this._keyMap[i];if(k||(k={key:i,data:this._groupData(h),firstItem:h,lastItem:h,size:1},this._keyMap[k.key]=k,this._handleMap[h.handle]=k),g>0&&(k.firstReached=!0,b||(j=0)),"number"!=typeof k.index&&"number"==typeof j){for(var l=k;l;l=this._nextGroup(l))l.index=j,this._indexMap[j]=l,j++;this._indexMax=j,"number"==typeof this._count&&!this._lastGroup&&this._count<=this._indexMax&&(this._count=this._indexMax+1)}c=h,d=0,b=k}else b&&(this._lastGroup=b,"number"==typeof b.index&&(this._count=b.index+1),this._listDataNotificationHandler.invalidateAll(),b=null)}a=h}var m;for(m=this._fetchQueue[0];m&&m.complete(f);m=this._fetchQueue[0])this._fetchQueue.splice(0,1);if(m){var n=this;e.schedule(function(){n._continueFetch(m)},e.Priority.normal,null,"WinJS.UI._GroupDataSource._continueFetch")}else this._itemBatch=null},_processPromise:function(a,b){a.retain(),this._itemBatch[b]=a;var c=this;a.then(function(a){c._itemBatch[b]=a,0===--c._itemsToFetch&&c._processBatch()})},_fetchBatch:function(a,b){this._itemBatch=new Array(this._batchSize),this._itemsToFetch=this._batchSize,this._processPromise(a,b);var c;for(this._listBinding.jumpToItem(a),c=b-1;c>=0;c--)this._processPromise(this._listBinding.previous(),c);for(this._listBinding.jumpToItem(a),c=b+1;c<this._batchSize;c++)this._processPromise(this._listBinding.next(),c)},_fetchAdjacent:function(a,b){this._fetchBatch(this._listBinding.fromKey?this._listBinding.fromKey(a.key):this._listBinding.fromIndex(a.index),b?0:this._batchSize-1,b?this._batchSize-1:0)},_fetchNextIndex:function(){var a=this._indexMap[this._indexMax-1];a?this._fetchAdjacent(a.lastItem,!0):this._fetchBatch(this._listBinding.first(),1,this._batchSize-2)},_continueFetch:function(a){if(a.initialBatch)a.initialBatch(),a.initialBatch=null;else{var b=a.getGroup();if(b){var c,d;b.firstReached?b.lastReached?a.countBefore>0&&0!==b.index&&!h(c=this._previousGroup(b))?this._fetchAdjacent(c&&c.lastReached?c.firstItem:b.firstItem,!1):(d=this._nextGroup(b),this._fetchAdjacent(d&&d.firstReached?d.lastItem:b.lastItem,!0)):this._fetchAdjacent(b.lastItem,!0):this._fetchAdjacent(b.firstItem,!1)}else this._fetchNextIndex()}},_fetchComplete:function(a,b,c,d,e){if(h(a)){var g=this._previousGroup(a);if(d||h(g)||0===a.index||0===b){var i=this._nextGroup(a);if(d||h(i)||this._lastGroup===a||0===c){for(var j=0,k=a;b>j&&(g=this._previousGroup(k),h(g));)k=g,j++;for(var l=0,m=a;c>l&&(i=this._nextGroup(m),h(i));)m=i,l++;for(var n=j+1+l,o=new Array(n),p=0;n>p;p++){var q={key:k.key,data:k.data,firstItemKey:k.firstItem.key,groupSize:k.size},r=k.firstItem.index;"number"==typeof r&&(q.firstItemIndexHint=r),o[p]=q,k=this._nextGroup(k)}var s={items:o,offset:j};return s.totalCount="number"==typeof this._count?this._count:f.CountResult.unknown,"number"==typeof a.index&&(s.absoluteIndex=a.index),m===this._lastGroup&&(s.atEnd=!0),e(s),!0}}}return!1},_fetchItems:function(b,c,e,f,g){var h=this;return new d(function(d,i){function j(e){var j=b();return j?h._fetchComplete(j,f,g,l,d,i):l&&!c(e)?(i(a()),!0):m>2?(i(a()),!0):(e?m++:m=0,!1)}var k=b(),l=!k,m=0;if(!j()){var n={initialBatch:l?e:null,getGroup:b,countBefore:f,countAfter:g,complete:j};h._fetchQueue.push(n),h._itemBatch||h._continueFetch(n)}})},_previousGroup:function(a){return a&&a.firstReached?(this._listBinding.jumpToItem(a.firstItem),this._handleMap[this._listBinding.previous().handle]):null},_nextGroup:function(a){return a&&a.lastReached?(this._listBinding.jumpToItem(a.lastItem),this._handleMap[this._listBinding.next().handle]):null},_invalidateIndices:function(a){this._count=null,this._lastGroup=null,"number"==typeof a.index&&(this._indexMax=a.index>0?a.index:null);for(var b=a;b&&"number"==typeof b.index;b=this._nextGroup(b))delete this._indexMap[b.index],b.index=null},_releaseGroup:function(a){this._invalidateIndices(a),delete this._keyMap[a.key],this._lastGroup===a&&(this._lastGroup=null),a.firstItem!==a.lastItem&&this._releaseItem(a.firstItem),this._releaseItem(a.lastItem)},_beginRefresh:function(){if(this._fetchQueue=[],this._itemBatch){for(var a=0;a<this._batchSize;a++){var b=this._itemBatch[a];b&&(b.cancel&&b.cancel(),this._listBinding.releaseItem(b))}this._itemBatch=null}this._itemsToFetch=0,this._listDataNotificationHandler.invalidateAll()},_processInsertion:function(a,b,c){var d=this._handleMap[b],e=this._handleMap[c],f=null;d&&(d.lastReached&&b===d.lastItem.handle&&(f=this._groupKey(a))!==d.key?this._lastGroup===d&&(this._lastGroup=null,this._count=null):this._releaseGroup(d),this._beginRefresh()),e&&e!==d&&(this._invalidateIndices(e),e.firstReached&&c===e.firstItem.handle&&(null!==f?f:this._groupKey(a))!==e.key||this._releaseGroup(e),this._beginRefresh())},_processRemoval:function(a){var b=this._handleMap[a];if(!b||a!==b.firstItem.handle&&a!==b.lastItem.handle){if(this._itemBatch)for(var c=0;c<this._batchSize;c++){var d=this._itemBatch[c];if(d&&d.handle===a){this._beginRefresh();break}}}else this._releaseGroup(b),this._beginRefresh()},_inserted:function(a,b,c){var d=this;a.then(function(a){d._processInsertion(a,b,c)})},_changed:function(a,b){var c=this._handleMap[a.handle];if(c&&a.handle===c.firstItem.handle&&(this._releaseGroup(c),this._beginRefresh()),this._groupKey(a)!==this._groupKey(b)){this._listBinding.jumpToItem(a);var d=this._listBinding.previous().handle;this._listBinding.jumpToItem(a);var e=this._listBinding.next().handle;this._processRemoval(a.handle),this._processInsertion(a,d,e)}},_moved:function(a,b,c){this._processRemoval(a.handle);var d=this;a.then(function(a){d._processInsertion(a,b,c)})},_removed:function(a,b){b||this._processRemoval(a)},_indexChanged:function(a,b,c){"number"==typeof c&&(this._indicesChanged=!0)},_endNotifications:function(){if(this._indicesChanged){this._indicesChanged=!1;for(var a in this._keyMap){var b=this._keyMap[a];if(b.firstReached&&b.lastReached){var c=b.lastItem.index+1-b.firstItem.index;isNaN(c)||(b.size=c)}}this._beginRefresh()}},_reload:function(){this._initializeState(),this._listDataNotificationHandler.reload()}},{supportedForProcessing:!1});return b.Class.derive(g.VirtualizedDataSource,function(a,b,c,d){var e=new k(a,b,c,d);this._baseDataSourceConstructor(e),this.extensions={invalidateGroups:function(){e.invalidateGroups()}}},{},{supportedForProcessing:!1})})})}),d("WinJS/VirtualizedDataSource/_GroupedItemDataSource",["../Core/_Base","./_GroupDataSource"],function(a,b){"use strict";a.Namespace.define("WinJS.UI",{computeDataSourceGroups:function(a,c,d,e){function f(a){if(a){var b=Object.create(a);return b.groupKey=c(a),d&&(b.groupData=d(a)),b}return null}function g(a){var b=Object.create(a);return b.then=function(b,c,d){return a.then(function(a){return b(f(a))},c,d)},b}var h=Object.create(a);h.createListBinding=function(b){var c;b?(c=Object.create(b),c.inserted=function(a,c,d){return b.inserted(g(a),c,d)},c.changed=function(a,c){return b.changed(f(a),f(c))},c.moved=function(a,c,d){return b.moved(g(a),c,d)}):c=null;for(var d=a.createListBinding(c),e=Object.create(d),h=["first","last","fromDescription","jumpToItem","current"],i=0,j=h.length;j>i;i++)!function(a){d[a]&&(e[a]=function(){return g(d[a].apply(d,arguments))})}(h[i]);return d.fromKey&&(e.fromKey=function(a){return g(d.fromKey(a))}),d.fromIndex&&(e.fromIndex=function(a){return g(d.fromIndex(a))}),e.prev=function(){return g(d.prev())},e.next=function(){return g(d.next())},e};for(var i=["itemFromKey","itemFromIndex","itemFromDescription","insertAtStart","insertBefore","insertAfter","insertAtEnd","change","moveToStart","moveBefore","moveAfter","moveToEnd"],j=0,k=i.length;k>j;j++)!function(b){a[b]&&(h[b]=function(){return g(a[b].apply(a,arguments))})}(i[j]);["addEventListener","removeEventListener","dispatchEvent"].forEach(function(b){a[b]&&(h[b]=function(){return a[b].apply(a,arguments)})});var l=null;return Object.defineProperty(h,"groups",{get:function(){return l||(l=new b._GroupDataSource(a,c,d,e)),l},enumerable:!0,configurable:!0}),h}})}),d("WinJS/VirtualizedDataSource/_StorageDataSource",["exports","../Core/_WinRT","../Core/_Global","../Core/_Base","../Core/_ErrorFromName","../Core/_WriteProfilerMark","../Animations","../Promise","../Utilities/_UI","./_VirtualizedDataSourceImpl"],function(a,b,c,d,e,f,g,h,i,j){"use strict";d.Namespace._moduleDefine(a,"WinJS.UI",{StorageDataSource:d.Namespace._lazy(function(){var a=d.Class.define(function(a,c){f("WinJS.UI.StorageDataSource:constructor,StartTM");var d,e=b.Windows.Storage.FileProperties.ThumbnailMode.singleItem,g=256,h=b.Windows.Storage.FileProperties.ThumbnailOptions.useCurrentScale,i=!0;if("Pictures"===a?(e=b.Windows.Storage.FileProperties.ThumbnailMode.picturesView,d=b.Windows.Storage.KnownFolders.picturesLibrary,g=190):"Music"===a?(e=b.Windows.Storage.FileProperties.ThumbnailMode.musicView,d=b.Windows.Storage.KnownFolders.musicLibrary,g=256):"Documents"===a?(e=b.Windows.Storage.FileProperties.ThumbnailMode.documentsView,d=b.Windows.Storage.KnownFolders.documentsLibrary,g=40):"Videos"===a&&(e=b.Windows.Storage.FileProperties.ThumbnailMode.videosView,d=b.Windows.Storage.KnownFolders.videosLibrary,g=190),d){var j=new b.Windows.Storage.Search.QueryOptions;j.folderDepth=b.Windows.Storage.Search.FolderDepth.deep,j.indexerOption=b.Windows.Storage.Search.IndexerOption.useIndexerWhenAvailable,this._query=d.createFileQueryWithOptions(j)}else this._query=a;if(c){if("number"==typeof c.mode&&(e=c.mode),"number"==typeof c.requestedThumbnailSize)g=Math.max(1,Math.min(c.requestedThumbnailSize,1024));else switch(e){case b.Windows.Storage.FileProperties.ThumbnailMode.picturesView:case b.Windows.Storage.FileProperties.ThumbnailMode.videosView:g=190;break;case b.Windows.Storage.FileProperties.ThumbnailMode.documentsView:case b.Windows.Storage.FileProperties.ThumbnailMode.listView:g=40;break;case b.Windows.Storage.FileProperties.ThumbnailMode.musicView:case b.Windows.Storage.FileProperties.ThumbnailMode.singleItem:g=256}"number"==typeof c.thumbnailOptions&&(h=c.thumbnailOptions),"boolean"==typeof c.waitForFileLoad&&(i=!c.waitForFileLoad)}this._loader=new b.Windows.Storage.BulkAccess.FileInformationFactory(this._query,e,g,h,i),this.compareByIdentity=!1,this.firstDataRequest=!0,f("WinJS.UI.StorageDataSource:constructor,StopTM")},{setNotificationHandler:function(a){this._notificationHandler=a,this._query.addEventListener("contentschanged",function(){a.invalidateAll()}),this._query.addEventListener("optionschanged",function(){a.invalidateAll()})},itemsFromEnd:function(a){var b=this;return f("WinJS.UI.StorageDataSource:itemsFromEnd,info"),this.getCount().then(function(c){return 0===c?h.wrapError(new e(i.FetchError.doesNotExist)):b.itemsFromIndex(c-1,Math.min(c-1,a-1),1)})},itemsFromIndex:function(a,b,c){function d(a){k._notificationHandler.changed(k._item(a.target))}b+c>64&&(b=Math.min(b,32),c=64-(b+1));var g=a-b,j=b+1+c,k=this;k.firstDataRequest&&(k.firstDataRequest=!1,j=Math.max(j,32));var l="WinJS.UI.StorageDataSource:itemsFromIndex("+g+"-"+(g+j-1)+")";return f(l+",StartTM"),this._loader.getItemsAsync(g,j).then(function(c){var m=c.size;if(b>=m)return h.wrapError(new e(i.FetchError.doesNotExist));var n=new Array(m),o=new Array(m);c.getMany(0,o);for(var p=0;m>p;p++)n[p]=k._item(o[p]),o[p].addEventListener("propertiesupdated",d);var q={items:n,offset:b,absoluteIndex:a};return j>m&&(q.totalCount=g+m),f(l+",StopTM"),q})},itemsFromDescription:function(a,b,c){var d=this;return f("WinJS.UI.StorageDataSource:itemsFromDescription,info"),this._query.findStartIndexAsync(a).then(function(a){return d.itemsFromIndex(a,b,c)})},getCount:function(){return f("WinJS.UI.StorageDataSource:getCount,info"),this._query.getItemCountAsync()},itemSignature:function(a){return a.folderRelativeId},_item:function(a){return{key:a.path||a.folderRelativeId,data:a}}},{supportedForProcessing:!1});return d.Class.derive(j.VirtualizedDataSource,function(b,c){this._baseDataSourceConstructor(new a(b,c))},{},{loadThumbnail:function(a,d){var e,i,j=!1;return new h(function(k){var l=d?!0:!1,m=function(m){if(m){var n=c.URL.createObjectURL(m,{oneTimeOnly:!0});i=i?i.then(function(b){return a.loadImage(n,b)}):a.loadImage(n,d).then(function(b){return a.isOnScreen().then(function(a){var c;return a&&l?c=g.fadeIn(b).then(function(){return b}):(b.style.opacity=1,c=h.wrap(b)),c})}),m.type===b.Windows.Storage.FileProperties.ThumbnailType.icon||m.returnedSmallerCachedSize||(f("WinJS.UI.StorageDataSource:loadThumbnail complete,info"),a.data.removeEventListener("thumbnailupdated",e),j=!1,i=i.then(function(a){e=null,i=null,k(a)}))}};e=function(a){j&&m(a.target.thumbnail)},a.data.addEventListener("thumbnailupdated",e),j=!0,m(a.data.thumbnail)},function(){a.data.removeEventListener("thumbnailupdated",e),j=!1,e=null,i&&(i.cancel(),i=null)})},supportedForProcessing:!1})})})}),d("WinJS/VirtualizedDataSource",["./VirtualizedDataSource/_VirtualizedDataSourceImpl","./VirtualizedDataSource/_GroupDataSource","./VirtualizedDataSource/_GroupedItemDataSource","./VirtualizedDataSource/_StorageDataSource"],function(){}),d("WinJS/Vui",["require","exports","./Core/_Global","./Utilities/_ElementUtilities"],function(a,b,c,d){function e(a){if(!a.defaultPrevented){var b=a.target,c=f[b.tagName];if(c)switch(a.state){case j.active:b[g.vuiData]||d.hasClass(b,h.active)?(d.removeClass(b,h.disambiguation),c.reactivate(b,a.label)):(d.addClass(b,h.active),c.activate(b,a.label));break;case j.disambiguation:d.addClass(b,h.active),d.addClass(b,h.disambiguation),c.disambiguate(b,a.label);break;case j.inactive:d.removeClass(b,h.active),d.removeClass(b,h.disambiguation),c.deactivate(b)}}}var f,g={vuiData:"_winVuiData"},h={active:"win-vui-active",disambiguation:"win-vui-disambiguation"},i={ListeningModeStateChanged:"ListeningStateChanged"},j={active:"active",disambiguation:"disambiguation",inactive:"inactive"};!function(a){a.BUTTON={activate:function(a,b){var c={nodes:[],width:a.style.width,height:a.style.height},e=d._getComputedStyle(a);for(a.style.width=e.width,a.style.height=e.height;a.childNodes.length;)c.nodes.push(a.removeChild(a.childNodes[0]));a[g.vuiData]=c,a.textContent=b},disambiguate:function(a,b){a.textContent=b},reactivate:function(a,b){a.textContent=b},deactivate:function(a){a.innerHTML="";var b=a[g.vuiData];a.style.width=b.width,a.style.height=b.height,b.nodes.forEach(function(b){return a.appendChild(b)}),delete a[g.vuiData]}}}(f||(f={})),c.document&&c.document.addEventListener(i.ListeningModeStateChanged,e)}),d("WinJS/_Accents",["require","exports","./Core/_Global","./Core/_WinRT","./Core/_Base","./Core/_BaseUtils","./Utilities/_ElementUtilities"],function(a,b,c,d,e,f,g){function h(a,b){t.push({selector:a,props:b}),i()}function i(){0!==t.length&&-1===u&&(u=f._setImmediate(function(){u=-1,m();var a=s?o.lightThemeSelector:o.darkThemeSelector,b=o.hoverSelector+" "+a,d=c.document.createElement("style");d.id=o.accentStyleId,d.textContent=t.map(function(c){var d=" "+c.props.map(function(a){return a.name+": "+r[a.value]+";"}).join("\n "),e=c.selector.split(",").map(function(a){return l(a)}),f=e.join(",\n"),g=f+" {\n"+d+"\n}",h=c.props.some(function(a){return 0!==a.value});if(h){var i=" "+c.props.map(function(a){return a.name+": "+r[a.value?a.value+3:a.value]+";"}).join("\n "),j=[];e.forEach(function(c){if(-1!==c.indexOf(o.hoverSelector)&&-1===c.indexOf(b)){j.push(c.replace(o.hoverSelector,b));var d=c.replace(o.hoverSelector,"").trim();-1!==p.indexOf(d[0])&&j.push(c.replace(o.hoverSelector+" ",b))}else j.push(a+" "+c),-1!==p.indexOf(c[0])&&j.push(a+c);g+="\n"+j.join(",\n")+" {\n"+i+"\n}"})}return g}).join("\n"),c.document.head.appendChild(d)}))}function j(){var a=(d.Windows.UI.ViewManagement.UIColorType,q.getColorValue(d.Windows.UI.ViewManagement.UIColorType.accent)),b=k(a,1);r[0]!==b&&(r.length=0,r.push(b,k(a,s?.6:.4),k(a,s?.8:.6),k(a,s?.9:.7),k(a,s?.4:.6),k(a,s?.6:.8),k(a,s?.7:.9)),i())}function k(a,b){return"rgba("+a.r+","+a.g+","+a.b+","+b+")"}function l(a){return a.replace(/ /g," ").replace(/ /g," ").trim()}function m(){var a=c.document.head.querySelector("#"+o.accentStyleId); a&&a.parentNode.removeChild(a)}function n(){t.length=0,m()}var o={accentStyleId:"WinJSAccentsStyle",themeDetectionTag:"winjs-themedetection-tag",hoverSelector:"html.win-hoverable",lightThemeSelector:".win-ui-light",darkThemeSelector:".win-ui-dark"},p=[".","#",":"],q=null,r=[],s=!1,t=[],u=-1;!function(a){a[a.accent=0]="accent",a[a.listSelectRest=1]="listSelectRest",a[a.listSelectHover=2]="listSelectHover",a[a.listSelectPress=3]="listSelectPress",a[a._listSelectRestInverse=4]="_listSelectRestInverse",a[a._listSelectHoverInverse=5]="_listSelectHoverInverse",a[a._listSelectPressInverse=6]="_listSelectPressInverse"}(b.ColorTypes||(b.ColorTypes={}));var v=b.ColorTypes;b.createAccentRule=h;var w=c.document.createElement(o.themeDetectionTag);c.document.head.appendChild(w);var x=g._getComputedStyle(w);s="0"===x.opacity,w.parentElement.removeChild(w);try{q=new d.Windows.UI.ViewManagement.UISettings,q.addEventListener("colorvalueschanged",j),j()}catch(y){r.push("rgb(0, 120, 215)","rgba(0, 120, 215, "+(s?"0.6":"0.4")+")","rgba(0, 120, 215, "+(s?"0.8":"0.6")+")","rgba(0, 120, 215, "+(s?"0.9":"0.7")+")","rgba(0, 120, 215, "+(s?"0.4":"0.6")+")","rgba(0, 120, 215, "+(s?"0.6":"0.8")+")","rgba(0, 120, 215, "+(s?"0.7":"0.9")+")")}var z={ColorTypes:v,createAccentRule:h,_colors:r,_reset:n,_isDarkTheme:s};e.Namespace.define("WinJS.UI._Accents",z)}),d("require-style",{load:function(a){throw new Error("Dynamic load not allowed: "+a)}}),d("require-style!less/styles-intrinsic",[],function(){}),d("require-style!less/colors-intrinsic",[],function(){}),d("WinJS/Controls/IntrinsicControls",["../Utilities/_Hoverable","../_Accents","require-style!less/styles-intrinsic","require-style!less/colors-intrinsic"],function(a,b){"use strict";b.createAccentRule(".win-link, .win-progress-bar, .win-progress-ring, .win-ring",[{name:"color",value:b.ColorTypes.accent}]),b.createAccentRule("::selection, .win-button.win-button-primary, .win-dropdown option:checked, select[multiple].win-dropdown option:checked",[{name:"background-color",value:b.ColorTypes.accent}]),b.createAccentRule(".win-textbox:focus, .win-textarea:focus, .win-textbox:focus:hover, .win-textarea:focus:hover",[{name:"border-color",value:b.ColorTypes.accent}]),b.createAccentRule(".win-textbox::-ms-clear:hover:not(:active), .win-textbox::-ms-reveal:hover:not(:active)",[{name:"color",value:b.ColorTypes.accent}]),b.createAccentRule(".win-checkbox:checked::-ms-check, .win-textbox::-ms-clear:active, .win-textbox::-ms-reveal:active",[{name:"background-color",value:b.ColorTypes.accent}]),b.createAccentRule(".win-progress-bar::-webkit-progress-value, .win-progress-ring::-webkit-progress-value, .win-ring::-webkit-progress-value",[{name:"background-color",value:b.ColorTypes.accent}]),b.createAccentRule(".win-progress-bar:not(:indeterminate)::-moz-progress-bar, .win-progress-ring:not(:indeterminate)::-moz-progress-bar, .win-ring:not(:indeterminate)::-moz-progress-bar",[{name:"background-color",value:b.ColorTypes.accent}]),b.createAccentRule(".win-checkbox:indeterminate::-ms-check, .win-checkbox:hover:indeterminate::-ms-check, .win-radio:checked::-ms-check",[{name:"border-color",value:b.ColorTypes.accent}]),b.createAccentRule(".win-slider::-ms-thumb, .win-slider::-ms-fill-lower",[{name:"background",value:b.ColorTypes.accent}]),b.createAccentRule(".win-slider::-webkit-slider-thumb",[{name:"background",value:b.ColorTypes.accent}]),b.createAccentRule(".win-slider::-moz-range-thumb",[{name:"background",value:b.ColorTypes.accent}])}),d("WinJS/Controls/ItemContainer/_Constants",["exports","../../Core/_Base"],function(a,b){"use strict";var c={};c._listViewClass="win-listview",c._viewportClass="win-viewport",c._rtlListViewClass="win-rtl",c._horizontalClass="win-horizontal",c._verticalClass="win-vertical",c._scrollableClass="win-surface",c._itemsContainerClass="win-itemscontainer",c._listHeaderContainerClass="win-headercontainer",c._listFooterContainerClass="win-footercontainer",c._padderClass="win-itemscontainer-padder",c._proxyClass="_win-proxy",c._itemClass="win-item",c._itemBoxClass="win-itembox",c._itemsBlockClass="win-itemsblock",c._containerClass="win-container",c._containerEvenClass="win-container-even",c._containerOddClass="win-container-odd",c._backdropClass="win-backdrop",c._footprintClass="win-footprint",c._groupsClass="win-groups",c._selectedClass="win-selected",c._selectionBorderClass="win-selectionborder",c._selectionBackgroundClass="win-selectionbackground",c._selectionCheckmarkClass="win-selectioncheckmark",c._selectionCheckmarkBackgroundClass="win-selectioncheckmarkbackground",c._pressedClass="win-pressed",c._headerClass="win-groupheader",c._headerContainerClass="win-groupheadercontainer",c._groupLeaderClass="win-groupleader",c._progressClass="win-progress",c._revealedClass="win-revealed",c._itemFocusClass="win-focused",c._itemFocusOutlineClass="win-focusedoutline",c._zoomingXClass="win-zooming-x",c._zoomingYClass="win-zooming-y",c._listLayoutClass="win-listlayout",c._gridLayoutClass="win-gridlayout",c._headerPositionTopClass="win-headerpositiontop",c._headerPositionLeftClass="win-headerpositionleft",c._structuralNodesClass="win-structuralnodes",c._singleItemsBlockClass="win-single-itemsblock",c._uniformGridLayoutClass="win-uniformgridlayout",c._uniformListLayoutClass="win-uniformlistlayout",c._cellSpanningGridLayoutClass="win-cellspanninggridlayout",c._laidOutClass="win-laidout",c._nonDraggableClass="win-nondraggable",c._nonSelectableClass="win-nonselectable",c._dragOverClass="win-dragover",c._dragSourceClass="win-dragsource",c._clipClass="win-clip",c._selectionModeClass="win-selectionmode",c._noCSSGrid="win-nocssgrid",c._hidingSelectionMode="win-hidingselectionmode",c._hidingSelectionModeAnimationTimeout=250,c._INVALID_INDEX=-1,c._UNINITIALIZED=-1,c._LEFT_MSPOINTER_BUTTON=0,c._RIGHT_MSPOINTER_BUTTON=2,c._TAP_END_THRESHOLD=10,c._DEFAULT_PAGES_TO_LOAD=5,c._DEFAULT_PAGE_LOAD_THRESHOLD=2,c._MIN_AUTOSCROLL_RATE=150,c._MAX_AUTOSCROLL_RATE=1500,c._AUTOSCROLL_THRESHOLD=100,c._AUTOSCROLL_DELAY=50,c._DEFERRED_ACTION=250,c._DEFERRED_SCROLL_END=250,c._SELECTION_CHECKMARK="",c._LISTVIEW_PROGRESS_DELAY=2e3;var d={uninitialized:0,low:1,medium:2,high:3},e={rebuild:0,remeasure:1,relayout:2,realize:3};c._ScrollToPriority=d,c._ViewChange=e,b.Namespace._moduleDefine(a,"WinJS.UI",c)}),d("WinJS/Controls/ItemContainer/_ItemEventsHandler",["exports","../../Core/_Global","../../Core/_WinRT","../../Core/_Base","../../Core/_BaseUtils","../../Core/_WriteProfilerMark","../../Animations","../../Animations/_TransitionAnimation","../../Promise","../../Utilities/_ElementUtilities","../../Utilities/_UI","./_Constants"],function(a,b,c,d,e,f,g,h,i,j,k,l){"use strict";function m(a,b,c){var d=44,e=750,f=2,g=9,h=2.11,i=13,k=e-d,l=c.width/2,m=c.height/2,n=j._clamp(c.width,d,e),o=j._clamp(c.height,d,e),p=g-(o-d)/k*(g-f),q=i-(n-d)/k*(i-h),r=(a-c.left-l)/l,s=(b-c.top-m)/m,t=p*s,u=q*r,v=.97+.03*(Math.abs(r)+Math.abs(s))/2,w="perspective(800px) scale("+v+") rotateX("+-t+"deg) rotateY("+u+"deg)";return w}var n=e._browserStyleEquivalents.transform;d.Namespace._moduleDefine(a,"WinJS.UI",{_tiltTransform:m,_ItemEventsHandler:d.Namespace._lazy(function(){function a(a,c){var d=b.document.createElement("div");return d.className=a,c||d.setAttribute("aria-hidden",!0),d}var g=j._MSPointerEvent.MSPOINTER_TYPE_TOUCH||"touch",o=d.Class.define(function(a){this._site=a,this._work=[],this._animations={}},{dispose:function(){this._disposed||(this._disposed=!0,j._removeEventListener(b,"pointerup",this._resetPointerDownStateBound),j._removeEventListener(b,"pointercancel",this._resetPointerDownStateBound))},onPointerDown:function(a){f("WinJS.UI._ItemEventsHandler:MSPointerDown,StartTM");var d,h,i=this._site,m=a.pointerType===g;if(i.pressedElement=a.target,c.Windows.UI.Input.PointerPoint){var n=this._getCurrentPoint(a),o=n.properties;m||o.isInverted||o.isEraser||o.isMiddleButtonPressed?d=h=!1:(h=o.isRightButtonPressed,d=!h&&o.isLeftButtonPressed)}else d=a.button===l._LEFT_MSPOINTER_BUTTON,h=a.button===l._RIGHT_MSPOINTER_BUTTON;this._DragStartBound=this._DragStartBound||this.onDragStart.bind(this),this._PointerEnterBound=this._PointerEnterBound||this.onPointerEnter.bind(this),this._PointerLeaveBound=this._PointerLeaveBound||this.onPointerLeave.bind(this);var p=this._isInteractive(a.target),q=i.indexForItemElement(a.target),r=i.indexForHeaderElement(a.target),s=!p&&q!==l._INVALID_INDEX;if((m||d)&&this._site.pressedEntity.index===l._INVALID_INDEX&&!p&&(this._site.pressedEntity=r===l._INVALID_INDEX?{type:k.ObjectType.item,index:q}:{type:k.ObjectType.groupHeader,index:r},this._site.pressedEntity.index!==l._INVALID_INDEX)){this._site.pressedPosition=j._getCursorPos(a);var t=i.verifySelectionAllowed(this._site.pressedEntity);this._canSelect=t.canSelect,this._canTapSelect=t.canTapSelect,this._site.pressedEntity.type===k.ObjectType.item?(this._site.pressedItemBox=i.itemBoxAtIndex(this._site.pressedEntity.index),this._site.pressedContainer=i.containerAtIndex(this._site.pressedEntity.index),this._site.animatedElement=this._site.pressedContainer,this._site.pressedHeader=null,this._togglePressed(!0,!1,a),this._site.pressedContainer.addEventListener("dragstart",this._DragStartBound),m||(j._addEventListener(this._site.pressedContainer,"pointerenter",this._PointerEnterBound,!1),j._addEventListener(this._site.pressedContainer,"pointerleave",this._PointerLeaveBound,!1))):(this._site.pressedHeader=this._site.headerFromElement(a.target),e.isPhone?(this._site.animatedElement=this._site.pressedHeader,this._togglePressed(!0,!1,a)):(this._site.pressedItemBox=null,this._site.pressedContainer=null,this._site.animatedElement=null)),this._resetPointerDownStateBound||(this._resetPointerDownStateBound=this._resetPointerDownStateForPointerId.bind(this)),m||(j._addEventListener(b,"pointerup",this._resetPointerDownStateBound,!1),j._addEventListener(b,"pointercancel",this._resetPointerDownStateBound,!1)),this._pointerId=a.pointerId,this._pointerRightButton=h}if(s&&m)try{j._setPointerCapture(i.canvasProxy,a.pointerId)}catch(u){return void f("WinJS.UI._ItemEventsHandler:MSPointerDown,StopTM")}this._site.pressedEntity.type===k.ObjectType.item&&this._selectionAllowed()&&this._multiSelection()&&this._site.pressedEntity.index!==l._INVALID_INDEX&&i.selection._getFocused().index!==l._INVALID_INDEX&&i.selection._pivot===l._INVALID_INDEX&&(i.selection._pivot=i.selection._getFocused().index),f("WinJS.UI._ItemEventsHandler:MSPointerDown,StopTM")},onPointerEnter:function(a){this._site.pressedContainer&&this._pointerId===a.pointerId&&this._togglePressed(!0,!1,a)},onPointerLeave:function(a){this._site.pressedContainer&&this._pointerId===a.pointerId&&this._togglePressed(!1,!0,a)},onDragStart:function(){this._resetPressedContainer()},_resetPressedContainer:function(){(this._site.pressedContainer||this._site.pressedHeader)&&this._site.animatedElement&&(this._togglePressed(!1),this._site.pressedContainer&&(this._site.pressedContainer.style[n.scriptName]="",this._site.pressedContainer.removeEventListener("dragstart",this._DragStartBound),j._removeEventListener(this._site.pressedContainer,"pointerenter",this._PointerEnterBound,!1),j._removeEventListener(this._site.pressedContainer,"pointerleave",this._PointerLeaveBound,!1)))},onClick:function(a){if(!this._skipClick){var b={type:k.ObjectType.item,index:this._site.indexForItemElement(a.target)};if(b.index===l._INVALID_INDEX&&(b.index=this._site.indexForHeaderElement(a.target),b.index!==l._INVALID_INDEX&&(b.type=k.ObjectType.groupHeader)),b.index!==l._INVALID_INDEX&&(j.hasClass(a.target,this._site.accessibleItemClass)||j.hasClass(a.target,l._headerClass))){var c=this._site.verifySelectionAllowed(b);c.canTapSelect&&this.handleTap(b),this._site.fireInvokeEvent(b,a.target)}}},onPointerUp:function(a){f("WinJS.UI._ItemEventsHandler:MSPointerUp,StartTM");var b=this._site;this._skipClick=!0;var c=this;e._yieldForEvents(function(){c._skipClick=!1});try{j._releasePointerCapture(b.canvasProxy,a.pointerId)}catch(d){}var h=a.pointerType===g,i=this._releasedElement(a),m=b.indexForItemElement(i),n=b.indexForHeaderElement(i&&j.hasClass(i,l._headerContainerClass)?b.pressedHeader:i);if(this._pointerId===a.pointerId){var o;if(o=n===l._INVALID_INDEX?{type:k.ObjectType.item,index:m}:{type:k.ObjectType.groupHeader,index:n},this._resetPressedContainer(),this._site.pressedEntity.type===k.ObjectType.item&&o.type===k.ObjectType.item&&this._site.pressedContainer&&this._site.pressedEntity.index===o.index)if(a.shiftKey||(b.selection._pivot=l._INVALID_INDEX),a.shiftKey){if(this._selectionAllowed()&&this._multiSelection()&&b.selection._pivot!==l._INVALID_INDEX){var p=Math.min(this._site.pressedEntity.index,b.selection._pivot),q=Math.max(this._site.pressedEntity.index,b.selection._pivot),r=this._pointerRightButton||a.ctrlKey||b.tapBehavior===k.TapBehavior.toggleSelect;b.selectRange(p,q,r)}}else a.ctrlKey&&this.toggleSelectionIfAllowed(this._site.pressedEntity.index);if(this._site.pressedHeader||this._site.pressedContainer){var s=j._getCursorPos(a),t=Math.abs(s.left-this._site.pressedPosition.left)<=l._TAP_END_THRESHOLD&&Math.abs(s.top-this._site.pressedPosition.top)<=l._TAP_END_THRESHOLD;this._pointerRightButton||a.ctrlKey||a.shiftKey||!(h&&t||!h&&this._site.pressedEntity.index===o.index&&this._site.pressedEntity.type===o.type)||(o.type===k.ObjectType.groupHeader?(this._site.pressedHeader=b.headerAtIndex(o.index),this._site.pressedItemBox=null,this._site.pressedContainer=null):(this._site.pressedItemBox=b.itemBoxAtIndex(o.index),this._site.pressedContainer=b.containerAtIndex(o.index),this._site.pressedHeader=null),this._canTapSelect&&this.handleTap(this._site.pressedEntity),this._site.fireInvokeEvent(this._site.pressedEntity,this._site.pressedItemBox||this._site.pressedHeader))}this._site.pressedEntity.index!==l._INVALID_INDEX&&b.changeFocus(this._site.pressedEntity,!0,!1,!0),this.resetPointerDownState()}f("WinJS.UI._ItemEventsHandler:MSPointerUp,StopTM")},onPointerCancel:function(a){this._pointerId===a.pointerId&&(f("WinJS.UI._ItemEventsHandler:MSPointerCancel,info"),this.resetPointerDownState())},onLostPointerCapture:function(a){this._pointerId===a.pointerId&&(f("WinJS.UI._ItemEventsHandler:MSLostPointerCapture,info"),this.resetPointerDownState())},onContextMenu:function(a){this._shouldSuppressContextMenu(a.target)&&a.preventDefault()},onMSHoldVisual:function(a){this._shouldSuppressContextMenu(a.target)&&a.preventDefault()},onDataChanged:function(){this.resetPointerDownState()},toggleSelectionIfAllowed:function(a){this._selectionAllowed(a)&&this._toggleItemSelection(a)},handleTap:function(a){if(a.type!==k.ObjectType.groupHeader){var b=this._site,c=b.selection;this._selectionAllowed(a.index)&&this._selectOnTap()&&(b.tapBehavior===k.TapBehavior.toggleSelect?this._toggleItemSelection(a.index):b.selectionMode!==k.SelectionMode.multi&&c._isIncluded(a.index)||c.set(a.index))}},_toggleItemSelection:function(a){var b=this._site,c=b.selection,d=c._isIncluded(a);b.selectionMode===k.SelectionMode.single?d?c.clear():c.set(a):d?c.remove(a):c.add(a)},_getCurrentPoint:function(a){return c.Windows.UI.Input.PointerPoint.getCurrentPoint(a.pointerId)},_containedInElementWithClass:function(a,b){if(a.parentNode)for(var c=a.parentNode.querySelectorAll("."+b+", ."+b+" *"),d=0,e=c.length;e>d;d++)if(c[d]===a)return!0;return!1},_isSelected:function(a){return this._site.selection._isIncluded(a)},_isInteractive:function(a){return this._containedInElementWithClass(a,"win-interactive")},_shouldSuppressContextMenu:function(a){var b=this._site.containerFromElement(a);return this._selectionAllowed()&&b&&!this._isInteractive(a)},_togglePressed:function(a,b,c){function d(a){o._site.disablePressAnimation()||(""===o._site.animatedElement.style[n.scriptName]?(o._site.animatedElement.style[n.scriptName]=a,o._site.animatedElementScaleTransform=o._site.animatedElement.style[n.scriptName]):o._site.animatedElementScaleTransform="")}function g(a,b){f("WinJS.UI._ItemEventsHandler:removePressedUI,info"),j.removeClass(a,l._pressedClass),o._containsTransform(a,b)&&h.executeTransition(a,{property:n.cssName,delay:150,duration:350,timing:"cubic-bezier(0.17,0.17,0.2,1)",to:a.style[n.scriptName].replace(b,"")})}var o=this,p=this._site.pressedEntity.type===k.ObjectType.groupHeader;if(this._site.animatedDownPromise&&this._site.animatedDownPromise.cancel(),(p||!j.hasClass(this._site.pressedItemBox,l._nonSelectableClass))&&!this._staticMode(p))if(a){if(!j.hasClass(this._site.animatedElement,l._pressedClass)){f("WinJS.UI._ItemEventsHandler:applyPressedUI,info"),j.addClass(this._site.animatedElement,l._pressedClass);var q=p?o._site.pressedHeader:o._site.pressedContainer,r=m(c.clientX,c.clientY,q.getBoundingClientRect());this._site.animatedDownPromise=i.timeout(50).then(function(){d(r)})}}else if(j.hasClass(this._site.animatedElement,l._pressedClass)){var s=this._site.animatedElement,t=this._site.animatedElementScaleTransform;b?g(s,t):e._setImmediate(function(){j.hasClass(s,l._pressedClass)&&g(s,t)})}},_containsTransform:function(a,b){return b&&-1!==a.style[n.scriptName].indexOf(b)},_resetPointerDownStateForPointerId:function(a){this._pointerId===a.pointerId&&this.resetPointerDownState()},resetPointerDownState:function(){this._site.pressedElement=null,j._removeEventListener(b,"pointerup",this._resetPointerDownStateBound),j._removeEventListener(b,"pointercancel",this._resetPointerDownStateBound),this._resetPressedContainer(),this._site.pressedContainer=null,this._site.animatedElement=null,this._site.pressedHeader=null,this._site.pressedItemBox=null,this._site.pressedEntity={type:k.ObjectType.item,index:l._INVALID_INDEX},this._pointerId=null},_releasedElement:function(a){return b.document.elementFromPoint(a.clientX,a.clientY)},_applyUIInBatches:function(a){function b(){c._work.length>0?(c._flushUIBatches(),c._paintedThisFrame=e._requestAnimationFrame(b.bind(c))):c._paintedThisFrame=null}var c=this;this._work.push(a),this._paintedThisFrame||b()},_flushUIBatches:function(){if(this._work.length>0){var a=this._work;this._work=[];for(var b=0;b<a.length;b++)a[b]()}},_selectionAllowed:function(a){var b=void 0!==a?this._site.itemAtIndex(a):null,c=!(b&&j.hasClass(b,l._nonSelectableClass));return c&&this._site.selectionMode!==k.SelectionMode.none},_multiSelection:function(){return this._site.selectionMode===k.SelectionMode.multi},_selectOnTap:function(){return this._site.tapBehavior===k.TapBehavior.toggleSelect||this._site.tapBehavior===k.TapBehavior.directSelect},_staticMode:function(a){return a?this._site.headerTapBehavior===k.GroupHeaderTapBehavior.none:this._site.tapBehavior===k.TapBehavior.none&&this._site.selectionMode===k.SelectionMode.none}},{setAriaSelected:function(a,b){var c="true"===a.getAttribute("aria-selected");b!==c&&a.setAttribute("aria-selected",b)},renderSelection:function(b,c,d,e,f){if(!o._selectionTemplate){o._selectionTemplate=[],o._selectionTemplate.push(a(l._selectionBackgroundClass)),o._selectionTemplate.push(a(l._selectionBorderClass)),o._selectionTemplate.push(a(l._selectionCheckmarkBackgroundClass));var g=a(l._selectionCheckmarkClass);g.textContent=l._SELECTION_CHECKMARK,o._selectionTemplate.push(g)}if(d!==j._isSelectionRendered(b)){if(d){b.insertBefore(o._selectionTemplate[0].cloneNode(!0),b.firstElementChild);for(var h=1,i=o._selectionTemplate.length;i>h;h++)b.appendChild(o._selectionTemplate[h].cloneNode(!0))}else for(var k=b.querySelectorAll(j._selectionPartsSelector),h=0,i=k.length;i>h;h++)b.removeChild(k[h]);j[d?"addClass":"removeClass"](b,l._selectedClass),f&&j[d?"addClass":"removeClass"](f,l._selectedClass)}e&&o.setAriaSelected(c,d)}});return o})})}),d("WinJS/Controls/ListView/_SelectionManager",["exports","../../Core/_Global","../../Core/_Base","../../Promise","../../_Signal","../../Utilities/_UI","../ItemContainer/_Constants"],function(a,b,c,d,e,f,g){"use strict";c.Namespace._moduleDefine(a,"WinJS.UI",{_ItemSet:c.Namespace._lazy(function(){var b=c.Class.define(function(a,b,c){this._listView=a,this._ranges=b,this._itemsCount=c});return b.prototype={getRanges:function(){for(var a=[],b=0,c=this._ranges.length;c>b;b++){var d=this._ranges[b];a.push({firstIndex:d.firstIndex,lastIndex:d.lastIndex,firstKey:d.firstKey,lastKey:d.lastKey})}return a},getItems:function(){return a.getItemsFromRanges(this._listView._itemsManager.dataSource,this._ranges)},isEverything:function(){return this.count()===this._itemsCount},count:function(){for(var a=0,b=0,c=this._ranges.length;c>b;b++){var d=this._ranges[b];a+=d.lastIndex-d.firstIndex+1}return a},getIndices:function(){for(var a=[],b=0,c=this._ranges.length;c>b;b++)for(var d=this._ranges[b],e=d.firstIndex;e<=d.lastIndex;e++)a.push(e);return a}},b}),getItemsFromRanges:function(a,b){function c(){for(var a=[],c=0,e=b.length;e>c;c++)for(var f=b[c],g=f.firstIndex;g<=f.lastIndex;g++)a.push(g);return d.wrap(a)}var e=a.createListBinding(),f=[];return c().then(function(a){for(var b=0;b<a.length;b++)f.push(e.fromIndex(a[b]));return d.join(f).then(function(a){return e.release(),a})})},_Selection:c.Namespace._lazy(function(){function b(a){return a&&0===a.firstIndex&&a.lastIndex===Number.MAX_VALUE}return c.Class.derive(a._ItemSet,function(a,b){this._listView=a,this._itemsCount=-1,this._ranges=[],b&&this.set(b)},{clear:function(){return this._releaseRanges(this._ranges),this._ranges=[],d.wrap()},set:function(a){if(b(a))return this.selectAll();this._releaseRanges(this._ranges),this._ranges=[];var c=this;return this._execute("_set",a).then(function(){return c._ranges.sort(function(a,b){return a.firstIndex-b.firstIndex}),c._ensureKeys()}).then(function(){return c._ensureCount()})},add:function(a){if(b(a))return this.selectAll();var c=this;return this._execute("_add",a).then(function(){return c._ensureKeys()}).then(function(){return c._ensureCount()})},remove:function(a){var b=this;return this._execute("_remove",a).then(function(){return b._ensureKeys()})},selectAll:function(){var a=this;return a._ensureCount().then(function(){if(a._itemsCount){var b={firstIndex:0,lastIndex:a._itemsCount-1};return a._retainRange(b),a._releaseRanges(a._ranges),a._ranges=[b],a._ensureKeys()}})},_execute:function(a,b){function c(a,b,c){var d={};return d["first"+a]=b,d["last"+a]=c,d}function e(b){var c=f._getListBinding(),e=d.join([c.fromKey(b.firstKey),c.fromKey(b.lastKey)]).then(function(c){return c[0]&&c[1]&&(b.firstIndex=c[0].index,b.lastIndex=c[1].index,f[a](b)),b});i.push(e)}for(var f=this,g=!!f._getListBinding().fromKey,h=Array.isArray(b)?b:[b],i=[d.wrap()],j=0,k=h.length;k>j;j++){var l=h[j];"number"==typeof l?this[a](c("Index",l,l)):l&&(g&&void 0!==l.key?e(c("Key",l.key,l.key)):g&&void 0!==l.firstKey&&void 0!==l.lastKey?e(c("Key",l.firstKey,l.lastKey)):void 0!==l.index&&"number"==typeof l.index?this[a](c("Index",l.index,l.index)):void 0!==l.firstIndex&&void 0!==l.lastIndex&&"number"==typeof l.firstIndex&&"number"==typeof l.lastIndex&&this[a](c("Index",l.firstIndex,l.lastIndex)))}return d.join(i)},_set:function(a){this._retainRange(a),this._ranges.push(a)},_add:function(a){for(var b,c,d,e=this,f=null,g=function(a,b){b.lastIndex>a.lastIndex&&(a.lastIndex=b.lastIndex,a.lastKey=b.lastKey,a.lastPromise&&a.lastPromise.release(),a.lastPromise=e._getListBinding().fromIndex(a.lastIndex).retain())},h=0,i=this._ranges.length;i>h;h++){if(b=this._ranges[h],a.firstIndex<b.firstIndex){d=f&&a.firstIndex<f.lastIndex+1,d?(c=h-1,g(f,a)):(this._insertRange(h,a),c=h);break}if(a.firstIndex===b.firstIndex){g(b,a),c=h;break}f=b}if(void 0===c){var j=this._ranges.length?this._ranges[this._ranges.length-1]:null,k=j&&a.firstIndex<j.lastIndex+1;k?g(j,a):(this._retainRange(a),this._ranges.push(a))}else{for(f=null,h=c+1,i=this._ranges.length;i>h;h++){if(b=this._ranges[h],a.lastIndex<b.firstIndex){d=f&&f.lastIndex>a.lastIndex,d&&g(this._ranges[c],f),this._removeRanges(c+1,h-c-1);break}if(a.lastIndex===b.firstIndex){g(this._ranges[c],b),this._removeRanges(c+1,h-c);break}f=b}h>=i&&(g(this._ranges[c],this._ranges[i-1]),this._removeRanges(c+1,i-c-1))}},_remove:function(a){function b(a){return c._getListBinding().fromIndex(a).retain()}for(var c=this,d=[],e=0,f=this._ranges.length;f>e;e++){var g=this._ranges[e];g.lastIndex<a.firstIndex||g.firstIndex>a.lastIndex?d.push(g):g.firstIndex<a.firstIndex&&g.lastIndex>=a.firstIndex&&g.lastIndex<=a.lastIndex?(d.push({firstIndex:g.firstIndex,firstKey:g.firstKey,firstPromise:g.firstPromise,lastIndex:a.firstIndex-1,lastPromise:b(a.firstIndex-1)}),g.lastPromise.release()):g.lastIndex>a.lastIndex&&g.firstIndex>=a.firstIndex&&g.firstIndex<=a.lastIndex?(d.push({firstIndex:a.lastIndex+1,firstPromise:b(a.lastIndex+1),lastIndex:g.lastIndex,lastKey:g.lastKey,lastPromise:g.lastPromise}),g.firstPromise.release()):g.firstIndex<a.firstIndex&&g.lastIndex>a.lastIndex?(d.push({firstIndex:g.firstIndex,firstKey:g.firstKey,firstPromise:g.firstPromise,lastIndex:a.firstIndex-1,lastPromise:b(a.firstIndex-1)}),d.push({firstIndex:a.lastIndex+1,firstPromise:b(a.lastIndex+1),lastIndex:g.lastIndex,lastKey:g.lastKey,lastPromise:g.lastPromise})):(g.firstPromise.release(),g.lastPromise.release())}this._ranges=d},_ensureKeys:function(){for(var a=[d.wrap()],b=this,c=function(a,b){var c=a+"Key";if(b[c])return d.wrap();var e=b[a+"Promise"];return e.then(function(a){a&&(b[c]=a.key)}),e},e=0,f=this._ranges.length;f>e;e++){var g=this._ranges[e];a.push(c("first",g)),a.push(c("last",g))}return d.join(a).then(function(){b._ranges=b._ranges.filter(function(a){return a.firstKey&&a.lastKey})}),d.join(a)},_mergeRanges:function(a,b){a.lastIndex=b.lastIndex,a.lastKey=b.lastKey},_isIncluded:function(a){if(this.isEverything())return!0;for(var b=0,c=this._ranges.length;c>b;b++){var d=this._ranges[b];if(d.firstIndex<=a&&a<=d.lastIndex)return!0}return!1},_ensureCount:function(){var a=this;return this._listView._itemsCount().then(function(b){a._itemsCount=b})},_insertRange:function(a,b){this._retainRange(b),this._ranges.splice(a,0,b)},_removeRanges:function(a,b){for(var c=0;b>c;c++)this._releaseRange(this._ranges[a+c]);this._ranges.splice(a,b)},_retainRange:function(a){a.firstPromise||(a.firstPromise=this._getListBinding().fromIndex(a.firstIndex).retain()),a.lastPromise||(a.lastPromise=this._getListBinding().fromIndex(a.lastIndex).retain())},_retainRanges:function(){for(var a=0,b=this._ranges.length;b>a;a++)this._retainRange(this._ranges[a])},_releaseRange:function(a){a.firstPromise.release(),a.lastPromise.release()},_releaseRanges:function(a){for(var b=0,c=a.length;c>b;++b)this._releaseRange(a[b])},_getListBinding:function(){return this._listView._itemsManager._listBinding}},{supportedForProcessing:!1})}),_SelectionManager:c.Namespace._lazy(function(){var c=function(b){this._listView=b,this._selected=new a._Selection(this._listView),this._pivot=g._INVALID_INDEX,this._focused={type:f.ObjectType.item,index:0},this._pendingChange=d.wrap()};return c.prototype={count:function(){return this._selected.count()},getIndices:function(){return this._selected.getIndices()},getItems:function(){return this._selected.getItems()},getRanges:function(){return this._selected.getRanges()},isEverything:function(){return this._selected.isEverything()},set:function(b){var c=this,f=new e;return this._synchronize(f).then(function(){var e=new a._Selection(c._listView);return e.set(b).then(function(){c._set(e),f.complete()},function(a){return e.clear(),f.complete(),d.wrapError(a)})})},clear:function(){var b=this,c=new e;return this._synchronize(c).then(function(){var e=new a._Selection(b._listView);return e.clear().then(function(){b._set(e),c.complete()},function(a){return e.clear(),c.complete(),d.wrapError(a)})})},add:function(a){var b=this,c=new e;return this._synchronize(c).then(function(){var e=b._cloneSelection();return e.add(a).then(function(){b._set(e),c.complete()},function(a){return e.clear(),c.complete(),d.wrapError(a)})})},remove:function(a){var b=this,c=new e;return this._synchronize(c).then(function(){var e=b._cloneSelection();return e.remove(a).then(function(){b._set(e),c.complete()},function(a){return e.clear(),c.complete(),d.wrapError(a)})})},selectAll:function(){var b=this,c=new e;return this._synchronize(c).then(function(){var e=new a._Selection(b._listView);return e.selectAll().then(function(){b._set(e),c.complete()},function(a){return e.clear(),c.complete(),d.wrapError(a)})})},_synchronize:function(a){var b=this;return this._listView._versionManager.unlocked.then(function(){var c=b._pendingChange;return b._pendingChange=d.join([c,a.promise]).then(function(){}),c})},_reset:function(){this._pivot=g._INVALID_INDEX,this._setFocused({type:f.ObjectType.item,index:0},this._keyboardFocused()),this._pendingChange.cancel(),this._pendingChange=d.wrap(),this._selected.clear(),this._selected=new a._Selection(this._listView)},_dispose:function(){this._selected.clear(),this._selected=null,this._listView=null},_set:function(a){var b=this;return this._fireSelectionChanging(a).then(function(c){return c?(b._selected.clear(),b._selected=a,b._listView._updateSelection(),b._fireSelectionChanged()):a.clear(),c})},_fireSelectionChanging:function(a){var c=b.document.createEvent("CustomEvent"),e=d.wrap();c.initCustomEvent("selectionchanging",!0,!0,{newSelection:a,preventTapBehavior:function(){},setPromise:function(a){e=a}});var f=this._listView._element.dispatchEvent(c);return e.then(function(){return f})},_fireSelectionChanged:function(){var a=b.document.createEvent("CustomEvent");a.initCustomEvent("selectionchanged",!0,!1,null),this._listView._element.dispatchEvent(a)},_getFocused:function(){return{type:this._focused.type,index:this._focused.index}},_setFocused:function(a,b){this._focused={type:a.type,index:a.index},this._focusedByKeyboard=b},_keyboardFocused:function(){return this._focusedByKeyboard},_updateCount:function(a){this._selected._itemsCount=a},_isIncluded:function(a){return this._selected._isIncluded(a)},_cloneSelection:function(){var b=new a._Selection(this._listView);return b._ranges=this._selected.getRanges(),b._itemsCount=this._selected._itemsCount,b._retainRanges(),b}},c.supportedForProcessing=!1,c})})}),d("WinJS/Controls/ListView/_BrowseMode",["exports","../../Core/_Global","../../Core/_Base","../../Core/_BaseUtils","../../Animations","../../Promise","../../Utilities/_ElementUtilities","../../Utilities/_UI","../ItemContainer/_Constants","../ItemContainer/_ItemEventsHandler","./_SelectionManager"],function(a,b,c,d,e,f,g,h,i,j,k){"use strict";var l=d._browserStyleEquivalents.transform.scriptName;c.Namespace._moduleDefine(a,"WinJS.UI",{_SelectionMode:c.Namespace._lazy(function(){function a(a,b,c){return Math.max(a,Math.min(b,c))}function e(a,c,d){var e=b.document.createEvent("CustomEvent");return e.initCustomEvent("keyboardnavigating",!0,!0,{oldFocus:c.index,oldFocusType:c.type,newFocus:d.index,newFocusType:d.type}),a.dispatchEvent(e)}var m=c.Class.define(function(a){this.inboundFocusHandled=!1,this._pressedContainer=null,this._pressedItemBox=null,this._pressedHeader=null,this._pressedEntity={type:h.ObjectType.item,index:i._INVALID_INDEX},this._pressedPosition=null,this.initialize(a)},{_dispose:function(){this._itemEventsHandler&&this._itemEventsHandler.dispose(),this._setNewFocusItemOffsetPromise&&this._setNewFocusItemOffsetPromise.cancel()},initialize:function(a){function b(b,c){var d=function(c){return a._view.getAdjacent(c,b)};return d.clampToBounds=c,d}this.site=a,this._keyboardNavigationHandlers={},this._keyboardAcceleratorHandlers={};var c=this.site,d=this;this._itemEventsHandler=new j._ItemEventsHandler(Object.create({containerFromElement:function(a){return c._view.items.containerFrom(a)},indexForItemElement:function(a){return c._view.items.index(a)},indexForHeaderElement:function(a){return c._groups.index(a)},itemBoxAtIndex:function(a){return c._view.items.itemBoxAt(a)},itemAtIndex:function(a){return c._view.items.itemAt(a)},headerAtIndex:function(a){return c._groups.group(a).header},headerFromElement:function(a){return c._groups.headerFrom(a) },containerAtIndex:function(a){return c._view.items.containerAt(a)},isZombie:function(){return c._isZombie()},getItemPosition:function(a){return c._getItemPosition(a)},rtl:function(){return c._rtl()},fireInvokeEvent:function(a,b){return d._fireInvokeEvent(a,b)},verifySelectionAllowed:function(a){return d._verifySelectionAllowed(a)},changeFocus:function(a,b,d,e,f){return c._changeFocus(a,b,d,e,f)},selectRange:function(a,b,c){return d._selectRange(a,b,c)},disablePressAnimation:function(){return c._isInSelectionMode()}},{pressedEntity:{enumerable:!0,get:function(){return d._pressedEntity},set:function(a){d._pressedEntity=a}},pressedContainerScaleTransform:{enumerable:!0,get:function(){return d._pressedContainerScaleTransform},set:function(a){d._pressedContainerScaleTransform=a}},pressedContainer:{enumerable:!0,get:function(){return d._pressedContainer},set:function(a){d._pressedContainer=a}},pressedItemBox:{enumerable:!0,get:function(){return d._pressedItemBox},set:function(a){d._pressedItemBox=a}},pressedHeader:{enumerable:!0,get:function(){return d._pressedHeader},set:function(a){return d._pressedHeader=a}},pressedPosition:{enumerable:!0,get:function(){return d._pressedPosition},set:function(a){d._pressedPosition=a}},pressedElement:{enumerable:!0,set:function(a){d._pressedElement=a}},eventHandlerRoot:{enumerable:!0,get:function(){return c._viewport}},selectionMode:{enumerable:!0,get:function(){return c._selectionMode}},accessibleItemClass:{enumerable:!0,get:function(){return i._itemClass}},canvasProxy:{enumerable:!0,get:function(){return c._canvasProxy}},tapBehavior:{enumerable:!0,get:function(){return c._tap}},headerTapBehavior:{enumerable:!0,get:function(){return c._groupHeaderTap}},draggable:{enumerable:!0,get:function(){return c.itemsDraggable||c.itemsReorderable}},selection:{enumerable:!0,get:function(){return c._selection}},customFootprintParent:{enumerable:!0,get:function(){return null}}}));var e=g.Key;this._keyboardNavigationHandlers[e.upArrow]=b(e.upArrow),this._keyboardNavigationHandlers[e.downArrow]=b(e.downArrow),this._keyboardNavigationHandlers[e.leftArrow]=b(e.leftArrow),this._keyboardNavigationHandlers[e.rightArrow]=b(e.rightArrow),this._keyboardNavigationHandlers[e.pageUp]=b(e.pageUp,!0),this._keyboardNavigationHandlers[e.pageDown]=b(e.pageDown,!0),this._keyboardNavigationHandlers[e.home]=function(a){return f.wrap(!d.site._header||a.type!==h.ObjectType.groupHeader&&a.type!==h.ObjectType.footer?{type:a.type!==h.ObjectType.footer?a.type:h.ObjectType.groupHeader,index:0}:{type:h.ObjectType.header,index:0})},this._keyboardNavigationHandlers[e.end]=function(a){if(!d.site._footer||a.type!==h.ObjectType.groupHeader&&a.type!==h.ObjectType.header){if(a.type===h.ObjectType.groupHeader||a.type===h.ObjectType.header)return f.wrap({type:h.ObjectType.groupHeader,index:c._groups.length()-1});var b=d.site._view.lastItemIndex();return b>=0?f.wrap({type:a.type,index:b}):f.cancel}return f.wrap({type:h.ObjectType.footer,index:0})},this._keyboardAcceleratorHandlers[e.a]=function(){d.site._multiSelection()&&d._selectAll()}},staticMode:function(){return this.site._tap===h.TapBehavior.none&&this.site._selectionMode===h.SelectionMode.none},itemUnrealized:function(a,b){if(this._pressedEntity.type!==h.ObjectType.groupHeader&&(this._pressedEntity.index===a&&this._resetPointerDownState(),this._itemBeingDragged(a)))for(var c=this._draggedItemBoxes.length-1;c>=0;c--)this._draggedItemBoxes[c]===b&&(g.removeClass(b,i._dragSourceClass),this._draggedItemBoxes.splice(c,1))},_fireInvokeEvent:function(a,c){function d(d,f){var g=d.createListBinding(),h=g.fromIndex(a.index),i=f?"groupheaderinvoked":"iteminvoked";h.done(function(){g.release()});var j=b.document.createEvent("CustomEvent");j.initCustomEvent(i,!0,!0,f?{groupHeaderPromise:h,groupHeaderIndex:a.index}:{itemPromise:h,itemIndex:a.index}),c.dispatchEvent(j)&&e.site._defaultInvoke(a)}if(c){var e=this;a.type===h.ObjectType.groupHeader?this.site._groupHeaderTap===h.GroupHeaderTapBehavior.invoke&&a.index!==i._INVALID_INDEX&&d(this.site.groupDataSource,!0):this.site._tap===h.TapBehavior.none||a.index===i._INVALID_INDEX||this.site._isInSelectionMode()||d(this.site.itemDataSource,!1)}},_verifySelectionAllowed:function(a){if(a.type===h.ObjectType.groupHeader)return{canSelect:!1,canTapSelect:!1};var c=a.index,d=this.site,e=this.site._view.items.itemAt(c);if(!d._selectionAllowed()||!d._selectOnTap()||e&&g.hasClass(e,i._nonSelectableClass))return{canSelect:!1,canTapSelect:!1};var j=d._selection._isIncluded(c),k=!d._multiSelection(),l=d._selection._cloneSelection();j?k?l.clear():l.remove(c):k?l.set(c):l.add(c);var m,n=b.document.createEvent("CustomEvent"),o=f.wrap(),p=!1,q=!1;n.initCustomEvent("selectionchanging",!0,!0,{newSelection:l,preventTapBehavior:function(){q=!0},setPromise:function(a){o=a}});var r=d._element.dispatchEvent(n);o.then(function(){p=!0,m=l._isIncluded(c),l.clear()});var s=r&&p&&(j||m);return{canSelect:s,canTapSelect:s&&!q}},_containedInElementWithClass:function(a,b){if(a.parentNode)for(var c=a.parentNode.querySelectorAll("."+b+", ."+b+" *"),d=0,e=c.length;e>d;d++)if(c[d]===a)return!0;return!1},_isDraggable:function(a){return!this._containedInElementWithClass(a,i._nonDraggableClass)},_isInteractive:function(a){return this._containedInElementWithClass(a,"win-interactive")},_resetPointerDownState:function(){this._itemEventsHandler.resetPointerDownState()},onPointerDown:function(a){this._itemEventsHandler.onPointerDown(a)},onclick:function(a){this._itemEventsHandler.onClick(a)},onPointerUp:function(a){this._itemEventsHandler.onPointerUp(a)},onPointerCancel:function(a){this._itemEventsHandler.onPointerCancel(a)},onLostPointerCapture:function(a){this._itemEventsHandler.onLostPointerCapture(a)},onContextMenu:function(a){this._itemEventsHandler.onContextMenu(a)},onMSHoldVisual:function(a){this._itemEventsHandler.onMSHoldVisual(a)},onDataChanged:function(a){this._itemEventsHandler.onDataChanged(a)},_removeTransform:function(a,b){b&&-1!==a.style[l].indexOf(b)&&(a.style[l]=a.style[l].replace(b,""))},_selectAll:function(){var a=[];this.site._view.items.each(function(b,c){c&&g.hasClass(c,i._nonSelectableClass)&&a.push(b)}),this.site._selection.selectAll(),a.length>0&&this.site._selection.remove(a)},_selectRange:function(a,b,c){for(var d=[],e=-1,f=a;b>=f;f++){var h=this.site._view.items.itemAt(f);h&&g.hasClass(h,i._nonSelectableClass)?-1!==e&&(d.push({firstIndex:e,lastIndex:f-1}),e=-1):-1===e&&(e=f)}-1!==e&&d.push({firstIndex:e,lastIndex:b}),d.length>0&&this.site._selection[c?"add":"set"](d)},onDragStart:function(a){if(this._pressedEntity={type:h.ObjectType.item,index:this.site._view.items.index(a.target)},this.site._selection._pivot=i._INVALID_INDEX,this._pressedEntity.index===i._INVALID_INDEX||!this.site.itemsDraggable&&!this.site.itemsReorderable||this.site._view.animating||!this._isDraggable(a.target)||this._pressedElement&&this._isInteractive(this._pressedElement))a.preventDefault();else{this._dragging=!0,this._dragDataTransfer=a.dataTransfer,this._pressedPosition=g._getCursorPos(a),this._dragInfo=null,this._lastEnteredElement=a.target,this.site._selection._isIncluded(this._pressedEntity.index)?this._dragInfo=this.site.selection:(this._draggingUnselectedItem=!0,this._dragInfo=new k._Selection(this.site,[{firstIndex:this._pressedEntity.index,lastIndex:this._pressedEntity.index}]));var c=this.site.itemsReorderable,e=b.document.createEvent("CustomEvent");if(e.initCustomEvent("itemdragstart",!0,!1,{dataTransfer:a.dataTransfer,dragInfo:this._dragInfo}),a.dataTransfer.setData("text",""),a.dataTransfer.setDragImage){var f=this.site._view.items.itemDataAt(this._pressedEntity.index);if(f&&f.container){var j=f.container.getBoundingClientRect();a.dataTransfer.setDragImage(f.container,a.clientX-j.left,a.clientY-j.top)}}this.site.element.dispatchEvent(e),this.site.itemsDraggable&&!this.site.itemsReorderable&&(this._firedDragEnter||this._fireDragEnterEvent(a.dataTransfer)&&(c=!0,this._dragUnderstood=!0)),c&&(this._addedDragOverClass=!0,g.addClass(this.site._element,i._dragOverClass)),this._draggedItemBoxes=[];var l=this,m=a.target;m.addEventListener("dragend",function n(a){m.removeEventListener("dragend",n),l.onDragEnd(a)}),d._yieldForDomModification(function(){if(l._dragging)for(var a=l._dragInfo.getIndices(),b=0,c=a.length;c>b;b++){var d=l.site._view.items.itemDataAt(a[b]);d&&d.itemBox&&l._addDragSourceClass(d.itemBox)}})}},onDragEnter:function(a){var c=this._dragUnderstood;this._lastEnteredElement=a.target,this._exitEventTimer&&(b.clearTimeout(this._exitEventTimer),this._exitEventTimer=0),this._firedDragEnter||this._fireDragEnterEvent(a.dataTransfer)&&(c=!0),(c||this._dragging&&this.site.itemsReorderable)&&(a.preventDefault(),this._dragUnderstood=!0,this._addedDragOverClass||(this._addedDragOverClass=!0,g.addClass(this.site._element,i._dragOverClass))),this._pointerLeftRegion=!1},onDragLeave:function(a){a.target===this._lastEnteredElement&&(this._pointerLeftRegion=!0,this._handleExitEvent())},fireDragUpdateEvent:function(){var a=b.document.createEvent("CustomEvent");a.initCustomEvent("itemdragchanged",!0,!1,{dataTransfer:this._dragDataTransfer,dragInfo:this._dragInfo}),this.site.element.dispatchEvent(a)},_fireDragEnterEvent:function(a){var c=b.document.createEvent("CustomEvent");c.initCustomEvent("itemdragenter",!0,!0,{dataTransfer:a});var d=!this.site.element.dispatchEvent(c);return this._firedDragEnter=!0,d},_fireDragBetweenEvent:function(a,c,d){var e=b.document.createEvent("CustomEvent");return e.initCustomEvent("itemdragbetween",!0,!0,{index:a,insertAfterIndex:c,dataTransfer:d}),this.site.element.dispatchEvent(e)},_fireDropEvent:function(a,c,d){var e=b.document.createEvent("CustomEvent");return e.initCustomEvent("itemdragdrop",!0,!0,{index:a,insertAfterIndex:c,dataTransfer:d}),this.site.element.dispatchEvent(e)},_handleExitEvent:function(){this._exitEventTimer&&(b.clearTimeout(this._exitEventTimer),this._exitEventTimer=0);var a=this;this._exitEventTimer=b.setTimeout(function(){if(!a.site._disposed&&a._pointerLeftRegion){if(a.site._layout.dragLeave&&a.site._layout.dragLeave(),a._pointerLeftRegion=!1,a._dragUnderstood=!1,a._lastEnteredElement=null,a._lastInsertPoint=null,a._dragBetweenDisabled=!1,a._firedDragEnter){var c=b.document.createEvent("CustomEvent");c.initCustomEvent("itemdragleave",!0,!1,{}),a.site.element.dispatchEvent(c),a._firedDragEnter=!1}a._addedDragOverClass&&(a._addedDragOverClass=!1,g.removeClass(a.site._element,i._dragOverClass)),a._exitEventTimer=0,a._stopAutoScroll()}},40)},_getEventPositionInElementSpace:function(a,b){var c={left:0,top:0};try{c=a.getBoundingClientRect()}catch(d){}var e=g._getComputedStyle(a,null),f=parseInt(e.paddingLeft),h=parseInt(e.paddingTop),i=parseInt(e.borderLeftWidth),j=parseInt(e.borderTopWidth),k=b.clientX,l=b.clientY,m={x:+k===k?k-c.left-f-i:0,y:+l===l?l-c.top-h-j:0};return this.site._rtl()&&(m.x=c.right-c.left-m.x),m},_getPositionInCanvasSpace:function(a){var b=this.site._horizontal()?this.site.scrollPosition:0,c=this.site._horizontal()?0:this.site.scrollPosition,d=this._getEventPositionInElementSpace(this.site.element,a);return{x:d.x+b,y:d.y+c}},_itemBeingDragged:function(a){return this._dragging?this._draggingUnselectedItem&&this._dragInfo._isIncluded(a)||!this._draggingUnselectedItem&&this.site._isSelected(a):!1},_addDragSourceClass:function(a){this._draggedItemBoxes.push(a),g.addClass(a,i._dragSourceClass),a.parentNode&&g.addClass(a.parentNode,i._footprintClass)},renderDragSourceOnRealizedItem:function(a,b){this._itemBeingDragged(a)&&this._addDragSourceClass(b)},onDragOver:function(b){if(this._dragUnderstood){this._pointerLeftRegion=!1,b.preventDefault();var c=this._getPositionInCanvasSpace(b),d=this._getEventPositionInElementSpace(this.site.element,b);if(this._checkAutoScroll(d.x,d.y),this.site._layout.hitTest)if(this._autoScrollFrame)this._lastInsertPoint&&(this.site._layout.dragLeave(),this._lastInsertPoint=null);else{var e=this.site._view.hitTest(c.x,c.y);e.insertAfterIndex=a(-1,this.site._cachedCount-1,e.insertAfterIndex),this._lastInsertPoint&&this._lastInsertPoint.insertAfterIndex===e.insertAfterIndex&&this._lastInsertPoint.index===e.index||(this._dragBetweenDisabled=!this._fireDragBetweenEvent(e.index,e.insertAfterIndex,b.dataTransfer),this._dragBetweenDisabled?this.site._layout.dragLeave():this.site._layout.dragOver(c.x,c.y,this._dragInfo)),this._lastInsertPoint=e}}},_clearDragProperties:function(){if(this._addedDragOverClass&&(this._addedDragOverClass=!1,g.removeClass(this.site._element,i._dragOverClass)),this._draggedItemBoxes){for(var a=0,b=this._draggedItemBoxes.length;b>a;a++)g.removeClass(this._draggedItemBoxes[a],i._dragSourceClass),this._draggedItemBoxes[a].parentNode&&g.removeClass(this._draggedItemBoxes[a].parentNode,i._footprintClass);this._draggedItemBoxes=[]}this.site._layout.dragLeave(),this._dragging=!1,this._dragInfo=null,this._draggingUnselectedItem=!1,this._dragDataTransfer=null,this._lastInsertPoint=null,this._resetPointerDownState(),this._lastEnteredElement=null,this._dragBetweenDisabled=!1,this._firedDragEnter=!1,this._dragUnderstood=!1,this._stopAutoScroll()},onDragEnd:function(){var a=b.document.createEvent("CustomEvent");a.initCustomEvent("itemdragend",!0,!1,{}),this.site.element.dispatchEvent(a),this._clearDragProperties()},_findFirstAvailableInsertPoint:function(a,b,c){for(var d=a.getIndices(),e=-1,f=this.site._cachedCount,g=d.length,h=-1,i=b,j=0;g>j;j++)if(d[j]===i){e=j,h=j;break}for(;e>=0&&i>=0;)c?(i++,g>e&&d[e+1]===i&&f>i?e++:i>=f?(c=!1,i=b,e=h):e=-1):(i--,e>0&&d[e-1]===i?e--:e=-1);return i},_reorderItems:function(a,b,c,d,e){var f=this.site,g=function(a){c?f._selection.remove({key:a[0].key}):f._selection.set({firstKey:a[0].key,lastKey:a[a.length-1].key}),e&&f.ensureVisible(f._selection._getFocused())};b.getItems().then(function(b){var c=f.itemDataSource;if(-1===a){c.beginEdits();for(var e=b.length-1;e>=0;e--)c.moveToStart(b[e].key);c.endEdits(),g(b)}else{var h=c.createListBinding();h.fromIndex(a).then(function(a){if(h.release(),c.beginEdits(),d)for(var e=0,f=b.length;f>e;e++)c.moveBefore(b[e].key,a.key);else for(var e=b.length-1;e>=0;e--)c.moveAfter(b[e].key,a.key);c.endEdits(),g(b)})}})},onDrop:function(b){if(this._draggedItemBoxes)for(var c=0,d=this._draggedItemBoxes.length;d>c;c++)this._draggedItemBoxes[c].parentNode&&g.removeClass(this._draggedItemBoxes[c].parentNode,i._footprintClass);if(!this._dragBetweenDisabled){var e=this._getPositionInCanvasSpace(b),f=this.site._view.hitTest(e.x,e.y),h=a(-1,this.site._cachedCount-1,f.insertAfterIndex),j=!0;if(this._lastInsertPoint&&this._lastInsertPoint.insertAfterIndex===h&&this._lastInsertPoint.index===f.index||(j=this._fireDragBetweenEvent(f.index,h,b.dataTransfer)),j&&(this._lastInsertPoint=null,this.site._layout.dragLeave(),this._fireDropEvent(f.index,h,b.dataTransfer)&&this._dragging&&this.site.itemsReorderable)){if(this._dragInfo.isEverything()||this.site._groupsEnabled())return;h=this._findFirstAvailableInsertPoint(this._dragInfo,h,!1),this._reorderItems(h,this._dragInfo,this._draggingUnselectedItem)}}this._clearDragProperties(),b.preventDefault()},_checkAutoScroll:function(a,c){var e=this.site._getViewportLength(),f=this.site._horizontal(),h=f?a:c,j=this.site._viewport[f?"scrollWidth":"scrollHeight"],k=Math.floor(this.site.scrollPosition),l=0;if(h<i._AUTOSCROLL_THRESHOLD?l=h-i._AUTOSCROLL_THRESHOLD:h>e-i._AUTOSCROLL_THRESHOLD&&(l=h-(e-i._AUTOSCROLL_THRESHOLD)),l=Math.round(l/i._AUTOSCROLL_THRESHOLD*(i._MAX_AUTOSCROLL_RATE-i._MIN_AUTOSCROLL_RATE)),(0===k&&0>l||k>=j-e&&l>0)&&(l=0),0===l)this._autoScrollDelay&&(b.clearTimeout(this._autoScrollDelay),this._autoScrollDelay=0);else if(!this._autoScrollDelay&&!this._autoScrollFrame){var m=this;this._autoScrollDelay=b.setTimeout(function(){if(m._autoScrollRate){m._lastDragTimeout=d._now();var a=function(){if(!m._autoScrollRate&&m._autoScrollFrame||m.site._disposed)m._stopAutoScroll();else{var b=d._now(),c=m._autoScrollRate*((b-m._lastDragTimeout)/1e3);c=0>c?Math.min(-1,c):Math.max(1,c);var e={};e[m.site._scrollProperty]=m.site._viewportScrollPosition+c,g.setScrollPosition(m.site._viewport,e),m._lastDragTimeout=b,m._autoScrollFrame=d._requestAnimationFrame(a)}};m._autoScrollFrame=d._requestAnimationFrame(a)}},i._AUTOSCROLL_DELAY)}this._autoScrollRate=l},_stopAutoScroll:function(){this._autoScrollDelay&&(b.clearTimeout(this._autoScrollDelay),this._autoScrollDelay=0),this._autoScrollRate=0,this._autoScrollFrame=0},onKeyDown:function(a){function b(a,b,g){function k(j){var k=!0,m=!1;if(g?a.index=Math.max(0,Math.min(j,a.index)):(a.index<0||a.index>j)&&(m=!0),!m&&(l.index!==a.index||l.type!==a.type)){var o=e(d._element,l,a);o&&(k=!1,c._setNewFocusItemOffsetPromise&&c._setNewFocusItemOffsetPromise.cancel(),d._batchViewUpdates(i._ViewChange.realize,i._ScrollToPriority.high,function(){return c._setNewFocusItemOffsetPromise=d._getItemOffset(l,!0).then(function(e){e=d._convertFromCanvasCoordinates(e);var g=e.end<=d.scrollPosition||e.begin>=d.scrollPosition+d._getViewportLength()-1;return c._setNewFocusItemOffsetPromise=d._getItemOffset(a).then(function(e){c._setNewFocusItemOffsetPromise=null;var h={position:d.scrollPosition,direction:"right"};return g&&(d._selection._setFocused(a,!0),e=d._convertFromCanvasCoordinates(e),a.index>l.index?(h.direction="right",h.position=e.end-d._getViewportLength()):(h.direction="left",h.position=e.begin)),d._changeFocus(a,b,n,g,!0),g?h:f.cancel},function(c){return d._changeFocus(a,b,n,!0,!0),f.wrapError(c)}),c._setNewFocusItemOffsetPromise},function(c){return d._changeFocus(a,b,n,!0,!0),f.wrapError(c)}),c._setNewFocusItemOffsetPromise},!0))}return k&&(d._selection._setFocused(l,!0),d.ensureVisible(l)),m?{type:h.ObjectType.item,index:i._INVALID_INDEX}:a}return a.type===h.ObjectType.item?f.wrap(j.lastItemIndex()).then(k):a.type===h.ObjectType.groupHeader?f.wrap(d._groups.length()-1).then(k):f.wrap(0).then(k)}var c=this,d=this.site,j=d._view,l=d._selection._getFocused(),m=!0,n=a.ctrlKey,o=g.Key,p=a.keyCode,q=d._rtl();if(!this._isInteractive(a.target)){if(a.ctrlKey&&!a.altKey&&!a.shiftKey&&this._keyboardAcceleratorHandlers[p]&&this._keyboardAcceleratorHandlers[p](),d.itemsReorderable&&!a.ctrlKey&&a.altKey&&a.shiftKey&&l.type===h.ObjectType.item&&(p===o.leftArrow||p===o.rightArrow||p===o.upArrow||p===o.downArrow)){var r=d._selection,s=l.index,t=!1,u=!0;if(!r.isEverything()){if(!r._isIncluded(s)){var v=d._view.items.itemAt(s);v&&g.hasClass(v,i._nonDraggableClass)?u=!1:(t=!0,r=new k._Selection(this.site,[{firstIndex:s,lastIndex:s}]))}if(u){var w=s;p===o.rightArrow?w+=q?-1:1:p===o.leftArrow?w+=q?1:-1:p===o.upArrow?w--:w++;var x=w>s,y=x;x&&w>=this.site._cachedCount&&(y=!1,w=this.site._cachedCount-1),w=this._findFirstAvailableInsertPoint(r,w,y),w=Math.min(Math.max(-1,w),this.site._cachedCount-1);var z=w-(x||-1===w?0:1),A=w,B=this.site._groupsEnabled();if(B){var C=this.site._groups,D=w>-1?C.groupFromItem(w):0;x?C.group(D).startIndex===w&&z--:D<C.length()-1&&w===C.group(D+1).startIndex-1&&z++}if(this._fireDragBetweenEvent(A,z,null)&&this._fireDropEvent(A,z,null)){if(B)return;this._reorderItems(w,r,t,!x,!0)}}}}else if(a.altKey)m=!1;else if(this._keyboardNavigationHandlers[p])this._keyboardNavigationHandlers[p](l).then(function(e){if(e.index!==l.index||e.type!==l.type){var f=c._keyboardNavigationHandlers[p].clampToBounds;e.type!==h.ObjectType.groupHeader&&a.shiftKey&&d._selectionAllowed()&&d._multiSelection()?(d._selection._pivot===i._INVALID_INDEX&&(d._selection._pivot=l.index),b(e,!0,f).then(function(b){if(b.index!==i._INVALID_INDEX){var e=Math.min(b.index,d._selection._pivot),f=Math.max(b.index,d._selection._pivot),g=a.ctrlKey||d._tap===h.TapBehavior.toggleSelect;c._selectRange(e,f,g)}})):(d._selection._pivot=i._INVALID_INDEX,b(e,!1,f))}else m=!1});else if(a.ctrlKey||p!==o.enter)l.type!==h.ObjectType.groupHeader&&(a.ctrlKey&&p===o.enter||p===o.space)?(this._itemEventsHandler.toggleSelectionIfAllowed(l.index),d._changeFocus(l,!0,n,!1,!0)):p===o.escape&&d._selection.count()>0?(d._selection._pivot=i._INVALID_INDEX,d._selection.clear()):m=!1;else{var E=l.type===h.ObjectType.groupHeader?d._groups.group(l.index).header:d._view.items.itemBoxAt(l.index);if(E){l.type===h.ObjectType.groupHeader?(this._pressedHeader=E,this._pressedItemBox=null,this._pressedContainer=null):(this._pressedItemBox=E,this._pressedContainer=d._view.items.containerAt(l.index),this._pressedHeader=null);var F=this._verifySelectionAllowed(l);F.canTapSelect&&this._itemEventsHandler.handleTap(l),this._fireInvokeEvent(l,E)}}this._keyDownHandled=m,m&&(a.stopPropagation(),a.preventDefault())}p===o.tab&&(this.site._keyboardFocusInbound=!0)},onKeyUp:function(a){this._keyDownHandled&&(a.stopPropagation(),a.preventDefault())},onTabEntered:function(a){if(0!==this.site._groups.length()||this.site._hasHeaderOrFooter){var b=this.site,c=b._selection._getFocused(),d=a.detail,f=!b._hasKeyboardFocus||a.target===b._viewport;if(f)if(this.inboundFocusHandled=!0,c.index=c.index===i._INVALID_INDEX?0:c.index,d||!this.site._supportsGroupHeaderKeyboarding&&!this.site._hasHeaderOrFooter){var g={type:h.ObjectType.item};c.type===h.ObjectType.groupHeader?(g.index=b._groupFocusCache.getIndexForGroup(c.index),e(b._element,c,g)?b._changeFocus(g,!0,!1,!1,!0):b._changeFocus(c,!0,!1,!1,!0)):(g.index=c.type!==h.ObjectType.item?b._groupFocusCache.getLastFocusedItemIndex():c.index,b._changeFocus(g,!0,!1,!1,!0)),a.preventDefault()}else{var g={type:h.ObjectType.groupHeader};this.site._hasHeaderOrFooter?this.site._lastFocusedElementInGroupTrack.type===h.ObjectType.groupHeader&&this.site._supportsGroupHeaderKeyboarding?(g.index=b._groups.groupFromItem(c.index),e(b._element,c,g)?b._changeFocus(g,!0,!1,!1,!0):b._changeFocus(c,!0,!1,!1,!0)):(g.type=this.site._lastFocusedElementInGroupTrack.type,g.index=0,b._changeFocus(g,!0,!1,!1,!0)):c.type!==h.ObjectType.groupHeader&&this.site._supportsGroupHeaderKeyboarding?(g.index=b._groups.groupFromItem(c.index),e(b._element,c,g)?b._changeFocus(g,!0,!1,!1,!0):b._changeFocus(c,!0,!1,!1,!0)):(g.index=c.index,b._changeFocus(g,!0,!1,!1,!0)),a.preventDefault()}}},onTabExiting:function(a){if(this.site._hasHeaderOrFooter||this.site._supportsGroupHeaderKeyboarding&&0!==this.site._groups.length()){var b=this.site,c=b._selection._getFocused(),d=a.detail;if(d){var f=null;if(c.type===h.ObjectType.item){var g=this.site._lastFocusedElementInGroupTrack.type;if(g!==h.ObjectType.header&&g!==h.ObjectType.footer&&this.site._supportsGroupHeaderKeyboarding)var f={type:h.ObjectType.groupHeader,index:b._groups.groupFromItem(c.index)};else var f={type:g===h.ObjectType.item?h.ObjectType.header:g,index:0}}f&&e(b._element,c,f)&&(b._changeFocus(f,!0,!1,!1,!0),a.preventDefault())}else if(!d&&c.type!==h.ObjectType.item){var i=0;i=c.type===h.ObjectType.groupHeader?b._groupFocusCache.getIndexForGroup(c.index):c.type===h.ObjectType.header?0:b._view.lastItemIndex();var f={type:h.ObjectType.item,index:i};e(b._element,c,f)&&(b._changeFocus(f,!0,!1,!1,!0),a.preventDefault())}}}});return m})})}),d("WinJS/Controls/ListView/_ErrorMessages",["exports","../../Core/_Base","../../Core/_Resources"],function(a,b){"use strict";b.Namespace._moduleDefine(a,null,{modeIsInvalid:{get:function(){return"Invalid argument: mode must be one of following values: 'none', 'single' or 'multi'."}},loadingBehaviorIsDeprecated:{get:function(){return"Invalid configuration: loadingBehavior is deprecated. The control will default this property to 'randomAccess'. Please refer to the 'ListView loading behaviors' SDK Sample for guidance on how to implement incremental load behavior."}},pagesToLoadIsDeprecated:{get:function(){return"Invalid configuration: pagesToLoad is deprecated. The control will not use this property. Please refer to the 'ListView loading behaviors' SDK Sample for guidance on how to implement incremental load behavior."}},pagesToLoadThresholdIsDeprecated:{get:function(){return"Invalid configuration: pagesToLoadThreshold is deprecated. The control will not use this property. Please refer to the 'ListView loading behaviors' SDK Sample for guidance on how to implement incremental load behavior."}},automaticallyLoadPagesIsDeprecated:{get:function(){return"Invalid configuration: automaticallyLoadPages is deprecated. The control will default this property to false. Please refer to the 'ListView loading behaviors' SDK Sample for guidance on how to implement incremental load behavior."}},invalidTemplate:{get:function(){return"Invalid template: Templates must be created before being passed to the ListView, and must contain a valid tree of elements."}},loadMorePagesIsDeprecated:{get:function(){return"loadMorePages is deprecated. Invoking this function will not have any effect. Please refer to the 'ListView loading behaviors' SDK Sample for guidance on how to implement incremental load behavior."}},disableBackdropIsDeprecated:{get:function(){return"Invalid configuration: disableBackdrop is deprecated. Style: .win-listview .win-container.win-backdrop { background-color:transparent; } instead."}},backdropColorIsDeprecated:{get:function(){return"Invalid configuration: backdropColor is deprecated. Style: .win-listview .win-container.win-backdrop { rgba(155,155,155,0.23); } instead."}},itemInfoIsDeprecated:{get:function(){return"GridLayout.itemInfo may be altered or unavailable in future versions. Instead, use CellSpanningLayout."}},groupInfoIsDeprecated:{get:function(){return"GridLayout.groupInfo may be altered or unavailable in future versions. Instead, use CellSpanningLayout."}},resetItemIsDeprecated:{get:function(){return"resetItem may be altered or unavailable in future versions. Instead, mark the element as disposable using WinJS.Utilities.markDisposable."}},resetGroupHeaderIsDeprecated:{get:function(){return"resetGroupHeader may be altered or unavailable in future versions. Instead, mark the header element as disposable using WinJS.Utilities.markDisposable."}},maxRowsIsDeprecated:{get:function(){return"GridLayout.maxRows may be altered or unavailable in future versions. Instead, use the maximumRowsOrColumns property."}},swipeOrientationDeprecated:{get:function(){return"Invalid configuration: swipeOrientation is deprecated. The control will default this property to 'none'"}},swipeBehaviorDeprecated:{get:function(){return"Invalid configuration: swipeBehavior is deprecated. The control will default this property to 'none'"}}})}),d("WinJS/Controls/ListView/_GroupFocusCache",["exports","../../Core/_Base"],function(a,b){"use strict";b.Namespace._moduleDefine(a,"WinJS.UI",{_GroupFocusCache:b.Namespace._lazy(function(){return b.Class.define(function(a){this._listView=a,this.clear()},{updateCache:function(a,b,c){this._lastFocusedItemKey=b,this._lastFocusedItemIndex=c,c=""+c,this._itemToIndex[b]=c,this._groupToItem[a]=b},deleteItem:function(a){if(a===this._lastFocusedItemKey&&(this._lastFocusedItemKey=null,this._lastFocusedItemIndex=0),this._itemToIndex[a])for(var b=this,c=Object.keys(this._groupToItem),d=0,e=c.length;e>d;d++){var f=c[d];if(b._groupToItem[f]===a){b.deleteGroup(f);break}}},deleteGroup:function(a){var b=this._groupToItem[a];b&&delete this._itemToIndex[b],delete this._groupToItem[a]},updateItemIndex:function(a,b){a===this._lastFocusedItemKey&&(this._lastFocusedItemIndex=b),this._itemToIndex[a]&&(this._itemToIndex[a]=""+b)},getIndexForGroup:function(a){var b=this._listView._groups.group(a).key,c=this._groupToItem[b];return c&&this._itemToIndex[c]?+this._itemToIndex[c]:this._listView._groups.fromKey(b).group.startIndex},clear:function(){this._groupToItem={},this._itemToIndex={},this._lastFocusedItemIndex=0,this._lastFocusedItemKey=null},getLastFocusedItemIndex:function(){return this._lastFocusedItemIndex}})}),_UnsupportedGroupFocusCache:b.Namespace._lazy(function(){return b.Class.define(null,{updateCache:function(a,b,c){this._lastFocusedItemKey=b,this._lastFocusedItemIndex=c},deleteItem:function(a){a===this._lastFocusedItemKey&&(this._lastFocusedItemKey=null,this._lastFocusedItemIndex=0)},deleteGroup:function(){},updateItemIndex:function(a,b){a===this._lastFocusedItemKey&&(this._lastFocusedItemIndex=b)},getIndexForGroup:function(){return 0},clear:function(){this._lastFocusedItemIndex=0,this._lastFocusedItemKey=null},getLastFocusedItemIndex:function(){return this._lastFocusedItemIndex}})})})}),d("WinJS/Controls/ListView/_GroupsContainer",["exports","../../Core/_Base","../../Promise","../../Utilities/_Dispose","../../Utilities/_ElementUtilities","../../Utilities/_ItemsManager","../../Utilities/_UI","../ItemContainer/_Constants"],function(a,b,c,d,e,f,g,h){"use strict";b.Namespace._moduleDefine(a,"WinJS.UI",{_GroupsContainerBase:b.Namespace._lazy(function(){return b.Class.define(function(){},{index:function(a){var b=this.headerFrom(a);if(b)for(var c=0,d=this.groups.length;d>c;c++)if(b===this.groups[c].header)return c;return h._INVALID_INDEX},headerFrom:function(a){for(;a&&!e.hasClass(a,h._headerClass);)a=a.parentNode;return a},requestHeader:function(a){this._waitingHeaderRequests=this._waitingHeaderRequests||{},this._waitingHeaderRequests[a]||(this._waitingHeaderRequests[a]=[]);var b=this;return new c(function(c){var d=b.groups[a];d&&d.header?c(d.header):b._waitingHeaderRequests[a].push(c)})},notify:function(a,b){if(this._waitingHeaderRequests&&this._waitingHeaderRequests[a]){for(var c=this._waitingHeaderRequests[a],d=0,e=c.length;e>d;d++)c[d](b);this._waitingHeaderRequests[a]=[]}},groupFromImpl:function(a,b,c){if(a>b)return null;var d=a+Math.floor((b-a)/2),e=this.groups[d];return c(e,d)?this.groupFromImpl(a,d-1,c):b>d&&!c(this.groups[d+1],d+1)?this.groupFromImpl(d+1,b,c):d},groupFrom:function(a){if(this.groups.length>0){var b=this.groups.length-1,c=this.groups[b];return a(c,b)?this.groupFromImpl(0,this.groups.length-1,a):b}return null},groupFromItem:function(a){return this.groupFrom(function(b){return a<b.startIndex})},groupFromOffset:function(a){return this.groupFrom(function(b){return a<b.offset})},group:function(a){return this.groups[a]},length:function(){return this.groups.length},cleanUp:function(){if(this.listBinding){for(var a=0,b=this.groups.length;b>a;a++){var c=this.groups[a];c.userData&&this.listBinding.releaseItem(c.userData)}this.listBinding.release()}},_dispose:function(){this.cleanUp()},synchronizeGroups:function(){var a=this;return this.pendingChanges=[],this.ignoreChanges=!0,this.groupDataSource.invalidateAll().then(function(){return c.join(a.pendingChanges)}).then(function(){return a._listView._ifZombieDispose()?c.cancel:void 0}).then(function(){a.ignoreChanges=!1},function(b){return a.ignoreChanges=!1,c.wrapError(b)})},fromKey:function(a){for(var b=0,c=this.groups.length;c>b;b++){var d=this.groups[b];if(d.key===a)return{group:d,index:b}}return null},fromHandle:function(a){for(var b=0,c=this.groups.length;c>b;b++){var d=this.groups[b];if(d.handle===a)return{group:d,index:b}}return null}})}),_UnvirtualizedGroupsContainer:b.Namespace._lazy(function(){return b.Class.derive(a._GroupsContainerBase,function(a,b){this._listView=a,this.groupDataSource=b,this.groups=[],this.pendingChanges=[],this.dirty=!0;var c=this,f={beginNotifications:function(){c._listView._versionManager.beginNotifications()},endNotifications:function(){c._listView._versionManager.endNotifications(),c._listView._ifZombieDispose()||!c.ignoreChanges&&c._listView._groupsChanged&&c._listView._scheduleUpdate()},indexChanged:function(){c._listView._versionManager.receivedNotification(),c._listView._ifZombieDispose()||this.scheduleUpdate()},itemAvailable:function(){},countChanged:function(a){c._listView._versionManager.receivedNotification(),c._listView._writeProfilerMark("groupCountChanged("+a+"),info"),c._listView._ifZombieDispose()||this.scheduleUpdate()},changed:function(a){if(c._listView._versionManager.receivedNotification(),!c._listView._ifZombieDispose()){var b=c.fromKey(a.key);b&&(c._listView._writeProfilerMark("groupChanged("+b.index+"),info"),b.group.userData=a,b.group.startIndex=a.firstItemIndexHint,this.markToRemove(b.group)),this.scheduleUpdate()}},removed:function(a){if(c._listView._versionManager.receivedNotification(),c._listView._groupRemoved(a),!c._listView._ifZombieDispose()){var b=c.fromHandle(a); if(b){c._listView._writeProfilerMark("groupRemoved("+b.index+"),info"),c.groups.splice(b.index,1);var d=c.groups.indexOf(b.group,b.index);d>-1&&c.groups.splice(d,1),this.markToRemove(b.group)}this.scheduleUpdate()}},inserted:function(a,b,d){if(c._listView._versionManager.receivedNotification(),!c._listView._ifZombieDispose()){c._listView._writeProfilerMark("groupInserted,info");var e=this;a.retain().then(function(f){var g;if(g=b||d||c.groups.length?e.findIndex(b,d):0,-1!==g){var h={key:f.key,startIndex:f.firstItemIndexHint,userData:f,handle:a.handle};c.groups.splice(g,0,h)}e.scheduleUpdate()}),c.pendingChanges.push(a)}},moved:function(a,b,d){if(c._listView._versionManager.receivedNotification(),!c._listView._ifZombieDispose()){c._listView._writeProfilerMark("groupMoved,info");var e=this;a.then(function(f){var g=e.findIndex(b,d),h=c.fromKey(f.key);if(h)c.groups.splice(h.index,1),-1!==g&&(h.index<g&&g--,h.group.key=f.key,h.group.userData=f,h.group.startIndex=f.firstItemIndexHint,c.groups.splice(g,0,h.group));else if(-1!==g){var i={key:f.key,startIndex:f.firstItemIndexHint,userData:f,handle:a.handle};c.groups.splice(g,0,i),a.retain()}e.scheduleUpdate()}),c.pendingChanges.push(a)}},reload:function(){c._listView._versionManager.receivedNotification(),c._listView._ifZombieDispose()||c._listView._processReload()},markToRemove:function(a){if(a.header){var b=a.header;a.header=null,a.left=-1,a.width=-1,a.decorator=null,a.tabIndex=-1,b.tabIndex=-1,c._listView._groupsToRemove[e._uniqueID(b)]={group:a,header:b}}},scheduleUpdate:function(){c.dirty=!0,c.ignoreChanges||(c._listView._groupsChanged=!0)},findIndex:function(a,b){var d,e=-1;return a&&(d=c.fromHandle(a),d&&(e=d.index+1)),-1===e&&b&&(d=c.fromHandle(b),d&&(e=d.index)),e},removeElements:function(a){if(a.header){var b=a.header.parentNode;b&&(d.disposeSubTree(a.header),b.removeChild(a.header)),a.header=null,a.left=-1,a.width=-1}}};this.listBinding=this.groupDataSource.createListBinding(f)},{initialize:function(){this.initializePromise&&this.initializePromise.cancel(),this._listView._writeProfilerMark("GroupsContainer_initialize,StartTM");var a=this;return this.initializePromise=this.groupDataSource.getCount().then(function(b){for(var d=[],e=0;b>e;e++)d.push(a.listBinding.fromIndex(e).retain());return c.join(d)}).then(function(b){a.groups=[];for(var c=0,d=b.length;d>c;c++){var e=b[c];a.groups.push({key:e.key,startIndex:e.firstItemIndexHint,handle:e.handle,userData:e})}a._listView._writeProfilerMark("GroupsContainer_initialize groups("+b.length+"),info"),a._listView._writeProfilerMark("GroupsContainer_initialize,StopTM")},function(b){return a._listView._writeProfilerMark("GroupsContainer_initialize,StopTM"),c.wrapError(b)}),this.initializePromise},renderGroup:function(a){if(this._listView.groupHeaderTemplate){var b=this.groups[a];return c.wrap(this._listView._groupHeaderRenderer(c.wrap(b.userData))).then(f._normalizeRendererReturn)}return c.wrap(null)},setDomElement:function(a,b){this.groups[a].header=b,this.notify(a,b)},removeElements:function(){for(var a=this._listView._groupsToRemove||{},b=Object.keys(a),c=!1,e=this._listView._selection._getFocused(),f=0,h=b.length;h>f;f++){var i=a[b[f]],j=i.header,k=i.group;if(c||e.type!==g.ObjectType.groupHeader||k.userData.index!==e.index||(this._listView._unsetFocusOnItem(),c=!0),j){var l=j.parentNode;l&&(d._disposeElement(j),l.removeChild(j))}}c&&this._listView._setFocusOnItem(e),this._listView._groupsToRemove={}},resetGroups:function(){for(var a=this.groups.slice(0),b=0,c=a.length;c>b;b++){var d=a[b];this.listBinding&&d.userData&&this.listBinding.releaseItem(d.userData)}this.groups.length=0,this.dirty=!0}})}),_NoGroups:b.Namespace._lazy(function(){return b.Class.derive(a._GroupsContainerBase,function(a){this._listView=a,this.groups=[{startIndex:0}],this.dirty=!0},{synchronizeGroups:function(){return c.wrap()},addItem:function(){return c.wrap(this.groups[0])},resetGroups:function(){this.groups=[{startIndex:0}],delete this.pinnedItem,delete this.pinnedOffset,this.dirty=!0},renderGroup:function(){return c.wrap(null)},ensureFirstGroup:function(){return c.wrap(this.groups[0])},groupOf:function(){return c.wrap(this.groups[0])},removeElements:function(){}})})})}),d("WinJS/Controls/ListView/_Helpers",["exports","../../Core/_Base","../ItemContainer/_Constants"],function(a,b,c){"use strict";function d(a){return Array.prototype.slice.call(a)}function e(a,b){if("string"==typeof a)return e([a],b);var c=new Array(Math.floor(b/a.length)+1).join(a.join(""));return c+=a.slice(0,b%a.length).join("")}function f(a,b){var d,f=c._containerEvenClass,g=c._containerOddClass,h=b%2===0?[f,g]:[g,f],i=["<div class='win-container "+h[0]+" win-backdrop'></div>","<div class='win-container "+h[1]+" win-backdrop'></div>"];return d=e(i,a)}b.Namespace._moduleDefine(a,"WinJS.UI",{_nodeListToArray:d,_repeat:e,_stripedContainers:f})}),d("WinJS/Controls/ListView/_ItemsContainer",["exports","../../Core/_Base","../../Promise","../../Utilities/_ElementUtilities","../ItemContainer/_Constants"],function(a,b,c,d,e){"use strict";b.Namespace._moduleDefine(a,"WinJS.UI",{_ItemsContainer:b.Namespace._lazy(function(){var a=function(a){this.site=a,this._itemData={},this.waitingItemRequests={}};return a.prototype={requestItem:function(a){this.waitingItemRequests[a]||(this.waitingItemRequests[a]=[]);var b=this,d=new c(function(c){var d=b._itemData[a];d&&!d.detached&&d.element?c(d.element):b.waitingItemRequests[a].push(c)});return d},removeItem:function(a){delete this._itemData[a]},removeItems:function(){this._itemData={},this.waitingItemRequests={}},setItemAt:function(a,b){this._itemData[a]=b,b.detached||this.notify(a,b)},notify:function(a,b){if(this.waitingItemRequests[a]){for(var c=this.waitingItemRequests[a],d=0;d<c.length;d++)c[d](b.element);this.waitingItemRequests[a]=[]}},elementAvailable:function(a){var b=this._itemData[a];b.detached=!1,this.notify(a,b)},itemAt:function(a){var b=this._itemData[a];return b?b.element:null},itemDataAt:function(a){return this._itemData[a]},containerAt:function(a){var b=this._itemData[a];return b?b.container:null},itemBoxAt:function(a){var b=this._itemData[a];return b?b.itemBox:null},itemBoxFrom:function(a){for(;a&&!d.hasClass(a,e._itemBoxClass);)a=a.parentNode;return a},containerFrom:function(a){for(;a&&!d.hasClass(a,e._containerClass);)a=a.parentNode;return a},index:function(a){var b=this.containerFrom(a);if(b)for(var c in this._itemData)if(this._itemData[c].container===b)return parseInt(c,10);return e._INVALID_INDEX},each:function(a){for(var b in this._itemData)if(this._itemData.hasOwnProperty(b)){var c=this._itemData[b];a(parseInt(b,10),c.element,c)}},eachIndex:function(a){for(var b in this._itemData)if(a(parseInt(b,10)))break},count:function(){return Object.keys(this._itemData).length}},a})})}),d("WinJS/Controls/ListView/_Layouts",["exports","../../Core/_Global","../../Core/_Base","../../Core/_BaseUtils","../../Core/_ErrorFromName","../../Core/_Resources","../../Core/_WriteProfilerMark","../../Animations/_TransitionAnimation","../../Promise","../../Scheduler","../../_Signal","../../Utilities/_Dispose","../../Utilities/_ElementUtilities","../../Utilities/_SafeHtml","../../Utilities/_UI","../ItemContainer/_Constants","./_ErrorMessages"],function(a,b,c,d,e,f,g,h,i,j,k,l,m,n,o,p,q){"use strict";function r(a){return"_win-dynamic-"+a+"-"+L++}function s(){var a,b,c,d=K.sheet.cssRules,e=M.length;for(a=0;e>a;a++)for(c="."+M[a]+" ",b=d.length-1;b>=0;b--)-1!==d[b].selectorText.indexOf(c)&&K.sheet.deleteRule(b);M=[]}function t(a,b,c,d){s();var e="."+p._listViewClass+" ."+a+" "+c+" { "+d+"}",f="_addDynamicCssRule:"+a+",info";b?b._writeProfilerMark(f):g("WinJS.UI.ListView:Layout"+f),K.sheet.insertRule(e,0)}function u(a){M.push(a)}function v(a,b,c){return Math.max(a,Math.min(b,c))}function w(a,b){return m.convertToPixels(a,m._getComputedStyle(a,null)[b])}function x(a,b){return w(b,"margin"+a)+w(b,"border"+a+"Width")+w(b,"padding"+a)}function y(a){return x("Top",a)+x("Bottom",a)}function z(a){return x("Left",a)+x("Right",a)}function A(a,b){if(a.items)for(var c=0,d=a.items.length;d>c;c++)b(a.items[c],c);else for(var e=0,f=0;e<a.itemsBlocks.length;e++)for(var g=a.itemsBlocks[e],c=0,d=g.items.length;d>c;c++)b(g.items[c],f++)}function B(a,b){if(0>b)return null;if(a.items)return b<a.items.length?a.items[b]:null;var c=a.itemsBlocks[0].items.length,d=Math.floor(b/c),e=b%c;return d<a.itemsBlocks.length&&e<a.itemsBlocks[d].items.length?a.itemsBlocks[d].items[e]:null}function C(a,b){for(var c,d=0,e=b.length;e>d;d++)if(b[d].itemsContainer.element===a){c=b[d].itemsContainer;break}return c}function D(a){var b,c;return a.itemsBlocks?(b=a.itemsBlocks.length,c=b>0?a.itemsBlocks[0].items.length*(b-1)+a.itemsBlocks[b-1].items.length:0):c=a.items.length,c}function E(a){if(!S){var c=b.document.createElement("div");c.style.width="500px",c.style.visibility="hidden";var d=b.document.createElement("div");d.style.cssText+="width: 500px; height: 200px; display: -webkit-flex; display: flex",n.setInnerHTMLUnsafe(d,"<div style='height: 100%; display: -webkit-flex; display: flex; flex-flow: column wrap; align-content: flex-start; -webkit-flex-flow: column wrap; -webkit-align-content: flex-start'><div style='width: 100px; height: 100px'></div><div style='width: 100px; height: 100px'></div><div style='width: 100px; height: 100px'></div></div>"),c.appendChild(d),a.viewport.insertBefore(c,a.viewport.firstChild);var e=c.offsetWidth>0,f=200;e&&(S={supportsCSSGrid:!!("-ms-grid-row"in b.document.documentElement.style),nestedFlexTooLarge:d.firstElementChild.offsetWidth>f,nestedFlexTooSmall:d.firstElementChild.offsetWidth<f}),a.readyToMeasure(),a.viewport.removeChild(c)}return S}function F(a){return i.is(a)?{realizedRangeComplete:a,layoutComplete:a}:"object"==typeof a&&a&&a.layoutComplete?a:{realizedRangeComplete:i.wrap(),layoutComplete:i.wrap()}}function G(a){return{left:w(a,"marginLeft"),right:w(a,"marginRight"),top:w(a,"marginTop"),bottom:w(a,"marginBottom")}}var H=m.Key,I=m._uniqueID,J={get itemInfoIsInvalid(){return"Invalid argument: An itemInfo function must be provided which returns an object with numeric width and height properties."},get groupInfoResultIsInvalid(){return"Invalid result: groupInfo result for cell spanning groups must include the following numeric properties: cellWidth and cellHeight."}},K=b.document.createElement("style");b.document.head.appendChild(K);var L=0,M=[],N=d._browserStyleEquivalents,O=N.transform,P=d._browserStyleEquivalents.transition.scriptName,Q=O.cssName+" cubic-bezier(0.1, 0.9, 0.2, 1) 167ms",R=12,S=null;c.Namespace._moduleDefine(a,"WinJS.UI",{Layout:c.Class.define(function(){}),_LayoutCommon:c.Namespace._lazy(function(){return c.Class.derive(a.Layout,null,{groupHeaderPosition:{enumerable:!0,get:function(){return this._groupHeaderPosition},set:function(a){this._groupHeaderPosition=a,this._invalidateLayout()}},initialize:function(a,b){a._writeProfilerMark("Layout:initialize,info"),this._inListMode||m.addClass(a.surface,p._gridLayoutClass),this._backdropColorClassName&&m.addClass(a.surface,this._backdropColorClassName),this._disableBackdropClassName&&m.addClass(a.surface,this._disableBackdropClassName),this._groups=[],this._groupMap={},this._oldGroupHeaderPosition=null,this._usingStructuralNodes=!1,this._site=a,this._groupsEnabled=b,this._resetAnimationCaches(!0)},orientation:{enumerable:!0,get:function(){return this._orientation},set:function(a){this._orientation=a,this._horizontal="horizontal"===a,this._invalidateLayout()}},uninitialize:function(){function a(a){var b,c=a.length;for(b=0;c>b;b++)a[b].cleanUp(!0)}var b="Layout:uninitialize,info";this._elementsToMeasure={},this._site?(this._site._writeProfilerMark(b),m.removeClass(this._site.surface,p._gridLayoutClass),m.removeClass(this._site.surface,p._headerPositionTopClass),m.removeClass(this._site.surface,p._headerPositionLeftClass),m.removeClass(this._site.surface,p._structuralNodesClass),m.removeClass(this._site.surface,p._singleItemsBlockClass),m.removeClass(this._site.surface,p._noCSSGrid),this._site.surface.style.cssText="",this._groups&&(a(this._groups),this._groups=null,this._groupMap=null),this._layoutPromise&&(this._layoutPromise.cancel(),this._layoutPromise=null),this._resetMeasurements(),this._oldGroupHeaderPosition=null,this._usingStructuralNodes=!1,this._envInfo=null,this._backdropColorClassName&&(m.removeClass(this._site.surface,this._backdropColorClassName),u(this._backdropColorClassName),this._backdropColorClassName=null),this._disableBackdropClassName&&(m.removeClass(this._site.surface,this._disableBackdropClassName),u(this._disableBackdropClassName),this._disableBackdropClassName=null),this._site=null,this._groupsEnabled=null,this._animationsRunning&&this._animationsRunning.cancel(),this._animatingItemsBlocks={}):g("WinJS.UI.ListView:"+b)},numberOfItemsPerItemsBlock:{get:function(){function b(){var a,b=c._site.groupCount;for(a=0;b>a;a++)if(c._isCellSpanning(a))return!1;return!0}var c=this;return c._measureItem(0).then(function(){return c._sizes.viewportContentSize!==c._getViewportCrossSize()&&c._viewportSizeChanged(c._getViewportCrossSize()),b()?c._envInfo.nestedFlexTooLarge||c._envInfo.nestedFlexTooSmall?(c._usingStructuralNodes=!0,Number.MAX_VALUE):(c._usingStructuralNodes=a._LayoutCommon._barsPerItemsBlock>0,a._LayoutCommon._barsPerItemsBlock*c._itemsPerBar):(c._usingStructuralNodes=!1,null)})}},layout:function(a,b,c,d){function e(a){function b(a){if(l._usingStructuralNodes){var b=[];return a.itemsBlocks.forEach(function(a){b=b.concat(a.items.slice(0))}),b}return a.items.slice(0)}return{element:a.element,items:b(a)}}function f(){function c(a,b){var c=a.enableCellSpanning?T.CellSpanningGroup:T.UniformGroup;return new c(l,b)}var d,f=l._groups.length>0?l._getRealizationRange():null,g=[],h=[],j={},k={},m=0,n=a.length;for(d=0;n>d;d++){var o=null,p=l._getGroupInfo(d),q=l._site.groupFromIndex(d).key,r=l._groupMap[q],s=r instanceof T.CellSpanningGroup,t=p.enableCellSpanning;if(r)if(s!==t)j[q]=!0;else{var u=Math.max(0,b.firstIndex-r.startIndex),v=l._rangeForGroup(r,f);v&&u<=v.lastIndex&&(o={firstIndex:Math.max(u,v.firstIndex),lastIndex:v.lastIndex})}var w,x=c(p,a[d].itemsContainer.element);w=x.prepareLayoutWithCopyOfTree?x.prepareLayoutWithCopyOfTree(e(a[d].itemsContainer),o,r,{groupInfo:p,startIndex:m}):x.prepareLayout(D(a[d].itemsContainer),o,r,{groupInfo:p,startIndex:m}),h.push(w),m+=x.count,g.push(x),k[q]=x}return i.join(h).then(function(){for(var a=0,b=0,c=g.length;c>b;b++){var d=g[b];d.offset=a,a+=l._getGroupSize(d)}Object.keys(l._groupMap).forEach(function(a){var b=!j[a];l._groupMap[a].cleanUp(b)}),l._groups=g,l._groupMap=k})}function g(a,c,d){var e,f=l._groups[a],g=Math.max(0,b.firstIndex-f.startIndex),h=l._rangeForGroup(f,c);return d?void f.layoutRealizedRange(g,h):(h||(e=f.startIndex+f.count-1<c.firstIndex),f.layoutUnrealizedRange(g,h,e))}function h(){if(0!==l._groups.length){var c,d=l._getRealizationRange(),e=a.length,f=n.groupIndexFromItemIndex(b.firstIndex);for(c=f;e>c;c++)g(c,d,!0),l._layoutGroup(c)}}function j(){if(0===l._groups.length)return i.wrap();var a=l._getRealizationRange(),c=n.groupIndexFromItemIndex(a.firstIndex-1),d=n.groupIndexFromItemIndex(a.lastIndex+1),e=n.groupIndexFromItemIndex(b.firstIndex),f=[],h=l._groups.length,j=!1,k=c,m=Math.max(e,d);for(m=Math.max(k+1,m);!j;)j=!0,k>=e&&(f.push(g(k,a,!1)),j=!1,k--),h>m&&(f.push(g(m,a,!1)),j=!1,m++);return i.join(f)}var k,l=this,n=l._site,o="Layout.layout",q=o+":realizedRange";return l._site._writeProfilerMark(o+",StartTM"),l._site._writeProfilerMark(q+",StartTM"),k=l._measureItem(0).then(function(){return m[l._usingStructuralNodes?"addClass":"removeClass"](l._site.surface,p._structuralNodesClass),m[l._envInfo.nestedFlexTooLarge||l._envInfo.nestedFlexTooSmall?"addClass":"removeClass"](l._site.surface,p._singleItemsBlockClass),l._sizes.viewportContentSize!==l._getViewportCrossSize()&&l._viewportSizeChanged(l._getViewportCrossSize()),l._cacheRemovedElements(c,l._cachedItemRecords,l._cachedInsertedItemRecords,l._cachedRemovedItems,!1),l._cacheRemovedElements(d,l._cachedHeaderRecords,l._cachedInsertedHeaderRecords,l._cachedRemovedHeaders,!0),f()}).then(function(){l._syncDomWithGroupHeaderPosition(a);var b=0;if(l._groups.length>0){var e=l._groups[l._groups.length-1];b=e.offset+l._getGroupSize(e)}l._horizontal?(l._groupsEnabled&&l._groupHeaderPosition===U.left?n.surface.style.cssText+=";height:"+l._sizes.surfaceContentSize+"px;-ms-grid-columns: ("+l._sizes.headerContainerWidth+"px auto)["+a.length+"]":n.surface.style.height=l._sizes.surfaceContentSize+"px",(l._envInfo.nestedFlexTooLarge||l._envInfo.nestedFlexTooSmall)&&(n.surface.style.width=b+"px")):(l._groupsEnabled&&l._groupHeaderPosition===U.top?n.surface.style.cssText+=";width:"+l._sizes.surfaceContentSize+"px;-ms-grid-rows: ("+l._sizes.headerContainerHeight+"px auto)["+a.length+"]":n.surface.style.width=l._sizes.surfaceContentSize+"px",(l._envInfo.nestedFlexTooLarge||l._envInfo.nestedFlexTooSmall)&&(n.surface.style.height=b+"px")),h(),l._layoutAnimations(c,d),l._site._writeProfilerMark(q+":complete,info"),l._site._writeProfilerMark(q+",StopTM")},function(a){return l._site._writeProfilerMark(q+":canceled,info"),l._site._writeProfilerMark(q+",StopTM"),i.wrapError(a)}),l._layoutPromise=k.then(function(){return j().then(function(){l._site._writeProfilerMark(o+":complete,info"),l._site._writeProfilerMark(o+",StopTM")},function(a){return l._site._writeProfilerMark(o+":canceled,info"),l._site._writeProfilerMark(o+",StopTM"),i.wrapError(a)})}),{realizedRangeComplete:k,layoutComplete:l._layoutPromise}},itemsFromRange:function(a,b){return this._rangeContainsItems(a,b)?{firstIndex:this._firstItemFromRange(a),lastIndex:this._lastItemFromRange(b)}:{firstIndex:0,lastIndex:-1}},getAdjacent:function(b,c){function d(){var a={type:b.type,index:b.index-g.startIndex},c=g.getAdjacent(a,h);if("boundary"===c){var d=e._groups[f-1],i=e._groups[f+1],j=e._groups.length-1;if(h===H.leftArrow){if(0===f)return b;if(d instanceof T.UniformGroup&&g instanceof T.UniformGroup){var k=e._indexToCoordinate(a.index),l=e._horizontal?k.row:k.column,m=Math.floor((d.count-1)/e._itemsPerBar),n=m*e._itemsPerBar;return{type:o.ObjectType.item,index:d.startIndex+Math.min(d.count-1,n+l)}}return{type:o.ObjectType.item,index:g.startIndex-1}}if(h===H.rightArrow){if(f===j)return b;if(g instanceof T.UniformGroup&&i instanceof T.UniformGroup){var k=e._indexToCoordinate(a.index),l=e._horizontal?k.row:k.column;return{type:o.ObjectType.item,index:i.startIndex+Math.min(i.count-1,l)}}return{type:o.ObjectType.item,index:i.startIndex}}return b}return c.index+=g.startIndex,c}var e=this,f=e._site.groupIndexFromItemIndex(b.index),g=e._groups[f],h=e._adjustedKeyForOrientationAndBars(e._adjustedKeyForRTL(c),g instanceof T.CellSpanningGroup);if(b.type||(b.type=o.ObjectType.item),b.type===o.ObjectType.item||c!==H.pageUp&&c!==H.pageDown){if(b.type===o.ObjectType.header&&h===H.rightArrow)return{type:e._groupsEnabled?o.ObjectType.groupHeader:o.ObjectType.footer,index:0};if(b.type===o.ObjectType.footer&&h===H.leftArrow)return{type:e._groupsEnabled?o.ObjectType.groupHeader:o.ObjectType.header,index:0};if(b.type===o.ObjectType.groupHeader){if(h===H.leftArrow){var i=b.index-1;return i=e._site.header?i:Math.max(0,i),{type:i>-1?o.ObjectType.groupHeader:o.ObjectType.header,index:i>-1?i:0}}if(h===H.rightArrow){var i=b.index+1;return i=e._site.header?i:Math.min(e._groups.length-1,b.index+1),{type:i>=e._groups.length?o.ObjectType.header:o.ObjectType.groupHeader,index:i>=e._groups.length?0:i}}return b}}else{var j=0;j=b.type===o.ObjectType.groupHeader?e._groups[b.index].startIndex:b.type===o.ObjectType.header?0:e._groups[e._groups.length-1].count-1,b={type:o.ObjectType.item,index:j}}switch(e._adjustedKeyForRTL(c)){case H.upArrow:case H.leftArrow:case H.downArrow:case H.rightArrow:return d();default:return a._LayoutCommon.prototype._getAdjacentForPageKeys.call(e,b,c)}},hitTest:function(a,b){var c,d=this._sizes;a-=d.layoutOriginX,b-=d.layoutOriginY;var e=this._groupFromOffset(this._horizontal?a:b),f=this._groups[e];return this._horizontal?a-=f.offset:b-=f.offset,this._groupsEnabled&&(this._groupHeaderPosition===U.left?a-=d.headerContainerWidth:b-=d.headerContainerHeight),c=f.hitTest(a,b),c.index+=f.startIndex,c.insertAfterIndex+=f.startIndex,c},setupAnimations:function(){if(0===this._groups.length)return void this._resetAnimationCaches();if(!Object.keys(this._cachedItemRecords).length){this._site._writeProfilerMark("Animation:setupAnimations,StartTM");for(var a=this._getRealizationRange(),b=this._site.tree,c=0,d="horizontal"===this.orientation,e=0,f=b.length;f>e;e++){var g=b[e],h=!1,i=this._groups[e],j=i instanceof T.CellSpanningGroup,k=i?i.offset:0;if(A(g.itemsContainer,function(b,d){if(a.firstIndex<=c&&a.lastIndex>=c&&(h=!0,!this._cachedItemRecords[c])){var f=this._getItemPositionForAnimations(c,e,d),g=f.row,i=f.column,k=f.left,l=f.top;this._cachedItemRecords[c]={oldRow:g,oldColumn:i,oldLeft:k,oldTop:l,width:f.width,height:f.height,element:b,inCellSpanningGroup:j}}c++}.bind(this)),h){var l=e;if(!this._cachedHeaderRecords[l]){var m=this._getHeaderPositionForAnimations(l);this._cachedHeaderRecords[l]={oldLeft:m.left,oldTop:m.top,width:m.width,height:m.height,element:g.header}}this._cachedGroupRecords[I(g.itemsContainer.element)]||(this._cachedGroupRecords[I(g.itemsContainer.element)]={oldLeft:d?k:0,left:d?k:0,oldTop:d?0:k,top:d?0:k,element:g.itemsContainer.element})}}this._site._writeProfilerMark("Animation:setupAnimations,StopTM")}},_layoutAnimations:function(a,b){if(Object.keys(this._cachedItemRecords).length||Object.keys(this._cachedGroupRecords).length||Object.keys(this._cachedHeaderRecords).length){this._site._writeProfilerMark("Animation:layoutAnimation,StartTM"),this._updateAnimationCache(a,b);for(var c=this._getRealizationRange(),d=this._site.tree,e=0,f="horizontal"===this.orientation,g=0,h=d.length;h>g;g++){var i=d[g],j=this._groups[g],k=j instanceof T.CellSpanningGroup,l=j?j.offset:0,n=0,o=0,q=this._cachedGroupRecords[I(i.itemsContainer.element)];q&&(f?n=q.oldLeft-l:o=q.oldTop-l),A(i.itemsContainer,function(a,b){if(c.firstIndex<=e&&c.lastIndex>=e){var d=this._cachedItemRecords[e];if(d){var f=this._getItemPositionForAnimations(e,g,b),h=f.row,i=f.column,j=f.left,l=f.top;if(d.inCellSpanningGroup=d.inCellSpanningGroup||k,d.oldRow!==h||d.oldColumn!==i||d.oldTop!==l||d.oldLeft!==j){d.row=h,d.column=i,d.left=j,d.top=l;var q=d.oldLeft-d.left-n,r=d.oldTop-d.top-o;if(q=(this._site.rtl?-1:1)*q,d.xOffset=q,d.yOffset=r,0!==q||0!==r){var s=d.element;d.needsToResetTransform=!0,s.style[P]="",s.style[O.scriptName]="translate("+q+"px,"+r+"px)"}var t=a.parentNode;m.hasClass(t,p._itemsBlockClass)&&(this._animatingItemsBlocks[I(t)]=t)}}else this._cachedInsertedItemRecords[e]=a,a.style[P]="",a.style.opacity=0}e++}.bind(this));var r=g,s=this._cachedHeaderRecords[r];if(s){var t=this._getHeaderPositionForAnimations(r);if(s.height=t.height,s.width=t.width,s.oldLeft!==t.left||s.oldTop!==t.top){s.left=t.left,s.top=t.top;var u=s.oldLeft-s.left,v=s.oldTop-s.top;if(u=(this._site.rtl?-1:1)*u,0!==u||0!==v){s.needsToResetTransform=!0;var w=s.element;w.style[P]="",w.style[O.scriptName]="translate("+u+"px,"+v+"px)"}}}if(q&&(f&&q.left!==l||!f&&q.top!==l)){var x=q.element;if(0===n&&0===o)q.needsToResetTransform&&(q.needsToResetTransform=!1,x.style[O.scriptName]="");else{var y=(this._site.rtl?-1:1)*n,z=o;q.needsToResetTransform=!0,x.style[P]="",x.style[O.scriptName]="translate("+y+"px, "+z+"px)"}}}if(this._inListMode||1===this._itemsPerBar)for(var B=Object.keys(this._animatingItemsBlocks),C=0,D=B.length;D>C;C++)this._animatingItemsBlocks[B[C]].style.overflow="visible";this._site._writeProfilerMark("Animation:layoutAnimation,StopTM")}},executeAnimations:function(){function b(){if(e(),H)f();else{if(bb._itemsPerBar>1)for(var a=bb._itemsPerBar*bb._sizes.containerCrossSize+bb._getHeaderSizeContentAdjustment()+bb._sizes.containerMargins[U?"top":v.rtl?"right":"left"]+(U?bb._sizes.layoutOriginY:bb._sizes.layoutOriginX),b=0,c=y.length;c>b;b++){var d=y[b];d[V]>d[W]?(N=Math.max(N,d[X]+d[U?"height":"width"]),R=Math.max(R,a-d[Y]),J=!0,T.push(d)):d[V]<d[W]&&(Q=Math.max(Q,a-d[X]),S=Math.max(S,d[Y]+d[U?"height":"width"]),T.push(d),J=!0)}v.rtl&&!U&&(N*=-1,R*=-1,Q*=-1,S*=-1),J?j(bb._itemsPerBar):q()}}function c(b){F=i.join(G),F.done(function(){G=[],t&&(a.Layout._debugAnimations?d._requestAnimationFrame(function(){b()}):b())})}function e(){if(x.length){v._writeProfilerMark("Animation:setupRemoveAnimation,StartTM"),B+=60,E+=60;var a=120;u&&(a*=10),G.push(h.executeTransition(x,[{property:"opacity",delay:A,duration:a,timing:"linear",to:0,skipStylesReset:!0}])),v._writeProfilerMark("Animation:setupRemoveAnimation,StopTM")}}function f(){v._writeProfilerMark("Animation:cellSpanningFadeOutMove,StartTM");for(var a=[],b=0,d=y.length;d>b;b++){var e=y[b],f=e.element;a.push(f)}for(var b=0,d=z.length;d>b;b++){var e=z[b],f=e.element;a.push(f)}var i=120;u&&(i*=10),G.push(h.executeTransition(a,{property:"opacity",delay:A,duration:i,timing:"linear",to:0})),c(g),v._writeProfilerMark("Animation:cellSpanningFadeOutMove,StopTM")}function g(){v._writeProfilerMark("Animation:cellSpanningFadeInMove,StartTM"),E=0;for(var a=[],b=0,c=y.length;c>b;b++){var d=y[b],e=d.element;e.style[O.scriptName]="",a.push(e)}for(var b=0,c=z.length;c>b;b++){var d=z[b],e=d.element;e.style[O.scriptName]="",a.push(e)}var f=120;u&&(f*=10),G.push(h.executeTransition(a,{property:"opacity",delay:E,duration:f,timing:"linear",to:1})),v._writeProfilerMark("Animation:cellSpanningFadeInMove,StopTM"),r()}function j(a){v._writeProfilerMark("Animation:setupReflowAnimation,StartTM");for(var b={},d=0,e=T.length;e>d;d++){var f=T[d],g=f.xOffset,i=f.yOffset;f[V]>f[W]?U?i-=N:g-=N:f[V]<f[W]&&(U?i+=Q:g+=Q);var j=f.element;K=Math.min(K,U?g:i),L=Math.max(L,U?g:i);var k=j.parentNode;m.hasClass(k,"win-itemscontainer")||(k=k.parentNode);var l=b[I(k)];if(!l){var n=D(C(k,v.tree));b[I(k)]=l=Math.ceil(n/a)-1}T[d][U?"column":"row"]===l&&(M[I(k)]=k);var q=80;u&&(q*=10),G.push(h.executeTransition(j,{property:O.cssName,delay:B,duration:q,timing:"cubic-bezier(0.1, 0.9, 0.2, 1)",to:"translate("+g+"px,"+i+"px)"}))}for(var r=Object.keys(M),d=0,e=r.length;e>d;d++){var s=M[r[d]];v.rtl&&U?(s.style.paddingLeft=-1*K+"px",s.style.marginLeft=K+"px"):(s.style[U?"paddingRight":"paddingBottom"]=L+"px",s.style[U?"marginRight":"marginBottom"]="-"+L+"px")}for(var t=Object.keys(Z),d=0,e=t.length;e>d;d++)Z[t[d]].classList.add(p._clipClass);c(o),v._writeProfilerMark("Animation:setupReflowAnimation,StopTM")}function n(){for(var a=Object.keys(M),b=0,c=a.length;c>b;b++){var d=M[a[b]];v.rtl&&U?(d.style.paddingLeft="",d.style.marginLeft=""):(d.style[U?"paddingRight":"paddingBottom"]="",d.style[U?"marginRight":"marginBottom"]="")}M={};for(var e=Object.keys(Z),b=0,c=e.length;c>b;b++){var f=Z[e[b]];f.style.overflow="",f.classList.remove(p._clipClass)}}function o(){v._writeProfilerMark("Animation:prepareReflowedItems,StartTM");for(var b=0,c=T.length;c>b;b++){var e=T[b],f=0,g=0;e[V]>e[W]?U?g=R:f=R:e[V]<e[W]&&(U?g=-1*S:f=-1*S),e.element.style[P]="",e.element.style[O.scriptName]="translate("+f+"px,"+g+"px)"}v._writeProfilerMark("Animation:prepareReflowedItems,StopTM"),a.Layout._debugAnimations?d._requestAnimationFrame(function(){q(!0)}):q(!0)}function q(a){var b=200;if(a&&(b=150,B=0,E=0),u&&(b*=10),y.length>0||z.length>0){v._writeProfilerMark("Animation:setupMoveAnimation,StartTM");for(var c=[],d=0,e=z.length;e>d;d++){var f=z[d].element;c.push(f)}for(var d=0,e=y.length;e>d;d++){var f=y[d].element;c.push(f)}G.push(h.executeTransition(c,{property:O.cssName,delay:B,duration:b,timing:"cubic-bezier(0.1, 0.9, 0.2, 1)",to:""})),E+=80,v._writeProfilerMark("Animation:setupMoveAnimation,StopTM")}r()}function r(){if(w.length>0){v._writeProfilerMark("Animation:setupInsertAnimation,StartTM");var a=120;u&&(a*=10),G.push(h.executeTransition(w,[{property:"opacity",delay:E,duration:a,timing:"linear",to:1}])),v._writeProfilerMark("Animation:setupInsertAnimation,StopTM")}c(s)}function s(){v._writeProfilerMark("Animation:cleanupAnimations,StartTM"),n();for(var a=0,b=x.length;b>a;a++){var c=x[a];c.parentNode&&(l._disposeElement(c),c.parentNode.removeChild(c))}v._writeProfilerMark("Animation:cleanupAnimations,StopTM"),bb._animationsRunning=null,t.complete()}var t=new k;if(this._filterInsertedElements(),this._filterMovedElements(),this._filterRemovedElements(),0===this._insertedElements.length&&0===this._removedElements.length&&0===this._itemMoveRecords.length&&0===this._moveRecords.length)return this._resetAnimationCaches(!0),t.complete(),t.promise;this._animationsRunning=t.promise;for(var u=a.Layout._debugAnimations||a.Layout._slowAnimations,v=this._site,w=this._insertedElements,x=this._removedElements,y=this._itemMoveRecords,z=this._moveRecords,A=0,B=0,E=0,F=null,G=[],H=!1,J=!1,K=0,L=0,M={},N=0,Q=0,R=0,S=0,T=[],U="horizontal"===this.orientation,V=U?"oldColumn":"oldRow",W=U?"column":"row",X=U?"oldTop":"oldLeft",Y=U?"top":"left",Z=this._animatingItemsBlocks,$=0,_=y.length;_>$;$++){var ab=y[$];if(ab.inCellSpanningGroup){H=!0;break}}var bb=this;return a.Layout._debugAnimations?d._requestAnimationFrame(function(){b()}):b(),this._resetAnimationCaches(!0),t.promise.then(null,function(){n();for(var a=0,b=z.length;b>a;a++){var c=z[a].element;c.style[O.scriptName]="",c.style.opacity=1}for(var a=0,b=y.length;b>a;a++){var c=y[a].element;c.style[O.scriptName]="",c.style.opacity=1}for(var a=0,b=w.length;b>a;a++)w[a].style.opacity=1;for(var a=0,b=x.length;b>a;a++){var c=x[a];c.parentNode&&(l._disposeElement(c),c.parentNode.removeChild(c))}this._animationsRunning=null,t=null,F&&F.cancel()}.bind(this)),t.promise},dragOver:function(a,b,c){var d=this.hitTest(a,b),e=this._groups?this._site.groupIndexFromItemIndex(d.index):0,f=this._site.tree[e].itemsContainer,g=D(f),h=this._groups?this._groups[e].startIndex:0,i=this._getVisibleRange();d.index-=h,d.insertAfterIndex-=h,i.firstIndex=Math.max(i.firstIndex-h-1,0),i.lastIndex=Math.min(i.lastIndex-h+1,g);var j=Math.max(Math.min(g-1,d.insertAfterIndex),-1),k=Math.min(j+1,g);if(c){for(var l=j;l>=i.firstIndex;l--){if(!c._isIncluded(l+h)){j=l;break}l===i.firstIndex&&(j=-1)}for(var l=k;l<i.lastIndex;l++){if(!c._isIncluded(l+h)){k=l;break}l===i.lastIndex-1&&(k=g)}}var m=B(f,k),n=B(f,j);if(this._animatedDragItems)for(var l=0,o=this._animatedDragItems.length;o>l;l++){var p=this._animatedDragItems[l];p&&(p.style[P]=this._site.animationsDisabled?"":Q,p.style[O.scriptName]="")}this._animatedDragItems=[];var q="horizontal"===this.orientation,r=this._inListMode||1===this._itemsPerBar;this._groups&&this._groups[e]instanceof T.CellSpanningGroup&&(r=1===this._groups[e]._slotsPerColumn);var s=0,t=0;!q&&!r||q&&r?s=this._site.rtl?-R:R:t=R,m&&(m.style[P]=this._site.animationsDisabled?"":Q,m.style[O.scriptName]="translate("+s+"px, "+t+"px)",this._animatedDragItems.push(m)),n&&(n.style[P]=this._site.animationsDisabled?"":Q,n.style[O.scriptName]="translate("+-s+"px, -"+t+"px)",this._animatedDragItems.push(n))},dragLeave:function(){if(this._animatedDragItems)for(var a=0,b=this._animatedDragItems.length;b>a;a++)this._animatedDragItems[a].style[P]=this._site.animationsDisabled?"":Q,this._animatedDragItems[a].style[O.scriptName]="";this._animatedDragItems=[]},_setMaxRowsOrColumns:function(a){a===this._maxRowsOrColumns||this._inListMode||(this._sizes&&this._sizes.containerSizeLoaded&&(this._itemsPerBar=Math.floor(this._sizes.maxItemsContainerContentSize/this._sizes.containerCrossSize),a&&(this._itemsPerBar=Math.min(this._itemsPerBar,a)),this._itemsPerBar=Math.max(1,this._itemsPerBar)),this._maxRowsOrColumns=a,this._invalidateLayout())},_getItemPosition:function(a){if(this._groupsEnabled){var b=Math.min(this._groups.length-1,this._site.groupIndexFromItemIndex(a)),c=this._groups[b],d=a-c.startIndex;return this._getItemPositionForAnimations(a,b,d)}return this._getItemPositionForAnimations(a,0,a)},_getRealizationRange:function(){var a=this._site.realizedRange;return{firstIndex:this._firstItemFromRange(a.firstPixel),lastIndex:this._lastItemFromRange(a.lastPixel)} },_getVisibleRange:function(){var a=this._site.visibleRange;return{firstIndex:this._firstItemFromRange(a.firstPixel),lastIndex:this._lastItemFromRange(a.lastPixel)}},_resetAnimationCaches:function(a){if(!a){this._resetStylesForRecords(this._cachedGroupRecords),this._resetStylesForRecords(this._cachedItemRecords),this._resetStylesForRecords(this._cachedHeaderRecords),this._resetStylesForInsertedRecords(this._cachedInsertedItemRecords),this._resetStylesForInsertedRecords(this._cachedInsertedHeaderRecords),this._resetStylesForRemovedRecords(this._cachedRemovedItems),this._resetStylesForRemovedRecords(this._cachedRemovedHeaders);for(var b=Object.keys(this._animatingItemsBlocks),c=0,d=b.length;d>c;c++){var e=this._animatingItemsBlocks[b[c]];e.style.overflow="",e.classList.remove(p._clipClass)}}this._cachedGroupRecords={},this._cachedItemRecords={},this._cachedHeaderRecords={},this._cachedInsertedItemRecords={},this._cachedInsertedHeaderRecords={},this._cachedRemovedItems=[],this._cachedRemovedHeaders=[],this._animatingItemsBlocks={}},_cacheRemovedElements:function(a,b,c,d,e){var f="left";this._site.rtl&&(f="right");var g,h;e?(g=this._sizes.headerContainerOuterX,h=this._sizes.headerContainerOuterY):(g=this._sizes.containerMargins[f],h=this._sizes.containerMargins.top);for(var i=0,j=a.length;j>i;i++){var k=a[i];if(-1===k.newIndex){var l=k.element,m=b[k.oldIndex];m&&(m.element=l,delete b[k.oldIndex],l.style.position="absolute",l.style[P]="",l.style.top=m.oldTop-h+"px",l.style[f]=m.oldLeft-g+"px",l.style.width=m.width+"px",l.style.height=m.height+"px",l.style[O.scriptName]="",this._site.surface.appendChild(l),d.push(m)),c[k.oldIndex]&&delete c[k.oldIndex]}}},_cacheInsertedElements:function(a,b,c){for(var d={},e=0,f=a.length;f>e;e++){var g=a[e],h=b[g.oldIndex];if(h&&delete b[g.oldIndex],h||-1===g.oldIndex||g.moved){var i=c[g.newIndex];i&&delete c[g.newIndex];var j=g.element;d[g.newIndex]=j,j.style[P]="",j.style[O.scriptName]="",j.style.opacity=0}}for(var k=Object.keys(b),e=0,f=k.length;f>e;e++)d[k[e]]=b[k[e]];return d},_resetStylesForRecords:function(a){for(var b=Object.keys(a),c=0,d=b.length;d>c;c++){var e=a[b[c]];e.needsToResetTransform&&(e.element.style[O.scriptName]="",e.needsToResetTransform=!1)}},_resetStylesForInsertedRecords:function(a){for(var b=Object.keys(a),c=0,d=b.length;d>c;c++){var e=a[b[c]];e.style.opacity=1}},_resetStylesForRemovedRecords:function(a){for(var b=0,c=a.length;c>b;b++){var d=a[b].element;d.parentNode&&(l._disposeElement(d),d.parentNode.removeChild(d))}},_updateAnimationCache:function(a,b){function c(a,b){for(var c={},e=0,f=a.length;f>e;e++){var g=a[e],h=b[g.oldIndex];h&&(c[g.newIndex]=h,h.element=g.element,delete b[g.oldIndex])}for(var i=Object.keys(b),e=0,f=i.length;f>e;e++){var j=i[e],k=b[j];(!k.element||d[I(k.element)])&&(c[j]=k)}return c}this._resetStylesForRecords(this._cachedItemRecords),this._resetStylesForRecords(this._cachedHeaderRecords),this._resetStylesForInsertedRecords(this._cachedInsertedItemRecords),this._resetStylesForInsertedRecords(this._cachedInsertedHeaderRecords);for(var d={},e=this._getRealizationRange(),f=this._site.tree,g=0,h=0,i=f.length;i>g;g++)A(f[g].itemsContainer,function(a){e.firstIndex<=h&&e.lastIndex>=h&&(d[I(a)]=!0),h++});this._cachedItemRecords=c(a,this._cachedItemRecords),this._cachedHeaderRecords=c(b,this._cachedHeaderRecords),this._cachedInsertedItemRecords=this._cacheInsertedElements(a,this._cachedInsertedItemRecords,this._cachedItemRecords),this._cachedInsertedHeaderRecords=this._cacheInsertedElements(b,this._cachedInsertedHeaderRecords,this._cachedHeaderRecords)},_filterRemovedElements:function(){function a(a,g){for(var h=0,i=a.length;i>h;h++){var j=a[h],k=j.element;j[c]+j[d]-1<e||j[c]>f||!b._site.viewport.contains(k)?k.parentNode&&(l._disposeElement(k),k.parentNode.removeChild(k)):g.push(k)}}if(this._removedElements=[],this._site.animationsDisabled)return this._resetStylesForRemovedRecords(this._cachedRemovedItems),void this._resetStylesForRemovedRecords(this._cachedRemovedHeaders);var b=this,c="horizontal"===this.orientation?"oldLeft":"oldTop",d="horizontal"===this.orientation?"width":"height",e=this._site.scrollbarPos,f=e+this._site.viewportSize[d]-1;a(this._cachedRemovedItems,this._removedElements),a(this._cachedRemovedHeaders,this._removedElements)},_filterInsertedElements:function(){function a(a,d){for(var e=Object.keys(a),f=0,g=e.length;g>f;f++){var h=e[f],i=a[h];h<c.firstIndex||h>c.lastIndex||b._site.viewport.contains(i.element)?i.style.opacity=1:d.push(i)}}if(this._insertedElements=[],this._site.animationsDisabled)return this._resetStylesForInsertedRecords(this._cachedInsertedItemRecords),void this._resetStylesForInsertedRecords(this._cachedInsertedHeaderRecords);var b=this,c=this._getVisibleRange();a(this._cachedInsertedItemRecords,this._insertedElements),a(this._cachedInsertedHeaderRecords,this._insertedElements)},_filterMovedElements:function(){var a=this,b="horizontal"===this.orientation?"oldLeft":"oldTop",c="horizontal"===this.orientation?"left":"top",d="horizontal"===this.orientation?"width":"height",e=this._getRealizationRange(),f=this._site.scrollbarPos,g=f+this._site.viewportSize[d]-1;if(this._itemMoveRecords=[],this._moveRecords=[],!this._site.animationsDisabled)for(var h=this._site.tree,i=0,j=0,k=h.length;k>j;j++){var l=h[j],m=!1;A(l.itemsContainer,function(){if(e.firstIndex<=i&&e.lastIndex>=i){var h=this._cachedItemRecords[i];if(h){var j=(h[b]+h[d]-1>=f&&h[b]<=g||h[c]+h[d]-1>=f&&h[c]<=g)&&a._site.viewport.contains(h.element);j&&(m=!0,h.needsToResetTransform&&(this._itemMoveRecords.push(h),delete this._cachedItemRecords[i]))}}i++}.bind(this));var n=j,o=this._cachedHeaderRecords[n];o&&m&&o.needsToResetTransform&&(this._moveRecords.push(o),delete this._cachedHeaderRecords[n]);var p=this._cachedGroupRecords[I(l.itemsContainer.element)];p&&m&&p.needsToResetTransform&&(this._moveRecords.push(p),delete this._cachedGroupRecords[I(l.itemsContainer.element)])}this._resetStylesForRecords(this._cachedGroupRecords),this._resetStylesForRecords(this._cachedItemRecords),this._resetStylesForRecords(this._cachedHeaderRecords)},_getItemPositionForAnimations:function(a,b,c){var d=this._groups[b],e=d.getItemPositionForAnimations(c),f=this._groups[b]?this._groups[b].offset:0,g=this._groupsEnabled&&this._groupHeaderPosition===U.left?this._sizes.headerContainerWidth:0,h=this._groupsEnabled&&this._groupHeaderPosition===U.top?this._sizes.headerContainerHeight:0;return e.left+=this._sizes.layoutOriginX+g+this._sizes.itemsContainerOuterX,e.top+=this._sizes.layoutOriginY+h+this._sizes.itemsContainerOuterY,e[this._horizontal?"left":"top"]+=f,e},_getHeaderPositionForAnimations:function(a){var b;if(this._groupsEnabled){var c=this._sizes.headerContainerWidth-this._sizes.headerContainerOuterWidth,d=this._sizes.headerContainerHeight-this._sizes.headerContainerOuterHeight;this._groupHeaderPosition!==U.left||this._horizontal?this._groupHeaderPosition===U.top&&this._horizontal&&(c=this._groups[a].getItemsContainerSize()-this._sizes.headerContainerOuterWidth):d=this._groups[a].getItemsContainerSize()-this._sizes.headerContainerOuterHeight;var e=this._horizontal?this._groups[a].offset:0,f=this._horizontal?0:this._groups[a].offset;b={top:this._sizes.layoutOriginY+f+this._sizes.headerContainerOuterY,left:this._sizes.layoutOriginX+e+this._sizes.headerContainerOuterX,height:d,width:c}}else b={top:0,left:0,height:0,width:0};return b},_rangeContainsItems:function(a,b){if(0===this._groups.length)return!1;var c=this._groups[this._groups.length-1],d=this._sizes.layoutOrigin+c.offset+this._getGroupSize(c)-1;return b>=0&&d>=a},_itemFromOffset:function(a,b){function c(a){if(!b.wholeItem){var c=e._horizontal?e._site.rtl?"right":"left":"top",d=e._horizontal?e._site.rtl?"left":"right":"bottom";return b.last?a-e._sizes.containerMargins[c]:a+e._sizes.containerMargins[d]}return a}function d(a){return b.last?a-e._getHeaderSizeGroupAdjustment()-e._sizes.itemsContainerOuterStart:a}var e=this;if(0===this._groups.length)return 0;b=b||{},a-=this._sizes.layoutOrigin,a=c(a);var f=this._groupFromOffset(d(a)),g=this._groups[f];return a-=g.offset,a-=this._getHeaderSizeGroupAdjustment(),g.startIndex+g.itemFromOffset(a,b)},_firstItemFromRange:function(a,b){return b=b||{},b.last=0,this._itemFromOffset(a,b)},_lastItemFromRange:function(a,b){return b=b||{},b.last=1,this._itemFromOffset(a,b)},_adjustedKeyForRTL:function(a){return this._site.rtl&&(a===H.leftArrow?a=H.rightArrow:a===H.rightArrow&&(a=H.leftArrow)),a},_adjustedKeyForOrientationAndBars:function(a,b){var c=a;if(b)return a;if(!this._horizontal)switch(c){case H.leftArrow:c=H.upArrow;break;case H.rightArrow:c=H.downArrow;break;case H.upArrow:c=H.leftArrow;break;case H.downArrow:c=H.rightArrow}return 1===this._itemsPerBar&&(c===H.upArrow?c=H.leftArrow:c===H.downArrow&&(c=H.rightArrow)),c},_getAdjacentForPageKeys:function(a,b){var c,d=this._sizes.containerMargins,e="horizontal"===this.orientation?d.left+d.right:d.top+d.bottom,f=this._site.viewportSize["horizontal"===this.orientation?"width":"height"],g=this._site.scrollbarPos,h=g+f-1-d["horizontal"===this.orientation?"right":"bottom"],i=this._firstItemFromRange(g,{wholeItem:!0}),j=this._lastItemFromRange(h,{wholeItem:!1}),k=this._getItemPosition(a.index),l=!1;if((a.index<i||a.index>j)&&(l=!0,g="horizontal"===this.orientation?k.left-e:k.top-e,h=g+f-1,i=this._firstItemFromRange(g,{wholeItem:!0}),j=this._lastItemFromRange(h,{wholeItem:!1})),b===H.pageUp){if(!l&&i!==a.index)return{type:o.ObjectType.item,index:i};var m;m="horizontal"===this.orientation?k.left+k.width+e+d.left:k.top+k.height+e+d.bottom;var n=this._firstItemFromRange(m-f,{wholeItem:!0});c=a.index===n?Math.max(0,a.index-this._itemsPerBar):n}else{if(!l&&j!==a.index)return{type:o.ObjectType.item,index:j};var p;p="horizontal"===this.orientation?k.left-e-d.right:k.top-e-d.bottom;var q=Math.max(0,this._lastItemFromRange(p+f-1,{wholeItem:!0}));c=a.index===q?a.index+this._itemsPerBar:q}return{type:o.ObjectType.item,index:c}},_isCellSpanning:function(a){var b=this._site.groupFromIndex(a),c=this._groupInfo;return c?!!("function"==typeof c?c(b):c).enableCellSpanning:!1},_getGroupInfo:function(a){var b=this._site.groupFromIndex(a),c=this._groupInfo,d=this._sizes.containerMargins,f={enableCellSpanning:!1};if(c="function"==typeof c?c(b):c){if(c.enableCellSpanning&&(+c.cellWidth!==c.cellWidth||+c.cellHeight!==c.cellHeight))throw new e("WinJS.UI.GridLayout.GroupInfoResultIsInvalid",J.groupInfoResultIsInvalid);f={enableCellSpanning:!!c.enableCellSpanning,cellWidth:c.cellWidth+d.left+d.right,cellHeight:c.cellHeight+d.top+d.bottom}}return f},_getItemInfo:function(a){var b;if(this._itemInfo&&"function"==typeof this._itemInfo)b=this._itemInfo(a);else{if(!this._useDefaultItemInfo)throw new e("WinJS.UI.GridLayout.ItemInfoIsInvalid",J.itemInfoIsInvalid);b=this._defaultItemInfo(a)}return i.as(b).then(function(a){if(!a||+a.width!==a.width||+a.height!==a.height)throw new e("WinJS.UI.GridLayout.ItemInfoIsInvalid",J.itemInfoIsInvalid);return a})},_defaultItemInfo:function(a){var b=this;return this._site.renderItem(this._site.itemFromIndex(a)).then(function(c){return b._elementsToMeasure[a]={element:c},b._measureElements()}).then(function(){var c=b._elementsToMeasure[a],d={width:c.width,height:c.height};return delete b._elementsToMeasure[a],d},function(c){return delete b._elementsToMeasure[a],i.wrapError(c)})},_getGroupSize:function(a){var b=0;return this._groupsEnabled&&(this._horizontal&&this._groupHeaderPosition===U.top?b=this._sizes.headerContainerMinWidth:this._horizontal||this._groupHeaderPosition!==U.left||(b=this._sizes.headerContainerMinHeight)),Math.max(b,a.getItemsContainerSize()+this._getHeaderSizeGroupAdjustment())},_groupFromOffset:function(a){return a<this._groups[0].offset?0:this._groupFrom(function(b){return a<b.offset})},_groupFromImpl:function(a,b,c){if(a>b)return null;var d=a+Math.floor((b-a)/2),e=this._groups[d];return c(e,d)?this._groupFromImpl(a,d-1,c):b>d&&!c(this._groups[d+1],d+1)?this._groupFromImpl(d+1,b,c):d},_groupFrom:function(a){if(this._groups.length>0){var b=this._groups.length-1,c=this._groups[b];return a(c,b)?this._groupFromImpl(0,this._groups.length-1,a):b}return null},_invalidateLayout:function(){this._site&&this._site.invalidateLayout()},_resetMeasurements:function(){this._measuringPromise&&(this._measuringPromise.cancel(),this._measuringPromise=null),this._containerSizeClassName&&(m.removeClass(this._site.surface,this._containerSizeClassName),u(this._containerSizeClassName),this._containerSizeClassName=null),this._sizes=null,this._resetAnimationCaches()},_measureElements:function(){if(!this._measuringElements){var a=this;a._measuringElements=j.schedulePromiseHigh(null,"WinJS.UI.GridLayout._measuringElements").then(function(){a._site._writeProfilerMark("_measureElements,StartTM");var c=a._createMeasuringSurface(),d=b.document.createElement("div"),e=a._site,f=a._measuringElements,g=a._elementsToMeasure,h=!1;d.className=p._itemsContainerClass+" "+p._laidOutClass,d.style.cssText+=";display: -ms-grid;-ms-grid-column: 1;-ms-grid-row: 1";var i,j,k=Object.keys(g);for(j=0,i=k.length;i>j;j++){var l=g[k[j]].element;l.style["-ms-grid-column"]=j+1,l.style["-ms-grid-row"]=j+1,d.appendChild(l)}for(c.appendChild(d),e.viewport.insertBefore(c,e.viewport.firstChild),f.then(null,function(){h=!0}),j=0,i=k.length;i>j&&!h;j++){var n=g[k[j]],o=n.element.querySelector("."+p._itemClass);n.width=m.getTotalWidth(o),n.height=m.getTotalHeight(o)}c.parentNode&&c.parentNode.removeChild(c),f===a._measuringElements&&(a._measuringElements=null),e._writeProfilerMark("_measureElements,StopTM")},function(b){return a._measuringElements=null,i.wrapError(b)})}return this._measuringElements},_ensureEnvInfo:function(){return this._envInfo||(this._envInfo=E(this._site),this._envInfo&&!this._envInfo.supportsCSSGrid&&m.addClass(this._site.surface,p._noCSSGrid)),!!this._envInfo},_createMeasuringSurface:function(){var a=b.document.createElement("div");return a.style.cssText="visibility: hidden;-ms-grid-columns: auto;-ms-grid-rows: auto;-ms-flex-align: start;-webkit-align-items: flex-start;align-items: flex-start",a.className=p._scrollableClass+" "+(this._inListMode?p._listLayoutClass:p._gridLayoutClass),this._envInfo.supportsCSSGrid||m.addClass(a,p._noCSSGrid),this._groupsEnabled&&(this._groupHeaderPosition===U.top?m.addClass(a,p._headerPositionTopClass):m.addClass(a,p._headerPositionLeftClass)),a},_measureItem:function(a){function c(a,e){var e,h=!!e,j={},k=f.rtl?"right":"left";return f.itemCount.then(function(b){return!b||d._groupsEnabled&&!f.groupCount?i.cancel:(e=e||f.itemFromIndex(a),j.container=f.renderItem(e),d._groupsEnabled&&(j.headerContainer=f.renderHeader(d._site.groupFromIndex(f.groupIndexFromItemIndex(a)))),i.join(j))}).then(function(j){function l(){var a=d._horizontal,b=d._groupsEnabled,c=!1;g.then(null,function(){c=!0});var e=G(C),h=f.rtl?f.viewport.offsetWidth-(C.offsetLeft+C.offsetWidth):C.offsetLeft,i=C.offsetTop,l={viewportContentSize:0,surfaceContentSize:0,maxItemsContainerContentSize:0,surfaceOuterHeight:y(o),surfaceOuterWidth:z(o),layoutOriginX:h-e[k],layoutOriginY:i-e.top,itemsContainerOuterHeight:y(q),itemsContainerOuterWidth:z(q),itemsContainerOuterX:x(f.rtl?"Right":"Left",q),itemsContainerOuterY:x("Top",q),itemsContainerMargins:G(q),itemBoxOuterHeight:y(s),itemBoxOuterWidth:z(s),containerOuterHeight:y(j.container),containerOuterWidth:z(j.container),emptyContainerContentHeight:m.getContentHeight(r),emptyContainerContentWidth:m.getContentWidth(r),containerMargins:G(j.container),containerWidth:0,containerHeight:0,containerSizeLoaded:!1};f.header&&(l[a?"layoutOriginX":"layoutOriginY"]+=m[a?"getTotalWidth":"getTotalHeight"](f.header)),b&&(l.headerContainerOuterX=x(f.rtl?"Right":"Left",j.headerContainer),l.headerContainerOuterY=x("Top",j.headerContainer),l.headerContainerOuterWidth=z(j.headerContainer),l.headerContainerOuterHeight=y(j.headerContainer),l.headerContainerWidth=m.getTotalWidth(j.headerContainer),l.headerContainerHeight=m.getTotalHeight(j.headerContainer),l.headerContainerMinWidth=w(j.headerContainer,"minWidth")+l.headerContainerOuterWidth,l.headerContainerMinHeight=w(j.headerContainer,"minHeight")+l.headerContainerOuterHeight);var n={sizes:l,viewportContentWidth:m.getContentWidth(f.viewport),viewportContentHeight:m.getContentHeight(f.viewport),containerContentWidth:m.getContentWidth(j.container),containerContentHeight:m.getContentHeight(j.container),containerWidth:m.getTotalWidth(j.container),containerHeight:m.getTotalHeight(j.container)};return n.viewportCrossSize=n[a?"viewportContentHeight":"viewportContentWidth"],f.readyToMeasure(),c?null:n}function n(){o.parentNode&&o.parentNode.removeChild(o)}var o=d._createMeasuringSurface(),q=b.document.createElement("div"),r=b.document.createElement("div"),s=j.container.querySelector("."+p._itemBoxClass),t=f.groupIndexFromItemIndex(a);r.className=p._containerClass,q.className=p._itemsContainerClass+" "+p._laidOutClass;var u=1,v=1,A=2,B=2,C=q,D=!1;d._inListMode&&d._groupsEnabled&&(d._horizontal&&d._groupHeaderPosition===U.top?(u=2,B=1,A=1,C=j.headerContainer,D=!0):d._horizontal||d._groupHeaderPosition!==U.left||(v=2,B=1,A=1,C=j.headerContainer,D=!0)),q.style.cssText+=";display: "+(d._inListMode?(d._horizontal?"flex":"block")+"; overflow: hidden":"inline-block")+";vertical-align:top;-ms-grid-column: "+v+";-ms-grid-row: "+u,d._inListMode||(j.container.style.display="inline-block"),d._groupsEnabled&&(j.headerContainer.style.cssText+=";display: inline-block;-ms-grid-column: "+B+";-ms-grid-row: "+A,m.addClass(j.headerContainer,p._laidOutClass+" "+p._groupLeaderClass),(d._groupHeaderPosition===U.top&&d._horizontal||d._groupHeaderPosition===U.left&&!d._horizontal)&&m.addClass(q,p._groupLeaderClass)),D&&o.appendChild(j.headerContainer),q.appendChild(j.container),q.appendChild(r),o.appendChild(q),!D&&d._groupsEnabled&&o.appendChild(j.headerContainer),f.viewport.insertBefore(o,f.viewport.firstChild);var E=l();if(!E)return n(),i.cancel;if(d._horizontal&&0===E.viewportContentHeight||!d._horizontal&&0===E.viewportContentWidth)return n(),i.cancel;if(!(h||d._isCellSpanning(t)||0!==E.containerContentWidth&&0!==E.containerContentHeight))return n(),e.then(function(){return c(a,e)});var F=d._sizes=E.sizes;if(Object.defineProperties(F,{surfaceOuterCrossSize:{get:function(){return d._horizontal?F.surfaceOuterHeight:F.surfaceOuterWidth},enumerable:!0},layoutOrigin:{get:function(){return d._horizontal?F.layoutOriginX:F.layoutOriginY},enumerable:!0},itemsContainerOuterSize:{get:function(){return d._horizontal?F.itemsContainerOuterWidth:F.itemsContainerOuterHeight},enumerable:!0},itemsContainerOuterCrossSize:{get:function(){return d._horizontal?F.itemsContainerOuterHeight:F.itemsContainerOuterWidth},enumerable:!0},itemsContainerOuterStart:{get:function(){return d._horizontal?F.itemsContainerOuterX:F.itemsContainerOuterY},enumerable:!0},itemsContainerOuterCrossStart:{get:function(){return d._horizontal?F.itemsContainerOuterY:F.itemsContainerOuterX},enumerable:!0},containerCrossSize:{get:function(){return d._horizontal?F.containerHeight:F.containerWidth},enumerable:!0},containerSize:{get:function(){return d._horizontal?F.containerWidth:F.containerHeight},enumerable:!0}}),!d._isCellSpanning(t)){if(d._inListMode){var H=E.viewportCrossSize-F.surfaceOuterCrossSize-d._getHeaderSizeContentAdjustment()-F.itemsContainerOuterCrossSize;d._horizontal?(F.containerHeight=H,F.containerWidth=E.containerWidth):(F.containerHeight=E.containerHeight,F.containerWidth=H)}else F.containerWidth=E.containerWidth,F.containerHeight=E.containerHeight;F.containerSizeLoaded=!0}d._createContainerStyleRule(),d._viewportSizeChanged(E.viewportCrossSize),n()})}var d=this,e="Layout:measureItem",f=d._site,g=d._measuringPromise;if(!g){f._writeProfilerMark(e+",StartTM");var h=new k;d._measuringPromise=g=h.promise.then(function(){return d._ensureEnvInfo()?c(a):i.cancel}).then(function(){f._writeProfilerMark(e+":complete,info"),f._writeProfilerMark(e+",StopTM")},function(a){return d._measuringPromise=null,f._writeProfilerMark(e+":canceled,info"),f._writeProfilerMark(e+",StopTM"),i.wrapError(a)}),h.complete()}return g},_getHeaderSizeGroupAdjustment:function(){if(this._groupsEnabled){if(this._horizontal&&this._groupHeaderPosition===U.left)return this._sizes.headerContainerWidth;if(!this._horizontal&&this._groupHeaderPosition===U.top)return this._sizes.headerContainerHeight}return 0},_getHeaderSizeContentAdjustment:function(){if(this._groupsEnabled){if(this._horizontal&&this._groupHeaderPosition===U.top)return this._sizes.headerContainerHeight;if(!this._horizontal&&this._groupHeaderPosition===U.left)return this._sizes.headerContainerWidth}return 0},_getViewportCrossSize:function(){return this._site.viewportSize[this._horizontal?"height":"width"]},_viewportSizeChanged:function(a){var b=this._sizes;b.viewportContentSize=a,b.surfaceContentSize=a-b.surfaceOuterCrossSize,b.maxItemsContainerContentSize=b.surfaceContentSize-b.itemsContainerOuterCrossSize-this._getHeaderSizeContentAdjustment(),b.containerSizeLoaded&&!this._inListMode?(this._itemsPerBar=Math.floor(b.maxItemsContainerContentSize/b.containerCrossSize),this.maximumRowsOrColumns&&(this._itemsPerBar=Math.min(this._itemsPerBar,this.maximumRowsOrColumns)),this._itemsPerBar=Math.max(1,this._itemsPerBar)):(this._inListMode&&(b[this._horizontal?"containerHeight":"containerWidth"]=b.maxItemsContainerContentSize),this._itemsPerBar=1),this._resetAnimationCaches()},_createContainerStyleRule:function(){var a=this._sizes;if(!this._containerSizeClassName&&a.containerSizeLoaded&&(0===a.emptyContainerContentHeight||0===a.emptyContainerContentWidth)){var b=a.containerWidth-a.containerOuterWidth+"px",c=a.containerHeight-a.containerOuterHeight+"px";this._inListMode&&(this._horizontal?c="calc(100% - "+(a.containerMargins.top+a.containerMargins.bottom)+"px)":b="auto"),this._containerSizeClassName||(this._containerSizeClassName=r("containersize"),m.addClass(this._site.surface,this._containerSizeClassName));var d="."+p._containerClass,e="width:"+b+";height:"+c+";";t(this._containerSizeClassName,this._site,d,e)}},_ensureContainerSize:function(a){var b=this._sizes;if(b.containerSizeLoaded||this._ensuringContainerSize)return this._ensuringContainerSize?this._ensuringContainerSize:i.wrap();var c;if(this._itemInfo&&"function"==typeof this._itemInfo||!this._useDefaultItemInfo)c=this._getItemInfo();else{var d=b.containerMargins;c=i.wrap({width:a.groupInfo.cellWidth-d.left-d.right,height:a.groupInfo.cellHeight-d.top-d.bottom})}var e=this;return this._ensuringContainerSize=c.then(function(a){b.containerSizeLoaded=!0,b.containerWidth=a.width+b.itemBoxOuterWidth+b.containerOuterWidth,b.containerHeight=a.height+b.itemBoxOuterHeight+b.containerOuterHeight,e._inListMode?e._itemsPerBar=1:(e._itemsPerBar=Math.floor(b.maxItemsContainerContentSize/b.containerCrossSize),e.maximumRowsOrColumns&&(e._itemsPerBar=Math.min(e._itemsPerBar,e.maximumRowsOrColumns)),e._itemsPerBar=Math.max(1,e._itemsPerBar)),e._createContainerStyleRule()}),c.done(function(){e._ensuringContainerSize=null},function(){e._ensuringContainerSize=null}),c},_indexToCoordinate:function(a,b){b=b||this._itemsPerBar;var c=Math.floor(a/b);return this._horizontal?{column:c,row:a-c*b}:{row:c,column:a-c*b}},_rangeForGroup:function(a,b){var c=a.startIndex,d=c+a.count-1;return!b||b.firstIndex>d||b.lastIndex<c?null:{firstIndex:Math.max(0,b.firstIndex-c),lastIndex:Math.min(a.count-1,b.lastIndex-c)}},_syncDomWithGroupHeaderPosition:function(a){if(this._groupsEnabled&&this._oldGroupHeaderPosition!==this._groupHeaderPosition){var b,c=a.length;if(this._oldGroupHeaderPosition===U.top)if(m.removeClass(this._site.surface,p._headerPositionTopClass),this._horizontal)for(b=0;c>b;b++)a[b].header.style.maxWidth="",m.removeClass(a[b].itemsContainer.element,p._groupLeaderClass);else this._site.surface.style.msGridRows="";else if(this._oldGroupHeaderPosition===U.left){if(m.removeClass(this._site.surface,p._headerPositionLeftClass),!this._horizontal)for(b=0;c>b;b++)a[b].header.style.maxHeight="",m.removeClass(a[b].itemsContainer.element,p._groupLeaderClass);this._site.surface.style.msGridColumns=""}if(this._groupHeaderPosition===U.top){if(m.addClass(this._site.surface,p._headerPositionTopClass),this._horizontal)for(b=0;c>b;b++)m.addClass(a[b].itemsContainer.element,p._groupLeaderClass)}else if(m.addClass(this._site.surface,p._headerPositionLeftClass),!this._horizontal)for(b=0;c>b;b++)m.addClass(a[b].itemsContainer.element,p._groupLeaderClass);this._oldGroupHeaderPosition=this._groupHeaderPosition}},_layoutGroup:function(a){var b=this._groups[a],c=this._site.tree[a],d=c.header,e=c.itemsContainer.element,f=this._sizes,g=b.getItemsContainerCrossSize();if(this._groupsEnabled){if(this._horizontal)if(this._groupHeaderPosition===U.top){var h=f.headerContainerMinWidth-f.headerContainerOuterWidth,i=b.getItemsContainerSize()-f.headerContainerOuterWidth;d.style.maxWidth=Math.max(h,i)+"px",this._envInfo.supportsCSSGrid?(d.style.msGridColumn=a+1,e.style.msGridColumn=a+1):(d.style.height=f.headerContainerHeight-f.headerContainerOuterHeight+"px",e.style.height=g-f.itemsContainerOuterHeight+"px",e.style.marginBottom=f.itemsContainerMargins.bottom+(f.maxItemsContainerContentSize-g+f.itemsContainerOuterHeight)+"px"),m.addClass(e,p._groupLeaderClass)}else this._envInfo.supportsCSSGrid?(d.style.msGridColumn=2*a+1,e.style.msGridColumn=2*a+2):(d.style.width=f.headerContainerWidth-f.headerContainerOuterWidth+"px",d.style.height=g-f.headerContainerOuterHeight+"px",e.style.height=g-f.itemsContainerOuterHeight+"px");else if(this._groupHeaderPosition===U.left){var j=f.headerContainerMinHeight-f.headerContainerOuterHeight,k=b.getItemsContainerSize()-f.headerContainerOuterHeight;d.style.maxHeight=Math.max(j,k)+"px",this._envInfo.supportsCSSGrid?(d.style.msGridRow=a+1,e.style.msGridRow=a+1):(d.style.width=f.headerContainerWidth-f.headerContainerOuterWidth+"px",e.style.width=g-f.itemsContainerOuterWidth+"px",e.style["margin"+(this._site.rtl?"Left":"Right")]=f.itemsContainerMargins[this._site.rtl?"left":"right"]+(f.maxItemsContainerContentSize-g+f.itemsContainerOuterWidth)+"px"),m.addClass(e,p._groupLeaderClass)}else d.style.msGridRow=2*a+1,this._inListMode?d.style.height=f.headerContainerHeight-f.headerContainerOuterHeight+"px":this._envInfo.supportsCSSGrid?e.style.msGridRow=2*a+2:(d.style.height=f.headerContainerHeight-f.headerContainerOuterHeight+"px",d.style.width=g-f.headerContainerOuterWidth+"px",e.style.width=g-f.itemsContainerOuterWidth+"px");m.addClass(d,p._laidOutClass+" "+p._groupLeaderClass)}m.addClass(e,p._laidOutClass)}},{_barsPerItemsBlock:4})}),_LegacyLayout:c.Namespace._lazy(function(){return c.Class.derive(a._LayoutCommon,null,{disableBackdrop:{get:function(){return this._backdropDisabled||!1},set:function(a){if(m._deprecated(q.disableBackdropIsDeprecated),a=!!a,this._backdropDisabled!==a&&(this._backdropDisabled=a,this._disableBackdropClassName&&(u(this._disableBackdropClassName),this._site&&m.removeClass(this._site.surface,this._disableBackdropClassName),this._disableBackdropClassName=null),this._disableBackdropClassName=r("disablebackdrop"),this._site&&m.addClass(this._site.surface,this._disableBackdropClassName),a)){var b=".win-container.win-backdrop",c="background-color:transparent;";t(this._disableBackdropClassName,this._site,b,c)}}},backdropColor:{get:function(){return this._backdropColor||"rgba(155,155,155,0.23)"},set:function(a){if(m._deprecated(q.backdropColorIsDeprecated),a&&this._backdropColor!==a){this._backdropColor=a,this._backdropColorClassName&&(u(this._backdropColorClassName),this._site&&m.removeClass(this._site.surface,this._backdropColorClassName),this._backdropColorClassName=null),this._backdropColorClassName=r("backdropcolor"),this._site&&m.addClass(this._site.surface,this._backdropColorClassName);var b=".win-container.win-backdrop",c="background-color:"+a+";";t(this._backdropColorClassName,this._site,b,c)}}}})}),GridLayout:c.Namespace._lazy(function(){return c.Class.derive(a._LegacyLayout,function(a){a=a||{},this.itemInfo=a.itemInfo,this.groupInfo=a.groupInfo,this._maxRowsOrColumns=0,this._useDefaultItemInfo=!0,this._elementsToMeasure={},this._groupHeaderPosition=a.groupHeaderPosition||U.top,this.orientation=a.orientation||"horizontal",a.maxRows&&(this.maxRows=+a.maxRows),a.maximumRowsOrColumns&&(this.maximumRowsOrColumns=+a.maximumRowsOrColumns)},{maximumRowsOrColumns:{get:function(){return this._maxRowsOrColumns},set:function(a){this._setMaxRowsOrColumns(a)}},maxRows:{get:function(){return this.maximumRowsOrColumns},set:function(a){m._deprecated(q.maxRowsIsDeprecated),this.maximumRowsOrColumns=a}},itemInfo:{enumerable:!0,get:function(){return this._itemInfo},set:function(a){a&&m._deprecated(q.itemInfoIsDeprecated),this._itemInfo=a,this._invalidateLayout()}},groupInfo:{enumerable:!0,get:function(){return this._groupInfo},set:function(a){a&&m._deprecated(q.groupInfoIsDeprecated),this._groupInfo=a,this._invalidateLayout()}}})})});var T=c.Namespace.defineWithParent(null,null,{UniformGroupBase:c.Namespace._lazy(function(){return c.Class.define(null,{cleanUp:function(){},itemFromOffset:function(a,b){b=b||{};var c=this._layout._sizes;a-=c.itemsContainerOuterStart,b.wholeItem&&(a+=(b.last?-1:1)*(c.containerSize-1));var d=this.count-1,e=Math.floor(d/this._layout._itemsPerBar),f=v(0,e,Math.floor(a/c.containerSize)),g=(f+b.last)*this._layout._itemsPerBar-b.last;return v(0,this.count-1,g)},hitTest:function(a,b){var c=this._layout._horizontal,d=this._layout._itemsPerBar,e=this._layout._inListMode||1===d,f=c?a:b,g=c?b:a,h=this._layout._sizes;f-=h.itemsContainerOuterStart,g-=h.itemsContainerOuterCrossStart;var i,j=Math.floor(f/h.containerSize),k=v(0,d-1,Math.floor(g/h.containerCrossSize)),l=Math.max(-1,j*d+k);if(i=!c&&e||c&&!e?(b-h.containerHeight/2)/h.containerHeight:(a-h.containerWidth/2)/h.containerWidth,e)return i=Math.floor(i),{index:l,insertAfterIndex:i>=0&&l>=0?i:-1};i=v(-1,d-1,i);var m;return m=0>i?j*d-1:j*d+Math.floor(i),{index:v(-1,this.count-1,l),insertAfterIndex:v(-1,this.count-1,m)}},getAdjacent:function(a,b){var c,d=a.index,e=Math.floor(d/this._layout._itemsPerBar),f=d%this._layout._itemsPerBar;switch(b){case H.upArrow:c=0===f?"boundary":d-1;break;case H.downArrow:var g=d===this.count-1,h=this._layout._itemsPerBar>1&&f===this._layout._itemsPerBar-1;c=g||h?"boundary":d+1;break;case H.leftArrow:c=0===e&&this._layout._itemsPerBar>1?"boundary":d-this._layout._itemsPerBar;break;case H.rightArrow:var i=this.count-1,j=Math.floor(i/this._layout._itemsPerBar);c=e===j?"boundary":Math.min(d+this._layout._itemsPerBar,this.count-1)}return"boundary"===c?c:{type:o.ObjectType.item,index:c}},getItemsContainerSize:function(){var a=this._layout._sizes,b=Math.ceil(this.count/this._layout._itemsPerBar);return b*a.containerSize+a.itemsContainerOuterSize},getItemsContainerCrossSize:function(){var a=this._layout._sizes;return this._layout._itemsPerBar*a.containerCrossSize+a.itemsContainerOuterCrossSize},getItemPositionForAnimations:function(a){var b=this._layout._sizes,c=this._layout._site.rtl?"right":"left",d=this._layout._sizes.containerMargins,e=this._layout._indexToCoordinate(a),f={row:e.row,column:e.column,top:d.top+e.row*b.containerHeight,left:d[c]+e.column*b.containerWidth,height:b.containerHeight-b.containerMargins.top-b.containerMargins.bottom,width:b.containerWidth-b.containerMargins.left-b.containerMargins.right};return f}})}),UniformGroup:c.Namespace._lazy(function(){return c.Class.derive(T.UniformGroupBase,function(a,b){this._layout=a,this._itemsContainer=b,m.addClass(this._itemsContainer,a._inListMode?p._uniformListLayoutClass:p._uniformGridLayoutClass)},{cleanUp:function(a){a||(m.removeClass(this._itemsContainer,p._uniformGridLayoutClass),m.removeClass(this._itemsContainer,p._uniformListLayoutClass),this._itemsContainer.style.height=this._itemsContainer.style.width=""),this._itemsContainer=null,this._layout=null,this.groupInfo=null,this.startIndex=null,this.offset=null,this.count=null},prepareLayout:function(a,b,c,d){return this.groupInfo=d.groupInfo,this.startIndex=d.startIndex,this.count=a,this._layout._ensureContainerSize(this) },layoutRealizedRange:function(){var a=this._layout._sizes;this._itemsContainer.style[this._layout._horizontal?"width":"height"]=this.getItemsContainerSize()-a.itemsContainerOuterSize+"px",this._itemsContainer.style[this._layout._horizontal?"height":"width"]=this._layout._inListMode?a.maxItemsContainerContentSize+"px":this._layout._itemsPerBar*a.containerCrossSize+"px"},layoutUnrealizedRange:function(){return i.wrap()}})}),UniformFlowGroup:c.Namespace._lazy(function(){return c.Class.derive(T.UniformGroupBase,function(a,b){this._layout=a,this._itemsContainer=b.element,m.addClass(this._itemsContainer,a._inListMode?p._uniformListLayoutClass:p._uniformGridLayoutClass)},{cleanUp:function(a){a||(m.removeClass(this._itemsContainer,p._uniformListLayoutClass),m.removeClass(this._itemsContainer,p._uniformGridLayoutClass),this._itemsContainer.style.height="")},layout:function(){this._layout._site._writeProfilerMark("Layout:_UniformFlowGroup:setItemsContainerHeight,info"),this._itemsContainer.style.height=this.count*this._layout._sizes.containerHeight+"px"}})}),CellSpanningGroup:c.Namespace._lazy(function(){return c.Class.define(function(a,b){this._layout=a,this._itemsContainer=b,m.addClass(this._itemsContainer,p._cellSpanningGridLayoutClass),this.resetMap()},{cleanUp:function(a){a||(this._cleanContainers(),m.removeClass(this._itemsContainer,p._cellSpanningGridLayoutClass),this._itemsContainer.style.cssText=""),this._itemsContainer=null,this._layoutPromise&&(this._layoutPromise.cancel(),this._layoutPromise=null),this.resetMap(),this._slotsPerColumn=null,this._offScreenSlotsPerColumn=null,this._items=null,this._layout=null,this._containersToHide=null,this.groupInfo=null,this.startIndex=null,this.offset=null,this.count=null},prepareLayoutWithCopyOfTree:function(a,b,c,d){var e,f=this;if(this._containersToHide={},b)for(e=b.firstIndex;e<=b.lastIndex;e++)this._containersToHide[I(c._items[e])]=c._items[e];this.groupInfo=d.groupInfo,this.startIndex=d.startIndex,this.count=a.items.length,this._items=a.items,this._slotsPerColumn=Math.floor(this._layout._sizes.maxItemsContainerContentSize/this.groupInfo.cellHeight),this._layout.maximumRowsOrColumns&&(this._slotsPerColumn=Math.min(this._slotsPerColumn,this._layout.maximumRowsOrColumns)),this._slotsPerColumn=Math.max(this._slotsPerColumn,1),this.resetMap();var g=new Array(this.count);for(e=0;e<this.count;e++)g[e]=this._layout._getItemInfo(this.startIndex+e);return i.join(g).then(function(a){a.forEach(function(a,b){f.addItemToMap(b,a)})})},layoutRealizedRange:function(a,b){if(b){var c,d=Math.max(a,b.firstIndex);for(c=d;c<=b.lastIndex;c++)this._layoutItem(c),delete this._containersToHide[I(this._items[c])]}Object.keys(this._containersToHide).forEach(function(a){m.removeClass(this._containersToHide[a],p._laidOutClass)}.bind(this)),this._containersToHide={},this._itemsContainer.style.cssText+=";width:"+(this.getItemsContainerSize()-this._layout._sizes.itemsContainerOuterSize)+"px;height:"+this._layout._sizes.maxItemsContainerContentSize+"px;-ms-grid-columns: ("+this.groupInfo.cellWidth+"px)["+this.getColumnCount()+"];-ms-grid-rows: ("+this.groupInfo.cellHeight+"px)["+(this._slotsPerColumn+this._offScreenSlotsPerColumn)+"]"},layoutUnrealizedRange:function(a,b,c){var d,e=this;return e._layoutPromise=new i(function(f){function g(){d=null,f()}function h(a){return j.schedule(a,j.Priority.normal,null,"WinJS.UI.GridLayout.CellSpanningGroup.LayoutUnrealizedRange")}if(b){var i=!1,k=b.firstIndex-1,l=Math.max(a,b.lastIndex+1);l=Math.max(k+1,l),d=h(function n(b){for(;!i;){if(b.shouldYield)return void b.setWork(n);i=!0,k>=a&&(e._layoutItem(k),k--,i=!1),l<e.count&&(e._layoutItem(l),l++,i=!1)}g()})}else if(c){var m=e.count-1;d=h(function o(b){for(;m>=a;m--){if(b.shouldYield)return void b.setWork(o);e._layoutItem(m)}g()})}else{var m=a;d=h(function p(a){for(;m<e.count;m++){if(a.shouldYield)return void a.setWork(p);e._layoutItem(m)}g()})}},function(){d&&d.cancel(),d=null}),e._layoutPromise},itemFromOffset:function(a,b){b=b||{};var c=this._layout._sizes,d=c.containerMargins;a-=c.itemsContainerOuterX,a-=(b.last?1:-1)*d[b.last?"left":"right"];var e=this.indexFromOffset(a,b.wholeItem,b.last).item;return v(0,this.count-1,e)},getAdjacent:function(a,b){var c,d;c=d=a.index;var e,f,g;g=this.lastAdjacent===c?this.lastInMapIndex:this.findItem(c);do{var h=Math.floor(g/this._slotsPerColumn),i=g-h*this._slotsPerColumn,j=Math.floor((this.occupancyMap.length-1)/this._slotsPerColumn);switch(b){case H.upArrow:if(!(i>0))return{type:o.ObjectType.item,index:d};g--;break;case H.downArrow:if(!(i+1<this._slotsPerColumn))return{type:o.ObjectType.item,index:d};g++;break;case H.leftArrow:g=h>0?g-this._slotsPerColumn:-1;break;case H.rightArrow:g=j>h?g+this._slotsPerColumn:this.occupancyMap.length}f=g>=0&&g<this.occupancyMap.length,f&&(e=this.occupancyMap[g]?this.occupancyMap[g].index:void 0)}while(f&&(c===e||void 0===e));return this.lastAdjacent=e,this.lastInMapIndex=g,f?{type:o.ObjectType.item,index:e}:"boundary"},hitTest:function(a,b){var c=this._layout._sizes,d=0;if(a-=c.itemsContainerOuterX,b-=c.itemsContainerOuterY,this.occupancyMap.length>0){for(var e=this.indexFromOffset(a,!1,0),f=Math.min(this._slotsPerColumn-1,Math.floor(b/this.groupInfo.cellHeight)),g=e.index,h=g;f-->0;)g++,this.occupancyMap[g]&&(h=g);this.occupancyMap[h]||h--,d=this.occupancyMap[h].index}var i=this.getItemSize(d),j=i.column*this.groupInfo.cellWidth,k=i.row*this.groupInfo.cellHeight,l=1===this._slotsPerColumn,m=d;return(l&&a<j+i.contentWidth/2||!l&&b<k+i.contentHeight/2)&&m--,{type:o.ObjectType.item,index:v(0,this.count-1,d),insertAfterIndex:v(-1,this.count-1,m)}},getItemsContainerSize:function(){var a=this._layout._sizes;return this.getColumnCount()*this.groupInfo.cellWidth+a.itemsContainerOuterSize},getItemsContainerCrossSize:function(){var a=this._layout._sizes;return a.maxItemsContainerContentSize+a.itemsContainerOuterCrossSize},getItemPositionForAnimations:function(a){var b=this._layout._site.rtl?"right":"left",c=this._layout._sizes.containerMargins,d=this.getItemSize(a),e=this.groupInfo,f={row:d.row,column:d.column,top:c.top+d.row*e.cellHeight,left:c[b]+d.column*e.cellWidth,height:d.contentHeight,width:d.contentWidth};return f},_layoutItem:function(a){var b=this.getItemSize(a);return this._items[a].style.cssText+=";-ms-grid-row:"+(b.row+1)+";-ms-grid-column:"+(b.column+1)+";-ms-grid-row-span:"+b.rows+";-ms-grid-column-span:"+b.columns+";height:"+b.contentHeight+"px;width:"+b.contentWidth+"px",m.addClass(this._items[a],p._laidOutClass),this._items[a]},_cleanContainers:function(){var a,b=this._items,c=b.length;for(a=0;c>a;a++)b[a].style.cssText="",m.removeClass(b[a],p._laidOutClass)},getColumnCount:function(){return Math.ceil(this.occupancyMap.length/this._slotsPerColumn)},getOccupancyMapItemCount:function(){var a=-1;return this.occupancyMap.forEach(function(b){b.index>a&&(a=b.index)}),a+1},coordinateToIndex:function(a,b){return a*this._slotsPerColumn+b},markSlotAsFull:function(a,b){for(var c=this._layout._indexToCoordinate(a,this._slotsPerColumn),d=c.row+b.rows,e=c.row;d>e&&e<this._slotsPerColumn;e++)for(var f=c.column,g=c.column+b.columns;g>f;f++)this.occupancyMap[this.coordinateToIndex(f,e)]=b;this._offScreenSlotsPerColumn=Math.max(this._offScreenSlotsPerColumn,d-this._slotsPerColumn)},isSlotEmpty:function(a,b,c){for(var d=b,e=b+a.rows;e>d;d++)for(var f=c,g=c+a.columns;g>f;f++)if(d>=this._slotsPerColumn||void 0!==this.occupancyMap[this.coordinateToIndex(f,d)])return!1;return!0},findEmptySlot:function(a,b,c){var d=this._layout._indexToCoordinate(a,this._slotsPerColumn),e=d.row,f=Math.floor((this.occupancyMap.length-1)/this._slotsPerColumn);if(c){for(var g=d.column+1;f>=g;g++)if(this.isSlotEmpty(b,0,g))return this.coordinateToIndex(g,0)}else for(var g=d.column;f>=g;g++){for(var h=e;h<this._slotsPerColumn;h++)if(this.isSlotEmpty(b,h,g))return this.coordinateToIndex(g,h);e=0}return(f+1)*this._slotsPerColumn},findItem:function(a){for(var b=a,c=this.occupancyMap.length;c>b;b++){var d=this.occupancyMap[b];if(d&&d.index===a)return b}return b},getItemSize:function(a){var b=this.findItem(a),c=this.occupancyMap[b],d=this._layout._indexToCoordinate(b,this._slotsPerColumn);return a===c.index?{row:d.row,column:d.column,contentWidth:c.contentWidth,contentHeight:c.contentHeight,columns:c.columns,rows:c.rows}:null},resetMap:function(){this.occupancyMap=[],this.lastAdded=0,this._offScreenSlotsPerColumn=0},addItemToMap:function(a,b){function c(a,b){var c=d.findEmptySlot(d.lastAdded,a,b);d.lastAdded=c,d.markSlotAsFull(c,a)}var d=this,e=d.groupInfo,f=d._layout._sizes.containerMargins,g={index:a,contentWidth:b.width,contentHeight:b.height,columns:Math.max(1,Math.ceil((b.width+f.left+f.right)/e.cellWidth)),rows:Math.max(1,Math.ceil((b.height+f.top+f.bottom)/e.cellHeight))};c(g,b.newColumn)},indexFromOffset:function(a,b,c){var d=0,e=0,f=this.groupInfo,g=0;if(this.occupancyMap.length>0){if(e=this.getOccupancyMapItemCount()-1,d=Math.ceil((this.occupancyMap.length-1)/this._slotsPerColumn)*f.cellWidth,d>a){for(var h=this._slotsPerColumn,g=(Math.max(0,Math.floor(a/f.cellWidth))+c)*this._slotsPerColumn-c;!this.occupancyMap[g]&&h-->0;)g+=c>0?-1:1;return{index:g,item:this.occupancyMap[g].index}}g=this.occupancyMap.length-1}return{index:g,item:e+(Math.max(0,Math.floor((a-d)/f.cellWidth))+c)*this._slotsPerColumn-c}}})})});c.Namespace._moduleDefine(a,"WinJS.UI",{ListLayout:c.Namespace._lazy(function(){return c.Class.derive(a._LegacyLayout,function(a){a=a||{},this._itemInfo={},this._groupInfo={},this._groupHeaderPosition=a.groupHeaderPosition||U.top,this._inListMode=!0,this.orientation=a.orientation||"vertical"},{initialize:function(b,c){m.addClass(b.surface,p._listLayoutClass),a._LegacyLayout.prototype.initialize.call(this,b,c)},uninitialize:function(){this._site&&m.removeClass(this._site.surface,p._listLayoutClass),a._LegacyLayout.prototype.uninitialize.call(this)},layout:function(b,c,d,e){return this._groupsEnabled||this._horizontal?a._LegacyLayout.prototype.layout.call(this,b,c,d,e):this._layoutNonGroupedVerticalList(b,c,d,e)},_layoutNonGroupedVerticalList:function(a,b,c,d){var e=this,f="Layout:_layoutNonGroupedVerticalList";return e._site._writeProfilerMark(f+",StartTM"),this._layoutPromise=e._measureItem(0).then(function(){m[e._usingStructuralNodes?"addClass":"removeClass"](e._site.surface,p._structuralNodesClass),m[e._envInfo.nestedFlexTooLarge||e._envInfo.nestedFlexTooSmall?"addClass":"removeClass"](e._site.surface,p._singleItemsBlockClass),e._sizes.viewportContentSize!==e._getViewportCrossSize()&&e._viewportSizeChanged(e._getViewportCrossSize()),e._cacheRemovedElements(c,e._cachedItemRecords,e._cachedInsertedItemRecords,e._cachedRemovedItems,!1),e._cacheRemovedElements(d,e._cachedHeaderRecords,e._cachedInsertedHeaderRecords,e._cachedRemovedHeaders,!0);var b=a[0].itemsContainer,g=new T.UniformFlowGroup(e,b);e._groups=[g],g.groupInfo={enableCellSpanning:!1},g.startIndex=0,g.count=D(b),g.offset=0,g.layout(),e._site._writeProfilerMark(f+":setSurfaceWidth,info"),e._site.surface.style.width=e._sizes.surfaceContentSize+"px",e._layoutAnimations(c,d),e._site._writeProfilerMark(f+":complete,info"),e._site._writeProfilerMark(f+",StopTM")},function(a){return e._site._writeProfilerMark(f+":canceled,info"),e._site._writeProfilerMark(f+",StopTM"),i.wrapError(a)}),{realizedRangeComplete:this._layoutPromise,layoutComplete:this._layoutPromise}},numberOfItemsPerItemsBlock:{get:function(){var b=this;return this._measureItem(0).then(function(){return b._envInfo.nestedFlexTooLarge||b._envInfo.nestedFlexTooSmall?(b._usingStructuralNodes=!0,Number.MAX_VALUE):(b._usingStructuralNodes=a.ListLayout._numberOfItemsPerItemsBlock>0,a.ListLayout._numberOfItemsPerItemsBlock)})}}},{_numberOfItemsPerItemsBlock:10})}),CellSpanningLayout:c.Namespace._lazy(function(){return c.Class.derive(a._LayoutCommon,function(a){a=a||{},this._itemInfo=a.itemInfo,this._groupInfo=a.groupInfo,this._groupHeaderPosition=a.groupHeaderPosition||U.top,this._horizontal=!0,this._cellSpanning=!0},{maximumRowsOrColumns:{get:function(){return this._maxRowsOrColumns},set:function(a){this._setMaxRowsOrColumns(a)}},itemInfo:{enumerable:!0,get:function(){return this._itemInfo},set:function(a){this._itemInfo=a,this._invalidateLayout()}},groupInfo:{enumerable:!0,get:function(){return this._groupInfo},set:function(a){this._groupInfo=a,this._invalidateLayout()}},orientation:{enumerable:!0,get:function(){return"horizontal"}}})}),_LayoutWrapper:c.Namespace._lazy(function(){return c.Class.define(function(a){this.defaultAnimations=!0,this.initialize=function(b,c){a.initialize(b,c)},this.hitTest=function(b,c){return a.hitTest(b,c)},a.uninitialize&&(this.uninitialize=function(){a.uninitialize()}),"numberOfItemsPerItemsBlock"in a&&Object.defineProperty(this,"numberOfItemsPerItemsBlock",{get:function(){return a.numberOfItemsPerItemsBlock}}),a._getItemPosition&&(this._getItemPosition=function(b){return a._getItemPosition(b)}),a.itemsFromRange&&(this.itemsFromRange=function(b,c){return a.itemsFromRange(b,c)}),a.getAdjacent&&(this.getAdjacent=function(b,c){return a.getAdjacent(b,c)}),a.dragOver&&(this.dragOver=function(b,c,d){return a.dragOver(b,c,d)}),a.dragLeave&&(this.dragLeave=function(){return a.dragLeave()});var b={enumerable:!0,get:function(){return"vertical"}};if(void 0!==a.orientation&&(b.get=function(){return a.orientation},b.set=function(b){a.orientation=b}),Object.defineProperty(this,"orientation",b),(a.setupAnimations||a.executeAnimations)&&(this.defaultAnimations=!1,this.setupAnimations=function(){return a.setupAnimations()},this.executeAnimations=function(){return a.executeAnimations()}),a.layout)if(this.defaultAnimations){var c=this;this.layout=function(b,d,e,f){var g,h=F(a.layout(b,d,[],[]));return h.realizedRangeComplete.then(function(){g=!0}),g&&c._layoutAnimations(e,f),h}}else this.layout=function(b,c,d,e){return F(a.layout(b,c,d,e))}},{uninitialize:function(){},numberOfItemsPerItemsBlock:{get:function(){}},layout:function(a,b,c,d){return this.defaultAnimations&&this._layoutAnimations(c,d),F()},itemsFromRange:function(){return{firstIndex:0,lastIndex:Number.MAX_VALUE}},getAdjacent:function(a,b){switch(b){case H.pageUp:case H.upArrow:case H.leftArrow:return{type:a.type,index:a.index-1};case H.downArrow:case H.rightArrow:case H.pageDown:return{type:a.type,index:a.index+1}}},dragOver:function(){},dragLeave:function(){},setupAnimations:function(){},executeAnimations:function(){},_getItemPosition:function(){},_layoutAnimations:function(){}})})});var U={left:"left",top:"top"};c.Namespace._moduleDefine(a,"WinJS.UI",{HeaderPosition:U,_getMargins:G})}),d("WinJS/Controls/ListView/_VirtualizeContentsView",["exports","../../Core/_Global","../../Core/_Base","../../Core/_BaseUtils","../../Promise","../../_Signal","../../Scheduler","../../Utilities/_Dispose","../../Utilities/_ElementUtilities","../../Utilities/_SafeHtml","../../Utilities/_UI","../ItemContainer/_Constants","../ItemContainer/_ItemEventsHandler","./_Helpers","./_ItemsContainer"],function(a,b,c,d,e,f,g,h,i,j,k,l,m,n,o){"use strict";function p(a,b){i._setAttribute(a,"aria-flowto",b.id),i._setAttribute(b,"x-ms-aria-flowfrom",a.id)}c.Namespace._moduleDefine(a,"WinJS.UI",{_VirtualizeContentsView:c.Namespace._lazy(function(){function a(b){for(var c,d=b.job._workItems;d.length&&!b.shouldYield;)(c=d.shift())();b.setWork(a),d.length||b.job.pause()}function q(b,c){var d=g.schedule(a,b,null,c);return d._workItems=[],d.addWork=function(a,b){b?this._workItems.unshift(a):this._workItems.push(a),this.resume()},d.clearWork=function(){this._workItems.length=0},d.dispose=function(){this.cancel(),this._workItems.length=0},d}function r(a){return a._zooming||a._pinching}function s(a,b){return a._isZombie()?e.wrap():r(a)?(+b!==b&&(b=v._waitForSeZoTimeoutDuration),e.timeout(v._waitForSeZoIntervalDuration).then(function(){return b-=v._waitForSeZoIntervalDuration,0>=b?!0:s(a,b)})):e.wrap()}function t(a){if("number"==typeof a){var b=a;a=function(){return{position:b,direction:"right"}}}return a}function u(){}var v=c.Class.define(function(a){this._listView=a,this._forceRelayout=!1,this.maxLeadingPages=d._isiOS?v._iOSMaxLeadingPages:v._defaultPagesToPrefetch,this.maxTrailingPages=d._isiOS?v._iOSMaxTrailingPages:v._defaultPagesToPrefetch,this.items=new o._ItemsContainer(a),this.firstIndexDisplayed=-1,this.lastIndexDisplayed=-1,this.begin=0,this.end=0,this._realizePass=1,this._firstLayoutPass=!0,this._runningAnimations=null,this._renderCompletePromise=e.wrap(),this._state=new w(this),this._createLayoutSignal(),this._createTreeBuildingSignal(),this._layoutWork=null,this._onscreenJob=q(g.Priority.aboveNormal,"on-screen items"),this._frontOffscreenJob=q(g.Priority.normal,"front off-screen items"),this._backOffscreenJob=q(g.Priority.belowNormal,"back off-screen items"),this._scrollbarPos=0,this._direction="right",this._scrollToFunctor=t(0)},{_dispose:function(){this.cleanUp(),this.items=null,this._renderCompletePromise&&this._renderCompletePromise.cancel(),this._renderCompletePromise=null,this._onscreenJob.dispose(),this._frontOffscreenJob.dispose(),this._backOffscreenJob.dispose()},_createItem:function(a,b,c,d){this._listView._writeProfilerMark("createItem("+a+") "+this._getBoundingRectString(a)+",info");var f=this;f._listView._itemsManager._itemFromItemPromiseThrottled(b).done(function(b){b?c(a,b,f._listView._itemsManager._recordFromElement(b)):d(a)},function(b){return d(a),e.wrapError(b)})},_addItem:function(a,b,c,d){if(this._realizePass===d){var e=this._listView._itemsManager._recordFromElement(c);delete this._pendingItemPromises[e.itemPromise.handle],this.items.setItemAt(b,{itemBox:null,container:null,element:c,detached:!0,itemsManagerRecord:e})}},lastItemIndex:function(){return this.containers?this.containers.length-1:-1},_setSkipRealizationForChange:function(a){a?this._realizationLevel!==v._realizationLevel.realize&&(this._realizationLevel=v._realizationLevel.skip):this._realizationLevel=v._realizationLevel.realize},_realizeItems:function(a,b,c,d,h,j,k,n,o,p){function q(a,b){C.push(e._cancelBlocker(b.renderComplete)),u(a)}function r(a,b){function c(a,b){a.updatedDraggableAttribute||!G._listView.itemsDraggable&&!G._listView.itemsReorderable||a.itemsManagerRecord.renderComplete.done(function(){G._realizePass===h&&(i.hasClass(b,l._nonDraggableClass)||(a.itemBox.draggable=!0),a.updatedDraggableAttribute=!0)})}if(G._listView._writeProfilerMark("_realizeItems_appendedItemsToDom,StartTM"),!G._listView._isZombie()){var d,e=0,f=-1,g=-1;for(d=a;b>=d;d++){var j=G.items.itemDataAt(d);if(j){var n=j.element,o=j.itemBox;o||(o=G._listView._itemBoxTemplate.cloneNode(!0),j.itemBox=o,o.appendChild(n),i.addClass(n,l._itemClass),G._listView._setupAriaSelectionObserver(n),G._listView._isSelected(d)&&m._ItemEventsHandler.renderSelection(o,n,!0,!0),G._listView._currentMode().renderDragSourceOnRealizedItem(d,o)),c(j,n);var p=G.getContainer(d);o.parentNode!==p&&(j.container=p,G._appendAndRestoreFocus(p,o),e++,0>f&&(f=d),g=d,G._listView._isSelected(d)&&i.addClass(p,l._selectedClass),i.removeClass(p,l._backdropClass),G.items.elementAvailable(d))}}G._listView._writeProfilerMark("_realizeItems_appendedItemsToDom,StopTM"),e>0&&(G._listView._writeProfilerMark("_realizeItems_appendedItemsToDom:"+e+" ("+f+"-"+g+"),info"),G._reportElementsLevel(k))}}function s(a,b,c,d){function e(a,b){var c=G.items.itemDataAt(a);if(c){var d=c.itemBox;return d&&d.parentNode?b?(i.addClass(d.parentNode,l._backdropClass),d.parentNode.removeChild(d),!0):!1:!0}return!0}if(!p){for(var f=!1;a>=c;)f=e(a,f),a--;for(f=!1;d>=b;)f=e(b,f),b++}}function t(a,b,c,d,f){function g(a){var b=G.items.itemDataAt(a);if(b){var d=b.itemsManagerRecord;d.readyComplete||G._realizePass!==h||c.addWork(function(){G._listView._isZombie()||d.pendingReady&&G._realizePass===h&&(G._listView._writeProfilerMark("pendingReady("+a+"),info"),d.pendingReady())},f)}}for(var i=[],j=a;b>=j;j++){var k=G.items.itemDataAt(j);k&&i.push(k.itemsManagerRecord.itemPromise)}e.join(i).then(function(){if("right"===d)for(var c=a;b>=c;c++)g(c);else for(var c=b;c>=a;c--)g(c)})}function u(a){if(G._realizePass===h){if(a>=n&&o>=a){if(0===--z){if(r(n,o),s(n,o,b,c),G._firstLayoutPass){t(n,o,G._frontOffscreenJob,"right"===k?"left":"right",!0);var d=g.schedulePromiseHigh(null,"WinJS.UI.ListView.entranceAnimation").then(function(){if(!G._listView._isZombie()){G._listView._writeProfilerMark("entranceAnimation,StartTM");var a=G._listView._animateListEntrance(!G._firstEntranceAnimated);return G._firstEntranceAnimated=!0,a}});G._runningAnimations=e.join([G._runningAnimations,d]),G._runningAnimations.done(function(){G._listView._writeProfilerMark("entranceAnimation,StopTM"),G._realizePass===h&&(G._runningAnimations=null,D.complete())}),G._firstLayoutPass=!1,G._listView._isCurrentZoomView&&g.requestDrain(G._onscreenJob.priority)}else t(n,o,G._frontOffscreenJob,k),D.complete();G._updateHeaders(G._listView._canvas,n,o+1).done(function(){E.complete()})}}else n>a?(--B,B%y===0&&r(b,n-1),B||(G._updateHeaders(G._listView._canvas,b,n).done(function(){"right"!==k&&F.complete()}),t(b,n-1,"right"!==k?G._frontOffscreenJob:G._backOffscreenJob,"left"))):a>o&&(--A,A%y===0&&r(o+1,c-1),A||(G._updateHeaders(G._listView._canvas,o+1,c).then(function(){"right"===k&&F.complete()}),t(o+1,c-1,"right"===k?G._frontOffscreenJob:G._backOffscreenJob,"right")));x--,0===x&&(G._renderCompletePromise=e.join(C).then(null,function(a){var b=Array.isArray(a)&&a.some(function(a){return a&&!(a instanceof Error&&"Canceled"===a.name)});return b?e.wrapError(a):void 0}),(G._headerRenderPromises||e.wrap()).done(function(){g.schedule(function(){G._listView._isZombie()?L.cancel():L.complete()},Math.min(G._onscreenJob.priority,G._backOffscreenJob.priority),null,"WinJS.UI.ListView._allItemsRealized")}))}}function v(b,c,d){if(G._realizePass===h){var c=d.element;G._addItem(a,b,c,h),q(b,d)}}var w="_realizeItems("+b+"-"+(c-1)+") visible("+n+"-"+o+")";this._listView._writeProfilerMark(w+",StartTM"),k=k||"right";var x=c-b,y=o-n+1,z=y,A=c-o-1,B=n-b,C=[],D=new f,E=new f,F=new f,G=this;if(x>0){var H=0,I=0,J=0;G.firstIndexDisplayed=n,G.lastIndexDisplayed=o;var K=G._listView._isCurrentZoomView;G._highPriorityRealize&&(G._firstLayoutPass||G._hasAnimationInViewportPending)?(G._highPriorityRealize=!1,G._onscreenJob.priority=g.Priority.high,G._frontOffscreenJob.priority=g.Priority.normal,G._backOffscreenJob.priority=g.Priority.belowNormal):G._highPriorityRealize?(G._highPriorityRealize=!1,G._onscreenJob.priority=g.Priority.high,G._frontOffscreenJob.priority=g.Priority.high-1,G._backOffscreenJob.priority=g.Priority.high-1):K?(G._onscreenJob.priority=g.Priority.aboveNormal,G._frontOffscreenJob.priority=g.Priority.normal,G._backOffscreenJob.priority=g.Priority.belowNormal):(G._onscreenJob.priority=g.Priority.belowNormal,G._frontOffscreenJob.priority=g.Priority.idle,G._backOffscreenJob.priority=g.Priority.idle);var L=new f,M=G._listView._versionManager.cancelOnNotification(L.promise),N=function(a,b){b.startStage1&&b.stage0.then(function(){G._realizePass===h&&b.startStage1&&a.addWork(b.startStage1)})},O=function(a,b){var c=G.items.itemDataAt(b);if(!c){var d=G._listView._itemsManager._itemPromiseAtIndex(b);G._pendingItemPromises[d.handle]=d,delete G._previousRealizationPendingItemPromises[d.handle],a.addWork(function(){if(!G._listView._isZombie()&&(H++,G._createItem(b,d,v,u),!G._listView._isZombie()&&G._realizePass===h&&d.handle)){var c=G._listView._itemsManager._recordFromHandle(d.handle);N(a,c)}})}},P=function(a,b,c){for(var d=b;c>=d;d++)O(a,d)},Q=function(a,b,c){for(var d=c;d>=b;d--)O(a,d)},R=function(a,b,c){for(var d=b;c>=d;d++){var e=G.items.itemDataAt(d);if(e){var f=e.itemsManagerRecord;q(d,f),I++,N(a,f)}}};this._previousRealizationPendingItemPromises=this._pendingItemPromises||{},this._pendingItemPromises={};var S;"left"===k?(Q(G._onscreenJob,n,o),Q(G._frontOffscreenJob,b,n-1),S=b>n-1):(P(G._onscreenJob,n,o),P(G._frontOffscreenJob,o+1,c-1),S=o+1>c-1);for(var T=0,U=Object.keys(this._previousRealizationPendingItemPromises),V=U.length;V>T;T++){var W=U[T];G._listView._itemsManager.releaseItemPromise(this._previousRealizationPendingItemPromises[W])}this._previousRealizationPendingItemPromises={},R(G._onscreenJob,n,o),"left"===k?R(G._frontOffscreenJob,b,n-1):R(G._frontOffscreenJob,o+1,c-1);var X=z===o-n+1;return G._firstLayoutPass?G._listView._canvas.style.opacity=0:X?G._listView._showProgressBar(G._listView._element,"50%","50%"):G._listView._hideProgressBar(),G._frontOffscreenJob.pause(),G._backOffscreenJob.pause(),E.promise.done(function(){G._frontOffscreenJob.resume(),S&&F.complete()},function(){L.cancel()}),F.promise.done(function(){G._listView._writeProfilerMark("frontItemsRealized,info"),"left"===k?(P(G._backOffscreenJob,o+1,c-1),R(G._backOffscreenJob,o+1,c-1)):(Q(G._backOffscreenJob,b,n-1),R(G._backOffscreenJob,b,n-1)),G._backOffscreenJob.resume()}),L.promise.done(function(){G._listView._versionManager.clearCancelOnNotification(M),G._listView._writeProfilerMark(w+" complete(created:"+H+" updated:"+I+"),info")},function(a){return G._listView._versionManager.clearCancelOnNotification(M),G._onscreenJob.clearWork(),G._frontOffscreenJob.clearWork(),G._backOffscreenJob.clearWork(),D.cancel(),E.cancel(),G._listView._writeProfilerMark(w+" canceled(created:"+H+" updated:"+I+" clean:"+J+"),info"),e.wrapError(a)}),G._listView._writeProfilerMark(w+",StopTM"),{viewportItemsRealized:E.promise,allItemsRealized:L.promise,loadingCompleted:e.join([L.promise,D.promise]).then(function(){for(var a=[],d=b;c>d;d++){var f=G.items.itemDataAt(d);f&&a.push(f.itemsManagerRecord.itemReadyPromise)}return e._cancelBlocker(e.join(a))})}}return G._listView._writeProfilerMark(w+",StopTM"),{viewportItemsRealized:e.wrap(),allItemsRealized:e.wrap(),loadingCompleted:e.wrap()}},_setAnimationInViewportState:function(a){if(this._hasAnimationInViewportPending=!1,a&&a.length>0)for(var b=this._listView._getViewportLength(),c=this._listView._layout.itemsFromRange(this._scrollbarPos,this._scrollbarPos+b-1),d=0,e=a.length;e>d;d++){var f=a[d];if(f.newIndex>=c.firstIndex&&f.newIndex<=c.lastIndex&&f.newIndex!==f.oldIndex){this._hasAnimationInViewportPending=!0;break}}},_addHeader:function(a,b){var c=this;return this._listView._groups.renderGroup(b).then(function(a){if(a){a.element.tabIndex=0;var d=c._getHeaderContainer(b);a.element.parentNode!==d&&(d.appendChild(a.element),i.addClass(a.element,l._headerClass)),c._listView._groups.setDomElement(b,a.element)}})},_updateHeaders:function(a,b,c){function d(b){var c=g._listView._groups.group(b);if(c&&!c.header){var d=c.headerPromise;return d||(d=c.headerPromise=g._addHeader(a,b),d.done(function(){c.headerPromise=null},function(){c.headerPromise=null})),d}return e.wrap()}function f(){g._headerRenderPromises=null}var g=this;this._listView._groups.removeElements();var h=this._listView._groups.groupFromItem(b),i=h,j=this._listView._groups.groupFromItem(c-1),k=[];if(null!==i)for(;j>=i;i++)k.push(d(i));return this._headerRenderPromises=e.join(k,this._headerRenderPromises).then(f,f),this._headerRenderPromises||e.wrap()},_unrealizeItem:function(a){var b,c=this._listView;this._listView._writeProfilerMark("_unrealizeItem("+a+"),info");var d=c._selection._getFocused();d.type===k.ObjectType.item&&d.index===a&&(c._unsetFocusOnItem(),b=!0);var e=this.items.itemDataAt(a),f=e.element,g=e.itemBox;g&&g.parentNode&&(i.removeClass(g.parentNode,l._selectedClass),i.removeClass(g.parentNode,l._footprintClass),i.addClass(g.parentNode,l._backdropClass),g.parentNode.removeChild(g)),e.container=null,c._currentMode().itemUnrealized&&c._currentMode().itemUnrealized(a,g),this.items.removeItem(a),e.removed||c._itemsManager.releaseItem(f),h._disposeElement(f),b&&c._setFocusOnItem(c._selection._getFocused())},_unrealizeGroup:function(a){var b,c=a.header,d=this._listView._selection._getFocused();d.type===k.ObjectType.groupHeader&&this._listView._groups.group(d.index)===a&&(this._listView._unsetFocusOnItem(),b=!0),c.parentNode&&c.parentNode.removeChild(c),h._disposeElement(c),a.header=null,a.left=-1,a.top=-1,b&&this._listView._setFocusOnItem(this._listView._selection._getFocused())},_unrealizeItems:function(a){var b=this,c=0;this.items.eachIndex(function(d){return d<b.begin||d>=b.end?(b._unrealizeItem(d),a&&++c>=a):void 0});var d=this._listView._groups,e=d.groupFromItem(this.begin);if(null!==e)for(var f=d.groupFromItem(this.end-1),g=0,h=d.length();h>g;g++){var i=d.group(g);(e>g||g>f)&&i.header&&this._unrealizeGroup(i)}},_unrealizeExcessiveItems:function(){var a=this.items.count(),b=this.end-this.begin,c=b+this._listView._maxDeferredItemCleanup;this._listView._writeProfilerMark("_unrealizeExcessiveItems realized("+a+") approved("+c+"),info"),a>c&&this._unrealizeItems(a-c)},_lazilyUnrealizeItems:function(){this._listView._writeProfilerMark("_lazilyUnrealizeItems,StartTM");var a=this;return s(this._listView).then(function(){function b(){a._listView._writeProfilerMark("_lazilyUnrealizeItems,StopTM")}if(a._listView._isZombie())return void b();var c=[];a.items.eachIndex(function(b){(b<a.begin||b>=a.end)&&c.push(b)}),a._listView._writeProfilerMark("_lazilyUnrealizeItems itemsToUnrealize("+c.length+"),info");var d=[],f=a._listView._groups,h=f.groupFromItem(a.begin);if(null!==h)for(var i=f.groupFromItem(a.end-1),j=0,k=f.length();k>j;j++){var l=f.group(j);(h>j||j>i)&&l.header&&d.push(l)}if(c.length||d.length){var m,n=new e(function(b){function e(f){if(!a._listView._isZombie()){for(var g=-1,h=-1,i=0,j=r(a._listView);c.length&&!j&&!f.shouldYield;){var k=c.shift();a._unrealizeItem(k),i++,0>g&&(g=k),h=k}for(a._listView._writeProfilerMark("unrealizeWorker removeItems:"+i+" ("+g+"-"+h+"),info");d.length&&!j&&!f.shouldYield;)a._unrealizeGroup(d.shift());c.length||d.length?j?f.setPromise(s(a._listView).then(function(){return e})):f.setWork(e):b()}}m=g.schedule(e,g.Priority.belowNormal,null,"WinJS.UI.ListView._lazilyUnrealizeItems")});return n.then(b,function(b){return m.cancel(),a._listView._writeProfilerMark("_lazilyUnrealizeItems canceled,info"),a._listView._writeProfilerMark("_lazilyUnrealizeItems,StopTM"),e.wrapError(b)})}return b(),e.wrap()})},_getBoundingRectString:function(a){var b;if(a>=0&&a<this.containers.length){var c=this._listView._layout._getItemPosition(a);c&&(b="["+c.left+"; "+c.top+"; "+c.width+"; "+c.height+" ]")}return b||""},_clearDeferTimeout:function(){this.deferTimeout&&(this.deferTimeout.cancel(),this.deferTimeout=null),-1!==this.deferredActionCancelToken&&(this._listView._versionManager.clearCancelOnNotification(this.deferredActionCancelToken),this.deferredActionCancelToken=-1)},_setupAria:function(a){function b(){d._listView._writeProfilerMark("aria work,StopTM")}function c(a){var b=d._listView._groups,c=b.group(a+1);return c?Math.min(c.startIndex-1,d.end-1):d.end-1}if(!this._listView._isZombie()){var d=this;return this._listView._createAriaMarkers(),this._listView._itemsCount().then(function(f){if(!(f>0&&-1!==d.firstIndexDisplayed&&-1!==d.lastIndexDisplayed))return e.wrap();d._listView._writeProfilerMark("aria work,StartTM");var h,j,k,l,m,n,o=d._listView._ariaStartMarker,q=d._listView._ariaEndMarker,t=d.begin,u=d.items.itemAt(d.begin);return u?(i._ensureId(u),d._listView._groupsEnabled()?(j=d._listView._groups,k=l=j.groupFromItem(d.begin),m=j.group(l),n=c(l),i._ensureId(m.header),i._setAttribute(m.header,"role",d._listView._headerRole),i._setAttribute(m.header,"x-ms-aria-flowfrom",o.id),p(m.header,u),i._setAttribute(m.header,"tabindex",d._listView._tabIndex)):i._setAttribute(u,"x-ms-aria-flowfrom",o.id),new e(function(e){var o=a;h=g.schedule(function v(a){if(d._listView._isZombie())return void b();for(;t<d.end;t++){if(!o&&r(d._listView))return void a.setPromise(s(d._listView).then(function(a){return o=a,v}));if(a.shouldYield)return void a.setWork(v);u=d.items.itemAt(t);var g=d.items.itemAt(t+1);if(g&&i._ensureId(g),i._setAttribute(u,"role",d._listView._itemRole),i._setAttribute(u,"aria-setsize",f),i._setAttribute(u,"aria-posinset",t+1),i._setAttribute(u,"tabindex",d._listView._tabIndex),d._listView._groupsEnabled())if(t!==n&&g)p(u,g); else{var h=j.group(l+1);h&&h.header&&g?(i._setAttribute(h.header,"tabindex",d._listView._tabIndex),i._setAttribute(h.header,"role",d._listView._headerRole),i._ensureId(h.header),p(u,h.header),p(h.header,g)):i._setAttribute(u,"aria-flowto",q.id),l++,m=h,n=c(l)}else g?p(u,g):i._setAttribute(u,"aria-flowto",q.id);if(!g)break}d._listView._fireAccessibilityAnnotationCompleteEvent(d.begin,t,k,l-1),b(),e()},g.Priority.belowNormal,null,"WinJS.UI.ListView._setupAria")},function(){h.cancel(),b()})):void b()})}},_setupDeferredActions:function(){function a(){b._listView._isZombie()||(b.deferTimeout=null,b._listView._versionManager.clearCancelOnNotification(b.deferredActionCancelToken),b.deferredActionCancelToken=-1)}this._listView._writeProfilerMark("_setupDeferredActions,StartTM");var b=this;this._clearDeferTimeout(),this.deferTimeout=this._lazilyRemoveRedundantItemsBlocks().then(function(){return e.timeout(l._DEFERRED_ACTION)}).then(function(){return s(b._listView)}).then(function(a){return b._setupAria(a)}).then(a,function(b){return a(),e.wrapError(b)}),this.deferredActionCancelToken=this._listView._versionManager.cancelOnNotification(this.deferTimeout),this._listView._writeProfilerMark("_setupDeferredActions,StopTM")},_updateAriaMarkers:function(a,b,c){function d(){return f.items.itemAt(b)}function e(){for(var a=c;a>=b;a--)if(f.items.itemAt(a))return f.items.itemAt(a);return null}var f=this;if(!this._listView._isZombie()){this._listView._createAriaMarkers();var g,h,j=this._listView._ariaStartMarker,k=this._listView._ariaEndMarker;if(-1!==b&&-1!==c&&c>=b&&(g=d(),h=e()),!a&&g&&h){if(i._ensureId(g),i._ensureId(h),this._listView._groupsEnabled()){var l=this._listView._groups,m=l.group(l.groupFromItem(b));m.header&&(i._ensureId(m.header),b===m.startIndex?i._setAttribute(j,"aria-flowto",m.header.id):i._setAttribute(j,"aria-flowto",g.id))}else i._setAttribute(j,"aria-flowto",g.id);i._setAttribute(k,"x-ms-aria-flowfrom",h.id)}else p(j,k),this._listView._fireAccessibilityAnnotationCompleteEvent(-1,-1)}},updateAriaForAnnouncement:function(a,b){if(a!==this._listView.header&&a!==this._listView.footer){var c=-1,d=k.ObjectType.item;i.hasClass(a,l._headerClass)?(c=this._listView._groups.index(a),d=k.ObjectType.groupHeader,i._setAttribute(a,"role",this._listView._headerRole),i._setAttribute(a,"tabindex",this._listView._tabIndex)):(c=this.items.index(a),i._setAttribute(a,"aria-setsize",b),i._setAttribute(a,"aria-posinset",c+1),i._setAttribute(a,"role",this._listView._itemRole),i._setAttribute(a,"tabindex",this._listView._tabIndex)),d===k.ObjectType.groupHeader?this._listView._fireAccessibilityAnnotationCompleteEvent(-1,-1,c,c):this._listView._fireAccessibilityAnnotationCompleteEvent(c,c,-1,-1)}},_reportElementsLevel:function(a){function b(a,b){for(var c=0,e=a;b>=e;e++){var f=d.itemDataAt(e);f&&f.container&&c++}return c}var c,d=this.items;c=Math.floor("right"===a?100*b(this.firstIndexDisplayed,this.end-1)/(this.end-this.firstIndexDisplayed):100*b(this.begin,this.lastIndexDisplayed)/(this.lastIndexDisplayed-this.begin+1)),this._listView._writeProfilerMark("elementsLevel level("+c+"),info")},_createHeaderContainer:function(a){return this._createSurfaceChild(l._headerContainerClass,a)},_createItemsContainer:function(a){var c=this._createSurfaceChild(l._itemsContainerClass,a),d=b.document.createElement("div");return d.className=l._padderClass,c.appendChild(d),c},_ensureContainerInDOM:function(a){var b=this.containers[a];return b&&!this._listView._canvas.contains(b)?(this._forceItemsBlocksInDOM(a,a+1),!0):!1},_ensureItemsBlocksInDOM:function(a,b){if(this._expandedRange){var c=this._expandedRange.first.index,d=this._expandedRange.last.index+1;c>=a&&b>c?b=Math.max(b,d):d>a&&b>=d&&(a=Math.min(a,c))}this._forceItemsBlocksInDOM(a,b)},_removeRedundantItemsBlocks:function(){-1!==this.begin&&-1!==this.end&&this._forceItemsBlocksInDOM(this.begin,this.end)},_lazilyRemoveRedundantItemsBlocks:function(){this._listView._writeProfilerMark("_lazilyRemoveRedundantItemsBlocks,StartTM");var a=this;return s(this._listView).then(function(){function b(){a._listView._writeProfilerMark("_lazilyRemoveRedundantItemsBlocks,StopTM")}if(a._listView._isZombie())return void b();if(a._expandedRange&&-1!==a.begin&&-1!==a.end&&(a._expandedRange.first.index<a.begin||a._expandedRange.last.index+1>a.end)){var c,d=new e(function(b){function d(c){if(!a._listView._isZombie()){for(var e=r(a._listView);a._expandedRange.first.index<a.begin&&!e&&!c.shouldYield;){var f=Math.min(a.begin,a._expandedRange.first.index+a._blockSize*v._blocksToRelease);a._forceItemsBlocksInDOM(f,a.end)}for(;a._expandedRange.last.index+1>a.end&&!e&&!c.shouldYield;){var g=Math.max(a.end,a._expandedRange.last.index-a._blockSize*v._blocksToRelease);a._forceItemsBlocksInDOM(a.begin,g)}a._expandedRange.first.index<a.begin||a._expandedRange.last.index+1>a.end?e?c.setPromise(s(a._listView).then(function(){return d})):c.setWork(d):b()}}c=g.schedule(d,g.Priority.belowNormal,null,"WinJS.UI.ListView._lazilyRemoveRedundantItemsBlocks")});return d.then(b,function(b){return c.cancel(),a._listView._writeProfilerMark("_lazilyRemoveRedundantItemsBlocks canceled,info"),a._listView._writeProfilerMark("_lazilyRemoveRedundantItemsBlocks,StopTM"),e.wrapError(b)})}return b(),e.wrap()})},_forceItemsBlocksInDOM:function(a,b){function c(a,b){var c=a.element.firstElementChild;c.style[q]=b}function d(a){for(var b=0;b<n.tree.length;b++)for(var c=n.tree[b].itemsContainer,d=0,e=c.itemsBlocks.length;e>d;d++)if(a(c,c.itemsBlocks[d]))return}function e(a){n._listView._writeProfilerMark("_itemsBlockExtent,StartTM"),n._listView._itemsBlockExtent=i[n._listView._horizontal()?"getTotalWidth":"getTotalHeight"](a.element),n._listView._writeProfilerMark("_itemsBlockExtent("+n._listView._itemsBlockExtent+"),info"),n._listView._writeProfilerMark("_itemsBlockExtent,StopTM")}function f(){return-1===n._listView._itemsBlockExtent&&d(function(a,b){return b.items.length===n._blockSize&&b.element.parentNode===a.element?(e(b),!0):!1}),-1===n._listView._itemsBlockExtent&&d(function(a,b){return b.items.length===n._blockSize?(a.element.appendChild(b.element),e(b),a.element.removeChild(b.element),!0):!1}),n._listView._itemsBlockExtent}function g(a,b,c){function d(b){var c=a.itemsBlocks[b];c&&c.element.parentNode===a.element&&(a.element.removeChild(c.element),p++)}if(Array.isArray(b))b.forEach(d);else for(var e=b;c>e;e++)d(e)}function h(a,b,c){for(var d=a.element.firstElementChild,e=d,f=b;c>f;f++){var g=a.itemsBlocks[f];g&&(g.element.parentNode!==a.element&&(a.element.insertBefore(g.element,e.nextElementSibling),o++),e=g.element)}}function j(a){if(a<n.tree.length){n._listView._writeProfilerMark("collapseGroup("+a+"),info");var b=n.tree[a].itemsContainer;g(b,0,b.itemsBlocks.length),c(b,"")}}function k(a){if(a<n.tree.length){n._listView._writeProfilerMark("expandGroup("+a+"),info");var b=n.tree[a].itemsContainer;h(b,0,b.itemsBlocks.length),c(b,"")}}function l(a,b){function c(a,b){for(var c=[],d=a;b>=d;d++)c.push(d);return c}var d=b[0],e=b[1],f=a[0],g=a[1];return f>e||d>g?c(f,g):d>f&&g>e?c(f,d-1).concat(c(e+1,g)):d>f?c(f,d-1):g>e?c(e+1,g):null}if(this._blockSize){var m="_forceItemsBlocksInDOM begin("+a+") end("+b+"),";this._listView._writeProfilerMark(m+"StartTM");var n=this,o=0,p=0,q="padding"+(this._listView._horizontal()?"Left":"Top"),r=this._listView._groups.groupFromItem(a),s=this._listView._groups.groupFromItem(b-1),t=this._listView._groups.group(r),u=n.tree[r].itemsContainer,v=Math.floor((a-t.startIndex)/this._blockSize),w=this._listView._groups.group(s),x=n.tree[s].itemsContainer,y=Math.floor((b-1-w.startIndex)/this._blockSize);v&&-1===n._listView._itemsBlockExtent&&d(function(a,b){return b.items.length===n._blockSize&&b.element.parentNode===a.element?(e(b),!0):!1});var z=this._expandedRange?l([this._expandedRange.first.groupIndex,this._expandedRange.last.groupIndex],[r,s]):null;if(z&&z.forEach(j),this._expandedRange&&this._expandedRange.first.groupKey===t.key){var A=l([this._expandedRange.first.block,Number.MAX_VALUE],[v,Number.MAX_VALUE]);A&&g(u,A)}else this._expandedRange&&r>=this._expandedRange.first.groupIndex&&r<=this._expandedRange.last.groupIndex&&g(u,0,v);if(r!==s?(h(u,v,u.itemsBlocks.length),h(x,0,y+1)):h(u,v,y+1),this._expandedRange&&this._expandedRange.last.groupKey===w.key){var A=l([0,this._expandedRange.last.block],[0,y]);A&&g(x,A)}else this._expandedRange&&s>=this._expandedRange.first.groupIndex&&s<=this._expandedRange.last.groupIndex&&g(x,y+1,x.itemsBlocks.length);c(u,v?v*f()+"px":""),r!==s&&c(x,"");for(var B=r+1;s>B;B++)k(B);this._expandedRange={first:{index:a,groupIndex:r,groupKey:t.key,block:v},last:{index:b-1,groupIndex:s,groupKey:w.key,block:y}},this._listView._writeProfilerMark("_forceItemsBlocksInDOM groups("+r+"-"+s+") blocks("+v+"-"+y+") added("+o+") removed("+p+"),info"),this._listView._writeProfilerMark(m+"StopTM")}},_realizePageImpl:function(){var a=this,b="realizePage(scrollPosition:"+this._scrollbarPos+" forceLayout:"+this._forceRelayout+")";return this._listView._writeProfilerMark(b+",StartTM"),this._listView._versionManager.locked?(this._listView._versionManager.unlocked.done(function(){a._listView._isZombie()||a._listView._batchViewUpdates(l._ViewChange.realize,l._ScrollToPriority.low,a._listView.scrollPosition)}),this._listView._writeProfilerMark(b+",StopTM"),e.cancel):new e(function(c){function d(){c(),k.complete()}function g(){a._listView._hideProgressBar(),a._state.setLoadingState(a._listView._LoadingState.viewPortLoaded),a._executeAnimations&&a._setState(F,k.promise)}function h(b){a._updateAriaMarkers(0===b,a.firstIndexDisplayed,a.lastIndexDisplayed),a._state.setLoadingState&&a._state.setLoadingState(a._listView._LoadingState.itemsLoaded)}function j(b){a._listView._clearInsertedItems(),a._listView._groups.removeElements(),g(),h(b),d()}var k=new f;a._state.setLoadingState(a._listView._LoadingState.itemsLoading),a._firstLayoutPass&&a._listView._showProgressBar(a._listView._element,"50%","50%");var l=a.containers.length;if(l){var m,n,o=a.maxLeadingPages,p=a.maxTrailingPages,q=a._listView._getViewportLength();if(a._listView._zooming)m=n=0;else if(v._disableCustomPagesPrefetch)m=n=v._defaultPagesToPrefetch;else{m="left"===a._direction?o:p;var r=Math.max(0,m-a._scrollbarPos/q);n=Math.min(o,r+("right"===a._direction?o:p))}var s=Math.max(0,a._scrollbarPos-m*q),t=a._scrollbarPos+(1+n)*q,u=a._listView._layout.itemsFromRange(s,t-1);if((u.firstIndex<0||u.firstIndex>=l)&&(u.lastIndex<0||u.lastIndex>=l))a.begin=-1,a.end=-1,a.firstIndexDisplayed=-1,a.lastIndexDisplayed=-1,j(l);else{var w=i._clamp(u.firstIndex,0,l-1),x=i._clamp(u.lastIndex+1,0,l),y=a._listView._layout.itemsFromRange(a._scrollbarPos,a._scrollbarPos+q-1),z=i._clamp(y.firstIndex,0,l-1),A=i._clamp(y.lastIndex,0,l-1);if(a._realizationLevel!==v._realizationLevel.skip||a.lastRealizePass||z!==a.firstIndexDisplayed||A!==a.lastIndexDisplayed)if((a._forceRelayout||w!==a.begin||x!==a.end||z!==a.firstIndexDisplayed||A!==a.lastIndexDisplayed)&&x>w&&t>s){a._listView._writeProfilerMark("realizePage currentInView("+z+"-"+A+") previousInView("+a.firstIndexDisplayed+"-"+a.lastIndexDisplayed+") change("+(z-a.firstIndexDisplayed)+"),info"),a._cancelRealize();var B=a._realizePass;a.begin=w,a.end=x,a.firstIndexDisplayed=z,a.lastIndexDisplayed=A,a.deletesWithoutRealize=0,a._ensureItemsBlocksInDOM(a.begin,a.end);var C=a._realizeItems(a._listView._itemCanvas,a.begin,a.end,l,B,a._scrollbarPos,a._direction,z,A,a._forceRelayout);a._forceRelayout=!1;var D=C.viewportItemsRealized.then(function(){return g(),C.allItemsRealized}).then(function(){return a._realizePass===B?a._updateHeaders(a._listView._canvas,a.begin,a.end).then(function(){h(l)}):void 0}).then(function(){return C.loadingCompleted}).then(function(){a._unrealizeExcessiveItems(),a.lastRealizePass=null,d()},function(b){return a._realizePass===B&&(a.lastRealizePass=null,a.begin=-1,a.end=-1),e.wrapError(b)});a.lastRealizePass=e.join([C.viewportItemsRealized,C.allItemsRealized,C.loadingCompleted,D]),a._unrealizeExcessiveItems()}else a.lastRealizePass?a.lastRealizePass.then(d):j(l);else a.begin=w,a.end=w+Object.keys(a.items._itemData).length,a._updateHeaders(a._listView._canvas,a.begin,a.end).done(function(){a.lastRealizePass=null,j(l)})}}else a.begin=-1,a.end=-1,a.firstIndexDisplayed=-1,a.lastIndexDisplayed=-1,j(l);a._reportElementsLevel(a._direction),a._listView._writeProfilerMark(b+",StopTM")})},realizePage:function(a,b,c,d){this._scrollToFunctor=t(a),this._forceRelayout=this._forceRelayout||b,this._scrollEndPromise=c,this._listView._writeProfilerMark(this._state.name+"_realizePage,info"),this._state.realizePage(d||A)},onScroll:function(a,b){this.realizePage(a,!1,b,C)},reload:function(a,b){this._listView._isZombie()||(this._scrollToFunctor=t(a),this._forceRelayout=!0,this._highPriorityRealize=!!b,this.stopWork(!0),this._listView._writeProfilerMark(this._state.name+"_rebuildTree,info"),this._state.rebuildTree())},refresh:function(a){this._listView._isZombie()||(this._scrollToFunctor=t(a),this._forceRelayout=!0,this._highPriorityRealize=!0,this.stopWork(),this._listView._writeProfilerMark(this._state.name+"_relayout,info"),this._state.relayout())},waitForValidScrollPosition:function(a){var b=this,c=this._listView._viewport[this._listView._scrollLength]-this._listView._getViewportLength();return a>c?b._listView._itemsCount().then(function(c){return b.containers.length<c?e._cancelBlocker(b._creatingContainersWork&&b._creatingContainersWork.promise).then(function(){return b._getLayoutCompleted()}).then(function(){return a}):a}):e.wrap(a)},waitForEntityPosition:function(a){var b=this;return a.type===k.ObjectType.header||a.type===k.ObjectType.footer?e.wrap():(this._listView._writeProfilerMark(this._state.name+"_waitForEntityPosition("+a.type+": "+a.index+"),info"),e._cancelBlocker(this._state.waitForEntityPosition(a).then(function(){return a.type!==k.ObjectType.groupHeader&&a.index>=b.containers.length||a.type===k.ObjectType.groupHeader&&b._listView._groups.group(a.index).startIndex>=b.containers.length?b._creatingContainersWork&&b._creatingContainersWork.promise:void 0}).then(function(){return b._getLayoutCompleted()})))},stopWork:function(a){this._listView._writeProfilerMark(this._state.name+"_stop,info"),this._state.stop(a),this._layoutWork&&this._layoutWork.cancel(),a&&this._creatingContainersWork&&this._creatingContainersWork.cancel(),a&&(this._state=new w(this))},_cancelRealize:function(){this._listView._writeProfilerMark("_cancelRealize,StartTM"),(this.lastRealizePass||this.deferTimeout)&&(this._forceRelayout=!0),this._clearDeferTimeout(),this._realizePass++,this._headerRenderPromises&&(this._headerRenderPromises.cancel(),this._headerRenderPromises=null);var a=this.lastRealizePass;a&&(this.lastRealizePass=null,this.begin=-1,this.end=-1,a.cancel()),this._listView._writeProfilerMark("_cancelRealize,StopTM")},resetItems:function(a){if(!this._listView._isZombie()){this.firstIndexDisplayed=-1,this.lastIndexDisplayed=-1,this._runningAnimations=null,this._executeAnimations=!1;var b=this._listView;this._firstLayoutPass=!0,b._unsetFocusOnItem(),b._currentMode().onDataChanged&&b._currentMode().onDataChanged(),this.items.each(function(c,d){a&&d.parentNode&&d.parentNode.parentNode&&d.parentNode.parentNode.removeChild(d.parentNode),b._itemsManager.releaseItem(d),h._disposeElement(d)}),this.items.removeItems(),this._deferredReparenting=[],a&&b._groups.removeElements(),b._clearInsertedItems()}},reset:function(){if(this.stopWork(!0),this._state=new w(this),this.resetItems(),!this._listView._isZombie()){var a=this._listView;a._groups.resetGroups(),a._resetCanvas(),this.tree=null,this.keyToGroupIndex=null,this.containers=null,this._expandedRange=null}},cleanUp:function(){this.stopWork(!0),this._runningAnimations&&this._runningAnimations.cancel();var a=this._listView._itemsManager;this.items.each(function(b,c){a.releaseItem(c),h._disposeElement(c)}),this._listView._unsetFocusOnItem(),this.items.removeItems(),this._deferredReparenting=[],this._listView._groups.resetGroups(),this._listView._resetCanvas(),this.tree=null,this.keyToGroupIndex=null,this.containers=null,this._expandedRange=null,this.destroyed=!0},getContainer:function(a){return this.containers[a]},_getHeaderContainer:function(a){return this.tree[a].header},_getGroups:function(a){if(this._listView._groupDataSource){var b=this._listView._groups.groups,c=[];if(a)for(var d=0,e=b.length;e>d;d++){var f=b[d],g=e>d+1?b[d+1].startIndex:a;c.push({key:f.key,size:g-f.startIndex})}return c}return[{key:"-1",size:a}]},_createChunk:function(a,b,c){function d(a,b){var d=a.element.children,e=d.length,g=Math.min(b-a.items.length,c);j.insertAdjacentHTMLUnsafe(a.element,"beforeend",n._repeat("<div class='win-container win-backdrop'></div>",g));for(var h=0;g>h;h++){var i=d[e+h];a.items.push(i),f.containers.push(i)}}function e(a){var b={header:f._listView._groupDataSource?f._createHeaderContainer():null,itemsContainer:{element:f._createItemsContainer(),items:[]}};f.tree.push(b),f.keyToGroupIndex[a.key]=f.tree.length-1,d(b.itemsContainer,a.size)}var f=this;if(this._listView._writeProfilerMark("createChunk,StartTM"),this.tree.length&&this.tree.length<=a.length){var g=this.tree[this.tree.length-1],h=a[this.tree.length-1].size;if(g.itemsContainer.items.length<h)return d(g.itemsContainer,h),void this._listView._writeProfilerMark("createChunk,StopTM")}this.tree.length<a.length&&e(a[this.tree.length]),this._listView._writeProfilerMark("createChunk,StopTM")},_createChunkWithBlocks:function(a,c,d,e){function f(a,c){var f,g=a.itemsBlocks.length?a.itemsBlocks[a.itemsBlocks.length-1]:null;if(c=Math.min(c,e),g&&g.items.length<d){var i=Math.min(c,d-g.items.length),k=g.items.length,f=(a.itemsBlocks.length-1)*d+k,l=n._stripedContainers(i,f);j.insertAdjacentHTMLUnsafe(g.element,"beforeend",l),w=g.element.children;for(var m=0;i>m;m++){var o=w[k+m];g.items.push(o),h.containers.push(o)}c-=i}f=a.itemsBlocks.length*d;var p=Math.floor(c/d),q="",r=f,s=f+d;if(p>0){var t=["<div class='win-itemsblock'>"+n._stripedContainers(d,r)+"</div>","<div class='win-itemsblock'>"+n._stripedContainers(d,s)+"</div>"];q=n._repeat(t,p),f+=p*d}var u=c%d;u>0&&(q+="<div class='win-itemsblock'>"+n._stripedContainers(u,f)+"</div>",f+=u,p++);var v=b.document.createElement("div");j.setInnerHTMLUnsafe(v,q);for(var w=v.children,x=0;p>x;x++){var y=w[x],z={element:y,items:n._nodeListToArray(y.children)};a.itemsBlocks.push(z);for(var A=0;A<z.items.length;A++)h.containers.push(z.items[A])}}function g(a){var b={header:h._listView._groupDataSource?h._createHeaderContainer():null,itemsContainer:{element:h._createItemsContainer(),itemsBlocks:[]}};h.tree.push(b),h.keyToGroupIndex[a.key]=h.tree.length-1,f(b.itemsContainer,a.size)}var h=this;if(this._listView._writeProfilerMark("createChunk,StartTM"),this.tree.length&&this.tree.length<=a.length){var i=this.tree[this.tree.length-1].itemsContainer,k=a[this.tree.length-1].size,l=0;if(i.itemsBlocks.length&&(l=(i.itemsBlocks.length-1)*d+i.itemsBlocks[i.itemsBlocks.length-1].items.length),k>l)return f(i,k-l),void this._listView._writeProfilerMark("createChunk,StopTM")}this.tree.length<a.length&&g(a[this.tree.length]),this._listView._writeProfilerMark("createChunk,StopTM")},_generateCreateContainersWorker:function(){var a=this,b=0,c=!1;return function e(f){a._listView._versionManager.locked?f.setPromise(a._listView._versionManager.unlocked.then(function(){return e})):a._listView._itemsCount().then(function(g){var h=!c&&r(a._listView);if(h)f.setPromise(s(a._listView).then(function(a){return c=a,e}));else{if(a._listView._isZombie())return;c=!1;var i=d._now()+v._createContainersJobTimeslice,j=a._getGroups(g),k=a.containers.length,l=a.end===a.containers.length,m=v._chunkSize;do a._blockSize?a._createChunkWithBlocks(j,g,a._blockSize,m):a._createChunk(j,g,m),b++;while(a.containers.length<g&&d._now()<i);a._listView._writeProfilerMark("createContainers yields containers("+a.containers.length+"),info"),a._listView._affectedRange.add({start:k,end:a.containers.length},g),l?(a.stopWork(),a._listView._writeProfilerMark(a._state.name+"_relayout,info"),a._state.relayout()):(a._listView._writeProfilerMark(a._state.name+"_layoutNewContainers,info"),a._state.layoutNewContainers()),a.containers.length<g?f.setWork(e):(a._listView._writeProfilerMark("createContainers completed steps("+b+"),info"),a._creatingContainersWork.complete())}})}},_scheduleLazyTreeCreation:function(){return g.schedule(this._generateCreateContainersWorker(),g.Priority.idle,this,"WinJS.UI.ListView.LazyTreeCreation")},_createContainers:function(){this.tree=null,this.keyToGroupIndex=null,this.containers=null,this._expandedRange=null;var a,b=this;return this._listView._itemsCount().then(function(c){return 0===c&&b._listView._hideProgressBar(),a=c,b._listView._writeProfilerMark("createContainers("+a+"),StartTM"),b._listView._groupDataSource?b._listView._groups.initialize():void 0}).then(function(){return b._listView._writeProfilerMark("numberOfItemsPerItemsBlock,StartTM"),a&&b._listView._groups.length()?b._listView._layout.numberOfItemsPerItemsBlock:null}).then(function(c){b._listView._writeProfilerMark("numberOfItemsPerItemsBlock("+c+"),info"),b._listView._writeProfilerMark("numberOfItemsPerItemsBlock,StopTM"),b._listView._resetCanvas(),b.tree=[],b.keyToGroupIndex={},b.containers=[],b._blockSize=c;var e,f=b._getGroups(a),g=d._now()+v._maxTimePerCreateContainers,h=Math.min(v._startupChunkSize,v._chunkSize);do e=c?b._createChunkWithBlocks(f,a,c,h):b._createChunk(f,a,h);while(d._now()<g&&b.containers.length<a&&!e);if(b._listView._writeProfilerMark("createContainers created("+b.containers.length+"),info"),b._listView._affectedRange.add({start:0,end:b.containers.length},a),b.containers.length<a){var i=b._scheduleLazyTreeCreation();b._creatingContainersWork.promise.done(null,function(){i.cancel()})}else b._listView._writeProfilerMark("createContainers completed synchronously,info"),b._creatingContainersWork.complete();b._listView._writeProfilerMark("createContainers("+a+"),StopTM")})},_updateItemsBlocks:function(a){function c(){var a=b.document.createElement("div");return a.className=l._itemsBlockClass,a}function d(b,d){function g(){b.itemsBlocks=null,b.items=[];for(var a=0;k>a;a++){var c=e.containers[d+a];b.element.appendChild(c),b.items.push(c)}}function h(){b.itemsBlocks=[{element:j.length?j.shift():c(),items:[]}];for(var f=b.itemsBlocks[0],g=0;k>g;g++){if(f.items.length===a){var h=j.length?j.shift():c();b.itemsBlocks.push({element:h,items:[]}),f=b.itemsBlocks[b.itemsBlocks.length-1]}var i=e.containers[d+g];f.element.appendChild(i),f.items.push(i)}b.items=null}var i,j=[],k=0,l=b.itemsBlocks;if(l)for(i=0;i<l.length;i++)k+=l[i].items.length,j.push(l[i].element);else k=b.items.length;for(f?h():g(),i=0;i<j.length;i++){var m=j[i];m.parentNode===b.element&&b.element.removeChild(m)}return k}for(var e=this,f=!!a,g=0,h=0;g<this.tree.length;g++)h+=d(this.tree[g].itemsContainer,h);e._blockSize=a},_layoutItems:function(){var a=this;return this._listView._itemsCount().then(function(){return e.as(a._listView._layout.numberOfItemsPerItemsBlock).then(function(b){a._listView._writeProfilerMark("numberOfItemsPerItemsBlock("+b+"),info"),b!==a._blockSize&&(a._updateItemsBlocks(b),a._listView._itemsBlockExtent=-1);var c,d=a._listView._affectedRange.get();return d&&(c={firstIndex:Math.max(d.start-1,0),lastIndex:Math.min(a.containers.length-1,d.end)},c.firstIndex<a.containers.length||0===a.containers.length)?a._listView._layout.layout(a.tree,c,a._modifiedElements||[],a._modifiedGroups||[]):(a._listView._affectedRange.clear(),{realizedRangeComplete:e.wrap(),layoutComplete:e.wrap()})})})},updateTree:function(a,b,c){return this._listView._writeProfilerMark(this._state.name+"_updateTree,info"),this._state.updateTree(a,b,c)},_updateTreeImpl:function(a,c,d,e){function f(a){for(var b=0,c=a.length;c>b;b++){var d=a[b];d.parentNode.removeChild(d)}}if(this._executeAnimations=!0,this._modifiedElements=d,!d.handled){d.handled=!0,this._listView._writeProfilerMark("_updateTreeImpl,StartTM");var g,h=this;e||this._unrealizeItems();for(var g=0,j=d.length;j>g;g++)d[g]._itemBox&&d[g]._itemBox.parentNode&&i.removeClass(d[g]._itemBox.parentNode,l._selectedClass);this.items.each(function(a,b,c){c.container&&i.removeClass(c.container,l._selectedClass),c.container&&i.addClass(c.container,l._backdropClass)});var k=this._listView._updateContainers(this._getGroups(a),a,c,d);f(k.removedHeaders),f(k.removedItemsContainers);for(var g=0,j=d.length;j>g;g++){var n=d[g];if(-1!==n.newIndex){if(n.element=this.getContainer(n.newIndex),!n.element)throw"Container missing after updateContainers."}else i.removeClass(n.element,l._backdropClass)}var o=b.document.activeElement;this._listView._canvas.contains(o)&&(this._requireFocusRestore=o),this._deferredReparenting=[],this.items.each(function(a,b,c){var d=h.getContainer(a),e=c.itemBox;e&&d&&(c.container=d,e.parentNode!==d&&(a>=h.firstIndexDisplayed&&a<=h.lastIndexDisplayed?h._appendAndRestoreFocus(d,e):h._deferredReparenting.push({itemBox:e,container:d})),i.removeClass(d,l._backdropClass),i[h._listView.selection._isIncluded(a)?"addClass":"removeClass"](d,l._selectedClass),!h._listView.selection._isIncluded(a)&&i.hasClass(e,l._selectedClass)&&m._ItemEventsHandler.renderSelection(e,c.element,!1,!0))}),this._listView._writeProfilerMark("_updateTreeImpl,StopTM")}},_completeUpdateTree:function(){if(this._deferredReparenting){var a=this._deferredReparenting.length;if(a>0){var b="_completeReparenting("+a+")";this._listView._writeProfilerMark(b+",StartTM");for(var c,d=0;a>d;d++)c=this._deferredReparenting[d],this._appendAndRestoreFocus(c.container,c.itemBox);this._deferredReparenting=[],this._listView._writeProfilerMark(b+",StopTM")}}this._requireFocusRestore=null},_appendAndRestoreFocus:function(a,c){if(c.parentNode!==a){var d;if(this._requireFocusRestore&&(d=b.document.activeElement),this._requireFocusRestore&&this._requireFocusRestore===d&&(a.contains(d)||c.contains(d))&&(this._listView._unsetFocusOnItem(),d=b.document.activeElement),i.empty(a),a.appendChild(c),this._requireFocusRestore&&d===this._listView._keyboardEventsHelper){var e=this._listView._selection._getFocused();e.type===k.ObjectType.item&&this.items.itemBoxAt(e.index)===c&&(i._setActive(this._requireFocusRestore),this._requireFocusRestore=null)}}},_startAnimations:function(){this._listView._writeProfilerMark("startAnimations,StartTM");var a=this;this._hasAnimationInViewportPending=!1;var b=e.as(this._listView._layout.executeAnimations()).then(function(){a._listView._writeProfilerMark("startAnimations,StopTM")});return b},_setState:function(a,b){if(!this._listView._isZombie()){var c=this._state.name;this._state=new a(this,b),this._listView._writeProfilerMark(this._state.name+"_enter from("+c+"),info"),this._state.enter()}},getAdjacent:function(a,b){var c=this;return this.waitForEntityPosition(a).then(function(){return c._listView._layout.getAdjacent(a,b)})},hitTest:function(a,b){if(this._realizedRangeLaidOut)return{index:-1,insertAfterIndex:-1};var c=this._listView._layout.hitTest(a,b);return c.index=i._clamp(c.index,-1,this._listView._cachedCount-1,0),c.insertAfterIndex=i._clamp(c.insertAfterIndex,-1,this._listView._cachedCount-1,0),c},_createTreeBuildingSignal:function(){if(!this._creatingContainersWork){this._creatingContainersWork=new f;var a=this;this._creatingContainersWork.promise.done(function(){a._creatingContainersWork=null},function(){a._creatingContainersWork=null})}},_createLayoutSignal:function(){var a=this;this._layoutCompleted||(this._layoutCompleted=new f,this._layoutCompleted.promise.done(function(){a._layoutCompleted=null},function(){a._layoutCompleted=null})),this._realizedRangeLaidOut||(this._realizedRangeLaidOut=new f,this._realizedRangeLaidOut.promise.done(function(){a._realizedRangeLaidOut=null},function(){a._realizedRangeLaidOut=null}))},_getLayoutCompleted:function(){return this._layoutCompleted?e._cancelBlocker(this._layoutCompleted.promise):e.wrap()},_createSurfaceChild:function(a,c){var d=b.document.createElement("div");return d.className=a,this._listView._canvas.insertBefore(d,c?c.nextElementSibling:null),d},_executeScrollToFunctor:function(){var a=this;return e.as(this._scrollToFunctor?this._scrollToFunctor():null).then(function(b){a._scrollToFunctor=null,b=b||{},+b.position===b.position&&(a._scrollbarPos=b.position),a._direction=b.direction||"right"})}},{_defaultPagesToPrefetch:2,_iOSMaxLeadingPages:6,_iOSMaxTrailingPages:2,_disableCustomPagesPrefetch:!1,_waitForSeZoIntervalDuration:100,_waitForSeZoTimeoutDuration:500,_chunkSize:500,_startupChunkSize:100,_maxTimePerCreateContainers:5,_createContainersJobTimeslice:15,_blocksToRelease:10,_realizationLevel:{skip:"skip",realize:"realize",normal:"normal"}}),w=c.Class.define(function(a){this.view=a,this.view._createTreeBuildingSignal(),this.view._createLayoutSignal()},{name:"CreatedState",enter:function(){this.view._createTreeBuildingSignal(),this.view._createLayoutSignal()},stop:u,realizePage:u,rebuildTree:function(){this.view._setState(x)},relayout:function(){this.view._setState(x)},layoutNewContainers:u,waitForEntityPosition:function(){return this.view._setState(x),this.view._getLayoutCompleted()},updateTree:u}),x=c.Class.define(function(a){this.view=a},{name:"BuildingState",enter:function(){this.canceling=!1,this.view._createTreeBuildingSignal(),this.view._createLayoutSignal();var a=this,b=new f;this.promise=b.promise.then(function(){return a.view._createContainers()}).then(function(){a.view._setState(y)},function(b){return a.canceling||(a.view._setState(w),a.view._listView._raiseViewComplete()),e.wrapError(b)}),b.complete()},stop:function(){this.canceling=!0,this.promise.cancel(),this.view._setState(w)},realizePage:u,rebuildTree:function(){this.canceling=!0,this.promise.cancel(),this.enter()},relayout:u,layoutNewContainers:u,waitForEntityPosition:function(){return this.view._getLayoutCompleted()},updateTree:u}),y=c.Class.define(function(a,b){this.view=a,this.nextStateType=b||A},{name:"LayingoutState",enter:function(){var a=this;this.canceling=!1,this.view._createLayoutSignal(),this.view._listView._writeProfilerMark(this.name+"_enter_layoutItems,StartTM");var b=new f;this.promise=b.promise.then(function(){return a.view._layoutItems()}).then(function(b){return a.view._layoutWork=b.layoutComplete,b.realizedRangeComplete}).then(function(){a.view._listView._writeProfilerMark(a.name+"_enter_layoutItems,StopTM"),a.view._listView._clearInsertedItems(),a.view._setAnimationInViewportState(a.view._modifiedElements),a.view._modifiedElements=[],a.view._modifiedGroups=[],a.view._realizedRangeLaidOut.complete(),a.view._layoutWork.then(function(){a.view._listView._writeProfilerMark(a.name+"_enter_layoutCompleted,info"),a.view._listView._affectedRange.clear(),a.view._layoutCompleted.complete()}),a.canceling||a.view._setState(a.nextStateType)},function(b){return a.view._listView._writeProfilerMark(a.name+"_enter_layoutCanceled,info"),a.canceling||(a.view.firstIndexDisplayed=a.view.lastIndexDisplayed=-1,a.view._updateAriaMarkers(!0,a.view.firstIndexDisplayed,a.view.lastIndexDisplayed),a.view._setState(G)),e.wrapError(b)}),b.complete(),this.canceling&&this.promise.cancel()},cancelLayout:function(a){this.view._listView._writeProfilerMark(this.name+"_cancelLayout,info"),this.canceling=!0,this.promise&&this.promise.cancel(),a&&this.view._setState(z)},stop:function(){this.cancelLayout(!0)},realizePage:u,rebuildTree:function(){this.cancelLayout(!1),this.view._setState(x)},relayout:function(){this.cancelLayout(!1),this.enter()},layoutNewContainers:function(){this.relayout()},waitForEntityPosition:function(){return this.view._getLayoutCompleted()},updateTree:function(a,b,c){return this.view._updateTreeImpl(a,b,c)}}),z=c.Class.define(function(a){this.view=a},{name:"LayoutCanceledState",enter:u,stop:u,realizePage:function(){this.relayout()},rebuildTree:function(){this.view._setState(x)},relayout:function(){this.view._setState(y)},layoutNewContainers:function(){this.relayout() },waitForEntityPosition:function(){return this.view._getLayoutCompleted()},updateTree:function(a,b,c){return this.view._updateTreeImpl(a,b,c)}}),A=c.Class.define(function(a){this.view=a,this.nextState=E,this.relayoutNewContainers=!0},{name:"RealizingState",enter:function(){var a=this,b=new f;this.promise=b.promise.then(function(){return a.view._executeScrollToFunctor()}).then(function(){return a.relayoutNewContainers=!1,e._cancelBlocker(a.view._realizePageImpl())}).then(function(){a.view._state===a&&(a.view._completeUpdateTree(),a.view._listView._writeProfilerMark("RealizingState_to_UnrealizingState"),a.view._setState(a.nextState))},function(b){return a.view._state!==a||a.canceling||(a.view._listView._writeProfilerMark("RealizingState_to_CanceledState"),a.view._setState(B)),e.wrapError(b)}),b.complete()},stop:function(){this.canceling=!0,this.promise.cancel(),this.view._cancelRealize(),this.view._setState(B)},realizePage:function(){this.canceling=!0,this.promise.cancel(),this.enter()},rebuildTree:function(){this.stop(),this.view._setState(x)},relayout:function(){this.stop(),this.view._setState(y)},layoutNewContainers:function(){this.relayoutNewContainers?this.relayout():(this.view._createLayoutSignal(),this.view._relayoutInComplete=!0)},waitForEntityPosition:function(){return this.view._getLayoutCompleted()},updateTree:function(a,b,c){return this.view._updateTreeImpl(a,b,c)},setLoadingState:function(a){this.view._listView._setViewState(a)}}),B=c.Class.define(function(a){this.view=a},{name:"CanceledState",enter:u,stop:function(){this.view._cancelRealize()},realizePage:function(a){this.stop(),this.view._setState(a)},rebuildTree:function(){this.stop(),this.view._setState(x)},relayout:function(a){this.stop(),this.view._setState(y,a)},layoutNewContainers:function(){this.relayout(B)},waitForEntityPosition:function(){return this.view._getLayoutCompleted()},updateTree:function(a,b,c){return this.view._updateTreeImpl(a,b,c)}}),C=c.Class.derive(A,function(a){this.view=a,this.nextState=D,this.relayoutNewContainers=!0},{name:"ScrollingState",setLoadingState:function(){}}),D=c.Class.derive(B,function(a){this.view=a},{name:"ScrollingPausedState",enter:function(){var a=this;this.promise=e._cancelBlocker(this.view._scrollEndPromise).then(function(){a.view._setState(E)})},stop:function(){this.promise.cancel(),this.view._cancelRealize()}}),E=c.Class.define(function(a){this.view=a},{name:"UnrealizingState",enter:function(){var a=this;this.promise=this.view._lazilyUnrealizeItems().then(function(){return a.view._listView._writeProfilerMark("_renderCompletePromise wait starts,info"),a.view._renderCompletePromise}).then(function(){a.view._setState(G)})},stop:function(){this.view._cancelRealize(),this.promise.cancel(),this.view._setState(B)},realizePage:function(a){this.promise.cancel(),this.view._setState(a)},rebuildTree:function(){this.view._setState(x)},relayout:function(){this.view._setState(y)},layoutNewContainers:function(){this.view._createLayoutSignal(),this.view._relayoutInComplete=!0},waitForEntityPosition:function(){return this.view._getLayoutCompleted()},updateTree:function(a,b,c){return this.view._updateTreeImpl(a,b,c)}}),F=c.Class.define(function(a,b){this.view=a,this.realizePromise=b,this.realizeId=1},{name:"RealizingAnimatingState",enter:function(){var a=this;this.animating=!0,this.animatePromise=this.view._startAnimations(),this.animateSignal=new f,this.view._executeAnimations=!1,this.animatePromise.done(function(){a.animating=!1,a.modifiedElements?(a.view._updateTreeImpl(a.count,a.delta,a.modifiedElements),a.modifiedElements=null,a.view._setState(B)):a.animateSignal.complete()},function(b){return a.animating=!1,e.wrapError(b)}),this._waitForRealize()},_waitForRealize:function(){var a=this;this.realizing=!0,this.realizePromise.done(function(){a.realizing=!1});var b=++this.realizeId;e.join([this.realizePromise,this.animateSignal.promise]).done(function(){b===a.realizeId&&(a.view._completeUpdateTree(),a.view._listView._writeProfilerMark("RealizingAnimatingState_to_UnrealizingState"),a.view._setState(E))})},stop:function(a){this.realizePromise.cancel(),this.view._cancelRealize(),a&&(this.animatePromise.cancel(),this.view._setState(B))},realizePage:function(){if(!this.modifiedElements){var a=this;this.realizePromise=this.view._executeScrollToFunctor().then(function(){return e._cancelBlocker(a.view._realizePageImpl())}),this._waitForRealize()}},rebuildTree:function(){this.stop(!0),this.view._setState(x)},relayout:function(){this.stop(!0),this.modifiedElements&&(this.view._updateTreeImpl(this.count,this.delta,this.modifiedElements),this.modifiedElements=null),this.view._setState(y)},layoutNewContainers:function(){this.view._createLayoutSignal(),this.view._relayoutInComplete=!0},waitForEntityPosition:function(){return this.view._getLayoutCompleted()},updateTree:function(a,b,c){if(this.animating){var d=this.modifiedElements;return this.count=a,this.delta=b,this.modifiedElements=c,d?e.cancel:this.animatePromise}return this.view._updateTreeImpl(a,b,c)},setLoadingState:function(a){this.view._listView._setViewState(a)}}),G=c.Class.derive(B,function(a){this.view=a},{name:"CompletedState",enter:function(){this._stopped=!1,this.view._setupDeferredActions(),this.view._realizationLevel=v._realizationLevel.normal,this.view._listView._raiseViewComplete(),this.view._state===this&&this.view._relayoutInComplete&&!this._stopped&&this.view._setState(H)},stop:function(){this._stopped=!0,B.prototype.stop.call(this)},layoutNewContainers:function(){this.view._createLayoutSignal(),this.view._setState(H)},updateTree:function(a,b,c){return this.view._updateTreeImpl(a,b,c,!0)}}),H=c.Class.derive(B,function(a){this.view=a},{name:"LayingoutNewContainersState",enter:function(){var a=this;this.promise=e.join([this.view.deferTimeout,this.view._layoutWork]),this.promise.then(function(){a.view._relayoutInComplete=!1,a.relayout(B)})},stop:function(){this.promise.cancel(),this.view._cancelRealize()},realizePage:function(a){this.stop(),this.view._setState(y,a)},layoutNewContainers:function(){this.view._createLayoutSignal()}});return v})})}),d("require-style!less/styles-listview",[],function(){}),d("require-style!less/colors-listview",[],function(){}),d("WinJS/Controls/ListView",["../Core/_Global","../Core/_Base","../Core/_BaseUtils","../Core/_ErrorFromName","../Core/_Events","../Core/_Log","../Core/_Resources","../Core/_WriteProfilerMark","../_Accents","../Animations","../Animations/_TransitionAnimation","../BindingList","../Promise","../Scheduler","../_Signal","../Utilities/_Control","../Utilities/_Dispose","../Utilities/_ElementUtilities","../Utilities/_Hoverable","../Utilities/_ItemsManager","../Utilities/_SafeHtml","../Utilities/_TabContainer","../Utilities/_UI","../Utilities/_VersionManager","./ItemContainer/_Constants","./ItemContainer/_ItemEventsHandler","./ListView/_BrowseMode","./ListView/_ErrorMessages","./ListView/_GroupFocusCache","./ListView/_GroupsContainer","./ListView/_Helpers","./ListView/_ItemsContainer","./ListView/_Layouts","./ListView/_SelectionManager","./ListView/_VirtualizeContentsView","require-style!less/styles-listview","require-style!less/colors-listview"],function(a,b,c,d,e,f,g,h,i,j,k,l,m,n,o,p,q,r,s,t,u,v,w,x,y,z,A,B,C,D,E,F,G,H,I){"use strict";function J(){var a=P;P=[],a=a.filter(function(a){return a._isZombie()?(a._dispose(),!1):!0}),P=P.concat(a)}function K(a){P.push(a),M&&M.cancel(),M=m.timeout(O).then(J)}function L(a){return a.offsetParent?a.offsetParent.offsetWidth-a.offsetLeft-a.offsetWidth:0}i.createAccentRule(".win-listview:not(.win-selectionstylefilled) .win-selectioncheckmarkbackground, .win-itemcontainer:not(.win-selectionstylefilled) .win-selectioncheckmarkbackground",[{name:"border-color",value:i.ColorTypes.accent},{name:"background-color",value:i.ColorTypes.accent}]),i.createAccentRule(".win-listview:not(.win-selectionstylefilled) .win-container.win-selected .win-selectionborder, .win-itemcontainer:not(.win-selectionstylefilled).win-container.win-selected .win-selectionborder",[{name:"border-color",value:i.ColorTypes.accent}]),i.createAccentRule(".win-listview.win-selectionstylefilled .win-selected .win-selectionbackground, .win-itemcontainer.win-selectionstylefilled.win-selected .win-selectionbackground",[{name:"background-color",value:i.ColorTypes.accent}]);var M,N=c._browserStyleEquivalents.transform,O=1e3,P=[],Q=r._uniqueID,R={get notCompatibleWithSemanticZoom(){return"ListView can only be used with SemanticZoom if randomAccess loading behavior is specified."},get listViewInvalidItem(){return"Item must provide index, key or description of corresponding item."},get listViewViewportAriaLabel(){return g._getWinJSString("ui/listViewViewportAriaLabel").value}},S=c.requireSupportedForProcessing,T={entrance:"entrance",contentTransition:"contentTransition"};b.Namespace.define("WinJS.UI",{ListViewAnimationType:T,ListView:b.Namespace._lazy(function(){var g=b.Class.define(function(){this.clear()},{add:function(a,b){if(a._lastKnownSizeOfData=b,this._range){this._range.start=Math.min(this._range.start,a.start);var c=this._range._lastKnownSizeOfData-this._range.end,d=a._lastKnownSizeOfData-a.end,e=Math.min(c,d);this._range._lastKnownSizeOfData=a._lastKnownSizeOfData,this._range.end=this._range._lastKnownSizeOfData-e}else this._range=a},addAll:function(){this.add({start:0,end:Number.MAX_VALUE},Number.MAX_VALUE)},clear:function(){this._range=null},get:function(){return this._range}}),i=b.Class.define(function(a){this._listView=a},{getPanAxis:function(){return this._listView._getPanAxis()},configureForZoom:function(a,b,c,d){this._listView._configureForZoom(a,b,c,d)},setCurrentItem:function(a,b){this._listView._setCurrentItem(a,b)},getCurrentItem:function(){return this._listView._getCurrentItem()},beginZoom:function(){return this._listView._beginZoom()},positionItem:function(a,b){return this._listView._positionItem(a,b)},endZoom:function(a){this._listView._endZoom(a)},pinching:{get:function(){return this._listView._pinching},set:function(a){this._listView._pinching=a}}}),s=b.Class.define(function(b,c){if(b=b||a.document.createElement("div"),this._id=b.id||"",this._writeProfilerMark("constructor,StartTM"),c=c||{},b.winControl=this,r.addClass(b,"win-disposable"),this._affectedRange=new g,this._mutationObserver=new r._MutationObserver(this._itemPropertyChange.bind(this)),this._versionManager=null,this._insertedItems={},this._element=b,this._startProperty=null,this._scrollProperty=null,this._scrollLength=null,this._scrolling=!1,this._zooming=!1,this._pinching=!1,this._itemsManager=null,this._canvas=null,this._cachedCount=y._UNINITIALIZED,this._loadingState=this._LoadingState.complete,this._firstTimeDisplayed=!0,this._currentScrollPosition=0,this._lastScrollPosition=0,this._notificationHandlers=[],this._itemsBlockExtent=-1,this._lastFocusedElementInGroupTrack={type:w.ObjectType.item,index:-1},this._headerFooterVisibilityStatus={headerVisible:!1,footerVisible:!1},this._viewportWidth=y._UNINITIALIZED,this._viewportHeight=y._UNINITIALIZED,this._manipulationState=r._MSManipulationEvent.MS_MANIPULATION_STATE_STOPPED,this._maxDeferredItemCleanup=Number.MAX_VALUE,this._groupsToRemove={},this._setupInternalTree(),this._isCurrentZoomView=!0,this._dragSource=!1,this._reorderable=!1,this._groupFocusCache=new C._UnsupportedGroupFocusCache,this._viewChange=y._ViewChange.rebuild,this._scrollToFunctor=null,this._setScrollbarPosition=!1,this._view=new I._VirtualizeContentsView(this),this._selection=new H._SelectionManager(this),this._createTemplates(),this._groupHeaderRenderer=t._trivialHtmlRenderer,this._itemRenderer=t._trivialHtmlRenderer,this._groupHeaderRelease=null,this._itemRelease=null,c.itemDataSource)this._dataSource=c.itemDataSource;else{var d=new l.List;this._dataSource=d.dataSource}this._selectionMode=w.SelectionMode.multi,this._tap=w.TapBehavior.invokeOnly,this._groupHeaderTap=w.GroupHeaderTapBehavior.invoke,this._mode=new A._SelectionMode(this),this._groups=new D._NoGroups(this),this._updateItemsAriaRoles(),this._updateGroupHeadersAriaRoles(),this._element.setAttribute("aria-multiselectable",this._multiSelection()),this._element.tabIndex=-1,this._tabManager.tabIndex=this._tabIndex,"absolute"!==this._element.style.position&&"relative"!==this._element.style.position&&(this._element.style.position="relative"),this._updateItemsManager(),c.layout||this._updateLayout(new G.GridLayout),this._attachEvents(),this._runningInit=!0,p.setOptions(this,c),this._runningInit=!1,this._batchViewUpdates(y._ViewChange.rebuild,y._ScrollToPriority.medium,0),this._writeProfilerMark("constructor,StopTM")},{element:{get:function(){return this._element}},layout:{get:function(){return this._layoutImpl},set:function(a){this._updateLayout(a),this._runningInit||(this._view.reset(),this._updateItemsManager(),this._batchViewUpdates(y._ViewChange.rebuild,y._ScrollToPriority.medium,0,!0))}},maxLeadingPages:{get:function(){return this._view.maxLeadingPages},set:function(a){this._view.maxLeadingPages=Math.max(0,Math.floor(a))}},maxTrailingPages:{get:function(){return this._view.maxTrailingPages},set:function(a){this._view.maxTrailingPages=Math.max(0,Math.floor(a))}},pagesToLoad:{get:function(){return 2*I._VirtualizeContentsView._defaultPagesToPrefetch+1},set:function(){r._deprecated(B.pagesToLoadIsDeprecated)}},pagesToLoadThreshold:{get:function(){return 0},set:function(){r._deprecated(B.pagesToLoadThresholdIsDeprecated)}},groupDataSource:{get:function(){return this._groupDataSource},set:function(a){function b(a){a.detail===w.DataSourceStatus.failure&&(c.itemDataSource=null,c.groupDataSource=null)}this._writeProfilerMark("set_groupDataSource,info");var c=this;this._groupDataSource&&this._groupDataSource.removeEventListener&&this._groupDataSource.removeEventListener("statuschanged",b,!1),this._groupDataSource=a,this._groupFocusCache=a&&this._supportsGroupHeaderKeyboarding?new C._GroupFocusCache(this):new C._UnsupportedGroupFocusCache,this._groupDataSource&&this._groupDataSource.addEventListener&&this._groupDataSource.addEventListener("statuschanged",b,!1),this._createGroupsContainer(),this._runningInit?(this._updateGroupWork(),this._resetLayout()):(this._view.reset(),this._pendingLayoutReset=!0,this._pendingGroupWork=!0,this._batchViewUpdates(y._ViewChange.rebuild,y._ScrollToPriority.medium,0,!0))}},_updateGroupWork:function(){this._pendingGroupWork=!1,this._groupDataSource?r.addClass(this._element,y._groupsClass):r.removeClass(this._element,y._groupsClass),this._resetLayout()},automaticallyLoadPages:{get:function(){return!1},set:function(){r._deprecated(B.automaticallyLoadPagesIsDeprecated)}},loadingBehavior:{get:function(){return"randomAccess"},set:function(){r._deprecated(B.loadingBehaviorIsDeprecated)}},selectionMode:{get:function(){return this._selectionMode},set:function(a){if("string"==typeof a&&a.match(/^(none|single|multi)$/)){if(c.isPhone&&a===w.SelectionMode.single)return;return this._selectionMode=a,this._element.setAttribute("aria-multiselectable",this._multiSelection()),this._updateItemsAriaRoles(),void this._configureSelectionMode()}throw new d("WinJS.UI.ListView.ModeIsInvalid",B.modeIsInvalid)}},tapBehavior:{get:function(){return this._tap},set:function(a){c.isPhone&&a===w.TapBehavior.directSelect||(this._tap=a,this._updateItemsAriaRoles(),this._configureSelectionMode())}},groupHeaderTapBehavior:{get:function(){return this._groupHeaderTap},set:function(a){this._groupHeaderTap=a,this._updateGroupHeadersAriaRoles()}},swipeBehavior:{get:function(){return"none"},set:function(){r._deprecated(B.swipeBehaviorDeprecated)}},itemDataSource:{get:function(){return this._itemsManager.dataSource},set:function(a){this._writeProfilerMark("set_itemDataSource,info"),this._dataSource=a||(new l.List).dataSource,this._groupFocusCache.clear(),this._runningInit||(this._selection._reset(),this._cancelAsyncViewWork(!0),this._updateItemsManager(),this._pendingLayoutReset=!0,this._batchViewUpdates(y._ViewChange.rebuild,y._ScrollToPriority.medium,0,!0))}},itemTemplate:{get:function(){return this._itemRenderer},set:function(a){this._setRenderer(a,!1),this._runningInit||(this._cancelAsyncViewWork(!0),this._updateItemsManager(),this._pendingLayoutReset=!0,this._batchViewUpdates(y._ViewChange.rebuild,y._ScrollToPriority.medium,0,!0))}},resetItem:{get:function(){return this._itemRelease},set:function(a){r._deprecated(B.resetItemIsDeprecated),this._itemRelease=a}},groupHeaderTemplate:{get:function(){return this._groupHeaderRenderer},set:function(a){this._setRenderer(a,!0),this._runningInit||(this._cancelAsyncViewWork(!0),this._pendingLayoutReset=!0,this._batchViewUpdates(y._ViewChange.rebuild,y._ScrollToPriority.medium,0,!0))}},resetGroupHeader:{get:function(){return this._groupHeaderRelease},set:function(a){r._deprecated(B.resetGroupHeaderIsDeprecated),this._groupHeaderRelease=a}},header:{get:function(){return this._header},set:function(a){r.empty(this._headerContainer),this._header=a,a&&(this._header.tabIndex=this._tabIndex,this._headerContainer.appendChild(a));var b=this._selection._getFocused();if(b.type===w.ObjectType.header){var c=b;a||(c={type:w.ObjectType.item,index:0}),this._hasKeyboardFocus?this._changeFocus(c,!0,!1,!0):this._changeFocusPassively(c)}this.recalculateItemPosition(),this._raiseHeaderFooterVisibilityEvent()}},footer:{get:function(){return this._footer},set:function(a){r.empty(this._footerContainer),this._footer=a,a&&(this._footer.tabIndex=this._tabIndex,this._footerContainer.appendChild(a));var b=this._selection._getFocused();if(b.type===w.ObjectType.footer){var c=b;a||(c={type:w.ObjectType.item,index:0}),this._hasKeyboardFocus?this._changeFocus(c,!0,!1,!0):this._changeFocusPassively(c)}this.recalculateItemPosition(),this._raiseHeaderFooterVisibilityEvent()}},loadingState:{get:function(){return this._loadingState}},selection:{get:function(){return this._selection}},indexOfFirstVisible:{get:function(){return this._view.firstIndexDisplayed},set:function(a){if(!(0>a)){this._writeProfilerMark("set_indexOfFirstVisible("+a+"),info"),this._raiseViewLoading(!0);var b=this;this._batchViewUpdates(y._ViewChange.realize,y._ScrollToPriority.high,function(){var c;return b._entityInRange({type:w.ObjectType.item,index:a}).then(function(a){return a.inRange?b._getItemOffset({type:w.ObjectType.item,index:a.index}).then(function(a){return c=a,b._ensureFirstColumnRange(w.ObjectType.item)}).then(function(){return c=b._correctRangeInFirstColumn(c,w.ObjectType.item),c=b._convertFromCanvasCoordinates(c),b._view.waitForValidScrollPosition(c.begin)}).then(function(a){var c=a<b._lastScrollPosition?"left":"right",d=b._viewport[b._scrollLength]-b._getViewportLength();return a=r._clamp(a,0,d),{position:a,direction:c}}):{position:0,direction:"left"}})},!0)}}},indexOfLastVisible:{get:function(){return this._view.lastIndexDisplayed}},currentItem:{get:function(){var a=this._selection._getFocused(),b={index:a.index,type:a.type,key:null,hasFocus:!!this._hasKeyboardFocus,showFocus:!1};if(a.type===w.ObjectType.groupHeader){var c=this._groups.group(a.index);c&&(b.key=c.key,b.showFocus=!(!c.header||!r.hasClass(c.header,y._itemFocusClass)))}else if(a.type===w.ObjectType.item){var d=this._view.items.itemAt(a.index);if(d){var e=this._itemsManager._recordFromElement(d);b.key=e.item&&e.item.key,b.showFocus=!!d.parentNode.querySelector("."+y._itemFocusOutlineClass)}}return b},set:function(a){function b(b,d,e){var f=!!a.showFocus&&c._hasKeyboardFocus;c._unsetFocusOnItem(d),c._selection._setFocused(e,f),c._hasKeyboardFocus?(c._keyboardFocusInbound=f,c._setFocusOnItem(e)):c._tabManager.childFocus=d?b:null,e.type!==w.ObjectType.groupHeader&&(c._updateFocusCache(e.index),c._updater&&(c._updater.newSelectionPivot=e.index,c._updater.oldSelectionPivot=-1),c._selection._pivot=e.index)}this._hasKeyboardFocus=a.hasFocus||this._hasKeyboardFocus,a.type||(a.type=w.ObjectType.item);var c=this;if(a.key&&(a.type===w.ObjectType.item&&this._dataSource.itemFromKey||a.type===w.ObjectType.groupHeader&&this._groupDataSource&&this._groupDataSource.itemFromKey)){this.oldCurrentItemKeyFetch&&this.oldCurrentItemKeyFetch.cancel();var d=a.type===w.ObjectType.groupHeader?this._groupDataSource:this._dataSource;this.oldCurrentItemKeyFetch=d.itemFromKey(a.key).then(function(d){if(c.oldCurrentItemKeyFetch=null,d){var e=a.type===w.ObjectType.groupHeader?c._groups.group(d.index).header:c._view.items.itemAt(d.index);b(e,!!e,{type:a.type,index:d.index})}})}else{var e;if(a.type===w.ObjectType.header||a.type===w.ObjectType.footer)e=a.type===w.ObjectType.header?this._header:this._footer,b(e,!!e,{type:a.type,index:a.index});else if(void 0!==a.index){if(a.type===w.ObjectType.groupHeader){var f=c._groups.group(a.index);e=f&&f.header}else e=c._view.items.itemAt(a.index);b(e,!!e,{type:a.type,index:a.index})}}}},zoomableView:{get:function(){return this._zoomableView||(this._zoomableView=new i(this)),this._zoomableView}},itemsDraggable:{get:function(){return this._dragSource},set:function(a){c.isPhone||this._dragSource!==a&&(this._dragSource=a,this._setDraggable())}},itemsReorderable:{get:function(){return this._reorderable},set:function(a){c.isPhone||this._reorderable!==a&&(this._reorderable=a,this._setDraggable())}},maxDeferredItemCleanup:{get:function(){return this._maxDeferredItemCleanup},set:function(a){this._maxDeferredItemCleanup=Math.max(0,+a||0)}},dispose:function(){this._dispose()},elementFromIndex:function(a){return this._view.items.itemAt(a)},indexOfElement:function(a){return this._view.items.index(a)},ensureVisible:function(a){var b=w.ObjectType.item,c=a;if(+a!==a&&(b=a.type,c=a.index),this._writeProfilerMark("ensureVisible("+b+": "+c+"),info"),!(0>c)){this._raiseViewLoading(!0);var d=this;this._batchViewUpdates(y._ViewChange.realize,y._ScrollToPriority.high,function(){var a;return d._entityInRange({type:b,index:c}).then(function(c){return c.inRange?d._getItemOffset({type:b,index:c.index}).then(function(c){return a=c,d._ensureFirstColumnRange(b)}).then(function(){a=d._correctRangeInFirstColumn(a,b);var e=d._getViewportLength(),f=d._viewportScrollPosition,g=f+e,h=d._viewportScrollPosition,i=a.end-a.begin;a=d._convertFromCanvasCoordinates(a);var j=!1;if(b===w.ObjectType.groupHeader&&f<=a.begin){var k=d._groups.group(c.index).header;if(k){var l,m=G._getMargins(k);if(d._horizontalLayout){var n=d._rtl(),o=n?L(k)-m.right:k.offsetLeft-m.left;l=o+k.offsetWidth+(n?m.left:m.right)}else l=k.offsetTop+k.offsetHeight+m.top;j=g>=l}}j||(i>=g-f?h=a.begin:a.begin<f?h=a.begin:a.end>g&&(h=a.end-e));var p=h<d._lastScrollPosition?"left":"right",q=d._viewport[d._scrollLength]-e;return h=r._clamp(h,0,q),{position:h,direction:p}}):{position:0,direction:"left"}})},!0)}},loadMorePages:function(){r._deprecated(B.loadMorePagesIsDeprecated)},recalculateItemPosition:function(){this._writeProfilerMark("recalculateItemPosition,info"),this._forceLayoutImpl(y._ViewChange.relayout)},forceLayout:function(){this._writeProfilerMark("forceLayout,info"),this._forceLayoutImpl(y._ViewChange.remeasure)},_entityInRange:function(a){if(a.type===w.ObjectType.item)return this._itemsCount().then(function(b){var c=r._clamp(a.index,0,b-1);return{inRange:c>=0&&b>c,index:c}});if(a.type===w.ObjectType.groupHeader){var b=r._clamp(a.index,0,this._groups.length()-1);return m.wrap({inRange:b>=0&&b<this._groups.length(),index:b})}return m.wrap({inRange:!0,index:0})},_forceLayoutImpl:function(a){var b=this;this._versionManager.unlocked.then(function(){b._writeProfilerMark("_forceLayoutImpl viewChange("+a+"),info"),b._cancelAsyncViewWork(),b._pendingLayoutReset=!0,b._resizeViewport(),b._batchViewUpdates(a,y._ScrollToPriority.low,function(){return{position:b._lastScrollPosition,direction:"right"}},!0,!0)})},_configureSelectionMode:function(){var b=y._selectionModeClass,c=y._hidingSelectionMode;if(this._isInSelectionMode())r.addClass(this._canvas,b),r.removeClass(this._canvas,c);else{if(r.hasClass(this._canvas,b)){var d=this;a.setTimeout(function(){a.setTimeout(function(){r.removeClass(d._canvas,c)},y._hidingSelectionModeAnimationTimeout)},50),r.addClass(this._canvas,c)}r.removeClass(this._canvas,b)}},_lastScrollPosition:{get:function(){return this._lastScrollPositionValue},set:function(a){if(0===a)this._lastDirection="right",this._direction="right",this._lastScrollPositionValue=0;else{var b=a<this._lastScrollPositionValue?"left":"right";this._direction=this._scrollDirection(a),this._lastDirection=b,this._lastScrollPositionValue=a}}},_hasHeaderOrFooter:{get:function(){return!(!this._header&&!this._footer)}},_getHeaderOrFooterFromElement:function(a){return this._header&&this._header.contains(a)?this._header:this._footer&&this._footer.contains(a)?this._footer:null},_supportsGroupHeaderKeyboarding:{get:function(){return this._groupDataSource}},_viewportScrollPosition:{get:function(){return this._currentScrollPosition=r.getScrollPosition(this._viewport)[this._scrollProperty],this._currentScrollPosition},set:function(a){var b={};b[this._scrollProperty]=a,r.setScrollPosition(this._viewport,b),this._currentScrollPosition=a}},_canvasStart:{get:function(){return this._canvasStartValue||0},set:function(a){var b=this._horizontal()?this._rtl()?-a:a:0,c=this._horizontal()?0:a;this._canvas.style[N.scriptName]=0!==a?"translate( "+b+"px, "+c+"px)":"",this._canvasStartValue=a}},scrollPosition:{get:function(){return this._viewportScrollPosition},set:function(a){var b=this;this._batchViewUpdates(y._ViewChange.realize,y._ScrollToPriority.high,function(){return b._view.waitForValidScrollPosition(a).then(function(){var c=b._viewport[b._scrollLength]-b._getViewportLength();a=r._clamp(a,0,c);var d=a<b._lastScrollPosition?"left":"right";return{position:a,direction:d}})},!0)}},_setRenderer:function(a,b){var e;if(a){if("function"==typeof a)e=a;else if("object"==typeof a){if(c.validation&&!a.renderItem)throw new d("WinJS.UI.ListView.invalidTemplate",B.invalidTemplate);e=a.renderItem}}else{if(c.validation)throw new d("WinJS.UI.ListView.invalidTemplate",B.invalidTemplate);e=t.trivialHtmlRenderer}e&&(b?this._groupHeaderRenderer=e:this._itemRenderer=e)},_renderWithoutReuse:function(a,b){b&&q._disposeElement(b);var c=this._itemRenderer(a);if(c.then)return c.then(function(a){return a.tabIndex=0,a});var d=c.element||c;return d.tabIndex=0,c},_isInsertedItem:function(a){return!!this._insertedItems[a.handle]},_clearInsertedItems:function(){for(var a=Object.keys(this._insertedItems),b=0,c=a.length;c>b;b++)this._insertedItems[a[b]].release();this._insertedItems={},this._modifiedElements=[],this._countDifference=0},_cancelAsyncViewWork:function(a){this._view.stopWork(a)},_updateView:function(){function a(){c._itemsBlockExtent=-1,c._firstItemRange=null,c._firstHeaderRange=null,c._itemMargins=null,c._headerMargins=null,c._canvasMargins=null,c._cachedRTL=null,c._rtl()}function b(){c._scrollToPriority=y._ScrollToPriority.uninitialized;var a=c._setScrollbarPosition;c._setScrollbarPosition=!1;var b="number"==typeof c._scrollToFunctor?{position:c._scrollToFunctor}:c._scrollToFunctor();return m.as(b).then(function(b){return b=b||{},a&&+b.position===b.position&&(c._lastScrollPosition=b.position,c._viewportScrollPosition=b.position),b},function(b){return c._setScrollbarPosition|=a,m.wrapError(b)})}if(!this._isZombie()){var c=this,d=this._viewChange;this._viewChange=y._ViewChange.realize,d===y._ViewChange.rebuild?(this._pendingGroupWork&&this._updateGroupWork(),this._pendingLayoutReset&&this._resetLayout(),a(),this._firstTimeDisplayed||this._view.reset(),this._view.reload(b,!0),this._setFocusOnItem(this._selection._getFocused()),this._headerFooterVisibilityStatus={headerVisible:!1,footerVisible:!1}):d===y._ViewChange.remeasure?(this._view.resetItems(!0),this._resetLayout(),a(),this._view.refresh(b),this._setFocusOnItem(this._selection._getFocused()),this._headerFooterVisibilityStatus={headerVisible:!1,footerVisible:!1}):d===y._ViewChange.relayout?(this._pendingLayoutReset&&(this._resetLayout(),a()),this._view.refresh(b)):(this._view.onScroll(b),this._raiseHeaderFooterVisibilityEvent())}},_batchViewUpdates:function(a,b,c,d,e){if(this._viewChange=Math.min(this._viewChange,a),(null===this._scrollToFunctor||b>=this._scrollToPriority)&&(this._scrollToPriority=b,this._scrollToFunctor=c),this._setScrollbarPosition|=!!d,!this._batchingViewUpdates){this._raiseViewLoading();var f=this;this._batchingViewUpdatesSignal=new o,this._batchingViewUpdates=m.any([this._batchingViewUpdatesSignal.promise,n.schedulePromiseHigh(null,"WinJS.UI.ListView._updateView")]).then(function(){return f._isZombie()?void 0:f._viewChange!==y._ViewChange.rebuild||f._firstTimeDisplayed||0===Object.keys(f._view.items._itemData).length||e?void 0:f._fadeOutViewport()}).then(function(){f._batchingViewUpdates=null,f._batchingViewUpdatesSignal=null,f._updateView(),f._firstTimeDisplayed=!1},function(){f._batchingViewUpdates=null,f._batchingViewUpdatesSignal=null})}return this._batchingViewUpdatesSignal},_resetCanvas:function(){if(!this._disposed){var b=a.document.createElement("div");b.className=this._canvas.className,this._viewport.replaceChild(b,this._canvas),this._canvas=b,this._groupsToRemove={},this._canvas.appendChild(this._canvasProxy)}},_setupInternalTree:function(){r.addClass(this._element,y._listViewClass),r[this._rtl()?"addClass":"removeClass"](this._element,y._rtlListViewClass),this._element.innerHTML='<div tabIndex="-1" role="group" class="'+y._viewportClass+" "+y._horizontalClass+'"><div></div><div class="'+y._scrollableClass+'"><div class="'+y._proxyClass+'"></div></div><div></div><div></div></div><div aria-hidden="true" style="position:absolute;left:50%;top:50%;width:0px;height:0px;" tabindex="-1"></div>',this._viewport=this._element.firstElementChild,this._headerContainer=this._viewport.firstElementChild,r.addClass(this._headerContainer,y._listHeaderContainerClass),this._canvas=this._headerContainer.nextElementSibling,this._footerContainer=this._canvas.nextElementSibling,r.addClass(this._footerContainer,y._listFooterContainerClass),this._canvasProxy=this._canvas.firstElementChild,this._deleteWrapper=this._canvas.nextElementSibling,this._keyboardEventsHelper=this._viewport.nextElementSibling,this._tabIndex=r.getTabIndex(this._element),this._tabIndex<0&&(this._tabIndex=0),this._tabManager=new v.TabContainer(this._viewport),this._tabManager.tabIndex=this._tabIndex,this._progressBar=a.document.createElement("progress"),r.addClass(this._progressBar,y._progressClass),r.addClass(this._progressBar,"win-progress-ring"),this._progressBar.style.position="absolute",this._progressBar.max=100},_unsetFocusOnItem:function(b){this._tabManager.childFocus&&this._clearFocusRectangle(this._tabManager.childFocus),this._isZombie()||(b||(this._tabManager.childFocus&&(this._tabManager.childFocus=null),this._keyboardEventsHelper._shouldHaveFocus=!1,a.document.activeElement!==this._viewport&&this._hasKeyboardFocus&&(this._keyboardEventsHelper._shouldHaveFocus=!0,r._setActive(this._keyboardEventsHelper))),this._itemFocused=!1)},_setFocusOnItem:function(a){if(this._writeProfilerMark("_setFocusOnItem,info"),this._focusRequest&&this._focusRequest.cancel(),!this._isZombie()){var b=this,c=function(c){b._isZombie()||(b._tabManager.childFocus!==c&&(b._tabManager.childFocus=c),b._focusRequest=null,b._hasKeyboardFocus&&!b._itemFocused&&(b._selection._keyboardFocused()&&b._drawFocusRectangle(c),(a.type===w.ObjectType.groupHeader||a.type===w.ObjectType.item)&&b._view.updateAriaForAnnouncement(c,a.type===w.ObjectType.groupHeader?b._groups.length():b._cachedCount),b._itemFocused=!0,r._setActive(c)))};this._focusRequest=a.type===w.ObjectType.item?this._view.items.requestItem(a.index):a.type===w.ObjectType.groupHeader?this._groups.requestHeader(a.index):m.wrap(a.type===w.ObjectType.header?this._header:this._footer),this._focusRequest.then(c)}},_attachEvents:function(){function b(a,b,c){return{name:b?a:a.toLowerCase(),handler:function(b){e["_on"+a](b)},capture:c}}function c(a,b,c){return{capture:c,name:b?a:a.toLowerCase(),handler:function(b){var c=e._mode,d="on"+a;!e._disposed&&c[d]&&c[d](b) }}}function d(a,b){return{handler:function(b){e["_on"+a](b)},filter:b}}var e=this,f=[d("PropertyChange",["dir","style","tabindex"])];this._cachedStyleDir=this._element.style.direction,f.forEach(function(a){new r._MutationObserver(a.handler).observe(e._element,{attributes:!0,attributeFilter:a.filter})});var g=[c("PointerDown"),c("click",!1),c("PointerUp"),c("LostPointerCapture"),c("MSHoldVisual",!0),c("PointerCancel",!0),c("DragStart"),c("DragOver"),c("DragEnter"),c("DragLeave"),c("Drop"),c("ContextMenu")];g.forEach(function(a){r._addEventListener(e._viewport,a.name,a.handler,!!a.capture)});var h=[b("FocusIn",!1,!1),b("FocusOut",!1,!1),c("KeyDown"),c("KeyUp"),b("MSElementResize",!1,!1)];h.forEach(function(a){r._addEventListener(e._element,a.name,a.handler,!!a.capture)}),this._onMSElementResizeBound=this._onMSElementResize.bind(this),r._resizeNotifier.subscribe(this._element,this._onMSElementResizeBound);var i=a.document.body.contains(this._element);r._addInsertedNotifier(this._element),this._element.addEventListener("WinJSNodeInserted",function(a){return i?void(i=!1):void e._onMSElementResizeBound(a)},!1);var j=[b("MSManipulationStateChanged",!0),b("Scroll")];j.forEach(function(a){e._viewport.addEventListener(a.name,a.handler,!1)}),this._viewport.addEventListener("onTabEnter",this._onTabEnter.bind(this)),this._viewport.addEventListener("onTabExit",this._onTabExit.bind(this)),this._viewport.addEventListener("onTabEntered",function(a){e._mode.onTabEntered(a)}),this._viewport.addEventListener("onTabExiting",function(a){e._mode.onTabExiting(a)})},_updateItemsManager:function(){function a(a){a.detail===w.DataSourceStatus.failure&&(b.itemDataSource=null,b.groupDataSource=null)}var b=this,c={beginNotifications:function(){},changed:function(a,c){if(!b._ifZombieDispose()){b._createUpdater();var d=b._updater.elements[Q(c)];if(d){var e=b.selection._isIncluded(d.index);if(e&&(b._updater.updateDrag=!0),c!==a){if((b._tabManager.childFocus===c||b._updater.newFocusedItem===c)&&(b._updater.newFocusedItem=a,b._tabManager.childFocus=null),d.itemBox){r.addClass(a,y._itemClass),b._setupAriaSelectionObserver(a);var f=c.nextElementSibling;d.itemBox.removeChild(c),d.itemBox.insertBefore(a,f)}b._setAriaSelected(a,e),b._view.items.setItemAt(d.newIndex,{element:a,itemBox:d.itemBox,container:d.container,itemsManagerRecord:d.itemsManagerRecord}),delete b._updater.elements[Q(c)],q._disposeElement(c),b._updater.elements[Q(a)]={item:a,container:d.container,itemBox:d.itemBox,index:d.index,newIndex:d.newIndex,itemsManagerRecord:d.itemsManagerRecord}}else d.itemBox&&d.container&&(z._ItemEventsHandler.renderSelection(d.itemBox,a,e,!0),r[e?"addClass":"removeClass"](d.container,y._selectedClass));b._updater.changed=!0}for(var g=0,h=b._notificationHandlers.length;h>g;g++)b._notificationHandlers[g].changed(a,c);b._writeProfilerMark("changed,info")}},removed:function(a,c,d){function e(a){b._updater.updateDrag=!0,b._currentMode()._dragging&&b._currentMode()._draggingUnselectedItem&&b._currentMode()._dragInfo._isIncluded(a)&&(b._updater.newDragInfo=new H._Selection(b,[]));var c=b._updater.selectionFirst[a],d=b._updater.selectionLast[a],e=c||d;e&&(delete b._updater.selectionFirst[e.oldFirstIndex],delete b._updater.selectionLast[e.oldLastIndex],b._updater.selectionChanged=!0)}if(!b._ifZombieDispose()){b._createUpdater();var f=b._insertedItems[d];f&&delete b._insertedItems[d];var g;if(a){var h=b._updater.elements[Q(a)],i=b._itemsManager.itemObject(a);if(i&&b._groupFocusCache.deleteItem(i.key),h){if(g=h.index,h.itemBox){var j=h.itemBox,k=y._containerOddClass,l=y._containerEvenClass,m=r.hasClass(j.parentElement,l)?l:k;b._updater.removed.push({index:g,itemBox:j,containerStripe:m})}b._updater.deletesCount++;var n=b._view.items.itemDataAt(g);n.removed=!0,delete b._updater.elements[Q(a)]}else g=i&&i.index;b._updater.oldFocus.type!==w.ObjectType.groupHeader&&b._updater.oldFocus.index===g&&(b._updater.newFocus.index=g,b._updater.focusedItemRemoved=!0),e(g)}else g=b._updater.selectionHandles[d],g===+g&&e(g);b._writeProfilerMark("removed("+g+"),info"),b._updater.changed=!0}},updateAffectedRange:function(a){b._itemsCount().then(function(c){var d=b._view.containers?b._view.containers.length:0;a.start=Math.min(a.start,d),b._affectedRange.add(a,c)}),b._createUpdater(),b._updater.changed=!0},indexChanged:function(a,c,d){if(!b._ifZombieDispose()){if(b._createUpdater(),a){var e=b._itemsManager.itemObject(a);e&&b._groupFocusCache.updateItemIndex(e.key,c);var f=b._updater.elements[Q(a)];f&&(f.newIndex=c,b._updater.changed=!0),b._updater.itemsMoved=!0}b._currentMode()._dragging&&b._currentMode()._draggingUnselectedItem&&b._currentMode()._dragInfo._isIncluded(d)&&(b._updater.newDragInfo=new H._Selection(b,[{firstIndex:c,lastIndex:c}]),b._updater.updateDrag=!0),b._updater.oldFocus.type!==w.ObjectType.groupHeader&&b._updater.oldFocus.index===d&&(b._updater.newFocus.index=c,b._updater.changed=!0),b._updater.oldSelectionPivot===d&&(b._updater.newSelectionPivot=c,b._updater.changed=!0);var g=b._updater.selectionFirst[d];g&&(g.newFirstIndex=c,b._updater.changed=!0,b._updater.selectionChanged=!0,b._updater.updateDrag=!0),g=b._updater.selectionLast[d],g&&(g.newLastIndex=c,b._updater.changed=!0,b._updater.selectionChanged=!0,b._updater.updateDrag=!0)}},endNotifications:function(){b._update()},inserted:function(a){b._ifZombieDispose()||(b._writeProfilerMark("inserted,info"),b._createUpdater(),b._updater.changed=!0,a.retain(),b._updater.insertsCount++,b._insertedItems[a.handle]=a)},moved:function(a,c,d,e){if(!b._ifZombieDispose()){if(b._createUpdater(),b._updater.movesCount++,a){b._updater.itemsMoved=!0;var f=b._updater.elements[Q(a)];f&&(f.moved=!0)}var g=b._updater.selectionHandles[e.handle];if(g===+g){b._updater.updateDrag=!0,b._updater.selectionChanged=!0,b._updater.changed=!0;var h=b._updater.selectionFirst[g],i=b._updater.selectionLast[g],j=h||i;j&&j.oldFirstIndex!==j.oldLastIndex&&(delete b._updater.selectionFirst[j.oldFirstIndex],delete b._updater.selectionLast[j.oldLastIndex])}b._writeProfilerMark("moved("+g+"),info")}},countChanged:function(a,c){b._ifZombieDispose()||(b._writeProfilerMark("countChanged("+a+"),info"),b._cachedCount=a,b._createUpdater(),b._view.lastIndexDisplayed+1===c&&(b._updater.changed=!0),b._updater.countDifference+=a-c)},reload:function(){b._ifZombieDispose()||(b._writeProfilerMark("reload,info"),b._processReload())}};this._versionManager&&this._versionManager._dispose(),this._versionManager=new x._VersionManager,this._updater=null;var d=this._selection.getRanges();this._selection._selected.clear(),this._itemsManager&&(this._itemsManager.dataSource&&this._itemsManager.dataSource.removeEventListener&&this._itemsManager.dataSource.removeEventListener("statuschanged",a,!1),this._clearInsertedItems(),this._itemsManager.release()),this._itemsCountPromise&&(this._itemsCountPromise.cancel(),this._itemsCountPromise=null),this._cachedCount=y._UNINITIALIZED,this._itemsManager=t._createItemsManager(this._dataSource,this._renderWithoutReuse.bind(this),c,{ownerElement:this._element,versionManager:this._versionManager,indexInView:function(a){return a>=b.indexOfFirstVisible&&a<=b.indexOfLastVisible},viewCallsReady:!0,profilerId:this._id}),this._dataSource.addEventListener&&this._dataSource.addEventListener("statuschanged",a,!1),this._selection._selected.set(d)},_processReload:function(){this._affectedRange.addAll(),this._cancelAsyncViewWork(!0),this._currentMode()._dragging&&this._currentMode()._clearDragProperties(),this._groupFocusCache.clear(),this._selection._reset(),this._updateItemsManager(),this._pendingLayoutReset=!0,this._batchViewUpdates(y._ViewChange.rebuild,y._ScrollToPriority.low,this.scrollPosition)},_createUpdater:function(){if(!this._updater){this.itemDataSource._isVirtualizedDataSource&&this._affectedRange.addAll(),this._versionManager.beginUpdating(),this._cancelAsyncViewWork();var a={changed:!1,elements:{},selectionFirst:{},selectionLast:{},selectionHandles:{},oldSelectionPivot:{type:w.ObjectType.item,index:y._INVALID_INDEX},newSelectionPivot:{type:w.ObjectType.item,index:y._INVALID_INDEX},removed:[],selectionChanged:!1,oldFocus:{type:w.ObjectType.item,index:y._INVALID_INDEX},newFocus:{type:w.ObjectType.item,index:y._INVALID_INDEX},hadKeyboardFocus:this._hasKeyboardFocus,itemsMoved:!1,lastVisible:this.indexOfLastVisible,updateDrag:!1,movesCount:0,insertsCount:0,deletesCount:0,countDifference:0};this._view.items.each(function(b,c,d){a.elements[Q(c)]={item:c,container:d.container,itemBox:d.itemBox,index:b,newIndex:b,itemsManagerRecord:d.itemsManagerRecord,detached:d.detached}});for(var b=this._selection._selected._ranges,c=0,d=b.length;d>c;c++){var e=b[c],f={newFirstIndex:b[c].firstIndex,oldFirstIndex:b[c].firstIndex,newLastIndex:b[c].lastIndex,oldLastIndex:b[c].lastIndex};a.selectionFirst[f.oldFirstIndex]=f,a.selectionLast[f.oldLastIndex]=f,a.selectionHandles[e.firstPromise.handle]=f.oldFirstIndex,a.selectionHandles[e.lastPromise.handle]=f.oldLastIndex}a.oldSelectionPivot=this._selection._pivot,a.newSelectionPivot=a.oldSelectionPivot,a.oldFocus=this._selection._getFocused(),a.newFocus=this._selection._getFocused(),this._updater=a}},_synchronize:function(){var a=this._updater;if(this._updater=null,this._groupsChanged=!1,this._countDifference=this._countDifference||0,a&&a.changed){a.itemsMoved&&this._layout.itemsMoved&&this._layout.itemsMoved(),a.removed.length&&this._layout.itemsRemoved&&this._layout.itemsRemoved(a.removed.map(function(a){return a.itemBox})),(a.itemsMoved||a.removed.length||Object.keys(this._insertedItems).length)&&this._layout.setupAnimations&&this._layout.setupAnimations(),this._currentMode().onDataChanged&&this._currentMode().onDataChanged();var b=[];for(var c in a.selectionFirst)if(a.selectionFirst.hasOwnProperty(c)){var d=a.selectionFirst[c];a.selectionChanged=a.selectionChanged||d.newLastIndex-d.newFirstIndex!==d.oldLastIndex-d.oldFirstIndex,d.newFirstIndex<=d.newLastIndex&&b.push({firstIndex:d.newFirstIndex,lastIndex:d.newLastIndex})}if(a.selectionChanged){var e=new H._Selection(this,b);this._selection._fireSelectionChanging(e),this._selection._selected.set(b),this._selection._fireSelectionChanged(),e.clear()}else this._selection._selected.set(b);this._selection._updateCount(this._cachedCount),a.newSelectionPivot=Math.min(this._cachedCount-1,a.newSelectionPivot),this._selection._pivot=a.newSelectionPivot>=0?a.newSelectionPivot:y._INVALID_INDEX,a.newFocus.type!==w.ObjectType.groupHeader&&(a.newFocus.index=Math.max(0,Math.min(this._cachedCount-1,a.newFocus.index))),this._selection._setFocused(a.newFocus,this._selection._keyboardFocused());var f=this._modifiedElements||[],g={};for(this._modifiedElements=[],this._countDifference+=a.countDifference,c=0;c<f.length;c++){var h=f[c];-1===h.newIndex?this._modifiedElements.push(h):g[h.newIndex]=h}for(c=0;c<a.removed.length;c++){var i=a.removed[c],h=g[i.index];h?delete g[i.index]:h={oldIndex:i.index},h.newIndex=-1,h._removalHandled||(h._itemBox=i.itemBox,h._containerStripe=i.containerStripe),this._modifiedElements.push(h)}var j=Object.keys(this._insertedItems);for(c=0;c<j.length;c++)this._modifiedElements.push({oldIndex:-1,newIndex:this._insertedItems[j[c]].index});this._writeProfilerMark("_synchronize:update_modifiedElements,StartTM");var k={};for(c in a.elements)if(a.elements.hasOwnProperty(c)){var l=a.elements[c];k[l.newIndex]={element:l.item,container:l.container,itemBox:l.itemBox,itemsManagerRecord:l.itemsManagerRecord,detached:l.detached};var h=g[l.index];h?(delete g[l.index],h.newIndex=l.newIndex):h={oldIndex:l.index,newIndex:l.newIndex},h.moved=l.moved,this._modifiedElements.push(h)}this._writeProfilerMark("_synchronize:update_modifiedElements,StopTM");var m=Object.keys(g);for(c=0;c<m.length;c++){var n=m[c],h=g[n];-1!==h.oldIndex&&this._modifiedElements.push(h)}this._view.items._itemData=k,a.updateDrag&&this._currentMode()._dragging&&(this._currentMode()._draggingUnselectedItem?a.newDragInfo&&(this._currentMode()._dragInfo=a.newDragInfo):this._currentMode()._dragInfo=this._selection,this._currentMode().fireDragUpdateEvent()),a.focusedItemRemoved||this._focusRequest&&a.oldFocus.index!==a.newFocus.index||a.oldFocus.type!==a.newFocus.type?(this._itemFocused=!1,this._setFocusOnItem(this._selection._getFocused())):a.newFocusedItem&&(this._hasKeyboardFocus=a.hadKeyboardFocus,this._itemFocused=!1,this._setFocusOnItem(this._selection._getFocused()));var o=this;return this._groups.synchronizeGroups().then(function(){return a.newFocus.type===w.ObjectType.groupHeader&&(a.newFocus.index=Math.min(o._groups.length()-1,a.newFocus.index),a.newFocus.index<0&&(a.newFocus={type:w.ObjectType.item,index:0}),o._selection._setFocused(a.newFocus,o._selection._keyboardFocused())),o._versionManager.endUpdating(),a.deletesCount>0&&o._updateDeleteWrapperSize(),o._view.updateTree(o._cachedCount,o._countDifference,o._modifiedElements)}).then(function(){return o._lastScrollPosition})}this._countDifference+=a?a.countDifference:0;var o=this;return this._groups.synchronizeGroups().then(function(){return a&&o._versionManager.endUpdating(),o._view.updateTree(o._cachedCount,o._countDifference,o._modifiedElements)}).then(function(){return o.scrollPosition})},_updateDeleteWrapperSize:function(a){var b=this._horizontal()?"width":"height";this._deleteWrapper.style["min-"+b]=(a?0:this.scrollPosition+this._getViewportSize()[b])+"px"},_verifyRealizationNeededForChange:function(){var a=!1,b=(this._view.lastIndexDisplayed||0)-(this._view.firstIndexDisplayed||0),c=this._updater&&0===this._updater.movesCount&&0===this._updater.insertsCount&&this._updater.deletesCount>0&&this._updater.deletesCount===Math.abs(this._updater.countDifference);if(c&&this._updater.elements)for(var d=Object.keys(this._updater.elements),e=0,f=d.length;f>e;e++){var g=this._updater.elements[d[e]],h=g.index-g.newIndex;if(0>h||h>this._updater.deletesCount){c=!1;break}}this._view.deletesWithoutRealize=this._view.deletesWithoutRealize||0,c&&this._view.lastIndexDisplayed<this._view.end-b&&this._updater.deletesCount+this._view.deletesWithoutRealize<b?(a=!0,this._view.deletesWithoutRealize+=Math.abs(this._updater.countDifference),this._writeProfilerMark("skipping realization on delete,info")):this._view.deletesWithoutRealize=0,this._view._setSkipRealizationForChange(a)},_update:function(){if(this._writeProfilerMark("update,StartTM"),!this._ifZombieDispose()){this._updateJob=null;var a=this;this._versionManager.noOutstandingNotifications&&(this._updater||this._groupsChanged?(this._cancelAsyncViewWork(),this._verifyRealizationNeededForChange(),this._synchronize().then(function(b){a._writeProfilerMark("update,StopTM"),a._batchViewUpdates(y._ViewChange.relayout,y._ScrollToPriority.low,b).complete()})):this._batchViewUpdates(y._ViewChange.relayout,y._ScrollToPriority.low,this._lastScrollPosition).complete())}},_scheduleUpdate:function(){if(!this._updateJob){var a=this;this._updateJob=n.schedulePromiseHigh(null,"WinJS.UI.ListView._update").then(function(){a._updateJob&&a._update()}),this._raiseViewLoading()}},_createGroupsContainer:function(){this._groups&&this._groups.cleanUp(),this._groups=this._groupDataSource?new D._UnvirtualizedGroupsContainer(this,this._groupDataSource):new D._NoGroups(this)},_createLayoutSite:function(){var b=this;return Object.create({invalidateLayout:function(){b._pendingLayoutReset=!0;var a="horizontal"===b._layout.orientation!==b._horizontalLayout;b._affectedRange.addAll(),b._batchViewUpdates(y._ViewChange.rebuild,y._ScrollToPriority.low,a?0:b.scrollPosition,!1,!0)},itemFromIndex:function(a){return b._itemsManager._itemPromiseAtIndex(a)},groupFromIndex:function(a){return b._groupsEnabled()?a<b._groups.length()?b._groups.group(a).userData:null:{key:"-1"}},groupIndexFromItemIndex:function(a){return a=Math.max(0,a),b._groups.groupFromItem(a)},renderItem:function(c){return m._cancelBlocker(b._itemsManager._itemFromItemPromise(c)).then(function(c){if(c){var d=b._itemsManager._recordFromElement(c);d.pendingReady&&d.pendingReady(),c=c.cloneNode(!0),r.addClass(c,y._itemClass);var e=a.document.createElement("div");r.addClass(e,y._itemBoxClass),e.appendChild(c);var f=a.document.createElement("div");return r.addClass(f,y._containerClass),f.appendChild(e),f}return m.cancel})},renderHeader:function(c){var d=t._normalizeRendererReturn(b.groupHeaderTemplate(m.wrap(c)));return d.then(function(b){r.addClass(b.element,y._headerClass);var c=a.document.createElement("div");return r.addClass(c,y._headerContainerClass),c.appendChild(b.element),c})},readyToMeasure:function(){b._getViewportLength(),b._getCanvasMargins()},_isZombie:function(){return b._isZombie()},_writeProfilerMark:function(a){b._writeProfilerMark(a)}},{_itemsManager:{enumerable:!0,get:function(){return b._itemsManager}},rtl:{enumerable:!0,get:function(){return b._rtl()}},surface:{enumerable:!0,get:function(){return b._canvas}},viewport:{enumerable:!0,get:function(){return b._viewport}},scrollbarPos:{enumerable:!0,get:function(){return b.scrollPosition}},viewportSize:{enumerable:!0,get:function(){return b._getViewportSize()}},loadingBehavior:{enumerable:!0,get:function(){return b.loadingBehavior}},animationsDisabled:{enumerable:!0,get:function(){return b._animationsDisabled()}},tree:{enumerable:!0,get:function(){return b._view.tree}},realizedRange:{enumerable:!0,get:function(){return{firstPixel:Math.max(0,b.scrollPosition-2*b._getViewportLength()),lastPixel:b.scrollPosition+3*b._getViewportLength()-1}}},visibleRange:{enumerable:!0,get:function(){return{firstPixel:b.scrollPosition,lastPixel:b.scrollPosition+b._getViewportLength()-1}}},itemCount:{enumerable:!0,get:function(){return b._itemsCount()}},groupCount:{enumerable:!0,get:function(){return b._groups.length()}},header:{enumerable:!0,get:function(){return b.header}},footer:{enumerable:!0,get:function(){return b.footer}}})},_initializeLayout:function(){this._affectedRange.addAll();var a=this._createLayoutSite();return this._layout.initialize(a,this._groupsEnabled()),"horizontal"===this._layout.orientation},_resetLayoutOrientation:function(a){this._horizontalLayout?(this._startProperty="left",this._scrollProperty="scrollLeft",this._scrollLength="scrollWidth",this._deleteWrapper.style.minHeight="",r.addClass(this._viewport,y._horizontalClass),r.removeClass(this._viewport,y._verticalClass),a&&(this._viewport.scrollTop=0)):(this._startProperty="top",this._scrollProperty="scrollTop",this._scrollLength="scrollHeight",this._deleteWrapper.style.minWidth="",r.addClass(this._viewport,y._verticalClass),r.removeClass(this._viewport,y._horizontalClass),a&&r.setScrollPosition(this._viewport,{scrollLeft:0}))},_resetLayout:function(){this._pendingLayoutReset=!1,this._affectedRange.addAll(),this._layout&&(this._layout.uninitialize(),this._horizontalLayout=this._initializeLayout(),this._resetLayoutOrientation())},_updateLayout:function(a){var b=!1;this._layout&&(this._cancelAsyncViewWork(!0),this._layout.uninitialize(),b=!0);var c;if(a&&"function"==typeof a.type){var d=S(a.type);c=new d(a)}else c=a&&a.initialize?a:new G.GridLayout(a);b&&this._resetCanvas(),this._layoutImpl=c,this._layout=new G._LayoutWrapper(c),b&&this._unsetFocusOnItem(),this._setFocusOnItem({type:w.ObjectType.item,index:0}),this._selection._setFocused({type:w.ObjectType.item,index:0}),this._lastFocusedElementInGroupTrack={type:w.ObjectType.item,index:-1},this._headerContainer.style.opacity=0,this._footerContainer.style.opacity=0,this._horizontalLayout=this._initializeLayout(),this._resetLayoutOrientation(b),b&&(this._canvas.style.width=this._canvas.style.height="")},_currentMode:function(){return this._mode},_setDraggable:function(){var a=this.itemsDraggable||this.itemsReorderable;this._view.items.each(function(b,c,d){d.itemBox&&(d.itemBox.draggable=a&&!r.hasClass(c,y._nonDraggableClass))})},_resizeViewport:function(){this._viewportWidth=y._UNINITIALIZED,this._viewportHeight=y._UNINITIALIZED},_onMSElementResize:function(){this._writeProfilerMark("_onMSElementResize,info"),n.schedule(function(){if(!this._isZombie()&&this._viewportWidth!==y._UNINITIALIZED&&this._viewportHeight!==y._UNINITIALIZED){var a=this._element.offsetWidth,b=this._element.offsetHeight;if(this._previousWidth!==a||this._previousHeight!==b){this._writeProfilerMark("resize ("+this._previousWidth+"x"+this._previousHeight+") => ("+a+"x"+b+"),info"),this._previousWidth=a,this._previousHeight=b,this._resizeViewport();var c=this;this._affectedRange.addAll(),this._batchViewUpdates(y._ViewChange.relayout,y._ScrollToPriority.low,function(){return{position:c.scrollPosition,direction:"right"}})}}},n.Priority.max,this,"WinJS.UI.ListView._onMSElementResize")},_onFocusIn:function(a){function b(a){c._changeFocus(c._selection._getFocused(),!0,!1,!1,a)}this._hasKeyboardFocus=!0;var c=this;if(a.target===this._keyboardEventsHelper)!this._keyboardEventsHelper._shouldHaveFocus&&this._keyboardFocusInbound?b(!0):this._keyboardEventsHelper._shouldHaveFocus=!1;else if(a.target===this._element)b();else{if(this._mode.inboundFocusHandled)return void(this._mode.inboundFocusHandled=!1);var d=this._view.items,e={},f=this._getHeaderOrFooterFromElement(a.target),g=null;if(f?(e.index=0,e.type=f===this._header?w.ObjectType.header:w.ObjectType.footer,this._lastFocusedElementInGroupTrack=e):(f=this._groups.headerFrom(a.target),f?(e.type=w.ObjectType.groupHeader,e.index=this._groups.index(f),this._lastFocusedElementInGroupTrack=e):(e.index=d.index(a.target),e.type=w.ObjectType.item,f=d.itemBoxAt(e.index),g=d.itemAt(e.index))),e.index!==y._INVALID_INDEX&&((this._keyboardFocusInbound||this._selection._keyboardFocused())&&(e.type===w.ObjectType.groupHeader&&a.target===f||e.type===w.ObjectType.item&&a.target.parentNode===f)&&this._drawFocusRectangle(f),this._tabManager.childFocus!==f&&this._tabManager.childFocus!==g&&(this._selection._setFocused(e,this._keyboardFocusInbound||this._selection._keyboardFocused()),this._keyboardFocusInbound=!1,e.type===w.ObjectType.item&&(f=d.itemAt(e.index)),this._tabManager.childFocus=f,c._updater))){var h=c._updater.elements[Q(f)],i=e.index;h&&h.newIndex&&(i=h.newIndex),c._updater.oldFocus={type:e.type,index:i},c._updater.newFocus={type:e.type,index:i}}}},_onFocusOut:function(a){if(!this._disposed){this._hasKeyboardFocus=!1,this._itemFocused=!1;var b=this._view.items.itemBoxFrom(a.target)||this._groups.headerFrom(a.target);b&&this._clearFocusRectangle(b)}},_onMSManipulationStateChanged:function(a){function b(){c._manipulationEndSignal=null}var c=this;this._manipulationState=a.currentState,c._writeProfilerMark("_onMSManipulationStateChanged state("+a.currentState+"),info"),this._manipulationState===r._MSManipulationEvent.MS_MANIPULATION_STATE_STOPPED||this._manipulationEndSignal||(this._manipulationEndSignal=new o,this._manipulationEndSignal.promise.done(b,b)),this._manipulationState===r._MSManipulationEvent.MS_MANIPULATION_STATE_STOPPED&&this._manipulationEndSignal.complete()},_pendingScroll:!1,_onScroll:function(){this._zooming||this._pendingScroll||this._checkScroller()},_checkScroller:function(){if(!this._isZombie()){var a=this._viewportScrollPosition;if(a!==this._lastScrollPosition){this._pendingScroll=c._requestAnimationFrame(this._checkScroller.bind(this)),a=Math.max(0,a);var b=this._scrollDirection(a);this._lastScrollPosition=a,this._raiseViewLoading(!0),this._raiseHeaderFooterVisibilityEvent();var d=this;this._view.onScroll(function(){return{position:d._lastScrollPosition,direction:b}},this._manipulationEndSignal?this._manipulationEndSignal.promise:m.timeout(y._DEFERRED_SCROLL_END))}else this._pendingScroll=null}},_scrollDirection:function(a){var b=a<this._lastScrollPosition?"left":"right";return b===this._lastDirection?b:this._direction},_onTabEnter:function(){this._keyboardFocusInbound=!0},_onTabExit:function(){this._keyboardFocusInbound=!1},_onPropertyChange:function(a){var b=this;a.forEach(function(a){var c=!1;if("dir"===a.attributeName?c=!0:"style"===a.attributeName&&(c=b._cachedStyleDir!==a.target.style.direction),c&&(b._cachedStyleDir=a.target.style.direction,b._cachedRTL=null,r[b._rtl()?"addClass":"removeClass"](b._element,y._rtlListViewClass),b._lastScrollPosition=0,b._viewportScrollPosition=0,b.forceLayout()),"tabIndex"===a.attributeName){var d=b._element.tabIndex;d>=0&&(b._view.items.each(function(a,b){b.tabIndex=d}),b._header&&(b._header.tabIndex=d),b._footer&&(b._footer.tabIndex=d),b._tabIndex=d,b._tabManager.tabIndex=d,b._element.tabIndex=-1)}})},_getCanvasMargins:function(){return this._canvasMargins||(this._canvasMargins=G._getMargins(this._canvas)),this._canvasMargins},_convertCoordinatesByCanvasMargins:function(a,b){function c(c,d){void 0!==a[c]&&(a[c]=b(a[c],d))}var d;return this._horizontal()?(d=this._getCanvasMargins()[this._rtl()?"right":"left"],c("left",d)):(d=this._getCanvasMargins().top,c("top",d)),c("begin",d),c("end",d),a},_convertFromCanvasCoordinates:function(a){return this._convertCoordinatesByCanvasMargins(a,function(a,b){return a+b})},_convertToCanvasCoordinates:function(a){return this._convertCoordinatesByCanvasMargins(a,function(a,b){return a-b})},_getViewportSize:function(){return(this._viewportWidth===y._UNINITIALIZED||this._viewportHeight===y._UNINITIALIZED)&&(this._viewportWidth=Math.max(0,r.getContentWidth(this._element)),this._viewportHeight=Math.max(0,r.getContentHeight(this._element)),this._writeProfilerMark("viewportSizeDetected width:"+this._viewportWidth+" height:"+this._viewportHeight),this._previousWidth=this._element.offsetWidth,this._previousHeight=this._element.offsetHeight),{width:this._viewportWidth,height:this._viewportHeight}},_itemsCount:function(){function a(){b._itemsCountPromise=null}var b=this;if(this._cachedCount!==y._UNINITIALIZED)return m.wrap(this._cachedCount);var c;return this._itemsCountPromise?c=this._itemsCountPromise:(c=this._itemsCountPromise=this._itemsManager.dataSource.getCount().then(function(a){return a===w.CountResult.unknown&&(a=0),b._cachedCount=a,b._selection._updateCount(b._cachedCount),a},function(){return m.cancel}),this._itemsCountPromise.then(a,a)),c},_isSelected:function(a){return this._selection._isIncluded(a)},_LoadingState:{itemsLoading:"itemsLoading",viewPortLoaded:"viewPortLoaded",itemsLoaded:"itemsLoaded",complete:"complete"},_raiseViewLoading:function(a){this._loadingState!==this._LoadingState.itemsLoading&&(this._scrolling=!!a),this._setViewState(this._LoadingState.itemsLoading)},_raiseViewComplete:function(){this._disposed||this._view.animating||this._setViewState(this._LoadingState.complete)},_raiseHeaderFooterVisibilityEvent:function(){var b=this,c=function(a){if(!a)return!1;var c=b._lastScrollPosition,d=a[b._horizontal()?"offsetLeft":"offsetTop"],e=a[b._horizontal()?"offsetWidth":"offsetHeight"];return d+e>c&&d<c+b._getViewportLength()},d=function(c,d){var e=a.document.createEvent("CustomEvent");e.initCustomEvent(c,!0,!0,{visible:d}),b._element.dispatchEvent(e)},e=!!this._header&&c(this._headerContainer),f=!!this._footer&&c(this._footerContainer);this._headerFooterVisibilityStatus.headerVisible!==e&&(this._headerFooterVisibilityStatus.headerVisible=e,d("headervisibilitychanged",e)),this._headerFooterVisibilityStatus.footerVisible!==f&&(this._headerFooterVisibilityStatus.footerVisible=f,d("footervisibilitychanged",f))},_setViewState:function(b){if(b!==this._loadingState){var c={scrolling:!1};switch(b){case this._LoadingState.viewPortLoaded:this._scheduledForDispose||(K(this),this._scheduledForDispose=!0),this._setViewState(this._LoadingState.itemsLoading);break;case this._LoadingState.itemsLoaded:c={scrolling:this._scrolling},this._setViewState(this._LoadingState.viewPortLoaded);break;case this._LoadingState.complete:this._setViewState(this._LoadingState.itemsLoaded),this._updateDeleteWrapperSize(!0)}this._writeProfilerMark("loadingStateChanged:"+b+",info"),this._loadingState=b;var d=a.document.createEvent("CustomEvent");d.initCustomEvent("loadingstatechanged",!0,!1,c),this._element.dispatchEvent(d)}},_createTemplates:function(){function b(b,c){var d=a.document.createElement("div");return d.className=b,c||d.setAttribute("aria-hidden",!0),d}this._itemBoxTemplate=b(y._itemBoxClass,!0)},_updateSelection:function(){var a=this._selection.getIndices(),b=this._selection.isEverything(),c={};if(!b)for(var d=0,e=a.length;e>d;d++){var f=a[d];c[f]=!0}this._view.items.each(function(a,d,e){if(e.itemBox){var f=b||!!c[a];z._ItemEventsHandler.renderSelection(e.itemBox,d,f,!0),e.container&&r[f?"addClass":"removeClass"](e.container,y._selectedClass)}})},_getViewportLength:function(){return this._getViewportSize()[this._horizontal()?"width":"height"]},_horizontal:function(){return this._horizontalLayout},_rtl:function(){return"boolean"!=typeof this._cachedRTL&&(this._cachedRTL="rtl"===r._getComputedStyle(this._element,null).direction),this._cachedRTL},_showProgressBar:function(a,b,c){var d=this._progressBar,e=d.style;if(!d.parentNode){this._fadingProgressBar=!1,this._progressIndicatorDelayTimer&&this._progressIndicatorDelayTimer.cancel();var f=this;this._progressIndicatorDelayTimer=m.timeout(y._LISTVIEW_PROGRESS_DELAY).then(function(){f._isZombie()||(a.appendChild(d),j.fadeIn(d),f._progressIndicatorDelayTimer=null)})}e[this._rtl()?"right":"left"]=b,e.top=c},_hideProgressBar:function(){this._progressIndicatorDelayTimer&&(this._progressIndicatorDelayTimer.cancel(),this._progressIndicatorDelayTimer=null);var a=this._progressBar;if(a.parentNode&&!this._fadingProgressBar){this._fadingProgressBar=!0;var b=this;j.fadeOut(a).then(function(){a.parentNode&&a.parentNode.removeChild(a),b._fadingProgressBar=!1})}},_getPanAxis:function(){return this._horizontal()?"horizontal":"vertical"},_configureForZoom:function(a,b,e){if(c.validation&&(!this._view.realizePage||"number"!=typeof this._view.begin))throw new d("WinJS.UI.ListView.NotCompatibleWithSemanticZoom",R.notCompatibleWithSemanticZoom);this._isZoomedOut=a,this._disableEntranceAnimation=!b,this._isCurrentZoomView=b,this._triggerZoom=e},_setCurrentItem:function(a,b){this._rtl()&&(a=this._viewportWidth-a),this._horizontal()?a+=this.scrollPosition:b+=this.scrollPosition;var c=this._view.hitTest(a,b),d={type:c.type?c.type:w.ObjectType.item,index:c.index};d.index>=0&&(this._hasKeyboardFocus?this._changeFocus(d,!0,!1,!0):this._changeFocusPassively(d))},_getCurrentItem:function(){var a=this._selection._getFocused();a.type===w.ObjectType.groupHeader?a={type:w.ObjectType.item,index:this._groups.group(a.index).startIndex}:a.type!==w.ObjectType.item&&(a={type:w.ObjectType.item,index:a.type===w.ObjectType.header?0:this._cachedCount}),"number"!=typeof a.index&&(this._setCurrentItem(.5*this._viewportWidth,.5*this._viewportHeight),a=this._selection._getFocused());var b=this,c=this._getItemOffsetPosition(a.index).then(function(a){var c=b._canvasStart;return a[b._startProperty]+=c,a});return m.join({item:this._dataSource.itemFromIndex(a.index),position:c})},_animateItemsForPhoneZoom:function(){function a(a,b,c){return function(d){return(b[d]-a)*c}}function b(){for(var a=0,b=c.length;b>a;a++)c[a].style[N.scriptName]=""}for(var c=[],d=[],e=[],f=Number.MAX_VALUE,g=this,h=this._view.firstIndexDisplayed,i=Math.min(this._cachedCount,this._view.lastIndexDisplayed+1);i>h;h++)e.push(this._view.waitForEntityPosition({type:w.ObjectType.item,index:h}).then(function(){c.push(g._view.items.containerAt(h));var a=0;if(g.layout._getItemPosition){var b=g.layout._getItemPosition(h);b.row&&(a=b.row)}d.push(a),f=Math.min(a,f)}));return m.join(e).then(function(){return(0===c.length?m.wrap():k.executeTransition(c,{property:N.cssName,delay:a(f,d,30),duration:100,timing:"ease-in-out",from:g._isCurrentZoomView?"rotateX(0deg)":"rotateX(-90deg)",to:g._isCurrentZoomView?"rotateX(90deg)":"rotateX(0deg)"})).then(b,b)}).then(b,b)},_beginZoom:function(){this._zooming=!0;var a=null;if(c.isPhone){if(this._isZoomedOut)if(this._zoomAnimationPromise&&this._zoomAnimationPromise.cancel(),this._isCurrentZoomView){var b=this,d=function(){b._zoomAnimationPromise=null};this._zoomAnimationPromise=a=this._animateItemsForPhoneZoom().then(d,d)}else this._zoomAnimationPromise=new o,a=this._zoomAnimationPromise.promise }else{var e=this._horizontal(),f=-this.scrollPosition;r.addClass(this._viewport,e?y._zoomingXClass:y._zoomingYClass),this._canvasStart=f,r.addClass(this._viewport,e?y._zoomingYClass:y._zoomingXClass)}return a},_positionItem:function(a,b){function e(a){return f._getItemOffsetPosition(a).then(function(d){var e,g=f._horizontal(),h=f._viewport[g?"scrollWidth":"scrollHeight"],i=g?f._viewportWidth:f._viewportHeight,j=g?"headerContainerWidth":"headerContainerHeight",k=f.layout._sizes,l=0;k&&k[j]&&(l=k[j]);var m=c.isPhone?l:b[f._startProperty],n=i-(g?d.width:d.height);m=Math.max(0,Math.min(n,m)),e=d[f._startProperty]-m;var o=Math.max(0,Math.min(h-i,e)),p=o-e;e=o;var q={type:w.ObjectType.item,index:a};if(f._hasKeyboardFocus?f._changeFocus(q,!0):f._changeFocusPassively(q),f._raiseViewLoading(!0),c.isPhone)f._viewportScrollPosition=e;else{var r=-e;f._canvasStart=r}if(f._view.realizePage(e,!0),c.isPhone&&f._isZoomedOut){var s=function(){f._zoomAnimationPromise&&f._zoomAnimationPromise.complete&&f._zoomAnimationPromise.complete(),f._zoomAnimationPromise=null};f._animateItemsForPhoneZoom().then(s,s)}return g?{x:p,y:0}:{x:0,y:p}})}var f=this,g=0;if(a&&(g=this._isZoomedOut?a.groupIndexHint:a.firstItemIndexHint),"number"==typeof g)return e(g);var h,i=this._isZoomedOut?a.groupKey:a.firstItemKey;if("string"==typeof i&&this._dataSource.itemFromKey)h=this._dataSource.itemFromKey(i,this._isZoomedOut?{groupMemberKey:a.key,groupMemberIndex:a.index}:null);else{var j=this._isZoomedOut?a.groupDescription:a.firstItemDescription;if(c.validation&&void 0===j)throw new d("WinJS.UI.ListView.InvalidItem",R.listViewInvalidItem);h=this._dataSource.itemFromDescription(j)}return h.then(function(a){return e(a.index)})},_endZoom:function(a){if(!this._isZombie()){if(!c.isPhone){var b=this._canvasStart;r.removeClass(this._viewport,y._zoomingYClass),r.removeClass(this._viewport,y._zoomingXClass),this._canvasStart=0,this._viewportScrollPosition=-b}this._disableEntranceAnimation=!a,this._isCurrentZoomView=a,this._zooming=!1,this._view.realizePage(this.scrollPosition,!1)}},_getItemOffsetPosition:function(a){var b=this;return this._getItemOffset({type:w.ObjectType.item,index:a}).then(function(a){return b._ensureFirstColumnRange(w.ObjectType.item).then(function(){return a=b._correctRangeInFirstColumn(a,w.ObjectType.item),a=b._convertFromCanvasCoordinates(a),b._horizontal()?(a.left=a.begin,a.width=a.end-a.begin,a.height=a.totalHeight):(a.top=a.begin,a.height=a.end-a.begin,a.width=a.totalWidth),a})})},_groupRemoved:function(a){this._groupFocusCache.deleteGroup(a)},_updateFocusCache:function(a){this._updateFocusCacheItemRequest&&this._updateFocusCacheItemRequest.cancel();var b=this;this._updateFocusCacheItemRequest=this._view.items.requestItem(a).then(function(){b._updateFocusCacheItemRequest=null;var c=b._view.items.itemDataAt(a),d=b._groups.groupFromItem(a),e=b._groups.group(d).key;c.itemsManagerRecord.item&&b._groupFocusCache.updateCache(e,c.itemsManagerRecord.item.key,a)})},_changeFocus:function(a,b,c,d,e){if(!this._isZombie()){var f;if(a.type===w.ObjectType.item)f=this._view.items.itemAt(a.index),!b&&f&&r.hasClass(f,y._nonSelectableClass)&&(b=!0),this._updateFocusCache(a.index);else if(a.type===w.ObjectType.groupHeader){this._lastFocusedElementInGroupTrack=a;var g=this._groups.group(a.index);f=g&&g.header}else this._lastFocusedElementInGroupTrack=a,f=a.type===w.ObjectType.footer?this._footer:this._header;this._unsetFocusOnItem(!!f),this._hasKeyboardFocus=!0,this._selection._setFocused(a,e),d||this.ensureVisible(a),!b&&this._selectFocused(c)&&this._selection.set(a.index),this._setFocusOnItem(a)}},_changeFocusPassively:function(a){var b;switch(a.type){case w.ObjectType.item:b=this._view.items.itemAt(a.index),this._updateFocusCache(a.index);break;case w.ObjectType.groupHeader:this._lastFocusedElementInGroupTrack=a;var c=this._groups.group(a.index);b=c&&c.header;break;case w.ObjectType.header:this._lastFocusedElementInGroupTrack=a,b=this._header;break;case w.ObjectType.footer:this._lastFocusedElementInGroupTrack=a,b=this._footer}this._unsetFocusOnItem(!!b),this._selection._setFocused(a),this._setFocusOnItem(a)},_drawFocusRectangle:function(b){if(b!==this._header&&b!==this._footer)if(r.hasClass(b,y._headerClass))r.addClass(b,y._itemFocusClass);else{var c=this._view.items.itemBoxFrom(b);if(c.querySelector("."+y._itemFocusOutlineClass))return;r.addClass(c,y._itemFocusClass);var d=a.document.createElement("div");d.className=y._itemFocusOutlineClass,c.appendChild(d)}},_clearFocusRectangle:function(a){if(a&&!this._isZombie()&&a!==this._header&&a!==this._footer){var b=this._view.items.itemBoxFrom(a);if(b){r.removeClass(b,y._itemFocusClass);var c=b.querySelector("."+y._itemFocusOutlineClass);c&&c.parentNode.removeChild(c)}else{var d=this._groups.headerFrom(a);d&&r.removeClass(d,y._itemFocusClass)}}},_defaultInvoke:function(a){(this._isZoomedOut||c.isPhone&&this._triggerZoom&&a.type===w.ObjectType.groupHeader)&&(this._changeFocusPassively(a),this._triggerZoom())},_selectionAllowed:function(a){var b=void 0!==a?this.elementFromIndex(a):null,c=!(b&&r.hasClass(b,y._nonSelectableClass));return c&&this._selectionMode!==w.SelectionMode.none},_multiSelection:function(){return this._selectionMode===w.SelectionMode.multi},_isInSelectionMode:function(){return this.tapBehavior===w.TapBehavior.toggleSelect&&this.selectionMode===w.SelectionMode.multi},_selectOnTap:function(){return this._tap===w.TapBehavior.toggleSelect||this._tap===w.TapBehavior.directSelect},_selectFocused:function(a){return this._tap===w.TapBehavior.directSelect&&this._selectionMode===w.SelectionMode.multi&&!a},_dispose:function(){if(!this._disposed){this._disposed=!0;var a=function(a){a&&(a.textContent="")};r._resizeNotifier.unsubscribe(this._element,this._onMSElementResizeBound),this._batchingViewUpdates&&this._batchingViewUpdates.cancel(),this._view&&this._view._dispose&&this._view._dispose(),this._mode&&this._mode._dispose&&this._mode._dispose(),this._groups&&this._groups._dispose&&this._groups._dispose(),this._selection&&this._selection._dispose&&this._selection._dispose(),this._layout&&this._layout.uninitialize&&this._layout.uninitialize(),this._itemsCountPromise&&this._itemsCountPromise.cancel(),this._versionManager&&this._versionManager._dispose(),this._clearInsertedItems(),this._itemsManager&&this._itemsManager.release(),this._zoomAnimationPromise&&this._zoomAnimationPromise.cancel(),a(this._viewport),a(this._canvas),a(this._canvasProxy),this._versionManager=null,this._view=null,this._mode=null,this._element=null,this._viewport=null,this._itemsManager=null,this._canvas=null,this._canvasProxy=null,this._itemsCountPromise=null,this._scrollToFunctor=null;var b=P.indexOf(this);b>=0&&P.splice(b,1)}},_isZombie:function(){return this._disposed||!(this.element.firstElementChild&&a.document.body.contains(this.element))},_ifZombieDispose:function(){var a=this._isZombie();return a&&!this._disposed&&K(this),a},_animationsDisabled:function(){return 0===this._viewportWidth||0===this._viewportHeight?!0:!k.isAnimationEnabled()},_fadeOutViewport:function(){var a=this;return new m(function(b){if(a._animationsDisabled())return void b();if(!a._fadingViewportOut){a._waitingEntranceAnimationPromise&&(a._waitingEntranceAnimationPromise.cancel(),a._waitingEntranceAnimationPromise=null);var c=a._fireAnimationEvent(T.contentTransition);a._firedAnimationEvent=!0,c.prevented?(a._disableEntranceAnimation=!0,a._viewport.style.opacity=1,b()):(a._fadingViewportOut=!0,a._viewport.style.overflow="hidden",j.fadeOut(a._viewport).then(function(){a._isZombie()||(a._fadingViewportOut=!1,a._viewport.style.opacity=1,b())}))}})},_animateListEntrance:function(){function a(){d._canvas.style.opacity=1,d._headerContainer.style.opacity=1,d._footerContainer.style.opacity=1,d._viewport.style.overflow="",d._raiseHeaderFooterVisibilityEvent()}var b={prevented:!1,animationPromise:m.wrap()},d=this;return this._raiseHeaderFooterVisibilityEvent(),this._disableEntranceAnimation||this._animationsDisabled()?(a(),this._waitingEntranceAnimationPromise&&(this._waitingEntranceAnimationPromise.cancel(),this._waitingEntranceAnimationPromise=null),m.wrap()):(this._firedAnimationEvent?this._firedAnimationEvent=!1:b=this._fireAnimationEvent(T.entrance),b.prevented||c.isPhone?(a(),m.wrap()):(this._waitingEntranceAnimationPromise&&this._waitingEntranceAnimationPromise.cancel(),this._canvas.style.opacity=0,this._viewport.style.overflow="hidden",this._headerContainer.style.opacity=1,this._footerContainer.style.opacity=1,this._waitingEntranceAnimationPromise=b.animationPromise.then(function(){return d._isZombie()?void 0:(d._canvas.style.opacity=1,j.enterContent(d._viewport).then(function(){d._isZombie()||(d._waitingEntranceAnimationPromise=null,d._viewport.style.overflow="")}))}),this._waitingEntranceAnimationPromise))},_fireAnimationEvent:function(b){var c=a.document.createEvent("CustomEvent"),d=m.wrap();c.initCustomEvent("contentanimating",!0,!0,{type:b}),b===T.entrance&&(c.detail.setPromise=function(a){d=a});var e=!this._element.dispatchEvent(c);return{prevented:e,animationPromise:d}},_createAriaMarkers:function(){this._viewport.getAttribute("aria-label")||this._viewport.setAttribute("aria-label",R.listViewViewportAriaLabel),this._ariaStartMarker||(this._ariaStartMarker=a.document.createElement("div"),this._ariaStartMarker.id=Q(this._ariaStartMarker),this._viewport.insertBefore(this._ariaStartMarker,this._viewport.firstElementChild)),this._ariaEndMarker||(this._ariaEndMarker=a.document.createElement("div"),this._ariaEndMarker.id=Q(this._ariaEndMarker),this._viewport.appendChild(this._ariaEndMarker))},_updateItemsAriaRoles:function(){var a,b,c=this,d=this._element.getAttribute("role");this._currentMode().staticMode()?(a="list",b="listitem"):(a="listbox",b="option"),(d!==a||this._itemRole!==b)&&(this._element.setAttribute("role",a),this._itemRole=b,this._view.items.each(function(a,b){b.setAttribute("role",c._itemRole)}))},_updateGroupHeadersAriaRoles:function(){var a=this.groupHeaderTapBehavior===w.GroupHeaderTapBehavior.none?"separator":"link";if(this._headerRole!==a){this._headerRole=a;for(var b=0,c=this._groups.length();c>b;b++){var d=this._groups.group(b).header;d&&d.setAttribute("role",this._headerRole)}}},_setAriaSelected:function(a,b){var c="true"===a.getAttribute("aria-selected");b!==c&&a.setAttribute("aria-selected",b)},_setupAriaSelectionObserver:function(a){a._mutationObserver||(this._mutationObserver.observe(a,{attributes:!0,attributeFilter:["aria-selected"]}),a._mutationObserver=!0)},_itemPropertyChange:function(a){function b(a){a.forEach(function(a){a.item.setAttribute("aria-selected",!a.selected)})}if(!this._isZombie()){for(var c=this,d=c._selectionMode===w.SelectionMode.single,e=[],f=[],g=0,h=a.length;h>g;g++){var i=a[g].target,j=c._view.items.itemBoxFrom(i),k="true"===i.getAttribute("aria-selected");if(j&&k!==r._isSelectionRendered(j)){var l=c._view.items.index(j),m={index:l,item:i,selected:k};(c._selectionAllowed(l)?e:f).push(m)}}if(e.length>0){var n=new o;c.selection._synchronize(n).then(function(){var a=c.selection._cloneSelection();return e.forEach(function(b){b.selected?a[d?"set":"add"](b.index):a.remove(b.index)}),c.selection._set(a)}).then(function(a){c._isZombie()||a||b(e),n.complete()})}b(f)}},_groupsEnabled:function(){return!!this._groups.groupDataSource},_getItemPosition:function(a,b){var c=this;return this._view.waitForEntityPosition(a).then(function(){var d,e=c._zooming&&0!==c._canvasStart;switch(a.type){case w.ObjectType.item:d=c._view.getContainer(a.index);break;case w.ObjectType.groupHeader:d=c._view._getHeaderContainer(a.index);break;case w.ObjectType.header:e=!0,d=c._headerContainer;break;case w.ObjectType.footer:e=!0,d=c._footerContainer}if(d){c._writeProfilerMark("WinJS.UI.ListView:getItemPosition,info");var f,g;c._view._expandedRange?(f=c._view._expandedRange.first.index,g=c._view._expandedRange.last.index):b=!1,a.type===w.ObjectType.item?(b=!!b,b&=c._view._ensureContainerInDOM(a.index)):b=!1;var h=c._getItemMargins(a.type),i={left:c._rtl()?L(d)-h.right:d.offsetLeft-h.left,top:d.offsetTop-h.top,totalWidth:r.getTotalWidth(d),totalHeight:r.getTotalHeight(d),contentWidth:r.getContentWidth(d),contentHeight:r.getContentHeight(d)};return b&&c._view._forceItemsBlocksInDOM(f,g+1),e?i:c._convertToCanvasCoordinates(i)}return m.cancel})},_getItemOffset:function(a,b){var c=this;return this._getItemPosition(a,b).then(function(b){var d=c._getItemMargins(a.type);if(c._horizontal()){var e=c._rtl();b.begin=b.left-d[e?"left":"right"],b.end=b.left+b.totalWidth+d[e?"right":"left"]}else b.begin=b.top-d.bottom,b.end=b.top+b.totalHeight+d.top;return b})},_getItemMargins:function(b){b=b||w.ObjectType.item;var c=this,d=function(b){var d,e=c._canvas.querySelector("."+b);e||(e=a.document.createElement("div"),r.addClass(e,b),c._viewport.appendChild(e),d=!0);var f=G._getMargins(e);return d&&c._viewport.removeChild(e),f};return b===w.ObjectType.item?this._itemMargins?this._itemMargins:this._itemMargins=d(y._containerClass):b===w.ObjectType.groupHeader?this._headerMargins?this._headerMargins:this._headerMargins=d(y._headerContainerClass):(this._headerFooterMargins||(this._headerFooterMargins={headerMargins:d(y._listHeaderContainerClass),footerMargins:d(y._listFooterContainerClass)}),this._headerFooterMargins[b===w.ObjectType.header?"headerMargins":"footerMargins"])},_fireAccessibilityAnnotationCompleteEvent:function(b,c,d,e){var f={firstIndex:b,lastIndex:c,firstHeaderIndex:+d||-1,lastHeaderIndex:+e||-1},g=a.document.createEvent("CustomEvent");g.initCustomEvent("accessibilityannotationcomplete",!0,!1,f),this._element.dispatchEvent(g)},_ensureFirstColumnRange:function(a){if(a===w.ObjectType.header||a===w.ObjectType.footer)return m.wrap();var b=a===w.ObjectType.item?"_firstItemRange":"_firstHeaderRange";if(this[b])return m.wrap();var c=this;return this._getItemOffset({type:a,index:0},!0).then(function(a){c[b]=a})},_correctRangeInFirstColumn:function(a,b){if(b===w.ObjectType.header||b===w.ObjectType.footer)return a;var c=b===w.ObjectType.groupHeader?this._firstHeaderRange:this._firstItemRange;return c.begin===a.begin&&(a.begin=this._horizontal()?-this._getCanvasMargins()[this._rtl()?"right":"left"]:-this._getCanvasMargins().top),a},_updateContainers:function(b,c,d,e){function f(){var b=a.document.createElement("div");return b.className=y._containerClass,b}function g(b,c,d){c+d>m&&(d=m-c);var e,f=b.itemsContainer,g=f.itemsBlocks,h=n._view._blockSize,i=g.length?g[g.length-1]:null,j=g.length?(g.length-1)*h+i.items.length:0,k=d-j;if(k>0){var l,o=k;if(i&&i.items.length<h){var p=Math.min(o,h-i.items.length);l=i.items.length;var q=E._stripedContainers(p,j);u.insertAdjacentHTMLUnsafe(i.element,"beforeend",q),e=i.element.children;for(var r=0;p>r;r++)i.items.push(e[l+r]);o-=p}j=g.length*h;var s=Math.floor(o/h),t="",v=j,y=j+h;if(s>0){var z=["<div class='win-itemsblock'>"+E._stripedContainers(h,v)+"</div>","<div class='win-itemsblock'>"+E._stripedContainers(h,y)+"</div>"];t=E._repeat(z,s),j+=s*h}var A=o%h;A>0&&(t+="<div class='win-itemsblock'>"+E._stripedContainers(A,j)+"</div>",j+=A,s++);var B=a.document.createElement("div");u.setInnerHTMLUnsafe(B,t);for(var e=B.children,r=0;s>r;r++){var C=e[r],D={element:C,items:E._nodeListToArray(C.children)};g.push(D)}}else if(0>k)for(var F=k;0>F;F++){var G=i.items.pop();!n._view._requireFocusRestore&&G.contains(a.document.activeElement)&&(n._view._requireFocusRestore=a.document.activeElement,n._unsetFocusOnItem()),i.element.removeChild(G),x.push(G),i.items.length||(f.element===i.element.parentNode&&f.element.removeChild(i.element),g.pop(),i=g[g.length-1])}for(var r=0,H=g.length;H>r;r++)for(var C=g[r],F=0;F<C.items.length;F++)w.push(C.items[F])}function h(a,b,c){for(var d=e.filter(function(a){return-1===a.oldIndex&&a.newIndex>=b&&a.newIndex<b+c}).sort(function(a,b){return a.newIndex-b.newIndex}),g=a.itemsContainer,h=0,i=d.length;i>h;h++){var j=d[h],k=j.newIndex-b,l=f(),m=k<g.items.length?g.items[k]:null;g.items.splice(k,0,l),g.element.insertBefore(l,m)}}function i(a,b,c){b+c>m&&(c=m-b);var d=a.itemsContainer,e=c-d.items.length;if(e>0){var f=d.element.children,g=f.length;u.insertAdjacentHTMLUnsafe(d.element,"beforeend",E._repeat("<div class='win-container win-backdrop'></div>",e));for(var h=0;e>h;h++){var i=f[g+h];d.items.push(i)}}for(var h=e;0>h;h++){var i=d.items.pop();d.element.removeChild(i),x.push(i)}for(var h=0,j=d.items.length;j>h;h++)w.push(d.items[h])}function j(a,b){var c=n._view._createHeaderContainer(J),d={header:c,itemsContainer:{element:n._view._createItemsContainer(c)}};return d.itemsContainer[n._view._blockSize?"itemsBlocks":"items"]=[],n._view._blockSize?g(d,b,a.size):i(d,b,a.size),d}function k(a,b,d,f){for(var g,h,i=d+f-1,j=0,k=e.length;k>j;j++){var l=e[j];l.newIndex>=d&&l.newIndex<=i&&-1!==l.oldIndex&&(g!==+g||l.newIndex<g)&&(g=l.newIndex,h=l.newIndex-l.oldIndex)}if(g===+g){var m=0;for(j=0,k=e.length;k>j;j++){var l=e[j];l.newIndex>=d&&l.newIndex<g&&-1===l.oldIndex&&m++}var o=0,p=g-h;for(j=0,k=e.length;k>j;j++){var l=e[j];l.oldIndex>=b&&l.oldIndex<p&&-1===l.newIndex&&o++}h+=o,h-=m,h-=d-b;var q=a.itemsContainer;if(h>0){var r=q.element.children;u.insertAdjacentHTMLUnsafe(q.element,"afterBegin",E._repeat("<div class='win-container win-backdrop'></div>",h));for(var s=0;h>s;s++){var t=r[s];q.items.splice(s,0,t)}}for(var s=h;0>s;s++){var t=q.items.shift();q.element.removeChild(t)}h&&n._affectedRange.add({start:d,end:d+f},c)}}function l(a){for(var b=0,c=0,d=n._view.tree.length;d>c;c++){var e=n._view.tree[c],f=e.itemsContainer.items.length,g=b+f-1;if(a>=b&&g>=a)return{group:c,item:a-b};b+=f}}var m,n=this,o=this._view.containers.length+d,p=c>o;if(p){for(var q=0,s=0;s<e.length;s++)-1===e[s].oldIndex&&q++;m=this._view.containers.length+q}else m=c;var t=[],v={},w=[],x=[],z=[],A=0;if(!n._view._blockSize)for(var s=0,B=this._view.tree.length;B>s;s++)z.push(A),A+=this._view.tree[s].itemsContainer.items.length;if(!n._view._blockSize)for(var C=e.filter(function(a){return-1===a.newIndex&&!a._removalHandled}).sort(function(a,b){return b.oldIndex-a.oldIndex}),s=0,B=C.length;B>s;s++){var D=C[s];D._removalHandled=!0;var F=D._itemBox;D._itemBox=null;var G=l(D.oldIndex),H=this._view.tree[G.group],I=H.itemsContainer.items[G.item];I.parentNode.removeChild(I),r.hasClass(F,y._selectedClass)&&r.addClass(I,y._selectedClass),H.itemsContainer.items.splice(G.item,1),D.element=I}this._view._modifiedGroups=[];var J=this._canvasProxy;A=0;for(var s=0,B=b.length;B>s&&(!this._groupsEnabled()||m>A);s++){var K=b[s],L=this._view.keyToGroupIndex[K.key],M=this._view.tree[L];if(M)n._view._blockSize?g(M,A,K.size):(k(M,z[L],A,K.size),h(M,A,K.size),i(M,A,K.size)),t.push(M),v[K.key]=t.length-1,delete this._view.keyToGroupIndex[K.key],J=M.itemsContainer.element,this._view._modifiedGroups.push({oldIndex:L,newIndex:t.length-1,element:M.header});else{var N=j(K,A);t.push(N),v[K.key]=t.length-1,this._view._modifiedGroups.push({oldIndex:-1,newIndex:t.length-1,element:N.header}),J=N.itemsContainer.element}A+=K.size}for(var O=[],P=[],Q=this._view.keyToGroupIndex?Object.keys(this._view.keyToGroupIndex):[],s=0,B=Q.length;B>s;s++){var G=this._view.keyToGroupIndex[Q[s]],R=this._view.tree[G];if(P.push(R.header),O.push(R.itemsContainer.element),this._view._blockSize)for(var S=0;S<R.itemsContainer.itemsBlocks.length;S++)for(var T=R.itemsContainer.itemsBlocks[S],U=0;U<T.items.length;U++)x.push(T.items[U]);else for(var U=0;U<R.itemsContainer.items.length;U++)x.push(R.itemsContainer.items[U]);this._view._modifiedGroups.push({oldIndex:G,newIndex:-1,element:R.header})}for(var s=0,B=e.length;B>s;s++)if(-1===e[s].newIndex&&!e[s]._removalHandled){e[s]._removalHandled=!0;var F=e[s]._itemBox;e[s]._itemBox=null;var I;x.length?(I=x.pop(),r.empty(I)):I=f(),r.hasClass(F,y._selectedClass)&&r.addClass(I,y._selectedClass),e._containerStripe===y._containerEvenClass?(r.addClass(I,y._containerEvenClass),r.removeClass(I,y._containerOddClass)):(r.addClass(I,y._containerOddClass),r.removeClass(I,y._containerEvenClass)),I.appendChild(F),e[s].element=I}return this._view.tree=t,this._view.keyToGroupIndex=v,this._view.containers=w,{removedHeaders:P,removedItemsContainers:O}},_writeProfilerMark:function(a){var b="WinJS.UI.ListView:"+this._id+":"+a;h(b),f.log&&f.log(b,null,"listviewprofiler")}},{triggerDispose:function(){J()}});return b.Class.mix(s,e.createEventProperties("iteminvoked","groupheaderinvoked","selectionchanging","selectionchanged","loadingstatechanged","keyboardnavigating","contentanimating","itemdragstart","itemdragenter","itemdragend","itemdragbetween","itemdragleave","itemdragchanged","itemdragdrop","headervisibilitychanged","footervisibilitychanged","accessibilityannotationcomplete")),b.Class.mix(s,p.DOMEventMixin),s})})}),d("WinJS/Controls/FlipView/_Constants",[],function(){"use strict";var a={};return a.datasourceCountChangedEvent="datasourcecountchanged",a.pageVisibilityChangedEvent="pagevisibilitychanged",a.pageSelectedEvent="pageselected",a.pageCompletedEvent="pagecompleted",a}),d("WinJS/Controls/FlipView/_PageManager",["exports","../../Core/_Global","../../Core/_Base","../../Core/_BaseUtils","../../Core/_ErrorFromName","../../Core/_Log","../../Core/_Resources","../../Core/_WriteProfilerMark","../../Animations","../../Promise","../../_Signal","../../Scheduler","../../Utilities/_Dispose","../../Utilities/_ElementUtilities","../../Utilities/_TabContainer","./_Constants"],function(a,b,c,d,e,f,g,h,i,j,k,l,m,n,o,p){"use strict";c.Namespace._moduleDefine(a,"WinJS.UI",{_FlipPageManager:c.Namespace._lazy(function(){function a(a){var b=a.winControl;return b&&b._isFlipView?!0:!1}function g(a){a.forEach(function(a){var b=a.target;b.winControl&&b.tabIndex>=0&&(b.winControl._pageManager._updateTabIndex(b.tabIndex),b.tabIndex=-1);var c=b.winControl;if(c&&c._isFlipView){var d=!1;"dir"===a.attributeName?d=!0:"style"===a.attributeName&&(d=c._cachedStyleDir!==b.style.direction),d&&(c._cachedStyleDir=b.style.direction,c._pageManager._rtl="rtl"===n._getComputedStyle(c._pageManager._flipperDiv,null).direction,c._pageManager.resized())}})}var q=n._uniqueID,r=d._browserStyleEquivalents,s=50,t=250,u={get badCurrentPage(){return"Invalid argument: currentPage must be a number greater than or equal to zero and be within the bounds of the datasource"}},v=c.Class.define(function(a,b,c,e,f,h,i){this._visibleElements=[],this._flipperDiv=a,this._panningDiv=b,this._panningDivContainer=c,this._buttonVisibilityHandler=i,this._currentPage=null,this._rtl="rtl"===n._getComputedStyle(this._flipperDiv,null).direction,this._itemsManager=e,this._itemSpacing=f,this._tabIndex=n.getTabIndex(a),this._tabIndex<0&&(this._tabIndex=0),b.tabIndex=-1,a.tabIndex=-1,this._tabManager=new o.TabContainer(this._panningDivContainer),this._tabManager.tabIndex=this._tabIndex,this._lastSelectedPage=null,this._lastSelectedElement=null,this._bufferSize=v.flipPageBufferCount,this._cachedSize=-1,this._environmentSupportsTouch=h;var j=this;this._panningDiv.addEventListener("keydown",function(a){j._blockTabs&&a.keyCode===n.Key.tab&&(a.stopImmediatePropagation(),a.preventDefault())},!0),n._addEventListener(this._flipperDiv,"focusin",function(a){a.target===j._flipperDiv&&j._currentPage.element&&n._setActive(j._currentPage.element)},!1),new n._MutationObserver(g).observe(this._flipperDiv,{attributes:!0,attributeFilter:["dir","style","tabindex"]}),this._cachedStyleDir=this._flipperDiv.style.direction,this._handleManipulationStateChangedBound=this._handleManipulationStateChanged.bind(this),this._environmentSupportsTouch&&this._panningDivContainer.addEventListener(d._browserEventEquivalents.manipulationStateChanged,this._handleManipulationStateChangedBound,!0)},{initialize:function(a,c){var d=null;if(this._panningDivContainerOffsetWidth=this._panningDivContainer.offsetWidth,this._panningDivContainerOffsetHeight=this._panningDivContainer.offsetHeight,this._isHorizontal=c,!this._currentPage){this._bufferAriaStartMarker=b.document.createElement("div"),this._bufferAriaStartMarker.id=q(this._bufferAriaStartMarker),this._panningDiv.appendChild(this._bufferAriaStartMarker),this._currentPage=this._createFlipPage(null,this),d=this._currentPage,this._panningDiv.appendChild(d.pageRoot);for(var e=2*this._bufferSize,f=0;e>f;f++)d=this._createFlipPage(d,this),this._panningDiv.appendChild(d.pageRoot);this._bufferAriaEndMarker=b.document.createElement("div"),this._bufferAriaEndMarker.id=q(this._bufferAriaEndMarker),this._panningDiv.appendChild(this._bufferAriaEndMarker)}this._prevMarker=this._currentPage.prev.prev,this._itemsManager&&this.setNewItemsManager(this._itemsManager,a)},dispose:function(){var a=this._currentPage,b=a;do m._disposeElement(b.element),b=b.next;while(b!==a)},setOrientation:function(a){if(this._notificationsEndedSignal){var b=this;return void this._notificationsEndedSignal.promise.done(function(){b._notificationsEndedSignal=null,b.setOrientation(a)})}if(a!==this._isHorizontal){this._isOrientationChanging=!0,this._isHorizontal?n.setScrollPosition(this._panningDivContainer,{scrollLeft:this._getItemStart(this._currentPage),scrollTop:0}):n.setScrollPosition(this._panningDivContainer,{scrollLeft:0,scrollTop:this._getItemStart(this._currentPage)}),this._isHorizontal=a;var c=this._panningDivContainer.style;c.overflowX="hidden",c.overflowY="hidden";var b=this;d._requestAnimationFrame(function(){b._isOrientationChanging=!1,b._forEachPage(function(a){var b=a.pageRoot.style;b.left="0px",b.top="0px"}),c.overflowX=b._isHorizontal&&b._environmentSupportsTouch?"scroll":"hidden",c.overflowY=b._isHorizontal||!b._environmentSupportsTouch?"hidden":"scroll",b._ensureCentered()})}},resetState:function(a){if(this._writeProfilerMark("WinJS.UI.FlipView:resetState,info"),0!==a){var b=this.jumpToIndex(a,!0);if(!b&&d.validation)throw new e("WinJS.UI.FlipView.BadCurrentPage",u.badCurrentPage);return b}m.disposeSubTree(this._flipperDiv),this._resetBuffer(null,!0);var c=this,f=j.wrap(!0);return this._itemsManager&&(f=c._itemsManager._firstItem().then(function(a){return c._currentPage.setElement(a),c._fetchPreviousItems(!0).then(function(){return c._fetchNextItems()}).then(function(){c._setButtonStates()})})),f.then(function(){c._tabManager.childFocus=c._currentPage.element,c._ensureCentered(),c._itemSettledOn()})},setNewItemsManager:function(a,b){this._itemsManager=a;var c=this;return this.resetState(b).then(function(){0!==b&&(c._tabManager.childFocus=c._currentPage.element,c._ensureCentered(),c._itemSettledOn())})},currentIndex:function(){if(!this._itemsManager)return 0;var a=0,b=this._navigationAnimationRecord?this._navigationAnimationRecord.newCurrentElement:this._currentPage.element;return b&&(a=this._getElementIndex(b)),a},resetScrollPos:function(){this._ensureCentered()},scrollPosChanged:function(){if(this._hasFocus&&(this._hadFocus=!0),this._itemsManager&&this._currentPage.element&&!this._isOrientationChanging){var a=this._getViewportStart(),b=this._lastScrollPos>a?this._getTailOfBuffer():this._getHeadOfBuffer();if(a!==this._lastScrollPos){for(;this._currentPage.element&&this._getItemStart(this._currentPage)>a&&this._currentPage.prev.element;)this._currentPage=this._currentPage.prev,this._fetchOnePrevious(b.prev),b=b.prev;for(;this._currentPage.element&&this._itemEnd(this._currentPage)<=a&&this._currentPage.next.element;)this._currentPage=this._currentPage.next,this._fetchOneNext(b.next),b=b.next;this._setButtonStates(),this._checkElementVisibility(!1),this._blockTabs=!0,this._lastScrollPos=a,this._currentPage.element&&(this._tabManager.childFocus=this._currentPage.element),this._setListEnds(),!this._manipulationState&&this._viewportOnItemStart()&&(this._currentPage.element.setAttribute("aria-setsize",this._cachedSize),this._currentPage.element.setAttribute("aria-posinset",this.currentIndex()+1),this._timeoutPageSelection())}}},itemRetrieved:function(a,b){var c=this;if(this._forEachPage(function(d){return d.element===b?(d===c._currentPage||d===c._currentPage.next?c._changeFlipPage(d,b,a):d.setElement(a,!0),!0):void 0}),this._navigationAnimationRecord&&this._navigationAnimationRecord.elementContainers)for(var d=this._navigationAnimationRecord.elementContainers,e=0,f=d.length;f>e;e++)d[e].element===b&&(c._changeFlipPage(d[e],b,a),d[e].element=a);this._checkElementVisibility(!1)},resized:function(){this._panningDivContainerOffsetWidth=this._panningDivContainer.offsetWidth,this._panningDivContainerOffsetHeight=this._panningDivContainer.offsetHeight;var a=this;this._forEachPage(function(b){b.pageRoot.style.width=a._panningDivContainerOffsetWidth+"px",b.pageRoot.style.height=a._panningDivContainerOffsetHeight+"px"}),this._ensureCentered(),this._writeProfilerMark("WinJS.UI.FlipView:resize,StopTM")},jumpToIndex:function(a,b){if(!b){if(!this._itemsManager||!this._currentPage.element||0>a)return j.wrap(!1);var c=this._getElementIndex(this._currentPage.element),d=Math.abs(a-c);if(0===d)return j.wrap(!1)}var e=j.wrap(!0),f=this;return e=e.then(function(){var c=f._itemsManager._itemPromiseAtIndex(a);return j.join({element:f._itemsManager._itemFromItemPromise(c),item:c}).then(function(a){var c=a.element;return f._resetBuffer(c,b),c?(f._currentPage.setElement(c),f._fetchNextItems().then(function(){return f._fetchPreviousItems(!0)}).then(function(){return!0})):!1})}),e=e.then(function(a){return f._setButtonStates(),a})},startAnimatedNavigation:function(a,b,c){if(this._writeProfilerMark("WinJS.UI.FlipView:startAnimatedNavigation,info"),this._currentPage.element){var d=this._currentPage,e=a?this._currentPage.next:this._currentPage.prev;if(e.element){this._hasFocus&&n._setActive(this._panningDiv),this._navigationAnimationRecord={},this._navigationAnimationRecord.goForward=a,this._navigationAnimationRecord.cancelAnimationCallback=b,this._navigationAnimationRecord.completionCallback=c,this._navigationAnimationRecord.oldCurrentPage=d,this._navigationAnimationRecord.newCurrentPage=e;var f=d.element,g=e.element;this._navigationAnimationRecord.newCurrentElement=g,d.setElement(null,!0),d.elementUniqueID=q(f),e.setElement(null,!0),e.elementUniqueID=q(g);var h=this._createDiscardablePage(f),i=this._createDiscardablePage(g);return h.pageRoot.itemIndex=this._getElementIndex(f),i.pageRoot.itemIndex=h.pageRoot.itemIndex+(a?1:-1),h.pageRoot.style.position="absolute",i.pageRoot.style.position="absolute",h.pageRoot.style.zIndex=1,i.pageRoot.style.zIndex=2,this._setItemStart(h,0),this._setItemStart(i,0),this._blockTabs=!0,this._visibleElements.push(g),this._announceElementVisible(g),this._navigationAnimationRecord.elementContainers=[h,i],{outgoing:h,incoming:i}}}return null},endAnimatedNavigation:function(a,b,c){if(this._writeProfilerMark("WinJS.UI.FlipView:endAnimatedNavigation,info"),this._navigationAnimationRecord&&this._navigationAnimationRecord.oldCurrentPage&&this._navigationAnimationRecord.newCurrentPage){var d=this._restoreAnimatedElement(this._navigationAnimationRecord.oldCurrentPage,b);this._restoreAnimatedElement(this._navigationAnimationRecord.newCurrentPage,c),d||this._setViewportStart(this._getItemStart(a?this._currentPage.next:this._currentPage.prev)),this._navigationAnimationRecord=null,this._itemSettledOn()}},startAnimatedJump:function(a,b,c){if(this._writeProfilerMark("WinJS.UI.FlipView:startAnimatedJump,info"),this._hasFocus&&(this._hadFocus=!0),this._currentPage.element){var d=this._currentPage.element,e=this._getElementIndex(d),f=this;return f.jumpToIndex(a).then(function(g){if(!g)return null;if(f._navigationAnimationRecord={},f._navigationAnimationRecord.cancelAnimationCallback=b,f._navigationAnimationRecord.completionCallback=c,f._navigationAnimationRecord.oldCurrentPage=null,f._forEachPage(function(a){return a.element===d?(f._navigationAnimationRecord.oldCurrentPage=a,!0):void 0}),f._navigationAnimationRecord.newCurrentPage=f._currentPage,f._navigationAnimationRecord.newCurrentPage===f._navigationAnimationRecord.oldCurrentPage)return null;var h=f._currentPage.element;f._navigationAnimationRecord.newCurrentElement=h,f._currentPage.setElement(null,!0),f._currentPage.elementUniqueID=q(h),f._navigationAnimationRecord.oldCurrentPage&&f._navigationAnimationRecord.oldCurrentPage.setElement(null,!0); var i=f._createDiscardablePage(d),j=f._createDiscardablePage(h);return i.pageRoot.itemIndex=e,j.pageRoot.itemIndex=a,i.pageRoot.style.position="absolute",j.pageRoot.style.position="absolute",i.pageRoot.style.zIndex=1,j.pageRoot.style.zIndex=2,f._setItemStart(i,0),f._setItemStart(j,f._itemSize(f._currentPage)),f._visibleElements.push(h),f._announceElementVisible(h),f._navigationAnimationRecord.elementContainers=[i,j],f._blockTabs=!0,{oldPage:i,newPage:j}})}return j.wrap(null)},simulateMouseWheelScroll:function(a){if(!this._environmentSupportsTouch&&!this._waitingForMouseScroll){var c;c="number"==typeof a.deltaY?(a.deltaX||a.deltaY)>0:a.wheelDelta<0;var d=c?this._currentPage.next:this._currentPage.prev;if(d.element){var e={contentX:0,contentY:0,viewportX:0,viewportY:0};e[this._isHorizontal?"contentX":"contentY"]=this._getItemStart(d),n._zoomTo(this._panningDivContainer,e),this._waitingForMouseScroll=!0,b.setTimeout(function(){this._waitingForMouseScroll=!1}.bind(this),n._zoomToDuration+100)}}},endAnimatedJump:function(a,b){this._writeProfilerMark("WinJS.UI.FlipView:endAnimatedJump,info"),this._navigationAnimationRecord.oldCurrentPage?this._navigationAnimationRecord.oldCurrentPage.setElement(a.element,!0):a.element.parentNode&&a.element.parentNode.removeChild(a.element),this._navigationAnimationRecord.newCurrentPage.setElement(b.element,!0),this._navigationAnimationRecord=null,this._ensureCentered(),this._itemSettledOn()},inserted:function(a,b,c,d){this._writeProfilerMark("WinJS.UI.FlipView:inserted,info");var e=this._prevMarker,f=!1,g=!1;if(d&&(this._createAnimationRecord(q(a),null),this._getAnimationRecord(a).inserted=!0),b){do{if(e===this._currentPage&&(f=!0),e.elementUniqueID===q(b)){g=!0;var h,i=e,j=a,k=q(a);if(f)for(;i.next!==this._prevMarker;)h=i.next.element,k=i.next.elementUniqueID,i.next.setElement(j,!0),!j&&k&&(i.next.elementUniqueID=k),j=h,i=i.next;else for(e.elementUniqueID===e.next.elementUniqueID&&e.elementUniqueID&&(i=e.next);i.next!==this._prevMarker;)h=i.element,k=i.elementUniqueID,i.setElement(j,!0),!j&&k&&(i.elementUniqueID=k),j=h,i=i.prev;if(j){var l=!1;this._forEachPage(function(a){return q(j)===a.elementUniqueID?(l=!0,!0):void 0}),l||this._releaseElementIfNotAnimated(j)}break}e=e.next}while(e!==this._prevMarker)}else if(c){for(;e.next!==this._prevMarker&&e.elementUniqueID!==q(c);)e===this._currentPage&&(f=!0),e=e.next;e.elementUniqueID===q(c)&&e!==this._prevMarker?(e.prev.setElement(a),g=!0):this._releaseElementIfNotAnimated(a)}else this._currentPage.setElement(a);this._getAnimationRecord(a).successfullyMoved=g,this._setButtonStates()},changed:function(a,b){this._writeProfilerMark("WinJS.UI.FlipView:changed,info");var c=this;if(this._forEachPage(function(d){if(d.elementUniqueID===q(b)){var e=c._animationRecords[d.elementUniqueID];return e.changed=!0,e.oldElement=b,e.newElement=a,d.element=a,d.elementUniqueID=q(a),c._animationRecords[q(a)]=e,!0}}),this._navigationAnimationRecord&&this._navigationAnimationRecord.elementContainers){for(var d=0,e=this._navigationAnimationRecord.elementContainers.length;e>d;d++){var f=this._navigationAnimationRecord.elementContainers[d];f&&f.elementUniqueID===q(b)&&(f.element=a,f.elementUniqueID=q(a))}var g=this._navigationAnimationRecord.newCurrentElement;g&&q(g)===q(b)&&(this._navigationAnimationRecord.newCurrentElement=a)}},moved:function(a,b,c){this._writeProfilerMark("WinJS.UI.FlipView:moved,info");var d=this._getAnimationRecord(a);d||(d=this._createAnimationRecord(q(a))),d.moved=!0,this.removed(a,!1,!1),b||c?this.inserted(a,b,c,!1):d.successfullyMoved=!1},removed:function(a,b,c){this._writeProfilerMark("WinJS.UI.FlipView:removed,info");var d=this,e=this._prevMarker,f=j.wrap();if(b){var g=!1;return this._forEachPage(function(b){(b.elementUniqueID===q(a)||g)&&(b.setElement(null,!0),g=!0)}),void this._setButtonStates()}if(c){var h=this._getAnimationRecord(a);h&&(h.removed=!0)}if(this._currentPage.elementUniqueID===q(a))this._currentPage.next.elementUniqueID?(this._shiftLeft(this._currentPage),this._ensureCentered()):this._currentPage.prev.elementUniqueID?this._shiftRight(this._currentPage):this._currentPage.setElement(null,!0);else if(e.elementUniqueID===q(a))e.next.element?f=this._itemsManager._previousItem(e.next.element).then(function(b){return b===a&&(b=d._itemsManager._previousItem(b)),b}).then(function(a){e.setElement(a,!0)}):e.setElement(null,!0);else if(e.prev.elementUniqueID===q(a))e.prev.prev&&e.prev.prev.element?f=this._itemsManager._nextItem(e.prev.prev.element).then(function(b){return b===a&&(b=d._itemsManager._nextItem(b)),b}).then(function(a){e.prev.setElement(a,!0)}):e.prev.setElement(null,!0);else{for(var i=this._currentPage.prev,k=!1;i!==e&&!k;)i.elementUniqueID===q(a)&&(this._shiftRight(i),k=!0),i=i.prev;for(i=this._currentPage.next;i!==e&&!k;)i.elementUniqueID===q(a)&&(this._shiftLeft(i),k=!0),i=i.next}return f.then(function(){d._setButtonStates()})},reload:function(){this._writeProfilerMark("WinJS.UI.FlipView:reload,info"),this.resetState(0)},getItemSpacing:function(){return this._itemSpacing},setItemSpacing:function(a){this._itemSpacing=a,this._ensureCentered()},notificationsStarted:function(){this._writeProfilerMark("WinJS.UI.FlipView:changeNotifications,StartTM"),this._logBuffer(),this._notificationsStarted=this._notificationsStarted||0,this._notificationsStarted++,this._notificationsEndedSignal=new k,this._temporaryKeys=[],this._animationRecords={};var a=this;this._forEachPage(function(b){a._createAnimationRecord(b.elementUniqueID,b)}),this._animationRecords.currentPage=this._currentPage.element,this._animationRecords.nextPage=this._currentPage.next.element},notificationsEnded:function(){var a=this;this._endNotificationsWork&&this._endNotificationsWork.cancel(),this._endNotificationsWork=this._ensureBufferConsistency().then(function(){function b(b){var c=null;return a._forEachPage(function(a){return a.element===b?(c=a,!0):void 0}),c}function c(b,c){a._writeProfilerMark("WinJS.UI.FlipView:_animateOldViewportItemRemoved,info");var d=a._createDiscardablePage(c);a._setItemStart(d,b.originalLocation),f.push(a._deleteFlipPage(d))}function d(c,d){a._writeProfilerMark("WinJS.UI.FlipView:_animateOldViewportItemMoved,info");var e,g=c.originalLocation;if(c.successfullyMoved)e=b(d),g=c.newLocation;else{e=a._createDiscardablePage(d);var h=a._getElementIndex(d),i=a._currentPage.element?a._getElementIndex(a._currentPage.element):0;g+=i>h?-100*a._bufferSize:100*a._bufferSize}e&&(a._setItemStart(e,c.originalLocation),f.push(a._moveFlipPage(e,function(){a._setItemStart(e,g)})))}function e(){return 0===f.length&&f.push(j.wrap()),j.join(f)}var f=[];a._forEachPage(function(b){var c=a._getAnimationRecord(b.element);c&&(c.changed&&(c.oldElement.removedFromChange=!0,f.push(a._changeFlipPage(b,c.oldElement,c.newElement))),c.newLocation=b.location,a._setItemStart(b,c.originalLocation),c.inserted&&(b.elementRoot.style.opacity=0))});var g=a._animationRecords.currentPage,h=a._getAnimationRecord(g),i=a._animationRecords.nextPage,k=a._getAnimationRecord(i);h&&h.changed&&(g=h.newElement),k&&k.changed&&(i=k.newElement),(g!==a._currentPage.element||i!==a._currentPage.next.element)&&(h&&h.removed&&c(h,g),k&&k.removed&&c(k,i)),a._blockTabs=!0,e().then(function(){f=[],h&&h.moved&&d(h,g),k&&k.moved&&d(k,i);var b=a._getAnimationRecord(a._currentPage.element),c=a._getAnimationRecord(a._currentPage.next.element);a._forEachPage(function(d){var e=a._getAnimationRecord(d.element);e&&(e.inserted?e!==b&&e!==c&&(d.elementRoot.style.opacity=1):e.originalLocation!==e.newLocation&&(e!==h&&e!==k||e===h&&!h.moved||e===k&&!k.moved)&&f.push(a._moveFlipPage(d,function(){a._setItemStart(d,e.newLocation)})))}),e().then(function(){f=[],b&&b.inserted&&f.push(a._insertFlipPage(a._currentPage)),c&&c.inserted&&f.push(a._insertFlipPage(a._currentPage.next)),e().then(function(){a._checkElementVisibility(!1),a._itemSettledOn(),a._setListEnds(),a._notificationsStarted--,0===a._notificationsStarted&&a._notificationsEndedSignal.complete(),a._writeProfilerMark("WinJS.UI.FlipView:changeNotifications,StopTM"),a._logBuffer(),a._endNotificationsWork=null})})})})},disableTouchFeatures:function(){this._environmentSupportsTouch=!1;var a=this._panningDivContainer.style;this._panningDivContainer.removeEventListener(d._browserEventEquivalents.manipulationStateChanged,this._handleManipulationStateChangedBound,!0),a.overflowX="hidden",a.overflowY="hidden";var b=["scroll-snap-type","scroll-snap-points-x","scroll-snap-points-y","scroll-limit-x-min","scroll-limit-x-max","scroll-limit-y-min","scroll-limit-y-max"];b.forEach(function(b){var c=r[b];c&&(a[c.scriptName]="")})},_hasFocus:{get:function(){return this._flipperDiv.contains(b.document.activeElement)}},_timeoutPageSelection:function(){var a=this;this._lastTimeoutRequest&&this._lastTimeoutRequest.cancel(),this._lastTimeoutRequest=j.timeout(t).then(function(){a._itemSettledOn()})},_updateTabIndex:function(a){this._forEachPage(function(b){b.element&&(b.element.tabIndex=a)}),this._tabIndex=a,this._tabManager.tabIndex=a},_releaseElementIfNotAnimated:function(a){var b=this._getAnimationRecord(a);b&&(b.changed||b.inserted||b.moved||b.removed)||this._itemsManager.releaseItem(a)},_getAnimationRecord:function(a){return a?this._animationRecords[q(a)]:null},_createAnimationRecord:function(a,b){if(a){var c=this._animationRecords[a]={removed:!1,changed:!1,inserted:!1};return b&&(c.originalLocation=b.location),c}},_writeProfilerMark:function(a){h(a),this._flipperDiv.winControl.constructor._enabledDebug&&f.log&&f.log(a,null,"flipviewdebug")},_getElementIndex:function(a){var b=0;try{b=this._itemsManager.itemObject(a).index}catch(c){}return b},_resetBuffer:function(a,b){this._writeProfilerMark("WinJS.UI.FlipView:_resetBuffer,info");var c=this._currentPage,d=c;do d.element&&d.element===a||b?d.setElement(null,!0):d.setElement(null),d=d.next;while(d!==c)},_getHeadOfBuffer:function(){return this._prevMarker.prev},_getTailOfBuffer:function(){return this._prevMarker},_insertNewFlipPage:function(a){this._writeProfilerMark("WinJS.UI.FlipView:_insertNewFlipPage,info");var b=this._createFlipPage(a,this);return this._panningDiv.appendChild(b.pageRoot),b},_fetchNextItems:function(){this._writeProfilerMark("WinJS.UI.FlipView:_fetchNextItems,info");for(var a=j.wrap(this._currentPage),b=this,c=0;c<this._bufferSize;c++)a=a.then(function(a){return a.next===b._prevMarker&&b._insertNewFlipPage(a),a.element?b._itemsManager._nextItem(a.element).then(function(b){return a.next.setElement(b),a.next}):(a.next.setElement(null),a.next)});return a},_fetchOneNext:function(a){this._writeProfilerMark("WinJS.UI.FlipView:_fetchOneNext,info");var b=a.prev.element;if(this._prevMarker===a&&(this._prevMarker=this._prevMarker.next),!b)return void a.setElement(null);var c=this;return this._itemsManager._nextItem(b).then(function(b){a.setElement(b),c._movePageAhead(a.prev,a)})},_fetchPreviousItems:function(a){this._writeProfilerMark("WinJS.UI.FlipView:_fetchPreviousItems,info");for(var b=this,c=j.wrap(this._currentPage),d=0;d<this._bufferSize;d++)c=c.then(function(a){return a.element?b._itemsManager._previousItem(a.element).then(function(b){return a.prev.setElement(b),a.prev}):(a.prev.setElement(null),a.prev)});return c.then(function(c){a&&(b._prevMarker=c)})},_fetchOnePrevious:function(a){this._writeProfilerMark("WinJS.UI.FlipView:_fetchOnePrevious,info");var b=a.next.element;if(this._prevMarker===a.next&&(this._prevMarker=this._prevMarker.prev),!b)return a.setElement(null),j.wrap();var c=this;return this._itemsManager._previousItem(b).then(function(b){a.setElement(b),c._movePageBehind(a.next,a)})},_setButtonStates:function(){this._currentPage.prev.element?this._buttonVisibilityHandler.showPreviousButton():this._buttonVisibilityHandler.hidePreviousButton(),this._currentPage.next.element?this._buttonVisibilityHandler.showNextButton():this._buttonVisibilityHandler.hideNextButton()},_ensureCentered:function(a){this._writeProfilerMark("WinJS.UI.FlipView:_ensureCentered,info"),this._setItemStart(this._currentPage,s*this._viewportSize());for(var b=this._currentPage;b!==this._prevMarker;)this._movePageBehind(b,b.prev),b=b.prev;for(b=this._currentPage;b.next!==this._prevMarker;)this._movePageAhead(b,b.next),b=b.next;var c=!1;this._lastScrollPos&&!a&&(this._setListEnds(),c=!0),this._lastScrollPos=this._getItemStart(this._currentPage),this._setViewportStart(this._lastScrollPos),this._checkElementVisibility(!0),this._setupSnapPoints(),c||this._setListEnds()},_ensureBufferConsistency:function(){var a=this,b=this._currentPage.element;if(!b)return j.wrap();var c=!1,d={},e={};this._forEachPage(function(a){if(a&&a.elementUniqueID){if(d[a.elementUniqueID])return c=!0,!0;if(d[a.elementUniqueID]=!0,a.location>0){if(e[a.location])return c=!0,!0;e[a.location]=!0}}});var f=Object.keys(this._animationRecords);return f.forEach(function(b){var d=a._animationRecords[b];d&&(d.changed||d.inserted||d.moved||d.removed)&&(c=!0)}),c?(this._resetBuffer(null,!0),this._currentPage.setElement(b),this._fetchNextItems().then(function(){return a._fetchPreviousItems(!0)}).then(function(){a._ensureCentered()})):j.wrap()},_shiftLeft:function(a){this._writeProfilerMark("WinJS.UI.FlipView:_shiftLeft,info");for(var b=a,c=null;b!==this._prevMarker&&b.next!==this._prevMarker;)c=b.next.element,!c&&b.next.elementUniqueID&&(b.elementUniqueID=b.next.elementUniqueID),b.next.setElement(null,!0),b.setElement(c,!0),b=b.next;if(b!==this._prevMarker&&b.prev.element){var d=this;return this._itemsManager._nextItem(b.prev.element).then(function(a){b.setElement(a),d._createAnimationRecord(b.elementUniqueID,b)})}},_logBuffer:function(){if(this._flipperDiv.winControl.constructor._enabledDebug){f.log&&f.log(this._currentPage.next.next.next.elementUniqueID+" @:"+this._currentPage.next.next.next.location+(this._currentPage.next.next.next.element?" "+this._currentPage.next.next.next.element.textContent:""),null,"flipviewdebug"),f.log&&f.log(this._currentPage.next.next.next.next.elementUniqueID+" @:"+this._currentPage.next.next.next.next.location+(this._currentPage.next.next.next.next.element?" "+this._currentPage.next.next.next.next.element.textContent:""),null,"flipviewdebug"),f.log&&f.log("> "+this._currentPage.elementUniqueID+" @:"+this._currentPage.location+(this._currentPage.element?" "+this._currentPage.element.textContent:""),null,"flipviewdebug"),f.log&&f.log(this._currentPage.next.elementUniqueID+" @:"+this._currentPage.next.location+(this._currentPage.next.element?" "+this._currentPage.next.element.textContent:""),null,"flipviewdebug"),f.log&&f.log(this._currentPage.next.next.elementUniqueID+" @:"+this._currentPage.next.next.location+(this._currentPage.next.next.element?" "+this._currentPage.next.next.element.textContent:""),null,"flipviewdebug");var a=Object.keys(this._itemsManager._elementMap),b=[];this._forEachPage(function(a){a&&a.elementUniqueID&&b.push(a.elementUniqueID)}),f.log&&f.log("itemsmanager = ["+a.join(" ")+"] flipview ["+b.join(" ")+"]",null,"flipviewdebug")}},_shiftRight:function(a){this._writeProfilerMark("WinJS.UI.FlipView:_shiftRight,info");for(var b=a,c=null;b!==this._prevMarker;)c=b.prev.element,!c&&b.prev.elementUniqueID&&(b.elementUniqueID=b.prev.elementUniqueID),b.prev.setElement(null,!0),b.setElement(c,!0),b=b.prev;if(b.next.element){var d=this;return this._itemsManager._previousItem(b.next.element).then(function(a){b.setElement(a),d._createAnimationRecord(b.elementUniqueID,b)})}},_checkElementVisibility:function(a){var b,c;if(a){var d=this._currentPage.element;for(b=0,c=this._visibleElements.length;c>b;b++)this._visibleElements[b]!==d&&this._announceElementInvisible(this._visibleElements[b]);this._visibleElements=[],d&&(this._visibleElements.push(d),this._announceElementVisible(d))}else{for(b=0,c=this._visibleElements.length;c>b;b++)(!this._visibleElements[b].parentNode||this._visibleElements[b].removedFromChange)&&this._announceElementInvisible(this._visibleElements[b]);this._visibleElements=[];var e=this;this._forEachPage(function(a){var b=a.element;b&&(e._itemInView(a)?(e._visibleElements.push(b),e._announceElementVisible(b)):e._announceElementInvisible(b))})}},_announceElementVisible:function(a){if(a&&!a.visible){a.visible=!0;var c=b.document.createEvent("CustomEvent");this._writeProfilerMark("WinJS.UI.FlipView:pageVisibilityChangedEvent(visible:true),info"),c.initCustomEvent(p.pageVisibilityChangedEvent,!0,!1,{source:this._flipperDiv,visible:!0}),a.dispatchEvent(c)}},_announceElementInvisible:function(a){if(a&&a.visible){a.visible=!1;var c=!1;a.parentNode||(c=!0,this._panningDivContainer.appendChild(a));var d=b.document.createEvent("CustomEvent");this._writeProfilerMark("WinJS.UI.FlipView:pageVisibilityChangedEvent(visible:false),info"),d.initCustomEvent(p.pageVisibilityChangedEvent,!0,!1,{source:this._flipperDiv,visible:!1}),a.dispatchEvent(d),c&&this._panningDivContainer.removeChild(a)}},_createDiscardablePage:function(a){var b=this._createPageContainer(),c={pageRoot:b.root,elementRoot:b.elementContainer,discardable:!0,element:a,elementUniqueID:q(a),discard:function(){c.pageRoot.parentNode&&c.pageRoot.parentNode.removeChild(c.pageRoot),c.element.parentNode&&c.element.parentNode.removeChild(c.element)}};return c.pageRoot.style.top="0px",c.elementRoot.appendChild(a),this._panningDiv.appendChild(c.pageRoot),c},_createPageContainer:function(){var a=this._panningDivContainerOffsetWidth,c=this._panningDivContainerOffsetHeight,d=b.document.createElement("div"),e=d.style,f=b.document.createElement("div");return f.className="win-item",e.position="absolute",e.overflow="hidden",e.width=a+"px",e.height=c+"px",d.appendChild(f),{root:d,elementContainer:f}},_createFlipPage:function(b,c){var d={};d.element=null,d.elementUniqueID=null,b?(d.prev=b,d.next=b.next,d.next.prev=d,b.next=d):(d.next=d,d.prev=d);var e=this._createPageContainer();return d.elementRoot=e.elementContainer,d.elementRoot.style.msOverflowStyle="auto",d.pageRoot=e.root,d.setElement=function(b,e){if(void 0===b&&(b=null),b===d.element)return void(b||(d.elementUniqueID=null));if(d.element&&(e||(c._itemsManager.releaseItem(d.element),m._disposeElement(d.element))),d.element=b,d.elementUniqueID=b?q(b):null,n.empty(d.elementRoot),d.element){if(d===c._currentPage&&(c._tabManager.childFocus=b),!a(d.element)){d.element.tabIndex=c._tabIndex,d.element.setAttribute("role","option"),d.element.setAttribute("aria-selected",!1),d.element.id||(d.element.id=q(d.element));var f=function(a,b,c){a.setAttribute(c,b.id)},g=!d.next.element||d===c._prevMarker.prev;g&&(f(d.element,c._bufferAriaEndMarker,"aria-flowto"),f(c._bufferAriaEndMarker,d.element,"x-ms-aria-flowfrom")),d!==c._prevMarker&&d.prev.element&&(f(d.prev.element,d.element,"aria-flowto"),f(d.element,d.prev.element,"x-ms-aria-flowfrom")),d.next!==c._prevMarker&&d.next.element&&(f(d.element,d.next.element,"aria-flowto"),f(d.next.element,d.element,"x-ms-aria-flowfrom")),d.prev.element||f(d.element,c._bufferAriaStartMarker,"x-ms-aria-flowfrom")}d.elementRoot.appendChild(d.element)}},d},_itemInView:function(a){return this._itemEnd(a)>this._getViewportStart()&&this._getItemStart(a)<this._viewportEnd()},_getViewportStart:function(){return this._panningDivContainer.parentNode?this._isHorizontal?n.getScrollPosition(this._panningDivContainer).scrollLeft:n.getScrollPosition(this._panningDivContainer).scrollTop:void 0},_setViewportStart:function(a){this._panningDivContainer.parentNode&&(this._isHorizontal?n.setScrollPosition(this._panningDivContainer,{scrollLeft:a}):n.setScrollPosition(this._panningDivContainer,{scrollTop:a}))},_viewportEnd:function(){var a=this._panningDivContainer;return this._isHorizontal?this._rtl?this._getViewportStart()+this._panningDivContainerOffsetWidth:n.getScrollPosition(a).scrollLeft+this._panningDivContainerOffsetWidth:a.scrollTop+this._panningDivContainerOffsetHeight},_viewportSize:function(){return this._isHorizontal?this._panningDivContainerOffsetWidth:this._panningDivContainerOffsetHeight},_getItemStart:function(a){return a.location},_setItemStart:function(a,b){void 0!==b&&(this._isHorizontal?a.pageRoot.style.left=(this._rtl?-b:b)+"px":a.pageRoot.style.top=b+"px",a.location=b)},_itemEnd:function(a){return(this._isHorizontal?a.location+this._panningDivContainerOffsetWidth:a.location+this._panningDivContainerOffsetHeight)+this._itemSpacing},_itemSize:function(){return this._isHorizontal?this._panningDivContainerOffsetWidth:this._panningDivContainerOffsetHeight},_movePageAhead:function(a,b){var c=this._itemSize(a)+this._itemSpacing;this._setItemStart(b,this._getItemStart(a)+c)},_movePageBehind:function(a,b){var c=this._itemSize(a)+this._itemSpacing;this._setItemStart(b,this._getItemStart(a)-c)},_setupSnapPoints:function(){if(this._environmentSupportsTouch){var a=this._panningDivContainer.style;a[r["scroll-snap-type"].scriptName]="mandatory";var b=this._viewportSize(),c=b+this._itemSpacing,d="scroll-snap-points",e=0,f=this._getItemStart(this._currentPage);e=f%(b+this._itemSpacing),a[r[this._isHorizontal?d+"-x":d+"-y"].scriptName]="snapInterval("+e+"px, "+c+"px)"}},_setListEnds:function(){if(this._environmentSupportsTouch&&this._currentPage.element){for(var a=this._panningDivContainer.style,b=0,c=0,d=this._getTailOfBuffer(),e=this._getHeadOfBuffer(),f=r["scroll-limit-"+(this._isHorizontal?"x-min":"y-min")].scriptName,g=r["scroll-limit-"+(this._isHorizontal?"x-max":"y-max")].scriptName;!e.element&&(e=e.prev,e!==this._prevMarker.prev););for(;!d.element&&(d=d.next,d!==this._prevMarker););c=this._getItemStart(e),b=this._getItemStart(d),a[f]=b+"px",a[g]=c+"px"}},_viewportOnItemStart:function(){return this._getItemStart(this._currentPage)===this._getViewportStart()},_restoreAnimatedElement:function(a,b){var c=!0;return a.elementUniqueID!==q(b.element)||a.element?this._forEachPage(function(a){a.elementUniqueID!==b.elementUniqueID||a.element||(a.setElement(b.element,!0),c=!1)}):(a.setElement(b.element,!0),c=!1),c},_itemSettledOn:function(){this._lastTimeoutRequest&&(this._lastTimeoutRequest.cancel(),this._lastTimeoutRequest=null);var c=this;d._setImmediate(function(){c._viewportOnItemStart()&&(c._blockTabs=!1,c._currentPage.element&&c._lastSelectedElement!==c._currentPage.element&&(c._lastSelectedPage&&c._lastSelectedPage.element&&!a(c._lastSelectedPage.element)&&c._lastSelectedPage.element.setAttribute("aria-selected",!1),c._lastSelectedPage=c._currentPage,c._lastSelectedElement=c._currentPage.element,a(c._currentPage.element)||c._currentPage.element.setAttribute("aria-selected",!0),l.schedule(function(){if(c._currentPage.element){(c._hasFocus||c._hadFocus)&&(c._hadFocus=!1,n._setActive(c._currentPage.element),c._tabManager.childFocus=c._currentPage.element);var a=b.document.createEvent("CustomEvent");a.initCustomEvent(p.pageSelectedEvent,!0,!1,{source:c._flipperDiv}),c._writeProfilerMark("WinJS.UI.FlipView:pageSelectedEvent,info"),c._currentPage.element.dispatchEvent(a);var d=c._currentPage.element;if(d){var e=c._itemsManager._recordFromElement(d,!0);e&&e.renderComplete.then(function(){d===c._currentPage.element&&(c._currentPage.element.setAttribute("aria-setsize",c._cachedSize),c._currentPage.element.setAttribute("aria-posinset",c.currentIndex()+1),c._bufferAriaStartMarker.setAttribute("aria-flowto",c._currentPage.element.id),a=b.document.createEvent("CustomEvent"),a.initCustomEvent(p.pageCompletedEvent,!0,!1,{source:c._flipperDiv}),c._writeProfilerMark("WinJS.UI.FlipView:pageCompletedEvent,info"),c._currentPage.element.dispatchEvent(a))})}}},l.Priority.normal,null,"WinJS.UI.FlipView._dispatchPageSelectedEvent")))})},_forEachPage:function(a){var b=this._prevMarker;do{if(a(b))break;b=b.next}while(b!==this._prevMarker)},_changeFlipPage:function(a,b,c){this._writeProfilerMark("WinJS.UI.FlipView:_changeFlipPage,info"),a.element=null,a.setElement?a.setElement(c,!0):(b.parentNode.removeChild(b),a.elementRoot.appendChild(c));var d=b.style;return d.position="absolute",d.left="0px",d.top="0px",d.opacity=1,a.pageRoot.appendChild(b),b.style.left=Math.max(0,(a.pageRoot.offsetWidth-b.offsetWidth)/2)+"px",b.style.top=Math.max(0,(a.pageRoot.offsetHeight-b.offsetHeight)/2)+"px",i.fadeOut(b).then(function(){b.parentNode&&b.parentNode.removeChild(b)})},_deleteFlipPage:function(a){h("WinJS.UI.FlipView:_deleteFlipPage,info"),a.elementRoot.style.opacity=0;var b=i.createDeleteFromListAnimation([a.elementRoot]),c=this;return b.execute().then(function(){a.discardable&&(a.discard(),c._itemsManager.releaseItem(a.element))})},_insertFlipPage:function(a){h("WinJS.UI.FlipView:_insertFlipPage,info"),a.elementRoot.style.opacity=1;var b=i.createAddToListAnimation([a.elementRoot]);return b.execute().then(function(){a.discardable&&a.discard()})},_moveFlipPage:function(a,b){h("WinJS.UI.FlipView:_moveFlipPage,info");var c=i.createRepositionAnimation(a.pageRoot);b();var d=this;return c.execute().then(function(){if(a.discardable){a.discard();var b=d._getAnimationRecord(a.element);b&&!b.successfullyMoved&&d._itemsManager.releaseItem(a.element)}})},_handleManipulationStateChanged:function(a){this._manipulationState=a.currentState,0===a.currentState&&a.target===this._panningDivContainer&&(this._itemSettledOn(),this._ensureCentered())}},{supportedForProcessing:!1});return v.flipPageBufferCount=2,v})})}),d("require-style!less/styles-flipview",[],function(){}),d("require-style!less/colors-flipview",[],function(){}),d("WinJS/Controls/FlipView",["../Core/_Global","../Core/_Base","../Core/_BaseUtils","../Core/_ErrorFromName","../Core/_Events","../Core/_Resources","../Core/_WriteProfilerMark","../Animations","../Animations/_TransitionAnimation","../BindingList","../Promise","../Scheduler","../Utilities/_Control","../Utilities/_Dispose","../Utilities/_ElementUtilities","../Utilities/_Hoverable","../Utilities/_ItemsManager","../Utilities/_UI","./FlipView/_Constants","./FlipView/_PageManager","require-style!less/styles-flipview","require-style!less/colors-flipview"],function(a,b,c,d,e,f,g,h,i,j,k,l,m,n,o,p,q,r,s,t){"use strict";b.Namespace.define("WinJS.UI",{FlipView:b.Namespace._lazy(function(){function p(a){var b=a[0].target.winControl;b&&b instanceof L&&a.some(function(a){return"dir"===a.attributeName?!0:"style"===a.attributeName?b._cachedStyleDir!==a.target.style.direction:!1})&&(b._cachedStyleDir=b._flipviewDiv.style.direction,b._rtl="rtl"===o._getComputedStyle(b._flipviewDiv,null).direction,b._setupOrientation())}function u(a){var b=a.target&&a.target.winControl;b&&b instanceof L&&(g("WinJS.UI.FlipView:resize,StartTM"),b._resize())}var v="win-navbutton",w="win-flipview",x="win-navleft",y="win-navright",z="win-navtop",A="win-navbottom",B="Previous",C="Next",D=3e3,E=500,F="&#57570;",G="&#57571;",H="&#57572;",I="&#57573;",J=40,K={get badAxis(){return"Invalid argument: orientation must be a string, either 'horizontal' or 'vertical'"},get badCurrentPage(){return"Invalid argument: currentPage must be a number greater than or equal to zero and be within the bounds of the datasource"},get noitemsManagerForCount(){return"Invalid operation: can't get count if no dataSource has been set"},get badItemSpacingAmount(){return"Invalid argument: itemSpacing must be a number greater than or equal to zero"},get navigationDuringStateChange(){return"Error: After changing itemDataSource or itemTemplate, any navigation in the FlipView control should be delayed until the pageselected event is fired."},get panningContainerAriaLabel(){return f._getWinJSString("ui/flipViewPanningContainerAriaLabel").value}},L=b.Class.define(function(b,c){g("WinJS.UI.FlipView:constructor,StartTM"),this._disposed=!1,b=b||a.document.createElement("div");var d=!0,e=null,f=q._trivialHtmlRenderer,h=0,i=0;if(c){if(c.orientation&&"string"==typeof c.orientation)switch(c.orientation.toLowerCase()){case"horizontal":d=!0;break;case"vertical":d=!1}c.currentPage&&(h=c.currentPage>>0,h=0>h?0:h),c.itemDataSource&&(e=c.itemDataSource),c.itemTemplate&&(f=this._getItemRenderer(c.itemTemplate)),c.itemSpacing&&(i=c.itemSpacing>>0,i=0>i?0:i)}if(!e){var k=new j.List;e=k.dataSource}o.empty(b),this._flipviewDiv=b,b.winControl=this,m._setOptions(this,c,!0),this._initializeFlipView(b,d,e,f,h,i),o.addClass(b,"win-disposable"),this._avoidTrappingTime=0,this._windowWheelHandlerBound=this._windowWheelHandler.bind(this),o._globalListener.addEventListener(b,"wheel",this._windowWheelHandlerBound),o._globalListener.addEventListener(b,"mousewheel",this._windowWheelHandlerBound),g("WinJS.UI.FlipView:constructor,StopTM")},{dispose:function(){g("WinJS.UI.FlipView:dispose,StopTM"),this._disposed||(o._globalListener.removeEventListener(this._flipviewDiv,"wheel",this._windowWheelHandlerBound),o._globalListener.removeEventListener(this._flipviewDiv,"mousewheel",this._windowWheelHandlerBound),o._resizeNotifier.unsubscribe(this._flipviewDiv,u),this._disposed=!0,this._pageManager.dispose(),this._itemsManager.release(),this.itemDataSource=null)},next:function(){g("WinJS.UI.FlipView:next,info");var a=this._nextAnimation?null:this._cancelDefaultAnimation;return this._navigate(!0,a)},previous:function(){g("WinJS.UI.FlipView:prev,info");var a=this._prevAnimation?null:this._cancelDefaultAnimation;return this._navigate(!1,a)},element:{get:function(){return this._flipviewDiv}},currentPage:{get:function(){return this._getCurrentIndex()},set:function(a){if(g("WinJS.UI.FlipView:set_currentPage,info"),this._pageManager._notificationsEndedSignal){var b=this;return void this._pageManager._notificationsEndedSignal.promise.done(function(){b._pageManager._notificationsEndedSignal=null,b.currentPage=a})}if(!this._animating||this._cancelAnimation())if(a>>=0,a=0>a?0:a,this._refreshTimer)this._indexAfterRefresh=a;else{this._pageManager._cachedSize>0?a=Math.min(this._pageManager._cachedSize-1,a):0===this._pageManager._cachedSize&&(a=0);var b=this;if(this._jumpingToIndex===a)return;var c=function(){b._jumpingToIndex=null};this._jumpingToIndex=a;var d=this._jumpAnimation?this._jumpAnimation:this._defaultAnimation.bind(this),e=this._jumpAnimation?null:this._cancelDefaultAnimation,f=function(){b._completeJump()};this._pageManager.startAnimatedJump(a,e,f).then(function(a){if(a){b._animationsStarted();var e=a.oldPage.pageRoot,h=a.newPage.pageRoot;b._contentDiv.appendChild(e),b._contentDiv.appendChild(h),b._completeJumpPending=!0,d(e,h).then(function(){b._completeJumpPending&&(f(),g("WinJS.UI.FlipView:set_currentPage.animationComplete,info"))}).done(c,c)}else c()},c)}}},orientation:{get:function(){return this._axisAsString()},set:function(a){g("WinJS.UI.FlipView:set_orientation,info");var b="horizontal"===a;b!==this._isHorizontal&&(this._isHorizontal=b,this._setupOrientation(),this._pageManager.setOrientation(this._isHorizontal))}},itemDataSource:{get:function(){return this._dataSource},set:function(a){g("WinJS.UI.FlipView:set_itemDataSource,info"),this._dataSourceAfterRefresh=a||(new j.List).dataSource,this._refresh()}},itemTemplate:{get:function(){return this._itemRenderer},set:function(a){g("WinJS.UI.FlipView:set_itemTemplate,info"),this._itemRendererAfterRefresh=this._getItemRenderer(a),this._refresh()}},itemSpacing:{get:function(){return this._pageManager.getItemSpacing()},set:function(a){g("WinJS.UI.FlipView:set_itemSpacing,info"),a>>=0,a=0>a?0:a,this._pageManager.setItemSpacing(a)}},count:function(){g("WinJS.UI.FlipView:count,info");var a=this;return new k(function(b,c){a._itemsManager?a._pageManager._cachedSize===r.CountResult.unknown||a._pageManager._cachedSize>=0?b(a._pageManager._cachedSize):a._dataSource.getCount().then(function(c){a._pageManager._cachedSize=c,b(c)}):c(L.noitemsManagerForCount)})},setCustomAnimations:function(a){g("WinJS.UI.FlipView:setCustomAnimations,info"),void 0!==a.next&&(this._nextAnimation=a.next),void 0!==a.previous&&(this._prevAnimation=a.previous),void 0!==a.jump&&(this._jumpAnimation=a.jump)},forceLayout:function(){g("WinJS.UI.FlipView:forceLayout,info"),this._pageManager.resized()},_initializeFlipView:function(b,d,e,f,g,h){function i(a){a.setAttribute("aria-hidden",!0),a.style.visibility="hidden",a.style.opacity=0,a.tabIndex=-1,a.style.zIndex=1e3 }function j(a){if(a.pointerType!==D){if(m._touchInteraction=!1,a.screenX===m._lastMouseX&&a.screenY===m._lastMouseY)return;m._lastMouseX=a.screenX,m._lastMouseY=a.screenY,m._mouseInViewport=!0,m._fadeInButton("prev"),m._fadeInButton("next"),m._fadeOutButtons()}}function k(a){a.pointerType===D?(m._mouseInViewport=!1,m._touchInteraction=!0,m._fadeOutButtons(!0)):(m._touchInteraction=!1,m._isInteractive(a.target)||0!==(4&a.buttons)&&(a.stopPropagation(),a.preventDefault()))}function l(a){a.pointerType!==D&&(m._touchInteraction=!1)}var m=this,n=!1;this._flipviewDiv=b,o.addClass(this._flipviewDiv,w),this._contentDiv=a.document.createElement("div"),this._panningDivContainer=a.document.createElement("div"),this._panningDivContainer.className="win-surface",this._panningDiv=a.document.createElement("div"),this._prevButton=a.document.createElement("button"),this._nextButton=a.document.createElement("button"),this._isHorizontal=d,this._dataSource=e,this._itemRenderer=f,this._itemsManager=null,this._pageManager=null;for(var s=["scroll-limit-x-max","scroll-limit-x-min","scroll-limit-y-max","scroll-limit-y-min","scroll-snap-type","scroll-snap-x","scroll-snap-y","overflow-style"],v=!0,x=c._browserStyleEquivalents,y=0,z=s.length;z>y;y++)v=v&&!!x[s[y]];v=v&&!!c._browserEventEquivalents.manipulationStateChanged,v=v&&o._supportsSnapPoints,this._environmentSupportsTouch=v;var A=this._flipviewDiv.getAttribute("aria-label");A||this._flipviewDiv.setAttribute("aria-label",""),this._flipviewDiv.setAttribute("role","listbox"),this._flipviewDiv.style.overflow||(this._flipviewDiv.style.overflow="hidden"),this._contentDiv.style.position="relative",this._contentDiv.style.zIndex=0,this._contentDiv.style.width="100%",this._contentDiv.style.height="100%",this._panningDiv.style.position="relative",this._panningDivContainer.style.position="relative",this._panningDivContainer.style.width="100%",this._panningDivContainer.style.height="100%",this._panningDivContainer.setAttribute("role","group"),this._panningDivContainer.setAttribute("aria-label",K.panningContainerAriaLabel),this._contentDiv.appendChild(this._panningDivContainer),this._flipviewDiv.appendChild(this._contentDiv),this._panningDiv.style.width="100%",this._panningDiv.style.height="100%",this._setupOrientation(),i(this._prevButton),i(this._nextButton),this._prevButton.setAttribute("aria-label",B),this._nextButton.setAttribute("aria-label",C),this._prevButton.setAttribute("type","button"),this._nextButton.setAttribute("type","button"),this._panningDivContainer.appendChild(this._panningDiv),this._contentDiv.appendChild(this._prevButton),this._contentDiv.appendChild(this._nextButton),this._itemsManagerCallback={inserted:function(a,b,c){m._itemsManager._itemFromPromise(a).then(function(a){var d=m._itemsManager._elementFromHandle(b),e=m._itemsManager._elementFromHandle(c);m._pageManager.inserted(a,d,e,!0)})},countChanged:function(a,b){m._pageManager._cachedSize=a,b!==r.CountResult.unknown&&m._fireDatasourceCountChangedEvent()},changed:function(a,b){m._pageManager.changed(a,b)},moved:function(a,b,c,d){var e=function(a){m._pageManager.moved(a,b,c)};a?e(a):m._itemsManager._itemFromPromise(d).then(e)},removed:function(a,b){a&&m._pageManager.removed(a,b,!0)},knownUpdatesComplete:function(){},beginNotifications:function(){m._cancelAnimation(),m._pageManager.notificationsStarted()},endNotifications:function(){m._pageManager.notificationsEnded()},itemAvailable:function(a,b){m._pageManager.itemRetrieved(a,b)},reload:function(){m._pageManager.reload()}},this._dataSource&&(this._itemsManager=q._createItemsManager(this._dataSource,this._itemRenderer,this._itemsManagerCallback,{ownerElement:this._flipviewDiv})),this._pageManager=new t._FlipPageManager(this._flipviewDiv,this._panningDiv,this._panningDivContainer,this._itemsManager,h,this._environmentSupportsTouch,{hidePreviousButton:function(){m._hasPrevContent=!1,m._fadeOutButton("prev"),m._prevButton.setAttribute("aria-hidden",!0)},showPreviousButton:function(){m._hasPrevContent=!0,m._fadeInButton("prev"),m._prevButton.setAttribute("aria-hidden",!1)},hideNextButton:function(){m._hasNextContent=!1,m._fadeOutButton("next"),m._nextButton.setAttribute("aria-hidden",!0)},showNextButton:function(){m._hasNextContent=!0,m._fadeInButton("next"),m._nextButton.setAttribute("aria-hidden",!1)}}),this._pageManager.initialize(g,this._isHorizontal),this._dataSource.getCount().then(function(a){m._pageManager._cachedSize=a}),this._prevButton.addEventListener("click",function(){m.previous()},!1),this._nextButton.addEventListener("click",function(){m.next()},!1),new o._MutationObserver(p).observe(this._flipviewDiv,{attributes:!0,attributeFilter:["dir","style"]}),this._cachedStyleDir=this._flipviewDiv.style.direction,this._flipviewDiv.addEventListener("mselementresize",u),o._resizeNotifier.subscribe(this._flipviewDiv,u),this._contentDiv.addEventListener("mouseleave",function(){m._mouseInViewport=!1},!1);var D=o._MSPointerEvent.MSPOINTER_TYPE_TOUCH||"touch";this._environmentSupportsTouch&&(o._addEventListener(this._contentDiv,"pointerdown",k,!1),o._addEventListener(this._contentDiv,"pointermove",j,!1),o._addEventListener(this._contentDiv,"pointerup",l,!1)),this._panningDivContainer.addEventListener("scroll",function(){m._scrollPosChanged()},!1),this._panningDiv.addEventListener("blur",function(){m._touchInteraction||m._fadeOutButtons()},!0);var E=a.document.body.contains(this._flipviewDiv);o._addInsertedNotifier(this._flipviewDiv),this._flipviewDiv.addEventListener("WinJSNodeInserted",function(){return E?void(E=!1):void m._pageManager.resized()},!1),this._flipviewDiv.addEventListener("keydown",function(a){if(!m._disposed){var b=!0;if(!m._isInteractive(a.target)){var c=o.Key,d=!1;if(m._isHorizontal)switch(a.keyCode){case c.leftArrow:!m._rtl&&m.currentPage>0?(m.previous(),d=!0):m._rtl&&m.currentPage<m._pageManager._cachedSize-1&&(m.next(),d=!0);break;case c.pageUp:m.currentPage>0&&(m.previous(),d=!0);break;case c.rightArrow:!m._rtl&&m.currentPage<m._pageManager._cachedSize-1?(m.next(),d=!0):m._rtl&&m.currentPage>0&&(m.previous(),d=!0);break;case c.pageDown:m.currentPage<m._pageManager._cachedSize-1&&(m.next(),d=!0);break;case c.upArrow:case c.downArrow:d=!0,b=!1}else switch(a.keyCode){case c.upArrow:case c.pageUp:m.currentPage>0&&(m.previous(),d=!0);break;case c.downArrow:case c.pageDown:m.currentPage<m._pageManager._cachedSize-1&&(m.next(),d=!0);break;case c.space:d=!0}switch(a.keyCode){case c.home:m.currentPage=0,d=!0;break;case c.end:m._pageManager._cachedSize>0&&(m.currentPage=m._pageManager._cachedSize-1),d=!0}if(d)return a.preventDefault(),b&&a.stopPropagation(),!0}}},!1),n=!0},_windowWheelHandler:function(a){if(!this._disposed){a=a.detail.originalEvent;var b=a.target&&(this._flipviewDiv.contains(a.target)||this._flipviewDiv===a.target),d=this,e=c._now(),f=this._avoidTrappingTime>e;(!b||f)&&(this._avoidTrappingTime=e+E),b&&f?(this._panningDivContainer.style.overflowX="hidden",this._panningDivContainer.style.overflowY="hidden",c._yieldForDomModification(function(){d._pageManager._ensureCentered(),d._isHorizontal?(d._panningDivContainer.style.overflowX=d._environmentSupportsTouch?"scroll":"hidden",d._panningDivContainer.style.overflowY="hidden"):(d._panningDivContainer.style.overflowY=d._environmentSupportsTouch?"scroll":"hidden",d._panningDivContainer.style.overflowX="hidden")})):b&&this._pageManager.simulateMouseWheelScroll(a)}},_isInteractive:function(a){if(a.parentNode)for(var b=a.parentNode.querySelectorAll(".win-interactive, .win-interactive *"),c=0,d=b.length;d>c;c++)if(b[c]===a)return!0;return!1},_refreshHandler:function(){var a=this._dataSourceAfterRefresh||this._dataSource,b=this._itemRendererAfterRefresh||this._itemRenderer,c=this._indexAfterRefresh||0;this._setDatasource(a,b,c),this._dataSourceAfterRefresh=null,this._itemRendererAfterRefresh=null,this._indexAfterRefresh=0,this._refreshTimer=!1},_refresh:function(){if(!this._refreshTimer){var a=this;this._refreshTimer=!0,l.schedule(function(){a._refreshTimer&&!a._disposed&&a._refreshHandler()},l.Priority.high,null,"WinJS.UI.FlipView._refreshHandler")}},_getItemRenderer:function(b){var c=null;if("function"==typeof b){var d=new k(function(){}),e=b(d);c=e.element?"object"==typeof e.element&&"function"==typeof e.element.then?function(c){var d=a.document.createElement("div");return d.className="win-template",n.markDisposable(d),{element:d,renderComplete:b(c).element.then(function(a){d.appendChild(a)})}}:b:function(c){var d=a.document.createElement("div");return d.className="win-template",n.markDisposable(d),{element:d,renderComplete:c.then(function(){return k.as(b(c)).then(function(a){d.appendChild(a)})})}}}else"object"==typeof b&&(c=b.renderItem);return c},_navigate:function(a,b){if(c.validation&&this._refreshTimer)throw new d("WinJS.UI.FlipView.NavigationDuringStateChange",K.navigationDuringStateChange);if(this._animating||(this._animatingForward=a),this._goForward=a,this._animating&&!this._cancelAnimation())return!1;var e=this,f=a?this._nextAnimation:this._prevAnimation,g=f?f:this._defaultAnimation.bind(this),h=function(a){e._completeNavigation(a)},i=this._pageManager.startAnimatedNavigation(a,b,h);if(i){this._animationsStarted();var j=i.outgoing.pageRoot,k=i.incoming.pageRoot;return this._contentDiv.appendChild(j),this._contentDiv.appendChild(k),this._completeNavigationPending=!0,g(j,k).then(function(){e._completeNavigationPending&&h(e._goForward)}).done(),!0}return!1},_cancelDefaultAnimation:function(a,b){a.style.opacity=0,b.style.animationName="",b.style.opacity=1},_cancelAnimation:function(){if(this._pageManager._navigationAnimationRecord&&this._pageManager._navigationAnimationRecord.completionCallback){var a=this._pageManager._navigationAnimationRecord.cancelAnimationCallback;if(a&&(a=a.bind(this)),this._pageManager._navigationAnimationRecord&&this._pageManager._navigationAnimationRecord.elementContainers){var b=this._pageManager._navigationAnimationRecord.elementContainers[0],c=this._pageManager._navigationAnimationRecord.elementContainers[1],d=b.pageRoot,e=c.pageRoot;return a&&a(d,e),this._pageManager._navigationAnimationRecord.completionCallback(this._animatingForward),!0}}return!1},_completeNavigation:function(a){if(!this._disposed){if(this._pageManager._resizing=!1,this._pageManager._navigationAnimationRecord&&this._pageManager._navigationAnimationRecord.elementContainers){var b=this._pageManager._navigationAnimationRecord.elementContainers[0],c=this._pageManager._navigationAnimationRecord.elementContainers[1],d=b.pageRoot,e=c.pageRoot;d.parentNode&&d.parentNode.removeChild(d),e.parentNode&&e.parentNode.removeChild(e),this._pageManager.endAnimatedNavigation(a,b,c),this._fadeOutButtons(),this._scrollPosChanged(),this._pageManager._ensureCentered(!0),this._animationsFinished()}this._completeNavigationPending=!1}},_completeJump:function(){if(!this._disposed){if(this._pageManager._resizing=!1,this._pageManager._navigationAnimationRecord&&this._pageManager._navigationAnimationRecord.elementContainers){var a=this._pageManager._navigationAnimationRecord.elementContainers[0],b=this._pageManager._navigationAnimationRecord.elementContainers[1],c=a.pageRoot,d=b.pageRoot;c.parentNode&&c.parentNode.removeChild(c),d.parentNode&&d.parentNode.removeChild(d),this._pageManager.endAnimatedJump(a,b),this._animationsFinished()}this._completeJumpPending=!1}},_resize:function(){this._pageManager.resized()},_setCurrentIndex:function(a){return this._pageManager.jumpToIndex(a)},_getCurrentIndex:function(){return this._pageManager.currentIndex()},_setDatasource:function(a,b,c){this._animating&&this._cancelAnimation();var d=0;void 0!==c&&(d=c),this._dataSource=a,this._itemRenderer=b;var e=this._itemsManager;this._itemsManager=q._createItemsManager(this._dataSource,this._itemRenderer,this._itemsManagerCallback,{ownerElement:this._flipviewDiv}),this._dataSource=this._itemsManager.dataSource;var f=this;this._dataSource.getCount().then(function(a){f._pageManager._cachedSize=a}),this._pageManager.setNewItemsManager(this._itemsManager,d),e&&e.release()},_fireDatasourceCountChangedEvent:function(){var b=this;l.schedule(function(){var c=a.document.createEvent("Event");c.initEvent(L.datasourceCountChangedEvent,!0,!0),g("WinJS.UI.FlipView:dataSourceCountChangedEvent,info"),b._flipviewDiv.dispatchEvent(c)},l.Priority.normal,null,"WinJS.UI.FlipView._dispatchDataSourceCountChangedEvent")},_scrollPosChanged:function(){this._disposed||this._pageManager.scrollPosChanged()},_axisAsString:function(){return this._isHorizontal?"horizontal":"vertical"},_setupOrientation:function(){if(this._isHorizontal){this._panningDivContainer.style.overflowX=this._environmentSupportsTouch?"scroll":"hidden",this._panningDivContainer.style.overflowY="hidden";var a="rtl"===o._getComputedStyle(this._flipviewDiv,null).direction;this._rtl=a,a?(this._prevButton.className=v+" "+y,this._nextButton.className=v+" "+x):(this._prevButton.className=v+" "+x,this._nextButton.className=v+" "+y),this._prevButton.innerHTML=a?G:F,this._nextButton.innerHTML=a?F:G}else this._panningDivContainer.style.overflowY=this._environmentSupportsTouch?"scroll":"hidden",this._panningDivContainer.style.overflowX="hidden",this._prevButton.className=v+" "+z,this._nextButton.className=v+" "+A,this._prevButton.innerHTML=H,this._nextButton.innerHTML=I;this._panningDivContainer.style.msOverflowStyle="none"},_fadeInButton:function(a,b){(this._mouseInViewport||b||!this._environmentSupportsTouch)&&("next"===a&&this._hasNextContent?(this._nextButtonAnimation&&(this._nextButtonAnimation.cancel(),this._nextButtonAnimation=null),this._nextButton.style.visibility="visible",this._nextButtonAnimation=this._fadeInFromCurrentValue(this._nextButton)):"prev"===a&&this._hasPrevContent&&(this._prevButtonAnimation&&(this._prevButtonAnimation.cancel(),this._prevButtonAnimation=null),this._prevButton.style.visibility="visible",this._prevButtonAnimation=this._fadeInFromCurrentValue(this._prevButton)))},_fadeOutButton:function(a){var b=this;return"next"===a?(this._nextButtonAnimation&&(this._nextButtonAnimation.cancel(),this._nextButtonAnimation=null),this._nextButtonAnimation=h.fadeOut(this._nextButton).then(function(){b._nextButton.style.visibility="hidden"}),this._nextButtonAnimation):(this._prevButtonAnimation&&(this._prevButtonAnimation.cancel(),this._prevButtonAnimation=null),this._prevButtonAnimation=h.fadeOut(this._prevButton).then(function(){b._prevButton.style.visibility="hidden"}),this._prevButtonAnimation)},_fadeOutButtons:function(a){if(this._environmentSupportsTouch){this._buttonFadePromise&&(this._buttonFadePromise.cancel(),this._buttonFadePromise=null);var b=this;this._buttonFadePromise=(a?k.wrap():k.timeout(i._animationTimeAdjustment(D))).then(function(){b._fadeOutButton("prev"),b._fadeOutButton("next"),b._buttonFadePromise=null})}},_animationsStarted:function(){this._animating=!0},_animationsFinished:function(){this._animating=!1},_defaultAnimation:function(a,b){var c={};b.style.left="0px",b.style.top="0px",b.style.opacity=0;var d=a.itemIndex>b.itemIndex?-J:J;c.left=(this._isHorizontal?this._rtl?-d:d:0)+"px",c.top=(this._isHorizontal?0:d)+"px";var e=h.fadeOut(a),f=h.enterContent(b,[c],{mechanism:"transition"});return k.join([e,f])},_fadeInFromCurrentValue:function(a){return i.executeTransition(a,{property:"opacity",delay:0,duration:167,timing:"linear",to:1})}},s);return b.Class.mix(L,e.createEventProperties(L.datasourceCountChangedEvent,L.pageVisibilityChangedEvent,L.pageSelectedEvent,L.pageCompletedEvent)),b.Class.mix(L,m.DOMEventMixin),L})})}),d("WinJS/Controls/ItemContainer",["exports","../Core/_Global","../Core/_Base","../Core/_BaseUtils","../Core/_ErrorFromName","../Core/_Events","../Core/_Log","../Core/_Resources","../Core/_WriteProfilerMark","../Promise","../Scheduler","../Utilities/_Control","../Utilities/_Dispose","../Utilities/_ElementUtilities","../Utilities/_Hoverable","../Utilities/_KeyboardBehavior","../Utilities/_UI","./ItemContainer/_Constants","./ItemContainer/_ItemEventsHandler"],function(a,b,c,d,e,f,g,h,i,j,k,l,m,n,o,p,q,r,s){"use strict";var t=f._createEventProperty,u={invoked:"invoked",selectionchanging:"selectionchanging",selectionchanged:"selectionchanged"};c.Namespace._moduleDefine(a,"WinJS.UI",{ItemContainer:c.Namespace._lazy(function(){var f={get duplicateConstruction(){return"Invalid argument: Controls may only be instantiated one time for each DOM element"},get swipeOrientationDeprecated(){return"Invalid configuration: swipeOrientation is deprecated. The control will default this property to 'none'"},get swipeBehaviorDeprecated(){return"Invalid configuration: swipeBehavior is deprecated. The control will default this property to 'none'"}},h=c.Class.define(function(c,d){function g(a,b,c){return{name:b?a:a.toLowerCase(),handler:function(b){i["_on"+a](b)},capture:c}}if(c=c||b.document.createElement("DIV"),this._id=c.id||n._uniqueID(c),this._writeProfilerMark("constructor,StartTM"),d=d||{},c.winControl)throw new e("WinJS.UI.ItemContainer.DuplicateConstruction",f.duplicateConstruction);c.winControl=this,this._element=c,n.addClass(c,"win-disposable"),this._selectionMode=q.SelectionMode.single,this._draggable=!1,this._pressedEntity={type:q.ObjectType.item,index:r._INVALID_INDEX},this.tapBehavior=q.TapBehavior.invokeOnly,n.addClass(this.element,h._ClassName.itemContainer+" "+r._containerClass),this._setupInternalTree(),this._selection=new a._SingleItemSelectionManager(c,this._itemBox),this._setTabIndex(),l.setOptions(this,d),this._mutationObserver=new n._MutationObserver(this._itemPropertyChange.bind(this)),this._mutationObserver.observe(c,{attributes:!0,attributeFilter:["aria-selected"]}),this._setAriaRole();var i=this;this.selectionDisabled||k.schedule(function(){i._setDirectionClass()},k.Priority.normal,null,"WinJS.UI.ItemContainer_async_initialize"),this._itemEventsHandler=new s._ItemEventsHandler(Object.create({containerFromElement:function(){return i.element},indexForItemElement:function(){return 1},indexForHeaderElement:function(){return r._INVALID_INDEX},itemBoxAtIndex:function(){return i._itemBox},itemAtIndex:function(){return i.element},headerAtIndex:function(){return null},containerAtIndex:function(){return i.element},isZombie:function(){return this._disposed},getItemPosition:function(){return i._getItemPosition()},rtl:function(){return i._rtl()},fireInvokeEvent:function(){i._fireInvokeEvent()},verifySelectionAllowed:function(){return i._verifySelectionAllowed()},changeFocus:function(){},selectRange:function(a,b){return i._selection.set({firstIndex:a,lastIndex:b})},disablePressAnimation:function(){return!1}},{pressedEntity:{get:function(){return i._pressedEntity},set:function(a){i._pressedEntity=a}},pressedElement:{enumerable:!0,set:function(a){i._pressedElement=a}},eventHandlerRoot:{enumerable:!0,get:function(){return i.element}},selectionMode:{enumerable:!0,get:function(){return i._selectionMode}},accessibleItemClass:{enumerable:!0,get:function(){return r._containerClass}},canvasProxy:{enumerable:!0,get:function(){return i._captureProxy}},tapBehavior:{enumerable:!0,get:function(){return i._tapBehavior}},draggable:{enumerable:!0,get:function(){return i._draggable}},selection:{enumerable:!0,get:function(){return i._selection}},customFootprintParent:{enumerable:!0,get:function(){return null}},skipPreventDefaultOnPointerDown:{enumerable:!0,get:function(){return!0}}}));var j=[g("PointerDown"),g("Click"),g("PointerUp"),g("PointerCancel"),g("LostPointerCapture"),g("ContextMenu"),g("MSHoldVisual",!0),g("FocusIn"),g("FocusOut"),g("DragStart"),g("DragEnd"),g("KeyDown")];j.forEach(function(a){n._addEventListener(i.element,a.name,a.handler,!!a.capture)}),this._writeProfilerMark("constructor,StopTM")},{element:{get:function(){return this._element}},draggable:{get:function(){return this._draggable},set:function(a){d.isPhone||this._draggable!==a&&(this._draggable=a,this._updateDraggableAttribute())}},selected:{get:function(){return this._selection.selected},set:function(a){this._selection.selected!==a&&(this._selection.selected=a)}},swipeOrientation:{get:function(){return"none"},set:function(){n._deprecated(f.swipeOrientationDeprecated)}},tapBehavior:{get:function(){return this._tapBehavior},set:function(a){d.isPhone&&a===q.TapBehavior.directSelect||(this._tapBehavior=a,this._setAriaRole())}},swipeBehavior:{get:function(){return"none"},set:function(){n._deprecated(f.swipeBehaviorDeprecated)}},selectionDisabled:{get:function(){return this._selectionMode===q.SelectionMode.none},set:function(a){a?this._selectionMode=q.SelectionMode.none:(this._setDirectionClass(),this._selectionMode=q.SelectionMode.single),this._setAriaRole()}},oninvoked:t(u.invoked),onselectionchanging:t(u.selectionchanging),onselectionchanged:t(u.selectionchanged),forceLayout:function(){this._forceLayout()},dispose:function(){this._disposed||(this._disposed=!0,this._itemEventsHandler.dispose(),m.disposeSubTree(this.element))},_onMSManipulationStateChanged:function(a){this._itemEventsHandler.onMSManipulationStateChanged(a)},_onPointerDown:function(a){this._itemEventsHandler.onPointerDown(a)},_onClick:function(a){this._itemEventsHandler.onClick(a)},_onPointerUp:function(a){n.hasClass(this._itemBox,r._itemFocusClass)&&this._onFocusOut(a),this._itemEventsHandler.onPointerUp(a)},_onPointerCancel:function(a){this._itemEventsHandler.onPointerCancel(a)},_onLostPointerCapture:function(a){this._itemEventsHandler.onLostPointerCapture(a)},_onContextMenu:function(a){this._itemEventsHandler.onContextMenu(a)},_onMSHoldVisual:function(a){this._itemEventsHandler.onMSHoldVisual(a)},_onFocusIn:function(){if(!this._itemBox.querySelector("."+r._itemFocusOutlineClass)&&p._keyboardSeenLast){n.addClass(this._itemBox,r._itemFocusClass);var a=b.document.createElement("div");a.className=r._itemFocusOutlineClass,this._itemBox.appendChild(a)}},_onFocusOut:function(){n.removeClass(this._itemBox,r._itemFocusClass);var a=this._itemBox.querySelector("."+r._itemFocusOutlineClass);a&&a.parentNode.removeChild(a)},_onDragStart:function(a){if(this._pressedElement&&this._itemEventsHandler._isInteractive(this._pressedElement))a.preventDefault();else{this._dragging=!0;var b=this;if(a.dataTransfer.setData("text",""),a.dataTransfer.setDragImage){var c=this.element.getBoundingClientRect();a.dataTransfer.setDragImage(this.element,a.clientX-c.left,a.clientY-c.top)}d._yieldForDomModification(function(){b._dragging&&n.addClass(b._itemBox,r._dragSourceClass)})}},_onDragEnd:function(){this._dragging=!1,n.removeClass(this._itemBox,r._dragSourceClass),this._itemEventsHandler.resetPointerDownState()},_onKeyDown:function(a){if(!this._itemEventsHandler._isInteractive(a.target)){var b=n.Key,c=a.keyCode,d=!1;if(a.ctrlKey||c!==b.enter)a.ctrlKey&&c===b.enter||c===b.space?this.selectionDisabled||(this.selected=!this.selected,d=n._setActive(this.element)):c===b.escape&&this.selected&&(this.selected=!1,d=!0);else{var e=this._verifySelectionAllowed();e.canTapSelect&&(this.selected=!this.selected),this._fireInvokeEvent(),d=!0}d&&(a.stopPropagation(),a.preventDefault())}},_setTabIndex:function(){var a=this.element.getAttribute("tabindex");a||this.element.setAttribute("tabindex","0")},_rtl:function(){return"boolean"!=typeof this._cachedRTL&&(this._cachedRTL="rtl"===n._getComputedStyle(this.element,null).direction),this._cachedRTL},_setDirectionClass:function(){n[this._rtl()?"addClass":"removeClass"](this.element,r._rtlListViewClass)},_forceLayout:function(){this._cachedRTL="rtl"===n._getComputedStyle(this.element,null).direction,this._setDirectionClass()},_getItemPosition:function(){var a=this.element;return a?j.wrap({left:this._rtl()?a.offsetParent.offsetWidth-a.offsetLeft-a.offsetWidth:a.offsetLeft,top:a.offsetTop,totalWidth:n.getTotalWidth(a),totalHeight:n.getTotalHeight(a),contentWidth:n.getContentWidth(a),contentHeight:n.getContentHeight(a)}):j.cancel},_itemPropertyChange:function(a){if(!this._disposed){var b=a[0].target,c="true"===b.getAttribute("aria-selected");c!==n._isSelectionRendered(this._itemBox)&&(this.selectionDisabled?n._setAttribute(b,"aria-selected",!c):(this.selected=c,c!==this.selected&&n._setAttribute(b,"aria-selected",!c)))}},_updateDraggableAttribute:function(){this._itemBox.setAttribute("draggable",this._draggable)},_verifySelectionAllowed:function(){if(this._selectionMode!==q.SelectionMode.none&&this._tapBehavior===q.TapBehavior.toggleSelect){var a=this._selection.fireSelectionChanging();return{canSelect:a,canTapSelect:a&&this._tapBehavior===q.TapBehavior.toggleSelect}}return{canSelect:!1,canTapSelect:!1}},_setupInternalTree:function(){var a=b.document.createElement("div");a.className=r._itemClass,this._captureProxy=b.document.createElement("div"),this._itemBox=b.document.createElement("div"),this._itemBox.className=r._itemBoxClass;for(var c=this.element.firstChild;c;){var d=c.nextSibling;a.appendChild(c),c=d}this.element.appendChild(this._itemBox),this._itemBox.appendChild(a),this.element.appendChild(this._captureProxy)},_fireInvokeEvent:function(){if(this.tapBehavior!==q.TapBehavior.none){var a=b.document.createEvent("CustomEvent");a.initCustomEvent(u.invoked,!0,!1,{}),this.element.dispatchEvent(a)}},_setAriaRole:function(){if(!this.element.getAttribute("role")||this._usingDefaultItemRole){this._usingDefaultItemRole=!0;var a;a=this.tapBehavior===q.TapBehavior.none&&this.selectionDisabled?"listitem":"option",n._setAttribute(this.element,"role",a)}},_writeProfilerMark:function(a){var b="WinJS.UI.ItemContainer:"+this._id+":"+a;i(b),g.log&&g.log(b,null,"itemcontainerprofiler")}},{_ClassName:{itemContainer:"win-itemcontainer",vertical:"win-vertical",horizontal:"win-horizontal"}});return c.Class.mix(h,l.DOMEventMixin),h}),_SingleItemSelectionManager:c.Namespace._lazy(function(){return c.Class.define(function(a,b){this._selected=!1,this._element=a,this._itemBox=b},{selected:{get:function(){return this._selected},set:function(a){a=!!a,this._selected!==a&&this.fireSelectionChanging()&&(this._selected=a,s._ItemEventsHandler.renderSelection(this._itemBox,this._element,a,!0,this._element),this.fireSelectionChanged())}},count:function(){return this._selected?1:0},getIndices:function(){},getItems:function(){},getRanges:function(){},isEverything:function(){return!1},set:function(){this.selected=!0},clear:function(){this.selected=!1},add:function(){this.selected=!0},remove:function(){this.selected=!1},selectAll:function(){},fireSelectionChanging:function(){var a=b.document.createEvent("CustomEvent");return a.initCustomEvent(u.selectionchanging,!0,!0,{}),this._element.dispatchEvent(a)},fireSelectionChanged:function(){var a=b.document.createEvent("CustomEvent");a.initCustomEvent(u.selectionchanged,!0,!1,{}),this._element.dispatchEvent(a)},_isIncluded:function(){return this._selected},_getFocused:function(){return{type:q.ObjectType.item,index:r._INVALID_INDEX}}})})})}),d("WinJS/Controls/Repeater",["exports","../Core/_Global","../Core/_Base","../Core/_ErrorFromName","../Core/_Events","../Core/_Resources","../Core/_WriteProfilerMark","../BindingList","../BindingTemplate","../Promise","../Utilities/_Control","../Utilities/_Dispose","../Utilities/_ElementUtilities","../Utilities/_Hoverable"],function(a,b,c,d,e,f,g,h,i,j,k,l,m){"use strict";c.Namespace._moduleDefine(a,"WinJS.UI",{Repeater:c.Namespace._lazy(function(){function a(a){var c=b.document.createElement("div");return c.textContent=JSON.stringify(a),c}var f="itemsloaded",n="itemchanging",o="itemchanged",p="iteminserting",q="iteminserted",r="itemmoving",s="itemmoved",t="itemremoving",u="itemremoved",v="itemsreloading",w="itemsreloaded",x=e._createEventProperty,y={get duplicateConstruction(){return"Invalid argument: Controls may only be instantiated one time for each DOM element"},get asynchronousRender(){return"Top level items must render synchronously"},get repeaterReentrancy(){return"Cannot modify Repeater data until Repeater has commited previous modification."}},z=c.Class.define(function(a,c){if(a&&a.winControl)throw new d("WinJS.UI.Repeater.DuplicateConstruction",y.duplicateConstruction);this._element=a||b.document.createElement("div"),this._id=this._element.id||m._uniqueID(this._element),this._writeProfilerMark("constructor,StartTM"),c=c||{},m.addClass(this._element,"win-repeater win-disposable"),this._render=null,this._modifying=!1,this._disposed=!1,this._element.winControl=this,this._dataListeners={itemchanged:this._dataItemChangedHandler.bind(this),iteminserted:this._dataItemInsertedHandler.bind(this),itemmoved:this._dataItemMovedHandler.bind(this),itemremoved:this._dataItemRemovedHandler.bind(this),reload:this._dataReloadHandler.bind(this)};var e=this._extractInlineTemplate();this._initializing=!0,this.template=c.template||e,this.data=c.data,this._initializing=!1,k._setOptions(this,c,!0),this._repeatedDOM=[],this._renderAllItems(),this.dispatchEvent(f,{}),this._writeProfilerMark("constructor,StopTM")},{element:{get:function(){return this._element}},data:{get:function(){return this._data},set:function(a){this._writeProfilerMark("data.set,StartTM"),this._data&&this._removeDataListeners(),this._data=a||new h.List,this._addDataListeners(),this._initializing||(this._reloadRepeater(!0),this.dispatchEvent(f,{})),this._writeProfilerMark("data.set,StopTM")}},template:{get:function(){return this._template},set:function(b){this._writeProfilerMark("template.set,StartTM"),this._template=b||a,this._render=m._syncRenderer(this._template,this.element.tagName),this._initializing||(this._reloadRepeater(!0),this.dispatchEvent(f,{})),this._writeProfilerMark("template.set,StopTM")}},length:{get:function(){return this._repeatedDOM.length}},elementFromIndex:function(a){return this._repeatedDOM[a]},dispose:function(){if(!this._disposed){this._disposed=!0,this._removeDataListeners(),this._data=null,this._template=null;for(var a=0,b=this._repeatedDOM.length;b>a;a++)l._disposeElement(this._repeatedDOM[a])}},onitemsloaded:x(f),onitemchanging:x(n),onitemchanged:x(o),oniteminserting:x(p),oniteminserted:x(q),onitemmoving:x(r),onitemmoved:x(s),onitemremoving:x(t),onitemremoved:x(u),onitemsreloading:x(v),onitemsreloaded:x(w),_extractInlineTemplate:function(){if(this._element.firstElementChild){for(var a=b.document.createElement(this._element.tagName);this._element.firstElementChild;)a.appendChild(this._element.firstElementChild);return new i.Template(a,{extractChild:!0})}},_renderAllItems:function(){for(var a=b.document.createDocumentFragment(),c=0,e=this._data.length;e>c;c++){var f=this._render(this._data.getAt(c));if(!f)throw new d("WinJS.UI.Repeater.AsynchronousRender",y.asynchronousRender);a.appendChild(f),this._repeatedDOM.push(f)}this._element.appendChild(a)},_reloadRepeater:function(a){this._unloadRepeatedDOM(a),this._repeatedDOM=[],this._renderAllItems()},_unloadRepeatedDOM:function(a){for(var b=0,c=this._repeatedDOM.length;c>b;b++){var d=this._repeatedDOM[b];a&&l._disposeElement(d),d.parentElement===this._element&&this._element.removeChild(d)}},_addDataListeners:function(){Object.keys(this._dataListeners).forEach(function(a){this._data.addEventListener(a,this._dataListeners[a],!1)}.bind(this))},_beginModification:function(){if(this._modifying)throw new d("WinJS.UI.Repeater.RepeaterModificationReentrancy",y.repeaterReentrancy);this._modifying=!0},_endModification:function(){this._modifying=!1},_removeDataListeners:function(){Object.keys(this._dataListeners).forEach(function(a){this._data.removeEventListener(a,this._dataListeners[a],!1)}.bind(this))},_dataItemChangedHandler:function(a){this._beginModification();var b,c=this._element,e=a.detail.index,f=this._render(a.detail.newValue);if(!f)throw new d("WinJS.UI.Repeater.AsynchronousRender",y.asynchronousRender);this._repeatedDOM[e]&&(a.detail.oldElement=this._repeatedDOM[e]),a.detail.newElement=f,a.detail.setPromise=function(a){b=a},this._writeProfilerMark(n+",info"),this.dispatchEvent(n,a.detail);var g=null;e<this._repeatedDOM.length?(g=this._repeatedDOM[e],c.replaceChild(f,g),this._repeatedDOM[e]=f):(c.appendChild(f),this._repeatedDOM.push(f)),this._endModification(),this._writeProfilerMark(o+",info"),this.dispatchEvent(o,a.detail),g&&j.as(b).done(function(){l._disposeElement(g) }.bind(this))},_dataItemInsertedHandler:function(a){this._beginModification();var b=a.detail.index,c=this._render(a.detail.value);if(!c)throw new d("WinJS.UI.Repeater.AsynchronousRender",y.asynchronousRender);var e=this._element;if(a.detail.affectedElement=c,this._writeProfilerMark(p+",info"),this.dispatchEvent(p,a.detail),b<this._repeatedDOM.length){var f=this._repeatedDOM[b];e.insertBefore(c,f)}else e.appendChild(c);this._repeatedDOM.splice(b,0,c),this._endModification(),this._writeProfilerMark(q+",info"),this.dispatchEvent(q,a.detail)},_dataItemMovedHandler:function(a){this._beginModification();var b=this._repeatedDOM[a.detail.oldIndex];if(a.detail.affectedElement=b,this._writeProfilerMark(r+",info"),this.dispatchEvent(r,a.detail),this._repeatedDOM.splice(a.detail.oldIndex,1)[0],b.parentNode.removeChild(b),a.detail.newIndex<this._data.length-1){var c=this._repeatedDOM[a.detail.newIndex];this._element.insertBefore(b,c),this._repeatedDOM.splice(a.detail.newIndex,0,b)}else this._repeatedDOM.push(b),this._element.appendChild(b);this._endModification(),this._writeProfilerMark(s+",info"),this.dispatchEvent(s,a.detail)},_dataItemRemovedHandler:function(a){this._beginModification();var b,c=this._repeatedDOM[a.detail.index],d={affectedElement:c,index:a.detail.index,item:a.detail.item};d.setPromise=function(a){b=a},this._writeProfilerMark(t+",info"),this.dispatchEvent(t,d),c.parentNode.removeChild(c),this._repeatedDOM.splice(a.detail.index,1),this._endModification(),this._writeProfilerMark(u+",info"),this.dispatchEvent(u,d),j.as(b).done(function(){l._disposeElement(c)}.bind(this))},_dataReloadHandler:function(){this._beginModification();var a,b=this._repeatedDOM.slice(0),c={affectedElements:b};c.setPromise=function(b){a=b},this._writeProfilerMark(v+",info"),this.dispatchEvent(v,c),this._reloadRepeater(!1);var d=this._repeatedDOM.slice(0);this._endModification(),this._writeProfilerMark(w+",info"),this.dispatchEvent(w,{affectedElements:d}),j.as(a).done(function(){for(var a=0,c=b.length;c>a;a++)l._disposeElement(b[a])}.bind(this))},_writeProfilerMark:function(a){g("WinJS.UI.Repeater:"+this._id+":"+a)}},{isDeclarativeControlContainer:!0});return c.Class.mix(z,k.DOMEventMixin),z})})}),d("require-style!less/styles-datetimepicker",[],function(){}),d("WinJS/Controls/DatePicker",["../Core/_Global","../Core/_WinRT","../Core/_Base","../Core/_BaseUtils","../Core/_Events","../Core/_Resources","../Utilities/_Control","../Utilities/_ElementUtilities","../Utilities/_Hoverable","../Utilities/_Select","require-style!less/styles-datetimepicker"],function(a,b,c,d,e,f,g,h,i,j){"use strict";c.Namespace.define("WinJS.UI",{DatePicker:c.Namespace._lazy(function(){function d(a,c,d){var e=b.Windows.Globalization.DateTimeFormatting;a=a?a:d;var f=new e.DateTimeFormatter(a);return c?new e.DateTimeFormatter(a,f.languages,f.geographicRegion,c,f.clock):f}function i(a,b,c){var e=t[a];e||(e=t[a]={});var f=e[b];f||(f=e[b]={});var g=f[c];return g||(g=f[c]={},g.formatter=d(a,b,c),g.years={}),g}function k(a,b,c,d,e,f){var g=i(a,b,c),h=g.years[f.year+"-"+f.era];return h||(h=g.formatter.format(f.getDateTime()),g.years[f.year+"-"+f.era]=h),h}function l(a,b,c,d){var e=i(a,b,c);return e.formatter.format(d.getDateTime())}function m(a,b,c,d){var e=i(a,b,c);return e.formatter.format(d.getDateTime())}function n(a){var c=b.Windows.Globalization,d=new c.Calendar;return a?new c.Calendar(d.languages,a,d.getClock()):d}function o(a,b){var c=0;if(a.era===b.era)c=b.year-a.year;else for(;a.era!==b.era||a.year!==b.year;)c++,a.addYears(1);return c}var p="day",q="{month.full}",r="year.full",s={get ariaLabel(){return f._getWinJSString("ui/datePicker").value},get selectDay(){return f._getWinJSString("ui/selectDay").value},get selectMonth(){return f._getWinJSString("ui/selectMonth").value},get selectYear(){return f._getWinJSString("ui/selectYear").value}},t={},u=c.Class.define(function(b,c){this._currentDate=new Date,this._minYear=this._currentDate.getFullYear()-100,this._maxYear=this._currentDate.getFullYear()+100,this._datePatterns={date:null,month:null,year:null},b=b||a.document.createElement("div"),h.addClass(b,"win-disposable"),b.winControl=this;var d=b.getAttribute("aria-label");d||b.setAttribute("aria-label",s.ariaLabel),this._init(b),g.setOptions(this,c)},{_information:null,_currentDate:null,_calendar:null,_disabled:!1,_dateElement:null,_dateControl:null,_monthElement:null,_monthControl:null,_minYear:null,_maxYear:null,_yearElement:null,_yearControl:null,_datePatterns:{date:null,month:null,year:null},_addAccessibilityAttributes:function(){this._domElement.setAttribute("role","group"),this._dateElement.setAttribute("aria-label",s.selectDay),this._monthElement.setAttribute("aria-label",s.selectMonth),this._yearElement.setAttribute("aria-label",s.selectYear)},_addControlsInOrder:function(){var a=this._domElement,b=this,c=0;b._information.order.forEach(function(d){switch(d){case"month":a.appendChild(b._monthElement),h.addClass(b._monthElement,"win-order"+c++);break;case"date":a.appendChild(b._dateElement),h.addClass(b._dateElement,"win-order"+c++);break;case"year":a.appendChild(b._yearElement),h.addClass(b._yearElement,"win-order"+c++)}})},_createControlElements:function(){this._monthElement=a.document.createElement("select"),this._monthElement.className="win-datepicker-month win-dropdown",this._dateElement=a.document.createElement("select"),this._dateElement.className="win-datepicker-date win-dropdown",this._yearElement=a.document.createElement("select"),this._yearElement.className="win-datepicker-year win-dropdown"},_createControls:function(){var a=this._information,b=a.getIndex(this.current);a.forceLanguage&&(this._domElement.setAttribute("lang",a.forceLanguage),this._domElement.setAttribute("dir",a.isRTL?"rtl":"ltr")),this._yearControl=new j._Select(this._yearElement,{dataSource:this._information.years,disabled:this.disabled,index:b.year}),this._monthControl=new j._Select(this._monthElement,{dataSource:this._information.months(b.year),disabled:this.disabled,index:b.month}),this._dateControl=new j._Select(this._dateElement,{dataSource:this._information.dates(b.year,b.month),disabled:this.disabled,index:b.date}),this._wireupEvents()},dispose:function(){},calendar:{get:function(){return this._calendar},set:function(a){this._calendar=a,this._setElement(this._domElement)}},current:{get:function(){var a=this._currentDate,b=a.getFullYear();return new Date(Math.max(Math.min(this.maxYear,b),this.minYear),a.getMonth(),a.getDate(),12,0,0,0)},set:function(a){var b;"string"==typeof a?(b=new Date(Date.parse(a)),b.setHours(12,0,0,0)):b=a;var c=this._currentDate;c!==b&&(this._currentDate=b,this._updateDisplay())}},disabled:{get:function(){return this._disabled},set:function(a){this._disabled!==a&&(this._disabled=a,this._yearControl&&(this._monthControl.setDisabled(a),this._dateControl.setDisabled(a),this._yearControl.setDisabled(a)))}},datePattern:{get:function(){return this._datePatterns.date},set:function(a){this._datePatterns.date!==a&&(this._datePatterns.date=a,this._init())}},element:{get:function(){return this._domElement}},_setElement:function(a){this._domElement=this._domElement||a,this._domElement&&(h.empty(this._domElement),h.addClass(this._domElement,"win-datepicker"),this._updateInformation(),this._createControlElements(),this._addControlsInOrder(),this._createControls(),this._addAccessibilityAttributes())},minYear:{get:function(){return this._information.getDate({year:0,month:0,date:0}).getFullYear()},set:function(a){this._minYear!==a&&(this._minYear=a,a>this._maxYear&&(this._maxYear=a),this._updateInformation(),this._yearControl&&(this._yearControl.dataSource=this._information.years),this._updateDisplay())}},maxYear:{get:function(){var a={year:this._information.years.getLength()-1};return a.month=this._information.months(a.year).getLength()-1,a.date=this._information.dates(a.year,a.month).getLength()-1,this._information.getDate(a).getFullYear()},set:function(a){this._maxYear!==a&&(this._maxYear=a,a<this._minYear&&(this._minYear=a),this._updateInformation(),this._yearControl&&(this._yearControl.dataSource=this._information.years),this._updateDisplay())}},monthPattern:{get:function(){return this._datePatterns.month},set:function(a){this._datePatterns.month!==a&&(this._datePatterns.month=a,this._init())}},_updateInformation:function(){var a=new Date(this._minYear,0,1,12,0,0),b=new Date(this._maxYear,11,31,12,0,0);a.setFullYear(this._minYear),b.setFullYear(this._maxYear),this._information=u.getInformation(a,b,this._calendar,this._datePatterns)},_init:function(a){this._setElement(a)},_updateDisplay:function(){if(this._domElement&&this._yearControl){var a=this._information.getIndex(this.current);this._yearControl.index=a.year,this._monthControl.dataSource=this._information.months(a.year),this._monthControl.index=a.month,this._dateControl.dataSource=this._information.dates(a.year,a.month),this._dateControl.index=a.date}},_wireupEvents:function(){function a(){b._currentDate=b._information.getDate({year:b._yearControl.index,month:b._monthControl.index,date:b._dateControl.index},b._currentDate);var a=b._information.getIndex(b._currentDate);b._monthControl.dataSource=b._information.months(a.year),b._monthControl.index=a.month,b._dateControl.dataSource=b._information.dates(a.year,a.month),b._dateControl.index=a.date}var b=this;this._dateElement.addEventListener("change",a,!1),this._monthElement.addEventListener("change",a,!1),this._yearElement.addEventListener("change",a,!1)},yearPattern:{get:function(){return this._datePatterns.year},set:function(a){this._datePatterns.year!==a&&(this._datePatterns.year=a,this._init())}}},{_getInformationWinRT:function(a,b,c,d){function e(a){return new Date(Math.min(new Date(Math.max(j,a)),s))}d=d||{date:p,month:q,year:r};var f=n(c),g=n(c),h=n(c);f.setToMin();var j=f.getDateTime();f.setToMax();var s=f.getDateTime();f.hour=12,a=e(a),b=e(b),f.setDateTime(b);var t={year:f.year,era:f.era};f.setDateTime(a);var u=0;u=o(f,t)+1;var v=i("day month.full year",c).formatter,w=v.patterns[0],x=8207===w.charCodeAt(0),y=["date","month","year"],z={month:w.indexOf("{month"),date:w.indexOf("{day"),year:w.indexOf("{year")};y.sort(function(a,b){return z[a]<z[b]?-1:z[a]>z[b]?1:0});var A=function(){return{getLength:function(){return u},getValue:function(b){return f.setDateTime(a),f.addYears(b),k(d.year,c,r,d,y,f)}}}(),B=function(b){return g.setDateTime(a),g.addYears(b),{getLength:function(){return g.numberOfMonthsInThisYear},getValue:function(a){return g.month=g.firstMonthInThisYear,g.addMonths(a),l(d.month,c,q,g)}}},C=function(b,e){return h.setDateTime(a),h.addYears(b),h.month=h.firstMonthInThisYear,h.addMonths(e),h.day=h.firstDayInThisMonth,{getLength:function(){return h.numberOfDaysInThisMonth},getValue:function(a){return h.day=h.firstDayInThisMonth,h.addDays(a),m(d.date,c,p,h)}}};return{isRTL:x,forceLanguage:v.resolvedLanguage,order:y,getDate:function(b,c){var d;c&&(f.setDateTime(c),d={year:f.year,month:f.month,day:f.day});var e=f;e.setDateTime(a),e.addYears(b.year);var g;e.firstMonthInThisYear>e.lastMonthInThisYear?(g=b.month+e.firstMonthInThisYear>e.numberOfMonthsInThisYear?b.month+e.firstMonthInThisYear-e.numberOfMonthsInThisYear:b.month+e.firstMonthInThisYear,d&&d.year!==e.year&&(g=Math.max(Math.min(d.month,e.numberOfMonthsInThisYear),1))):g=d&&d.year!==e.year?Math.max(Math.min(d.month,e.firstMonthInThisYear+e.numberOfMonthsInThisYear-1),e.firstMonthInThisYear):Math.max(Math.min(b.month+e.firstMonthInThisYear,e.firstMonthInThisYear+e.numberOfMonthsInThisYear-1),e.firstMonthInThisYear),e.month=g;var h=Math.max(Math.min(b.date+e.firstDayInThisMonth,e.firstDayInThisMonth+e.numberOfDaysInThisMonth-1),e.firstDayInThisMonth);return!d||d.year===e.year&&d.month===e.month||(h=Math.max(Math.min(d.day,e.firstDayInThisMonth+e.numberOfDaysInThisMonth-1),e.firstDayInThisMonth)),e.day=e.firstDayInThisMonth,e.addDays(h-e.firstDayInThisMonth),e.getDateTime()},getIndex:function(b){var c=e(b);f.setDateTime(c);var d={year:f.year,era:f.era},g=0;f.setDateTime(a),f.month=1,g=o(f,d),f.setDateTime(c);var h=f.month-f.firstMonthInThisYear;0>h&&(h=f.month-f.firstMonthInThisYear+f.numberOfMonthsInThisYear);var i=f.day-f.firstDayInThisMonth,j={year:g,month:h,date:i};return j},years:A,months:B,dates:C}},_getInformationJS:function(a,b){var c=a.getFullYear(),d=b.getFullYear(),e={getLength:function(){return Math.max(0,d-c+1)},getValue:function(a){return c+a}},f=["January","February","March","April","May","June","July","August","September","October","November","December"],g=function(){return{getLength:function(){return f.length},getValue:function(a){return f[a]},getMonthNumber:function(a){return Math.min(a,f.length-1)}}},h=function(a,b){var c=new Date,d=e.getValue(a),f=b+1;c.setFullYear(d,f,0);var g=c.getDate();return{getLength:function(){return g},getValue:function(a){return""+(a+1)},getDateNumber:function(a){return Math.min(a+1,g)}}};return{order:["month","date","year"],getDate:function(a){return new Date(e.getValue(a.year),g(a.year).getMonthNumber(a.month),h(a.year,a.month).getDateNumber(a.date),12,0)},getIndex:function(a){var b=0,d=a.getFullYear();b=c>d?0:d>this.maxYear?e.getLength()-1:a.getFullYear()-c;var f=Math.min(a.getMonth(),g(b).getLength()),i=Math.min(a.getDate()-1,h(b,f).getLength());return{year:b,month:f,date:i}},years:e,months:g,dates:h}}});return u.getInformation=b.Windows.Globalization.Calendar&&b.Windows.Globalization.DateTimeFormatting?u._getInformationWinRT:u._getInformationJS,c.Class.mix(u,e.createEventProperties("change")),c.Class.mix(u,g.DOMEventMixin),u})})}),d("WinJS/Controls/TimePicker",["../Core/_Global","../Core/_WinRT","../Core/_Base","../Core/_BaseUtils","../Core/_Events","../Core/_Resources","../Utilities/_Control","../Utilities/_ElementUtilities","../Utilities/_Hoverable","../Utilities/_Select","require-style!less/styles-datetimepicker"],function(a,b,c,d,e,f,g,h,i,j){"use strict";c.Namespace.define("WinJS.UI",{TimePicker:c.Namespace._lazy(function(){var d="{minute.integer(2)}",i="{hour.integer(1)}",k="{period.abbreviated(2)}",l={get ariaLabel(){return f._getWinJSString("ui/timePicker").value},get selectHour(){return f._getWinJSString("ui/selectHour").value},get selectMinute(){return f._getWinJSString("ui/selectMinute").value},get selectAMPM(){return f._getWinJSString("ui/selectAMPM").value}},m=function(a,b){return a.getHours()===b.getHours()&&a.getMinutes()===b.getMinutes()},n=c.Class.define(function(b,c){this._currentTime=n._sentinelDate(),b=b||a.document.createElement("div"),h.addClass(b,"win-disposable"),b.winControl=this;var d=b.getAttribute("aria-label");d||b.setAttribute("aria-label",l.ariaLabel),this._timePatterns={minute:null,hour:null,period:null},this._init(b),g.setOptions(this,c)},{_currentTime:null,_clock:null,_disabled:!1,_hourElement:null,_hourControl:null,_minuteElement:null,_minuteControl:null,_ampmElement:null,_ampmControl:null,_minuteIncrement:1,_timePatterns:{minute:null,hour:null,period:null},_information:null,_addAccessibilityAttributes:function(){this._domElement.setAttribute("role","group"),this._hourElement.setAttribute("aria-label",l.selectHour),this._minuteElement.setAttribute("aria-label",l.selectMinute),this._ampmElement&&this._ampmElement.setAttribute("aria-label",l.selectAMPM)},_addControlsInOrder:function(a){var b=this;a.order.forEach(function(a,c){switch(a){case"hour":b._domElement.appendChild(b._hourElement),h.addClass(b._hourElement,"win-order"+c);break;case"minute":b._domElement.appendChild(b._minuteElement),h.addClass(b._minuteElement,"win-order"+c);break;case"period":b._ampmElement&&(b._domElement.appendChild(b._ampmElement),h.addClass(b._ampmElement,"win-order"+c))}})},dispose:function(){},clock:{get:function(){return this._clock},set:function(a){this._clock!==a&&(this._clock=a,this._init())}},current:{get:function(){var a=this._currentTime;if(a){var b=n._sentinelDate();return b.setHours(a.getHours()),b.setMinutes(this._getMinutesIndex(a)*this.minuteIncrement),b.setSeconds(0),b.setMilliseconds(0),b}return a},set:function(a){var b;"string"==typeof a?(b=n._sentinelDate(),b.setTime(Date.parse(b.toDateString()+" "+a))):(b=n._sentinelDate(),b.setHours(a.getHours()),b.setMinutes(a.getMinutes()));var c=this._currentTime;m(c,b)||(this._currentTime=b,this._updateDisplay())}},disabled:{get:function(){return this._disabled},set:function(a){this._disabled!==a&&(this._disabled=a,this._hourControl&&(this._hourControl.setDisabled(a),this._minuteControl.setDisabled(a)),this._ampmControl&&this._ampmControl.setDisabled(a))}},element:{get:function(){return this._domElement}},_init:function(a){this._setElement(a),this._updateDisplay()},hourPattern:{get:function(){return this._timePatterns.hour.pattern},set:function(a){this._timePatterns.hour!==a&&(this._timePatterns.hour=a,this._init())}},_getHoursAmpm:function(a){var b=a.getHours();return this._ampmElement?0===b?{hours:12,ampm:0}:12>b?{hours:b,ampm:0}:{hours:b-12,ampm:1}:{hours:b}},_getHoursIndex:function(a){return this._ampmElement&&12===a?0:a},_getMinutesIndex:function(a){return parseInt(a.getMinutes()/this.minuteIncrement)},minuteIncrement:{get:function(){return Math.max(1,Math.abs(0|this._minuteIncrement)%60)},set:function(a){this._minuteIncrement!==a&&(this._minuteIncrement=a,this._init())}},minutePattern:{get:function(){return this._timePatterns.minute.pattern},set:function(a){this._timePatterns.minute!==a&&(this._timePatterns.minute=a,this._init())}},periodPattern:{get:function(){return this._timePatterns.period.pattern},set:function(a){this._timePatterns.period!==a&&(this._timePatterns.period=a,this._init())}},_setElement:function(b){if(this._domElement=this._domElement||b,this._domElement){var c=n.getInformation(this.clock,this.minuteIncrement,this._timePatterns);this._information=c,c.forceLanguage&&(this._domElement.setAttribute("lang",c.forceLanguage),this._domElement.setAttribute("dir",c.isRTL?"rtl":"ltr")),h.empty(this._domElement),h.addClass(this._domElement,"win-timepicker"),this._hourElement=a.document.createElement("select"),h.addClass(this._hourElement,"win-timepicker-hour win-dropdown"),this._minuteElement=a.document.createElement("select"),h.addClass(this._minuteElement,"win-timepicker-minute win-dropdown"),this._ampmElement=null,"12HourClock"===c.clock&&(this._ampmElement=a.document.createElement("select"),h.addClass(this._ampmElement,"win-timepicker-period win-dropdown")),this._addControlsInOrder(c);var d=this._getHoursAmpm(this.current);this._hourControl=new j._Select(this._hourElement,{dataSource:this._getInfoHours(),disabled:this.disabled,index:this._getHoursIndex(d.hours)}),this._minuteControl=new j._Select(this._minuteElement,{dataSource:c.minutes,disabled:this.disabled,index:this._getMinutesIndex(this.current)}),this._ampmControl=null,this._ampmElement&&(this._ampmControl=new j._Select(this._ampmElement,{dataSource:c.periods,disabled:this.disabled,index:d.ampm})),this._wireupEvents(),this._updateValues(),this._addAccessibilityAttributes()}},_getInfoHours:function(){return this._information.hours},_updateLayout:function(){this._domElement&&this._updateValues()},_updateValues:function(){if(this._hourControl){var a=this._getHoursAmpm(this.current);this._ampmControl&&(this._ampmControl.index=a.ampm),this._hourControl.index=this._getHoursIndex(a.hours),this._minuteControl.index=this._getMinutesIndex(this.current)}},_updateDisplay:function(){var a=this._getHoursAmpm(this.current);this._ampmControl&&(this._ampmControl.index=a.ampm),this._hourControl&&(this._hourControl.index=this._getHoursIndex(a.hours),this._minuteControl.index=this._getMinutesIndex(this.current))},_wireupEvents:function(){var a=this,b=function(){var b=a._hourControl.index;return a._ampmElement&&1===a._ampmControl.index&&12!==b&&(b+=12),b},c=function(){var c=b();a._currentTime.setHours(c),a._currentTime.setMinutes(a._minuteControl.index*a.minuteIncrement)};this._hourElement.addEventListener("change",c,!1),this._minuteElement.addEventListener("change",c,!1),this._ampmElement&&this._ampmElement.addEventListener("change",c,!1)}},{_sentinelDate:function(){var a=new Date;return new Date(2011,6,15,a.getHours(),a.getMinutes())},_getInformationWinRT:function(a,c,e){var f=function(c,d){var e=b.Windows.Globalization.DateTimeFormatting;c=c?c:d;var f=new e.DateTimeFormatter(c);return a&&(f=e.DateTimeFormatter(c,f.languages,f.geographicRegion,f.calendar,a)),f},g=b.Windows.Globalization,h=new g.Calendar;a&&(h=new g.Calendar(h.languages,h.getCalendarSystem(),a)),h.setDateTime(n._sentinelDate());var j=h.getClock(),l=24;l=h.numberOfHoursInThisPeriod;var m=function(){var a=f(e.period,k);return{getLength:function(){return 2},getValue:function(b){var c=n._sentinelDate();if(0===b){c.setHours(1);var d=a.format(c);return d}if(1===b){c.setHours(13);var e=a.format(c);return e}return null}}}(),o=function(){var a=f(e.minute,d),b=n._sentinelDate();return{getLength:function(){return 60/c},getValue:function(d){var e=d*c;return b.setMinutes(e),a.format(b)}}}(),p=function(){var a=f(e.hour,i),b=n._sentinelDate();return{getLength:function(){return l},getValue:function(c){return b.setHours(c),a.format(b)}}}(),q=f("hour minute"),r=q.patterns[0],s=["hour","minute"],t={period:r.indexOf("{period"),hour:r.indexOf("{hour"),minute:r.indexOf("{minute")};t.period>-1&&s.push("period");var u=b.Windows.Globalization.DateTimeFormatting.DateTimeFormatter,v=new u("month.full",b.Windows.Globalization.ApplicationLanguages.languages,"ZZ","GregorianCalendar","24HourClock"),w=v.patterns[0],x=8207===w.charCodeAt(0);if(x){var y=t.hour;t.hour=t.minute,t.minute=y}return s.sort(function(a,b){return t[a]<t[b]?-1:t[a]>t[b]?1:0}),{minutes:o,hours:p,clock:j,periods:m,order:s,forceLanguage:q.resolvedLanguage,isRTL:x}},_getInformationJS:function(a,b){var c=[12,1,2,3,4,5,6,7,8,9,10,11],d={};d.getLength=function(){return 60/b},d.getValue=function(a){var c=a*b;return 10>c?"0"+c.toString():c.toString()};var e=["hour","minute","period"];return"24HourClock"===a&&(c=["00","01","02","03","04","05","06","07","08","09",10,11,12,13,14,15,16,17,18,19,20,21,22,23],e=["hour","minute"]),{minutes:d,hours:c,clock:a||"12HourClock",periods:["AM","PM"],order:e}}});return n.getInformation=b.Windows.Globalization.DateTimeFormatting&&b.Windows.Globalization.Calendar&&b.Windows.Globalization.ApplicationLanguages?n._getInformationWinRT:n._getInformationJS,c.Class.mix(n,e.createEventProperties("change")),c.Class.mix(n,g.DOMEventMixin),n})})}),d("require-style!less/styles-backbutton",[],function(){}),d("require-style!less/colors-backbutton",[],function(){}),d("WinJS/Controls/BackButton",["exports","../Core/_Global","../Core/_Base","../Core/_ErrorFromName","../Core/_Resources","../Navigation","../Utilities/_Control","../Utilities/_ElementUtilities","../Utilities/_Hoverable","require-style!less/styles-backbutton","require-style!less/colors-backbutton"],function(a,b,c,d,e,f,g,h){"use strict";var i=h.Key,j="win-navigation-backbutton",k="win-back",l=3,m=function(){function a(){b.addEventListener("keyup",d,!1),h._addEventListener(b,"pointerup",e,!1)}function c(){b.removeEventListener("keyup",d,!1),h._removeEventListener(b,"pointerup",e,!1)}function d(a){(a.keyCode===i.leftArrow&&a.altKey&&!a.shiftKey&&!a.ctrlKey||a.keyCode===i.browserBack)&&(f.back(),a.preventDefault())}function e(a){a.button===l&&f.back()}var g=0;return{addRef:function(){0===g&&a(),g++},release:function(){g>0&&(g--,0===g&&c())},getCount:function(){return g}}}();c.Namespace._moduleDefine(a,"WinJS.UI",{BackButton:c.Namespace._lazy(function(){var a={get ariaLabel(){return e._getWinJSString("ui/backbuttonarialabel").value},get duplicateConstruction(){return"Invalid argument: Controls may only be instantiated one time for each DOM element"},get badButtonElement(){return"Invalid argument: For a button, toggle, or flyout command, the element must be null or a button element"}},i=c.Class.define(function(c,e){if(c&&c.winControl)throw new d("WinJS.UI.BackButton.DuplicateConstruction",a.duplicateConstruction);this._element=c||b.document.createElement("button"),e=e||{},this._initializeButton(),this._disposed=!1,this._element.winControl=this,g.setOptions(this,e),this._buttonClickHandler=this._handleBackButtonClick.bind(this),this._element.addEventListener("click",this._buttonClickHandler,!1),this._navigatedHandler=this._handleNavigatedEvent.bind(this),f.addEventListener("navigated",this._navigatedHandler,!1),m.addRef()},{element:{get:function(){return this._element}},dispose:function(){this._disposed||(this._disposed=!0,f.removeEventListener("navigated",this._navigatedHandler,!1),m.release())},refresh:function(){this._element.disabled=f.canGoBack?!1:!0},_initializeButton:function(){if("BUTTON"!==this._element.tagName)throw new d("WinJS.UI.BackButton.BadButtonElement",a.badButtonElement);h.addClass(this._element,j),h.addClass(this._element,"win-disposable"),this._element.innerHTML='<span class="'+k+'"></span>',this.refresh(),this._element.setAttribute("aria-label",a.ariaLabel),this._element.setAttribute("title",a.ariaLabel),this._element.setAttribute("type","button")},_handleNavigatedEvent:function(){this.refresh()},_handleBackButtonClick:function(){f.back()}});return i._getReferenceCount=function(){return m.getCount()},c.Class.mix(i,g.DOMEventMixin),i})})}),d("require-style!less/styles-tooltip",[],function(){}),d("require-style!less/colors-tooltip",[],function(){}),d("WinJS/Controls/Tooltip",["exports","../Core/_Global","../Core/_WinRT","../Core/_Base","../Core/_BaseUtils","../Core/_Events","../Animations","../Animations/_TransitionAnimation","../Utilities/_Control","../Utilities/_Dispose","../Utilities/_ElementUtilities","../Utilities/_Hoverable","require-style!less/styles-tooltip","require-style!less/colors-tooltip"],function(a,b,c,d,e,f,g,h,i,j,k){"use strict";d.Namespace._moduleDefine(a,"WinJS.UI",{Tooltip:d.Namespace._lazy(function(){function a(a,b){return"pointerdown"===a?b===G:a in H}function l(a,b){return"pointerdown"===a?b!==G:a in J}var m=0,n=k.Key,o="top",p=h._animationTimeAdjustment(400),q=h._animationTimeAdjustment(1200),r=h._animationTimeAdjustment(400),s=h._animationTimeAdjustment(5e3),t=h._animationTimeAdjustment(0),u=h._animationTimeAdjustment(600),v=h._animationTimeAdjustment(400),w=h._animationTimeAdjustment(600),x=h._animationTimeAdjustment(200),y=h._animationTimeAdjustment(3e5),z=12,A=20,B=45,C=20,D=12,E=1,F=k._MSPointerEvent.MSPOINTER_TYPE_MOUSE||"mouse",G=k._MSPointerEvent.MSPOINTER_TYPE_TOUCH||"touch",H={keyup:"",pointerover:"",pointerdown:""},I={pointermove:""},J={pointerdown:"",keydown:"",focusout:"",pointerout:"",pointercancel:"",pointerup:""},K={pointerover:"",pointerout:""},L="win-tooltip",M="win-tooltip-phantom",N=r,O=2*N,P=2.5*N,Q=s,R=!1,S=!1,T=f._createEventProperty;return d.Class.define(function(a,d){a=a||b.document.createElement("div");var e=k.data(a).tooltip;if(e)return e;if(!S&&c.Windows.UI.ViewManagement.UISettings){var f=new c.Windows.UI.ViewManagement.UISettings;N=h._animationTimeAdjustment(f.mouseHoverTime),O=2*N,P=2.5*N,Q=h._animationTimeAdjustment(1e3*f.messageDuration);var g=f.handPreference;R=g===c.Windows.UI.ViewManagement.HandPreference.leftHanded}S=!0,this._disposed=!1,this._placement=o,this._infotip=!1,this._innerHTML=null,this._contentElement=null,this._extraClass=null,this._lastContentType="html",this._anchorElement=a,this._domElement=null,this._phantomDiv=null,this._triggerByOpen=!1,this._eventListenerRemoveStack=[],this._lastKeyOrBlurEvent=null,this._currentKeyOrBlurEvent=null,a.winControl=this,k.addClass(a,"win-disposable"),a.title&&(this._innerHTML=this._anchorElement.title,this._anchorElement.removeAttribute("title")),i.setOptions(this,d),this._events(),k.data(a).tooltip=this},{innerHTML:{get:function(){return this._innerHTML},set:function(a){if(this._innerHTML=a,this._domElement){if(!this._innerHTML||""===this._innerHTML)return void this._onDismiss();this._domElement.innerHTML=a,this._position()}this._lastContentType="html"}},element:{get:function(){return this._anchorElement}},contentElement:{get:function(){return this._contentElement},set:function(a){if(this._contentElement=a,this._domElement){if(!this._contentElement)return void this._onDismiss();this._domElement.innerHTML="",this._domElement.appendChild(this._contentElement),this._position()}this._lastContentType="element"}},placement:{get:function(){return this._placement},set:function(a){"top"!==a&&"bottom"!==a&&"left"!==a&&"right"!==a&&(a=o),this._placement=a,this._domElement&&this._position()}},infotip:{get:function(){return this._infotip},set:function(a){this._infotip=!!a}},extraClass:{get:function(){return this._extraClass},set:function(a){this._extraClass=a}},onbeforeopen:T("beforeopen"),onopened:T("opened"),onbeforeclose:T("beforeclose"),onclosed:T("closed"),dispose:function(){if(!this._disposed){this._disposed=!0,j.disposeSubTree(this.element);for(var a=0,b=this._eventListenerRemoveStack.length;b>a;a++)this._eventListenerRemoveStack[a]();this._onDismiss();var c=k.data(this._anchorElement);c&&delete c.tooltip}},addEventListener:function(a,b,c){if(this._anchorElement){this._anchorElement.addEventListener(a,b,c);var d=this;this._eventListenerRemoveStack.push(function(){d._anchorElement.removeEventListener(a,b,c)})}},removeEventListener:function(a,b,c){this._anchorElement&&this._anchorElement.removeEventListener(a,b,c)},open:function(a){switch(this._triggerByOpen=!0,"touch"!==a&&"mouseover"!==a&&"mousedown"!==a&&"keyboard"!==a&&(a="default"),a){case"touch":this._onInvoke("touch","never");break;case"mouseover":this._onInvoke("mouse","auto");break;case"keyboard":this._onInvoke("keyboard","auto");break;case"mousedown":case"default":this._onInvoke("nodelay","never")}},close:function(){this._onDismiss()},_cleanUpDOM:function(){this._domElement&&(j.disposeSubTree(this._domElement),b.document.body.removeChild(this._domElement),this._domElement=null,b.document.body.removeChild(this._phantomDiv),this._phantomDiv=null)},_createTooltipDOM:function(){this._cleanUpDOM(),this._domElement=b.document.createElement("div");var a=k._uniqueID(this._domElement);this._domElement.setAttribute("id",a);var c=k._getComputedStyle(this._anchorElement,null),d=this._domElement.style;d.direction=c.direction,d.writingMode=c["writing-mode"],this._domElement.setAttribute("tabindex",-1),this._domElement.setAttribute("role","tooltip"),this._anchorElement.setAttribute("aria-describedby",a),"element"===this._lastContentType?this._domElement.appendChild(this._contentElement):this._domElement.innerHTML=this._innerHTML,b.document.body.appendChild(this._domElement),k.addClass(this._domElement,L),this._extraClass&&k.addClass(this._domElement,this._extraClass),this._phantomDiv=b.document.createElement("div"),this._phantomDiv.setAttribute("tabindex",-1),b.document.body.appendChild(this._phantomDiv),k.addClass(this._phantomDiv,M);var e=k._getComputedStyle(this._domElement,null).zIndex+1;this._phantomDiv.style.zIndex=e},_raiseEvent:function(a,c){if(this._anchorElement){var d=b.document.createEvent("CustomEvent");d.initCustomEvent(a,!1,!1,c),this._anchorElement.dispatchEvent(d)}},_captureLastKeyBlurOrPointerOverEvent:function(a){switch(this._lastKeyOrBlurEvent=this._currentKeyOrBlurEvent,a.type){case"keyup":this._currentKeyOrBlurEvent=a.keyCode===n.shift?null:"keyboard";break;case"focusout":this._currentKeyOrBlurEvent=null}},_registerEventToListener:function(a,b){var c=this,d=function(a){c._captureLastKeyBlurOrPointerOverEvent(a),c._handleEvent(a)};k._addEventListener(a,b,d,!1),this._eventListenerRemoveStack.push(function(){k._removeEventListener(a,b,d,!1)})},_events:function(){for(var a in H)this._registerEventToListener(this._anchorElement,a);for(var a in I)this._registerEventToListener(this._anchorElement,a);for(a in J)this._registerEventToListener(this._anchorElement,a);this._registerEventToListener(this._anchorElement,"contextmenu"),this._registerEventToListener(this._anchorElement,"MSHoldVisual")},_handleEvent:function(b){var c=b._normalizedType||b.type;if(!this._triggerByOpen){if(c in K&&k.eventWithinElement(this._anchorElement,b))return;if(a(c,b.pointerType))if(b.pointerType===G)this._isShown||(this._showTrigger="touch"),this._onInvoke("touch","never",b); else{if(this._skipMouseOver&&b.pointerType===F&&"pointerover"===c)return void(this._skipMouseOver=!1);var d="key"===c.substring(0,3)?"keyboard":"mouse";this._isShown||(this._showTrigger=d),this._onInvoke(d,"auto",b)}else if(c in I)this._contactPoint={x:b.clientX,y:b.clientY};else if(l(c,b.pointerType)){var f;if(b.pointerType===G){if("pointerup"===c){this._skipMouseOver=!0;var g=this;e._yieldForEvents(function(){g._skipMouseOver=!1})}f="touch"}else f="key"===c.substring(0,3)?"keyboard":"mouse";if("focusout"!==c&&f!==this._showTrigger)return;this._onDismiss()}else("contextmenu"===c||"MSHoldVisual"===c)&&b.preventDefault()}},_onShowAnimationEnd:function(){if(!this._shouldDismiss&&!this._disposed&&(this._raiseEvent("opened"),this._domElement&&"never"!==this._hideDelay)){var a=this,b=this._infotip?Math.min(3*Q,y):Q;this._hideDelayTimer=this._setTimeout(function(){a._onDismiss()},b)}},_onHideAnimationEnd:function(){b.document.body.removeEventListener("DOMNodeRemoved",this._removeTooltip,!1),this._cleanUpDOM(),this._anchorElement&&this._anchorElement.removeAttribute("aria-describedby"),m=(new Date).getTime(),this._triggerByOpen=!1,this._disposed||this._raiseEvent("closed")},_decideOnDelay:function(a){var b;if(this._useAnimation=!0,"nodelay"===a)b=0,this._useAnimation=!1;else{var c=(new Date).getTime();x>=c-m?(b="touch"===a?this._infotip?v:t:this._infotip?w:u,this._useAnimation=!1):b="touch"===a?this._infotip?q:p:this._infotip?P:O}return b},_getAnchorPositionFromElementWindowCoord:function(){var a=this._anchorElement.getBoundingClientRect();return{x:a.left,y:a.top,width:a.width,height:a.height}},_getAnchorPositionFromPointerWindowCoord:function(a){return{x:a.x,y:a.y,width:1,height:1}},_canPositionOnSide:function(a,b,c,d){var e=0,f=0;switch(a){case"top":e=d.width+this._offset,f=c.y;break;case"bottom":e=d.width+this._offset,f=b.height-c.y-c.height;break;case"left":e=c.x,f=d.height+this._offset;break;case"right":e=b.width-c.x-c.width,f=d.height+this._offset}return e>=d.width+this._offset&&f>=d.height+this._offset},_positionOnSide:function(a,b,c,d){var e=0,f=0;switch(a){case"top":case"bottom":e=c.x+c.width/2-d.width/2,e=Math.min(Math.max(e,0),b.width-d.width-E),f="top"===a?c.y-d.height-this._offset:c.y+c.height+this._offset;break;case"left":case"right":f=c.y+c.height/2-d.height/2,f=Math.min(Math.max(f,0),b.height-d.height-E),e="left"===a?c.x-d.width-this._offset:c.x+c.width+this._offset}this._domElement.style.left=e+"px",this._domElement.style.top=f+"px",this._phantomDiv.style.left=e+"px",this._phantomDiv.style.top=f+"px",this._phantomDiv.style.width=d.width+"px",this._phantomDiv.style.height=d.height+"px"},_position:function(a){var c={width:0,height:0},d={x:0,y:0,width:0,height:0},e={width:0,height:0};c.width=b.document.documentElement.clientWidth,c.height=b.document.documentElement.clientHeight,"tb-rl"===k._getComputedStyle(b.document.body,null)["writing-mode"]&&(c.width=b.document.documentElement.clientHeight,c.height=b.document.documentElement.clientWidth),d=!this._contactPoint||"touch"!==a&&"mouse"!==a?this._getAnchorPositionFromElementWindowCoord():this._getAnchorPositionFromPointerWindowCoord(this._contactPoint),e.width=this._domElement.offsetWidth,e.height=this._domElement.offsetHeight;var f={top:["top","bottom","left","right"],bottom:["bottom","top","left","right"],left:["left","right","top","bottom"],right:["right","left","top","bottom"]};R&&(f.top[2]="right",f.top[3]="left",f.bottom[2]="right",f.bottom[3]="left");for(var g=f[this._placement],h=g.length,i=0;h>i;i++)if(i===h-1||this._canPositionOnSide(g[i],c,d,e)){this._positionOnSide(g[i],c,d,e);break}return g[i]},_showTooltip:function(a){if(!this._shouldDismiss&&(this._isShown=!0,this._raiseEvent("beforeopen"),b.document.body.contains(this._anchorElement)&&!this._shouldDismiss)){if("element"===this._lastContentType){if(!this._contentElement)return void(this._isShown=!1)}else if(!this._innerHTML||""===this._innerHTML)return void(this._isShown=!1);var c=this;this._removeTooltip=function(a){for(var d=c._anchorElement;d;){if(a.target===d){b.document.body.removeEventListener("DOMNodeRemoved",c._removeTooltip,!1),c._cleanUpDOM();break}d=d.parentNode}},b.document.body.addEventListener("DOMNodeRemoved",this._removeTooltip,!1),this._createTooltipDOM(),this._position(a),this._useAnimation?g.fadeIn(this._domElement).then(this._onShowAnimationEnd.bind(this)):this._onShowAnimationEnd()}},_onInvoke:function(a,b,c){if(this._shouldDismiss=!1,!this._isShown&&(!c||"keyup"!==c.type||"keyboard"!==this._lastKeyOrBlurEvent&&(this._lastKeyOrBlurEvent||c.keyCode===n.tab))){this._hideDelay=b,this._contactPoint=null,c?(this._contactPoint={x:c.clientX,y:c.clientY},this._offset="touch"===a?B:"keyboard"===a?z:A):this._offset="touch"===a?C:D,this._clearTimeout(this._delayTimer),this._clearTimeout(this._hideDelayTimer);var d=this._decideOnDelay(a);if(d>0){var e=this;this._delayTimer=this._setTimeout(function(){e._showTooltip(a)},d)}else this._showTooltip(a)}},_onDismiss:function(){this._shouldDismiss=!0,this._isShown&&(this._isShown=!1,this._showTrigger="mouse",this._domElement?(this._raiseEvent("beforeclose"),this._useAnimation?g.fadeOut(this._domElement).then(this._onHideAnimationEnd.bind(this)):this._onHideAnimationEnd()):(this._raiseEvent("beforeclose"),this._raiseEvent("closed")))},_setTimeout:function(a,c){return b.setTimeout(a,c)},_clearTimeout:function(a){b.clearTimeout(a)}},{_DELAY_INITIAL_TOUCH_SHORT:{get:function(){return p}},_DELAY_INITIAL_TOUCH_LONG:{get:function(){return q}},_DEFAULT_MOUSE_HOVER_TIME:{get:function(){return r}},_DEFAULT_MESSAGE_DURATION:{get:function(){return s}},_DELAY_RESHOW_NONINFOTIP_TOUCH:{get:function(){return t}},_DELAY_RESHOW_NONINFOTIP_NONTOUCH:{get:function(){return u}},_DELAY_RESHOW_INFOTIP_TOUCH:{get:function(){return v}},_DELAY_RESHOW_INFOTIP_NONTOUCH:{get:function(){return w}},_RESHOW_THRESHOLD:{get:function(){return x}},_HIDE_DELAY_MAX:{get:function(){return y}}})})})}),d("require-style!less/styles-rating",[],function(){}),d("require-style!less/colors-rating",[],function(){}),d("WinJS/Controls/Rating",["../Core/_Global","../Core/_Base","../Core/_ErrorFromName","../Core/_Events","../Core/_Resources","../_Accents","../Utilities/_Control","../Utilities/_ElementUtilities","../Utilities/_Hoverable","../Utilities/_SafeHtml","./Tooltip","require-style!less/styles-rating","require-style!less/colors-rating"],function(a,b,c,d,e,f,g,h,i,j,k){"use strict";f.createAccentRule(".win-rating .win-star.win-user.win-full, .win-rating .win-star.win-user.win-full.win-disabled",[{name:"color",value:f.ColorTypes.accent}]),b.Namespace.define("WinJS.UI",{Rating:b.Namespace._lazy(function(){var f=d._createEventProperty,i={get averageRating(){return e._getWinJSString("ui/averageRating").value},get clearYourRating(){return e._getWinJSString("ui/clearYourRating").value},get tentativeRating(){return e._getWinJSString("ui/tentativeRating").value},get tooltipStringsIsInvalid(){return"Invalid argument: tooltipStrings must be null or an array of strings."},get unrated(){return e._getWinJSString("ui/unrated").value},get userRating(){return e._getWinJSString("ui/userRating").value}},l=5,m=!1,n="cancel",o="change",p="previewchange",q=0,r=h._MSPointerEvent.MSPOINTER_TYPE_TOUCH||"touch",s=h._MSPointerEvent.MSPOINTER_TYPE_PEN||"pen",t=h._MSPointerEvent.MSPOINTER_TYPE_MOUSE||"mouse",u="padding-left: 0px; padding-right: 0px; border-left: 0px; border-right: 0px; -ms-flex: none; -webkit-flex: none; flex: none; display: none",v="win-rating",w="win-star win-empty",x="win-star win-average win-empty",y="win-star win-average win-full",z="win-star win-user win-empty",A="win-star win-user win-full",B="win-star win-tentative win-empty",C="win-star win-tentative win-full",D="win-disabled",E="win-average",F="win-user";return b.Class.define(function(b,c){this._disposed=!1,b=b||a.document.createElement("div"),c=c||{},this._element=b,h.addClass(this._element,"win-disposable"),this._userRating=0,this._averageRating=0,this._disabled=m,this._enableClear=!0,this._tooltipStrings=[],this._controlUpdateNeeded=!1,this._setControlSize(c.maxRating),c.tooltipStrings||this._updateTooltips(null),g.setOptions(this,c),this._controlUpdateNeeded=!0,this._forceLayout(),h._addInsertedNotifier(this._element),b.winControl=this,this._events()},{maxRating:{get:function(){return this._maxRating},set:function(a){this._setControlSize(a),this._forceLayout()}},userRating:{get:function(){return this._userRating},set:function(a){this._userRating=Math.max(0,Math.min(Number(a)>>0,this._maxRating)),this._updateControl()}},averageRating:{get:function(){return this._averageRating},set:function(a){this._averageRating=Number(a)<1?0:Math.min(Number(a)||0,this._maxRating),this._averageRatingElement&&this._ensureAverageMSStarRating(),this._updateControl()}},disabled:{get:function(){return this._disabled},set:function(a){this._disabled=!!a,this._disabled&&this._clearTooltips(),this._updateTabIndex(),this._updateControl()}},enableClear:{get:function(){return this._enableClear},set:function(a){this._enableClear=!!a,this._setAriaValueMin(),this._updateControl()}},tooltipStrings:{get:function(){return this._tooltipStrings},set:function(a){if("object"!=typeof a)throw new c("WinJS.UI.Rating.TooltipStringsIsInvalid",i.tooltipStringsIsInvalid);this._updateTooltips(a),this._updateAccessibilityRestState()}},element:{get:function(){return this._element}},oncancel:f(n),onchange:f(o),onpreviewchange:f(p),dispose:function(){if(!this._disposed){this._disposed=!0;for(var a=0;a<this._toolTips.length;a++)this._toolTips[a].dispose();this._toolTips=null}},addEventListener:function(a,b,c){this._element.addEventListener(a,b,c)},removeEventListener:function(a,b,c){return this._element.removeEventListener(a,b,c)},_forceLayout:function(){if(this._controlUpdateNeeded){var a=!1;this._updateControl=function(){a=!0},this.userRating=this._userRating,this.averageRating=this._averageRating,this._lastEventWasChange=!1,this._lastEventWasCancel=!1,this._tentativeRating=-1,this._captured=!1,this._pointerDownFocus=!1,this._elements=[],this._toolTips=[],this._clearElement=null,this._averageRatingElement=null,this._elementWidth=null,this._elementPadding=null,this._elementBorder=null,this._floatingValue=0,this._createControl(),this._setAccessibilityProperties(),delete this._updateControl,a&&this._updateControl()}},_hideAverageRating:function(){this._averageRatingHidden||(this._averageRatingHidden=!0,this._averageRatingElement.style.cssText=u)},_createControl:function(){h.addClass(this._element,v);var a="";this._averageRatingHidden=!0;for(var b=0;b<=this._maxRating;b++)a=b===this._maxRating?a+"<div class='"+y+"' style='"+u+"'></div>":a+"<div class='"+z+"'></div>";j.setInnerHTMLUnsafe(this._element,a);for(var c=this._element.firstElementChild,b=0;c;)this._elements[b]=c,b<this._maxRating&&(h.data(c).msStarRating=b+1),c=c.nextElementSibling,b++;this._averageRatingElement=this._elements[this._maxRating],this._ensureAverageMSStarRating(),this._updateTabIndex()},_setAriaValueMin:function(){this._element.setAttribute("aria-valuemin",this._enableClear?0:1)},_setAccessibilityProperties:function(){this._element.setAttribute("role","slider"),this._element.setAttribute("aria-valuemax",this._maxRating),this._setAriaValueMin(),this._updateAccessibilityRestState()},_getText:function(b){var c=this._tooltipStrings[b];if(c){var d=a.document.createElement("div");return d.innerHTML=c,d.textContent}return b===this._maxRating?i.clearYourRating:b+1},_updateAccessibilityRestState:function(){var a=this._element;this._ariaValueNowMutationObserver&&this._ariaValueNowMutationObserver.disconnect(),a.setAttribute("aria-readOnly",this._disabled),0!==this._userRating?(a.setAttribute("aria-valuenow",this._userRating),a.setAttribute("aria-label",i.userRating),a.setAttribute("aria-valuetext",this._getText(this._userRating-1))):0!==this._averageRating?(a.setAttribute("aria-valuenow",this._averageRating),a.setAttribute("aria-label",i.averageRating),a.setAttribute("aria-valuetext",this._averageRating)):(a.setAttribute("aria-valuenow",i.unrated),a.setAttribute("aria-label",i.userRating),a.setAttribute("aria-valuetext",i.unrated)),this._ariaValueNowMutationObserver&&this._ariaValueNowMutationObserver.observe(this._element,{attributes:!0,attributeFilter:["aria-valuenow"]})},_updateAccessibilityHoverState:function(){var a=this._element;this._ariaValueNowMutationObserver&&this._ariaValueNowMutationObserver.disconnect(),a.setAttribute("aria-readOnly",this._disabled),this._tentativeRating>0?(a.setAttribute("aria-label",i.tentativeRating),a.setAttribute("aria-valuenow",this._tentativeRating),a.setAttribute("aria-valuetext",this._getText(this._tentativeRating-1))):0===this._tentativeRating?(a.setAttribute("aria-valuenow",i.unrated),a.setAttribute("aria-label",i.tentativeRating),a.setAttribute("aria-valuetext",this._getText(this._maxRating))):(a.setAttribute("aria-valuenow",i.unrated),a.setAttribute("aria-label",i.tentativeRating),a.setAttribute("aria-valuetext",i.unrated)),this._ariaValueNowMutationObserver&&this._ariaValueNowMutationObserver.observe(this._element,{attributes:!0,attributeFilter:["aria-valuenow"]})},_ensureTooltips:function(){if(!this.disabled&&0===this._toolTips.length)for(var a=0;a<this._maxRating;a++)this._toolTips[a]=new k.Tooltip(this._elements[a])},_decrementRating:function(){this._closeTooltip();var a=!0;0===this._tentativeRating||-1===this._tentativeRating&&0===this._userRating?a=!1:(this._tentativeRating>0?this._tentativeRating--:-1===this._tentativeRating&&(this._tentativeRating=0!==this._userRating&&this._userRating>0?this._userRating-1:0),0!==this._tentativeRating||this._enableClear||(this._tentativeRating=1,a=!1)),this._showTentativeRating(a,"keyboard")},_events:function(){function a(a){return{name:a,lowerCaseName:a.toLowerCase(),handler:function(b){var d=c["_on"+a];d&&d.apply(c,[b])}}}var b,c=this,d=[a("KeyDown"),a("FocusOut"),a("FocusIn"),a("PointerCancel"),a("PointerDown"),a("PointerMove"),a("PointerOver"),a("PointerUp"),a("PointerOut")],e=[a("WinJSNodeInserted")];for(b=0;b<d.length;++b)h._addEventListener(this._element,d[b].lowerCaseName,d[b].handler,!1);for(b=0;b<e.length;++b)this._element.addEventListener(e[b].name,e[b].handler,!1);this._ariaValueNowMutationObserver=new h._MutationObserver(this._ariaValueNowChanged.bind(this)),this._ariaValueNowMutationObserver.observe(this._element,{attributes:!0,attributeFilter:["aria-valuenow"]})},_onWinJSNodeInserted:function(){this._recalculateStarProperties(),this._updateControl()},_recalculateStarProperties:function(){var a=0;1===this._averageRating&&(a=1);var b=h._getComputedStyle(this._elements[a]);this._elementWidth=b.width,"rtl"===h._getComputedStyle(this._element).direction?(this._elementPadding=b.paddingRight,this._elementBorder=b.borderRight):(this._elementPadding=b.paddingLeft,this._elementBorder=b.borderLeft)},_hideAverageStar:function(){0!==this._averageRating&&this._resetAverageStar(!1)},_incrementRating:function(){this._closeTooltip();var a=!0;(this._tentativeRating===this._maxRating||-1===this._tentativeRating&&this._userRating===this._maxRating)&&(a=!1),-1!==this._tentativeRating?this._tentativeRating<this._maxRating&&this._tentativeRating++:this._tentativeRating=0!==this._userRating?this._userRating<this._maxRating?this._userRating+1:this._maxRating:1,this._showTentativeRating(a,"keyboard")},_ariaValueNowChanged:function(){if(!this._disabled){var a=this._element.getAttributeNode("aria-valuenow");if(null!==a){var b=Number(a.nodeValue);this.userRating!==b&&(this.userRating=b,this._tentativeRating=this._userRating,this._raiseEvent(o,this._userRating))}}},_onPointerCancel:function(){this._showCurrentRating(),this._lastEventWasChange||this._raiseEvent(n,null),this._captured=!1},_onPointerDown:function(a){(a.pointerType!==t||a.button===q)&&(this._captured||(this._pointerDownAt={x:a.clientX,y:a.clientY},this._pointerDownFocus=!0,this._disabled||(h._setPointerCapture(this._element,a.pointerId),this._captured=!0,a.pointerType===r?(this._tentativeRating=h.data(a.target).msStarRating||0,this._setStarClasses(C,this._tentativeRating,B),this._hideAverageStar(),this._updateAccessibilityHoverState(),this._openTooltip("touch"),this._raiseEvent(p,this._tentativeRating)):this._openTooltip("mousedown"))))},_onCapturedPointerMove:function(a,b){var c,d=this._pointerDownAt||{x:a.clientX,y:a.clientY},e=h._elementsFromPoint(a.clientX,d.y);if(e)for(var f=0,g=e.length;g>f;f++){var i=e[f];if("tooltip"===i.getAttribute("role"))return;if(h.hasClass(i,"win-star")){c=i;break}}var j;if(c&&c.parentElement===this._element)j=h.data(c).msStarRating||0;else{var k=0,l=this.maxRating;"rtl"===h._getComputedStyle(this._element).direction&&(k=l,l=0),j=a.clientX<d.x?k:l}var m=!1,n=Math.min(Math.ceil(j),this._maxRating);0!==n||this._enableClear||(n=1),n!==this._tentativeRating&&(this._closeTooltip(),m=!0),this._tentativeRating=n,this._showTentativeRating(m,b),a.preventDefault()},_onPointerMove:function(a){this._captured&&(a.pointerType===r?this._onCapturedPointerMove(a,"touch"):this._onCapturedPointerMove(a,"mousedown"))},_onPointerOver:function(a){this._disabled||a.pointerType!==s&&a.pointerType!==t||this._onCapturedPointerMove(a,"mouseover")},_onPointerUp:function(a){this._captured&&(h._releasePointerCapture(this._element,a.pointerId),this._captured=!1,this._onUserRatingChanged()),this._pointerDownAt=null},_onFocusOut:function(){this._captured||(this._onUserRatingChanged(),this._lastEventWasChange||this._lastEventWasCancel||this._raiseEvent(n,null))},_onFocusIn:function(){if(!this._pointerDownFocus){if(!this._disabled){if(0===this._userRating)for(var a=0;a<this._maxRating;a++)this._elements[a].className=B;this._hideAverageStar()}0!==this._userRating?this._raiseEvent(p,this._userRating):this._raiseEvent(p,0),this._tentativeRating=this._userRating}this._pointerDownFocus=!1},_onKeyDown:function(a){var b=h.Key,c=a.keyCode,d=h._getComputedStyle(this._element).direction,e=!0;switch(c){case b.enter:this._onUserRatingChanged();break;case b.tab:this._onUserRatingChanged(),e=!1;break;case b.escape:this._showCurrentRating(),this._lastEventWasChange||this._raiseEvent(n,null);break;case b.leftArrow:"rtl"===d&&this.userRating<this.maxRating-1?this._incrementRating():"rtl"!==d&&this.userRating>0?this._decrementRating():e=!1;break;case b.upArrow:this.userRating<this.maxRating-1?this._incrementRating():e=!1;break;case b.rightArrow:"rtl"===d&&this.userRating>0?this._decrementRating():"rtl"!==d&&this.userRating<this.maxRating-1?this._incrementRating():e=!1;break;case b.downArrow:this.userRating>0?this._decrementRating():e=!1;break;default:var f=0;if(c>=b.num0&&c<=b.num9?f=b.num0:c>=b.numPad0&&c<=b.numPad9&&(f=b.numPad0),f>0){var g=!1,i=Math.min(c-f,this._maxRating);0!==i||this._enableClear||(i=1),i!==this._tentativeRating&&(this._closeTooltip(),g=!0),this._tentativeRating=i,this._showTentativeRating(g,"keyboard")}else e=!1}e&&(a.stopPropagation(),a.preventDefault())},_onPointerOut:function(a){this._captured||h.eventWithinElement(this._element,a)||(this._showCurrentRating(),this._lastEventWasChange||this._raiseEvent(n,null))},_onUserRatingChanged:function(){this._disabled||(this._closeTooltip(),this._userRating===this._tentativeRating||this._lastEventWasCancel||this._lastEventWasChange?this._updateControl():(this.userRating=this._tentativeRating,this._raiseEvent(o,this._userRating)))},_raiseEvent:function(b,c){if(!this._disabled&&(this._lastEventWasChange=b===o,this._lastEventWasCancel=b===n,a.document.createEvent)){var d=a.document.createEvent("CustomEvent");d.initCustomEvent(b,!1,!1,{tentativeRating:c}),this._element.dispatchEvent(d)}},_resetNextElement:function(a){if(null!==this._averageRatingElement.nextSibling){h._setFlexStyle(this._averageRatingElement.nextSibling,{grow:1,shrink:1});var b=this._averageRatingElement.nextSibling.style,c=h._getComputedStyle(this._element).direction;a&&(c="rtl"===c?"ltr":"rtl"),"rtl"===c?(b.paddingRight=this._elementPadding,b.borderRight=this._elementBorder,b.direction="rtl"):(b.paddingLeft=this._elementPadding,b.borderLeft=this._elementBorder,b.direction="ltr"),b.backgroundPosition="left",b.backgroundSize="100% 100%",b.width=this._resizeStringValue(this._elementWidth,1,b.width)}},_resetAverageStar:function(a){this._resetNextElement(a),this._hideAverageRating()},_resizeStringValue:function(a,b,c){var d=parseFloat(a);if(isNaN(d))return null!==c?c:a;var e=a.substring(d.toString(10).length);return d*=b,d+e},_setControlSize:function(a){var b=(Number(a)||l)>>0;this._maxRating=b>0?b:l},_updateTooltips:function(a){var b,c=0;if(null!==a)for(c=a.length<=this._maxRating+1?a.length:this._maxRating+1,b=0;c>b;b++)this._tooltipStrings[b]=a[b];else{for(b=0;b<this._maxRating;b++)this._tooltipStrings[b]=b+1;this._tooltipStrings[this._maxRating]=i.clearYourRating}},_updateTabIndex:function(){this._element.tabIndex=this._disabled?"-1":"0"},_setStarClasses:function(a,b,c){for(var d=0;d<this._maxRating;d++)this._elements[d].className=b>d?a:c},_updateAverageStar:function(){var a=this._averageRatingElement.style,b=this._averageRatingElement.nextSibling.style;"rtl"===h._getComputedStyle(this._element).direction?(a.backgroundPosition="right",a.paddingRight=this._elementPadding,a.borderRight=this._elementBorder,b.paddingRight="0px",b.borderRight="0px",b.direction="ltr"):(a.backgroundPosition="left",b.backgroundPosition="right",a.paddingLeft=this._elementPadding,a.borderLeft=this._elementBorder,b.paddingLeft="0px",b.borderLeft="0px",b.direction="rtl"),h._setFlexStyle(this._averageRatingElement,{grow:this._floatingValue,shrink:this._floatingValue}),a.width=this._resizeStringValue(this._elementWidth,this._floatingValue,a.width),a.backgroundSize=100/this._floatingValue+"% 100%",a.display=h._getComputedStyle(this._averageRatingElement.nextSibling).display,this._averageRatingHidden=!1,h._setFlexStyle(this._averageRatingElement.nextSibling,{grow:1-this._floatingValue,shrink:1-this._floatingValue}),b.width=this._resizeStringValue(this._elementWidth,1-this._floatingValue,b.width),b.backgroundSize=100/(1-this._floatingValue)+"% 100%"},_showCurrentRating:function(){this._closeTooltip(),this._tentativeRating=-1,this._disabled||this._updateControl(),this._updateAccessibilityRestState()},_showTentativeRating:function(a,b){!this._disabled&&this._tentativeRating>=0&&(this._setStarClasses(C,this._tentativeRating,B),this._hideAverageStar()),this._updateAccessibilityHoverState(),a&&(this._openTooltip(b),this._raiseEvent(p,this._tentativeRating))},_openTooltip:function(b){if(!this.disabled)if(this._ensureTooltips(),this._tentativeRating>0)this._toolTips[this._tentativeRating-1].innerHTML=this._tooltipStrings[this._tentativeRating-1],this._toolTips[this._tentativeRating-1].open(b);else if(0===this._tentativeRating){this._clearElement=a.document.createElement("div");var c=this._elements[0].offsetWidth+parseInt(this._elementPadding,10);"ltr"===h._getComputedStyle(this._element).direction&&(c*=-1),this._clearElement.style.cssText="visiblity:hidden; position:absolute; width:0px; height:100%; left:"+c+"px; top:0px;",this._elements[0].appendChild(this._clearElement),this._toolTips[this._maxRating]=new k.Tooltip(this._clearElement),this._toolTips[this._maxRating].innerHTML=this._tooltipStrings[this._maxRating],this._toolTips[this._maxRating].open(b)}},_closeTooltip:function(){0!==this._toolTips.length&&(this._tentativeRating>0?this._toolTips[this._tentativeRating-1].close():0===this._tentativeRating&&null!==this._clearElement&&(this._toolTips[this._maxRating].close(),this._elements[0].removeChild(this._clearElement),this._clearElement=null))},_clearTooltips:function(){if(this._toolTips&&0!==this._toolTips.length)for(var a=0;a<this._maxRating;a++)this._toolTips[a].innerHTML=null},_appendClass:function(a){for(var b=0;b<=this._maxRating;b++)h.addClass(this._elements[b],a)},_setClasses:function(a,b,c){for(var d=0;d<this._maxRating;d++)this._elements[d].className=b>d?a:c},_ensureAverageMSStarRating:function(){h.data(this._averageRatingElement).msStarRating=Math.ceil(this._averageRating)},_updateControl:function(){if(this._controlUpdateNeeded){if(0!==this._averageRating&&0===this._userRating&&this._averageRating>=1&&this._averageRating<=this._maxRating){this._setClasses(y,this._averageRating-1,x),this._averageRatingElement.className=y;for(var a=0;a<this._maxRating;a++)if(a<this._averageRating&&a+1>=this._averageRating){this._resetNextElement(!1),this._element.insertBefore(this._averageRatingElement,this._elements[a]),this._floatingValue=this._averageRating-a;var b=h._getComputedStyle(this._elements[a]);this._elementWidth=b.width,"rtl"===h._getComputedStyle(this._element).direction?(this._elementPadding=b.paddingRight,this._elementBorder=b.borderRight):(this._elementPadding=b.paddingLeft,this._elementBorder=b.borderLeft),this._updateAverageStar()}}0!==this._userRating&&this._userRating>=1&&this._userRating<=this._maxRating&&(this._setClasses(A,this._userRating,z),this._resetAverageStar(!1)),0===this._userRating&&0===this._averageRating&&(this._setClasses(w,this._maxRating),this._resetAverageStar(!1)),this.disabled&&this._appendClass(D),this._appendClass(0!==this._averageRating&&0===this._userRating?E:F),this._updateAccessibilityRestState()}}})})})}),d("require-style!less/styles-toggleswitch",[],function(){}),d("require-style!less/colors-toggleswitch",[],function(){}),d("WinJS/Controls/ToggleSwitch",["../Core/_Global","../Core/_Base","../Core/_BaseUtils","../Core/_Events","../Core/_Resources","../_Accents","../Utilities/_Control","../Utilities/_ElementUtilities","require-style!less/styles-toggleswitch","require-style!less/colors-toggleswitch"],function(a,b,c,d,e,f,g,h){"use strict";f.createAccentRule(".win-toggleswitch-on .win-toggleswitch-track",[{name:"background-color",value:f.ColorTypes.accent}]),f.createAccentRule("html.win-hoverable .win-toggleswitch-on:not(.win-toggleswitch-disabled):not(.win-toggleswitch-pressed) .win-toggleswitch-clickregion:hover .win-toggleswitch-track",[{name:"background-color",value:f.ColorTypes.listSelectPress}]),b.Namespace.define("WinJS.UI",{ToggleSwitch:b.Namespace._lazy(function(){var c="win-toggleswitch",f="win-toggleswitch-header",i="win-toggleswitch-clickregion",j="win-toggleswitch-track",k="win-toggleswitch-thumb",l="win-toggleswitch-values",m="win-toggleswitch-value",n="win-toggleswitch-value-on",o="win-toggleswitch-value-off",p="win-toggleswitch-description",q="win-toggleswitch-on",r="win-toggleswitch-off",s="win-toggleswitch-disabled",t="win-toggleswitch-enabled",u="win-toggleswitch-dragging",v="win-toggleswitch-pressed",w={get on(){return e._getWinJSString("ui/on").value},get off(){return e._getWinJSString("ui/off").value}},x=b.Class.define(function(b,d){b=b||a.document.createElement("div"),this._domElement=b,h.addClass(this._domElement,c),this._domElement.innerHTML=['<div class="'+f+'"></div>','<div class="'+i+'">',' <div class="'+j+'">',' <div class="'+k+'"></div>'," </div>",' <div class="'+l+'">',' <div class="'+m+" "+n+'"></div>',' <div class="'+m+" "+o+'"></div>'," </div>","</div>",'<div class="'+p+'"></div>'].join("\n"),this._headerElement=this._domElement.firstElementChild,this._clickElement=this._headerElement.nextElementSibling,this._trackElement=this._clickElement.firstElementChild,this._thumbElement=this._trackElement.firstElementChild,this._labelsElement=this._trackElement.nextElementSibling,this._labelOnElement=this._labelsElement.firstElementChild,this._labelOffElement=this._labelOnElement.nextElementSibling,this._descriptionElement=this._clickElement.nextElementSibling,this._headerElement.setAttribute("aria-hidden",!0),this._labelsElement.setAttribute("aria-hidden",!0),this._headerElement.setAttribute("id",h._uniqueID(this._headerElement)),this._domElement.setAttribute("aria-labelledby",this._headerElement.id),this._domElement.setAttribute("role","checkbox"),this._domElement.winControl=this,h.addClass(this._domElement,"win-disposable"),this._domElement.addEventListener("keydown",this._keyDownHandler.bind(this)),h._addEventListener(this._clickElement,"pointerdown",this._pointerDownHandler.bind(this)),h._addEventListener(this._clickElement,"pointercancel",this._pointerCancelHandler.bind(this)),this._boundPointerMove=this._pointerMoveHandler.bind(this),this._boundPointerUp=this._pointerUpHandler.bind(this),this._mutationObserver=new h._MutationObserver(this._ariaChangedHandler.bind(this)),this._mutationObserver.observe(this._domElement,{attributes:!0,attributeFilter:["aria-checked"]}),this._dragX=0,this._dragging=!1,this.checked=!1,this.disabled=!1,this.labelOn=w.on,this.labelOff=w.off,g.setOptions(this,d)},{element:{get:function(){return this._domElement}},checked:{get:function(){return this._checked},set:function(a){a=!!a,a!==this.checked&&(this._checked=a,this._domElement.setAttribute("aria-checked",a),a?(h.addClass(this._domElement,q),h.removeClass(this._domElement,r)):(h.addClass(this._domElement,r),h.removeClass(this._domElement,q)),this.dispatchEvent("change"))}},disabled:{get:function(){return this._disabled},set:function(a){a=!!a,a!==this._disabled&&(a?(h.addClass(this._domElement,s),h.removeClass(this._domElement,t)):(h.removeClass(this._domElement,s),h.addClass(this._domElement,t)),this._disabled=a,this._domElement.setAttribute("aria-disabled",a),this._domElement.setAttribute("tabIndex",a?-1:0))}},labelOn:{get:function(){return this._labelOnElement.innerHTML},set:function(a){this._labelOnElement.innerHTML=a}},labelOff:{get:function(){return this._labelOffElement.innerHTML},set:function(a){this._labelOffElement.innerHTML=a}},title:{get:function(){return this._headerElement.innerHTML},set:function(a){this._headerElement.innerHTML=a}},onchange:d._createEventProperty("change"),dispose:function(){this._disposed||(this._disposed=!0)},_ariaChangedHandler:function(){var a=this._domElement.getAttribute("aria-checked");a="true"===a?!0:!1,this.checked=a},_keyDownHandler:function(a){this.disabled||(a.keyCode===h.Key.space&&(a.preventDefault(),this.checked=!this.checked),(a.keyCode===h.Key.rightArrow||a.keyCode===h.Key.upArrow)&&(a.preventDefault(),this.checked=!0),(a.keyCode===h.Key.leftArrow||a.keyCode===h.Key.downArrow)&&(a.preventDefault(),this.checked=!1))},_pointerDownHandler:function(a){this.disabled||this._mousedown||(a.preventDefault(),this._mousedown=!0,this._dragXStart=a.pageX-this._trackElement.getBoundingClientRect().left,this._dragX=this._dragXStart,this._dragging=!1,h.addClass(this._domElement,v),h._globalListener.addEventListener(this._domElement,"pointermove",this._boundPointerMove,!0),h._globalListener.addEventListener(this._domElement,"pointerup",this._boundPointerUp,!0),a.pointerType===h._MSPointerEvent.MSPOINTER_TYPE_TOUCH&&h._setPointerCapture(this._domElement,a.pointerId))},_pointerCancelHandler:function(a){this._resetPressedState(),a.pointerType===h._MSPointerEvent.MSPOINTER_TYPE_TOUCH&&h._releasePointerCapture(this._domElement,a.pointerId)},_pointerUpHandler:function(a){if(!this.disabled&&this._mousedown){a=a.detail.originalEvent,a.preventDefault();var b=this._trackElement.getBoundingClientRect(),c=this._thumbElement.getBoundingClientRect(),d="rtl"===h._getComputedStyle(this._domElement).direction;if(this._dragging){var e=b.width-c.width;this.checked=d?this._dragX<e/2:this._dragX>=e/2,this._dragging=!1,h.removeClass(this._domElement,u)}else this.checked=!this.checked;this._resetPressedState()}},_pointerMoveHandler:function(a){if(!this.disabled&&this._mousedown){a=a.detail.originalEvent,a.preventDefault();var b=this._trackElement.getBoundingClientRect(),c=a.pageX-b.left;if(!(c>b.width)){var d=this._thumbElement.getBoundingClientRect(),e=b.width-d.width-6;this._dragX=Math.min(e,c-d.width/2),this._dragX=Math.max(2,this._dragX),!this._dragging&&Math.abs(c-this._dragXStart)>3&&(this._dragging=!0,h.addClass(this._domElement,u)),this._thumbElement.style.left=this._dragX+"px"}}},_resetPressedState:function(){this._mousedown=!1,this._thumbElement.style.left="",h.removeClass(this._domElement,v),h._globalListener.removeEventListener(this._domElement,"pointermove",this._boundPointerMove,!0),h._globalListener.removeEventListener(this._domElement,"pointerup",this._boundPointerUp,!0) }});return b.Class.mix(x,g.DOMEventMixin),x})})}),d("require-style!less/styles-semanticzoom",[],function(){}),d("require-style!less/colors-semanticzoom",[],function(){}),d("WinJS/Controls/SemanticZoom",["../Core/_Global","../Core/_Base","../Core/_BaseUtils","../Core/_ErrorFromName","../Core/_Events","../Core/_Resources","../Core/_WriteProfilerMark","../Animations","../Animations/_TransitionAnimation","../ControlProcessor","../Promise","../Utilities/_Control","../Utilities/_Dispose","../Utilities/_ElementUtilities","../Utilities/_ElementListUtilities","../Utilities/_Hoverable","require-style!less/styles-semanticzoom","require-style!less/colors-semanticzoom"],function(a,b,c,d,e,f,g,h,i,j,k,l,m,n,o,p){"use strict";b.Namespace.define("WinJS.UI",{SemanticZoom:b.Namespace._lazy(function(){function f(a){return a}function q(a,b,c){return a+" "+i._animationTimeAdjustment(b)+"s "+c+" "+i._libraryDelay+"ms"}function r(){return q(X.cssName,Q,"ease-in-out")+", "+q("opacity",O,"ease-in-out")}function s(){return q(X.cssName,R,"ease-in-out")+", "+q("opacity",P,"ease-in-out")}function t(){return q(X.cssName,U,W)}function u(){return q(X.cssName,V,W)}function v(a,b){return n.convertToPixels(a,b)}function w(a,b){i.isAnimationEnabled()&&(a.style[X.scriptName]="scale("+b+")")}function x(a){var b=a.target&&a.target.winControl;b&&!b._resizing&&b._onResize()}function y(a){var b=a[0].target&&a[0].target.winControl;b&&b instanceof hb&&b._onPropertyChanged()}var z=c._browserStyleEquivalents,A={get invalidZoomFactor(){return"Invalid zoomFactor"}},B="win-semanticzoom-button",C="win-semanticzoom-button-location",D=3e3,E=8,F="win-semanticzoom",G="win-semanticzoom-zoomedinview",H="win-semanticzoom-zoomedoutview",I="zoomchanged",J=1.05,K=.65,L=.8,M=.2,N=4096,O=.333,P=.333,Q=.333,R=.333,S=1e3*O,T=50,U=.333,V=.333,W="cubic-bezier(0.1,0.9,0.2,1)",X=z.transform,Y=z.transition.scriptName,Z=2,$=.2,_=.45,ab=1e3,bb=50,cb={none:0,zoomedIn:1,zoomedOut:2},db=n._MSPointerEvent.MSPOINTER_TYPE_TOUCH||"touch",eb=n._MSPointerEvent.MSPOINTER_TYPE_PEN||"pen",fb=n._MSPointerEvent.MSPOINTER_TYPE_MOUSE||"mouse",gb={x:0,y:0},hb=b.Class.define(function(b,e){this._disposed=!1;var f=this,g=c.isPhone;this._element=b,this._element.winControl=this,n.addClass(this._element,"win-disposable"),n.addClass(this._element,F),this._element.setAttribute("role","ms-semanticzoomcontainer");var h=this._element.getAttribute("aria-label");if(h||this._element.setAttribute("aria-label",""),e=e||{},this._zoomedOut=!!e.zoomedOut||!!e.initiallyZoomedOut||!1,this._enableButton=!g,g||void 0===e.enableButton||(this._enableButton=!!e.enableButton),this._element.setAttribute("aria-checked",this._zoomedOut.toString()),this._zoomFactor=n._clamp(e.zoomFactor,M,L,K),this.zoomedInItem=e.zoomedInItem,this.zoomedOutItem=e.zoomedOutItem,c.validation&&e._zoomFactor&&e._zoomFactor!==this._zoomFactor)throw new d("WinJS.UI.SemanticZoom.InvalidZoomFactor",A.invalidZoomFactor);this._locked=!!e.locked,this._zoomInProgress=!1,this._isBouncingIn=!1,this._isBouncing=!1,this._zooming=!1,this._aligning=!1,this._gesturing=!1,this._gestureEnding=!1,this._buttonShown=!1,this._shouldFakeTouchCancel="TouchEvent"in a,this._initialize(),this._configure();var i=a.document.body.contains(this._element);n._addInsertedNotifier(this._element),this._element.addEventListener("WinJSNodeInserted",function(a){return i?void(i=!1):void x(a)},!1),this._element.addEventListener("mselementresize",x),n._resizeNotifier.subscribe(this._element,x),new n._MutationObserver(y).observe(this._element,{attributes:!0,attributeFilter:["aria-checked"]}),g||(this._element.addEventListener("wheel",this._onWheel.bind(this),!0),this._element.addEventListener("mousewheel",this._onMouseWheel.bind(this),!0),this._element.addEventListener("keydown",this._onKeyDown.bind(this),!0),n._addEventListener(this._element,"pointerdown",this._onPointerDown.bind(this),!0),n._addEventListener(this._element,"pointermove",this._onPointerMove.bind(this),!0),n._addEventListener(this._element,"pointerout",this._onPointerOut.bind(this),!0),n._addEventListener(this._element,"pointercancel",this._onPointerCancel.bind(this),!0),n._addEventListener(this._element,"pointerup",this._onPointerUp.bind(this),!1),this._hiddenElement.addEventListener("gotpointercapture",this._onGotPointerCapture.bind(this),!1),this._hiddenElement.addEventListener("lostpointercapture",this._onLostPointerCapture.bind(this),!1),this._element.addEventListener("click",this._onClick.bind(this),!0),this._canvasIn.addEventListener(c._browserEventEquivalents.transitionEnd,this._onCanvasTransitionEnd.bind(this),!1),this._canvasOut.addEventListener(c._browserEventEquivalents.transitionEnd,this._onCanvasTransitionEnd.bind(this),!1),this._element.addEventListener("MSContentZoom",this._onMSContentZoom.bind(this),!0),this._resetPointerRecords()),this._onResizeImpl(),l._setOptions(this,e,!0),f._setVisibility()},{element:{get:function(){return this._element}},enableButton:{get:function(){return this._enableButton},set:function(a){var b=!!a;this._enableButton===b||c.isPhone||(this._enableButton=b,b?this._createSemanticZoomButton():this._removeSemanticZoomButton())}},zoomedOut:{get:function(){return this._zoomedOut},set:function(a){this._zoom(!!a,{x:.5*this._sezoClientWidth,y:.5*this._sezoClientHeight},!1,!1,this._zoomedOut&&c.isPhone)}},zoomFactor:{get:function(){return this._zoomFactor},set:function(a){var b=this._zoomFactor,c=n._clamp(a,M,L,K);b!==c&&(this._zoomFactor=c,this._onResize())}},locked:{get:function(){return this._locked},set:function(a){this._locked=!!a,a?this._hideSemanticZoomButton():this._displayButton()}},zoomedInItem:{get:function(){return this._zoomedInItem},set:function(a){this._zoomedInItem=a||f}},zoomedOutItem:{get:function(){return this._zoomedOutItem},set:function(a){this._zoomedOutItem=a||f}},dispose:function(){this._disposed||(this._disposed=!0,n._resizeNotifier.unsubscribe(this._element,x),m._disposeElement(this._elementIn),m._disposeElement(this._elementOut),this._clearTimeout(this._completeZoomTimer),this._clearTimeout(this._TTFFTimer))},forceLayout:function(){this._onResizeImpl()},_initialize:function(){var b=o.children(this._element);this._elementIn=b[0],this._elementOut=b[1],this._elementIn.style.height=this._elementOut.style.height=this._element.offsetHeight+"px",j.processAll(this._elementIn),j.processAll(this._elementOut),this._viewIn=this._elementIn.winControl.zoomableView,this._viewOut=this._elementOut.winControl.zoomableView,this._element.removeChild(this._elementOut),this._element.removeChild(this._elementIn),this._element.innerHTML="",this._cropViewport=a.document.createElement("div"),this._element.appendChild(this._cropViewport),this._viewportIn=a.document.createElement("div"),this._opticalViewportIn=a.document.createElement("div"),this._viewportOut=a.document.createElement("div"),this._opticalViewportOut=a.document.createElement("div"),this._opticalViewportIn.appendChild(this._viewportIn),this._opticalViewportOut.appendChild(this._viewportOut),this._cropViewport.appendChild(this._opticalViewportIn),this._cropViewport.appendChild(this._opticalViewportOut),this._canvasIn=a.document.createElement("div"),this._canvasOut=a.document.createElement("div"),this._viewportIn.appendChild(this._canvasIn),this._viewportOut.appendChild(this._canvasOut),this._canvasIn.appendChild(this._elementIn),this._canvasOut.appendChild(this._elementOut),this._enableButton&&this._createSemanticZoomButton(),this._hiddenElement=a.document.createElement("div"),this._hiddenElement.tabIndex=-1,this._hiddenElement.visibility="hidden",this._hiddenElement.setAttribute("aria-hidden","true"),this._element.appendChild(this._hiddenElement),n.addClass(this._elementIn,G),n.addClass(this._elementOut,H),this._setLayout(this._element,"relative","hidden"),this._setLayout(this._cropViewport,"absolute","hidden"),this._setLayout(this._opticalViewportIn,"absolute","auto"),this._setLayout(this._opticalViewportOut,"absolute","auto"),this._setLayout(this._viewportIn,"absolute","hidden"),this._setLayout(this._viewportOut,"absolute","hidden"),this._setLayout(this._canvasIn,"absolute","hidden"),this._setLayout(this._canvasOut,"absolute","hidden"),this._setupOpticalViewport(this._opticalViewportIn),this._setupOpticalViewport(this._opticalViewportOut),this._viewportIn.style["-ms-overflow-style"]="-ms-autohiding-scrollbar",this._viewportOut.style["-ms-overflow-style"]="-ms-autohiding-scrollbar",this._elementIn.style.position="absolute",this._elementOut.style.position="absolute"},_createSemanticZoomButton:function(){this._sezoButton=a.document.createElement("button"),this._sezoButton.setAttribute("type","button"),this._sezoButton.className=B+" "+C+" win-button",this._sezoButton.tabIndex=-1,this._sezoButton.style.visibility="hidden",this._sezoButton.setAttribute("aria-hidden",!0),this._element.appendChild(this._sezoButton),this._sezoButton.addEventListener("click",this._onSeZoButtonZoomOutClick.bind(this),!1),this._element.addEventListener("scroll",this._onSeZoChildrenScroll.bind(this),!0),n._addEventListener(this._element,"pointermove",this._onPenHover.bind(this),!1)},_removeSemanticZoomButton:function(){this._sezoButton&&(this._element.removeChild(this._sezoButton),this._sezoButton=null)},_configure:function(){var a=this._viewIn.getPanAxis(),b=this._viewOut.getPanAxis(),d=c.isPhone;if(this._pansHorizontallyIn="horizontal"===a||"both"===a,this._pansVerticallyIn="vertical"===a||"both"===a,this._pansHorizontallyOut="horizontal"===b||"both"===b,this._pansVerticallyOut="vertical"===b||"both"===b,!this._zoomInProgress){var e=1/this._zoomFactor-1,f=J-1;this._setLayout(this._elementIn,"absolute","visible"),this._setLayout(this._elementOut,"absolute","visible"),this._viewIn.configureForZoom(!1,!this._zoomedOut,this._zoomFromCurrent.bind(this,!0),e),this._viewOut.configureForZoom(!0,this._zoomedOut,this._zoomFromCurrent.bind(this,!1),f),this._pinching=!1,this._pinchGesture=0,this._canvasLeftIn=0,this._canvasTopIn=0,this._canvasLeftOut=0,this._canvasTopOut=0,d||(this._zoomedOut?w(this._canvasIn,this._zoomFactor):w(this._canvasOut,1/this._zoomFactor));var g=this._opticalViewportIn.style,h=this._opticalViewportOut.style,j=this._canvasIn.style,k=this._canvasOut.style;j.opacity=this._zoomedOut&&!d?0:1,k.opacity=this._zoomedOut?1:0,d&&(j.zIndex=1,k.zIndex=2),i.isAnimationEnabled()&&!d&&(g[z["transition-property"].scriptName]=X.cssName,g[z["transition-duration"].scriptName]="0s",g[z["transition-timing-function"].scriptName]="linear",h[z["transition-property"].scriptName]=X.cssName,h[z["transition-duration"].scriptName]="0s",h[z["transition-timing-function"].scriptName]="linear")}},_onPropertyChanged:function(){var a=this._element.getAttribute("aria-checked"),b="true"===a;this._zoomedOut!==b&&(this.zoomedOut=b)},_onResizeImpl:function(){this._resizing=this._resizing||0,this._resizing++;try{var a=function(a,b,c,d,e){var f=a.style;f.left=b+"px",f.top=c+"px",f.width=d+"px",f.height=e+"px"},b=n._getComputedStyle(this._element,null),c=parseFloat(b.width),d=parseFloat(b.height),e=v(this._element,b.paddingLeft),f=v(this._element,b.paddingRight),g=v(this._element,b.paddingTop),h=v(this._element,b.paddingBottom),i=c-e-f,j=d-g-h,k=1/this._zoomFactor;if(this._viewportWidth===i&&this._viewportHeight===j)return;this._sezoClientHeight=d,this._sezoClientWidth=c,this._viewportWidth=i,this._viewportHeight=j,this._configure();var l=2*k-1,m=Math.min(N,(this._pansHorizontallyIn?l:1)*i),o=Math.min(N,(this._pansVerticallyIn?l:1)*j);this._canvasLeftIn=.5*(m-i),this._canvasTopIn=.5*(o-j),a(this._cropViewport,e,g,i,j),a(this._viewportIn,0,0,i,j),a(this._opticalViewportIn,0,0,i,j),a(this._canvasIn,-this._canvasLeftIn,-this._canvasTopIn,m,o),a(this._elementIn,this._canvasLeftIn,this._canvasTopIn,i,j);var p=2*J-1,q=(this._pansHorizontallyOut?p:1)*i,r=(this._pansVerticallyOut?p:1)*j;this._canvasLeftOut=.5*(q-i),this._canvasTopOut=.5*(r-j),a(this._viewportOut,0,0,i,j),a(this._opticalViewportOut,0,0,i,j),a(this._canvasOut,-this._canvasLeftOut,-this._canvasTopOut,q,r),a(this._elementOut,this._canvasLeftOut,this._canvasTopOut,i,j)}finally{this._resizing--}},_onResize:function(){this._onResizeImpl()},_onMouseMove:function(a){return this._zooming||!this._lastMouseX&&!this._lastMouseY||a.screenX===this._lastMouseX&&a.screenY===this._lastMouseY?(this._lastMouseX=a.screenX,void(this._lastMouseY=a.screenY)):void(Math.abs(a.screenX-this._lastMouseX)<=E&&Math.abs(a.screenY-this._lastMouseY)<=E||(this._lastMouseX=a.screenX,this._lastMouseY=a.screenY,this._displayButton()))},_displayButton:function(){if(p.isHoverable){a.clearTimeout(this._dismissButtonTimer),this._showSemanticZoomButton();var b=this;this._dismissButtonTimer=a.setTimeout(function(){b._hideSemanticZoomButton()},i._animationTimeAdjustment(D))}},_showSemanticZoomButton:function(){this._disposed||this._buttonShown||!this._sezoButton||this._zoomedOut||this._locked||(h.fadeIn(this._sezoButton),this._sezoButton.style.visibility="visible",this._buttonShown=!0)},_hideSemanticZoomButton:function(a){if(!this._disposed&&this._buttonShown&&this._sezoButton){if(a)this._sezoButton.style.visibility="hidden";else{var b=this;h.fadeOut(this._sezoButton).then(function(){b._sezoButton.style.visibility="hidden"})}this._buttonShown=!1}},_onSeZoChildrenScroll:function(a){a.target!==this.element&&this._hideSemanticZoomButton(!0)},_onWheel:function(a){a.ctrlKey&&(this._zoom(a.deltaY>0,this._getPointerLocation(a)),a.stopPropagation(),a.preventDefault())},_onMouseWheel:function(a){a.ctrlKey&&(this._zoom(a.wheelDelta<0,this._getPointerLocation(a)),a.stopPropagation(),a.preventDefault())},_onPenHover:function(a){a.pointerType===eb&&0===a.buttons&&this._displayButton()},_onSeZoButtonZoomOutClick:function(){this._hideSemanticZoomButton(),this._zoom(!0,{x:.5*this._sezoClientWidth,y:.5*this._sezoClientHeight},!1)},_onKeyDown:function(a){var b=!1;if(a.ctrlKey){var c=n.Key;switch(a.keyCode){case c.add:case c.equal:case 61:this._zoom(!1),b=!0;break;case c.subtract:case c.dash:case 173:this._zoom(!0),b=!0}}b&&(a.stopPropagation(),a.preventDefault())},_createPointerRecord:function(a,b){var c=this._getPointerLocation(a),d={};return d.startX=d.currentX=c.x,d.startY=d.currentY=c.y,d.fireCancelOnPinch=b,this._pointerRecords[a.pointerId]=d,this._pointerCount=Object.keys(this._pointerRecords).length,d},_deletePointerRecord:function(a){var b=this._pointerRecords[a];return delete this._pointerRecords[a],this._pointerCount=Object.keys(this._pointerRecords).length,2!==this._pointerCount&&(this._pinching=!1),b},_fakeCancelOnPointer:function(b){var c=a.document.createEvent("UIEvent");c.initUIEvent("touchcancel",!0,!0,a,0),c.touches=b.touches,c.targetTouches=b.targetTouches,c.changedTouches=[b._currentTouch],c._fakedBySemanticZoom=!0,b.target.dispatchEvent(c)},_handlePointerDown:function(a){this._createPointerRecord(a,!1);for(var b=Object.keys(this._pointerRecords),c=0,d=b.length;d>c;c++)try{n._setPointerCapture(this._hiddenElement,b[c]||0)}catch(e){return void this._resetPointerRecords()}a.stopImmediatePropagation(),a.preventDefault()},_handleFirstPointerDown:function(a){this._resetPointerRecords(),this._createPointerRecord(a,this._shouldFakeTouchCancel),this._startedZoomedOut=this._zoomedOut},_onClick:function(a){a.target!==this._element&&this._isBouncing&&a.stopImmediatePropagation()},_onPointerDown:function(a){a.pointerType===db&&(0===this._pointerCount?this._handleFirstPointerDown(a):this._handlePointerDown(a))},_onPointerMove:function(a){function b(a,b,c,d){return Math.sqrt((c-a)*(c-a)+(d-b)*(d-b))}function c(a,b){return{x:.5*(a.currentX+b.currentX)|0,y:.5*(a.currentY+b.currentY)|0}}if(a.pointerType===fb||a.pointerType===eb)return void this._onMouseMove(a);if(a.pointerType===db){var d=this._pointerRecords[a.pointerId],e=this._getPointerLocation(a);if(d){if(d.currentX=e.x,d.currentY=e.y,2===this._pointerCount){this._pinching=!0;var f=Object.keys(this._pointerRecords),h=this._pointerRecords[f[0]],i=this._pointerRecords[f[1]];this._currentMidPoint=c(h,i);var j=b(h.currentX,h.currentY,i.currentX,i.currentY),k=this,l=function(a){var b=a?cb.zoomedOut:cb.zoomedIn,d=a?k._pinchedDirection===cb.zoomedIn&&!k._zoomingOut:k._pinchedDirection===cb.zoomedOut&&k._zoomingOut,e=a?!k._zoomedOut:k._zoomedOut;if(k._pinchedDirection===cb.none)e?(k._isBouncingIn=!1,k._zoom(a,c(h,i),!0),k._pinchedDirection=b):k._isBouncingIn||k._playBounce(!0,c(h,i));else if(d){var f=k._lastPinchDistance/k._lastPinchStartDistance,g=k._lastLastPinchDistance/k._lastPinchDistance;(a&&f>$||!a&&g>_)&&(k._zoom(a,c(h,i),!0),k._pinchedDirection=b)}};this._updatePinchDistanceRecords(j),this._pinchDistanceCount>=Z&&(this._zooming||this._isBouncing||(g("WinJS.UI.SemanticZoom:EndPinchDetection,info"),l(this._lastPinchDirection===cb.zoomedOut)))}else this._pointerCount>2&&this._resetPinchDistanceRecords();this._pointerCount>=2&&(d.fireCancelOnPinch&&(this._fakeCancelOnPointer(a,d),d.fireCancelOnPinch=!1),a.stopImmediatePropagation(),a.preventDefault()),2!==this._pointerCount&&this._isBouncingIn&&this._playBounce(!1)}}},_onPointerOut:function(a){a.pointerType===db&&a.target===this._element&&this._completePointerUp(a,!1)},_onPointerUp:function(a){this._releasePointerCapture(a),this._completePointerUp(a,!0),this._completeZoomingIfTimeout()},_onPointerCancel:function(a){a._fakedBySemanticZoom||(this._releasePointerCapture(a),this._completePointerUp(a,!1),this._completeZoomingIfTimeout())},_onGotPointerCapture:function(a){var b=this._pointerRecords[a.pointerId];b&&(b.dirty=!1)},_onLostPointerCapture:function(a){var b=this._pointerRecords[a.pointerId];if(b){b.dirty=!0;var c=this;k.timeout(bb).then(function(){b.dirty&&c._completePointerUp(a,!1)})}},_onMSContentZoom:function(a){var b=a.target;if(b===this._opticalViewportIn||b===this._opticalViewportOut){var c=b.msContentZoomFactor<.995,d=b.msContentZoomFactor>1.005;!c||this._zoomedOut||this._zoomingOut?d&&(this._zoomedOut||this._zoomingOut)&&(this.zoomedOut=!1):this.zoomedOut=!0}},_updatePinchDistanceRecords:function(a){function b(b){c._lastPinchDirection===b?c._pinchDistanceCount++:(c._pinchGesture++,c._pinchDistanceCount=0,c._lastPinchStartDistance=a),c._lastPinchDirection=b,c._lastPinchDistance=a,c._lastLastPinchDistance=c._lastPinchDistance}var c=this;-1===this._lastPinchDistance?(g("WinJS.UI.SemanticZoom:StartPinchDetection,info"),this._lastPinchDistance=a):this._lastPinchDistance!==a&&b(this._lastPinchDistance>a?cb.zoomedOut:cb.zoomedIn)},_zoomFromCurrent:function(a){this._zoom(a,null,!1,!0)},_zoom:function(a,b,d,e,f){if(g("WinJS.UI.SemanticZoom:StartZoom(zoomOut="+a+"),info"),this._clearTimeout(this._completeZoomTimer),this._clearTimeout(this._TTFFTimer),this._hideSemanticZoomButton(),this._resetPinchDistanceRecords(),!this._locked&&!this._gestureEnding)if(this._zoomInProgress){if(this._gesturing===!d)return;a!==this._zoomingOut&&this._startAnimations(a)}else if(a!==this._zoomedOut){this._zooming=!0,this._aligning=!0,this._gesturing=!!d,b&&(a?this._viewIn:this._viewOut).setCurrentItem(b.x,b.y),this._zoomInProgress=!0,(a?this._opticalViewportOut:this._opticalViewportIn).style.visibility="visible",a&&c.isPhone&&(this._canvasOut.style.opacity=1);var h=this._viewIn.beginZoom(),i=this._viewOut.beginZoom(),j=null;if((h||i)&&c.isPhone&&(j=k.join([h,i])),e&&!f){var l=this;(a?this._viewIn:this._viewOut).getCurrentItem().then(function(b){var c=b.position;l._prepareForZoom(a,{x:l._rtl()?l._sezoClientWidth-c.left-.5*c.width:c.left+.5*c.width,y:c.top+.5*c.height},k.wrap(b),j)})}else this._prepareForZoom(a,b||{},null,j,f)}},_prepareForZoom:function(a,b,c,d,e){function f(a,b){h._canvasIn.style[z["transform-origin"].scriptName]=h._canvasLeftIn+i-a.x+"px "+(h._canvasTopIn+j-a.y)+"px",h._canvasOut.style[z["transform-origin"].scriptName]=h._canvasLeftOut+i-b.x+"px "+(h._canvasTopOut+j-b.y)+"px"}g("WinJS.UI.SemanticZoom:prepareForZoom,StartTM");var h=this,i=b.x,j=b.y;"number"==typeof i&&this._pansHorizontallyIn&&this._pansHorizontallyOut||(i=.5*this._sezoClientWidth),"number"==typeof j&&this._pansVerticallyIn&&this._pansVerticallyOut||(j=.5*this._sezoClientHeight),f(gb,gb),e?this._aligning=!1:this._alignViewsPromise=this._alignViews(a,i,j,c).then(function(){h._aligning=!1,h._gestureEnding=!1,h._alignViewsPromise=null,h._zooming||h._gesturing||h._completeZoom()}),this._zoomingOut=a,n._getComputedStyle(this._canvasIn).opacity,n._getComputedStyle(this._canvasOut).opacity,g("WinJS.UI.SemanticZoom:prepareForZoom,StopTM"),this._startAnimations(a,d)},_alignViews:function(a,b,c,d){var e=1-this._zoomFactor,f=this._rtl(),g=e*(f?this._viewportWidth-b:b),h=e*c,i=this;if(a){var j=d||this._viewIn.getCurrentItem();if(j)return j.then(function(a){var b=a.position,c={left:b.left*i._zoomFactor+g,top:b.top*i._zoomFactor+h,width:b.width*i._zoomFactor,height:b.height*i._zoomFactor};return i._viewOut.positionItem(i._zoomedOutItem(a.item),c)})}else{var l=d||this._viewOut.getCurrentItem();if(l)return l.then(function(a){var b=a.position,c={left:(b.left-g)/i._zoomFactor,top:(b.top-h)/i._zoomFactor,width:b.width/i._zoomFactor,height:b.height/i._zoomFactor};return i._viewIn.positionItem(i._zoomedInItem(a.item),c)})}return new k(function(a){a({x:0,y:0})})},_startAnimations:function(a,b){this._zoomingOut=a;var d=c.isPhone;if(i.isAnimationEnabled()&&!d&&(g("WinJS.UI.SemanticZoom:ZoomAnimation,StartTM"),this._canvasIn.style[Y]=a?r():s(),this._canvasOut.style[Y]=a?s():r()),d||(w(this._canvasIn,a?this._zoomFactor:1),w(this._canvasOut,a?1:1/this._zoomFactor)),this._canvasIn.style.opacity=a&&!d?0:1,(!d||a)&&(this._canvasOut.style.opacity=a?1:0),i.isAnimationEnabled())if(b){var e=this,f=function(){e._canvasIn.style[X.scriptName]="",e._canvasOut.style[X.scriptName]="",e._onZoomAnimationComplete()};b.then(f,f)}else this.setTimeoutAfterTTFF(this._onZoomAnimationComplete.bind(this),i._animationTimeAdjustment(S));else this._zooming=!1,this._canvasIn.style[X.scriptName]="",this._canvasOut.style[X.scriptName]="",this._completeZoom()},_onBounceAnimationComplete:function(){this._isBouncingIn||this._disposed||this._completeZoom()},_onZoomAnimationComplete:function(){g("WinJS.UI.SemanticZoom:ZoomAnimation,StopTM"),this._disposed||(this._zooming=!1,this._aligning||this._gesturing||this._gestureEnding||this._completeZoom())},_onCanvasTransitionEnd:function(a){return this._disposed?void 0:a.target!==this._canvasOut&&a.target!==this._canvasIn||!this._isBouncing?void(a.target===this._canvasIn&&a.propertyName===X.cssName&&this._onZoomAnimationComplete()):void this._onBounceAnimationComplete()},_clearTimeout:function(b){b&&a.clearTimeout(b)},_completePointerUp:function(a,b){if(!this._disposed){var c=a.pointerId,d=this._pointerRecords[c];if(d&&(this._deletePointerRecord(c),this._isBouncingIn&&this._playBounce(!1),b&&this._pinchedDirection!==cb.none&&a.stopImmediatePropagation(),0===this._pointerCount)){if(1===this._pinchGesture&&!this._zooming&&this._lastPinchDirection!==cb.none&&this._pinchDistanceCount<Z)return this._zoom(this._lastPinchDirection===cb.zoomedOut,this._currentMidPoint,!1),this._pinchGesture=0,void this._attemptRecordReset();this._pinchedDirection!==cb.none&&(this._gesturing=!1,this._aligning||this._zooming||this._completeZoom()),this._pinchGesture=0,this._attemptRecordReset()}}},setTimeoutAfterTTFF:function(b,c){var d=this;d._TTFFTimer=a.setTimeout(function(){this._disposed||(d._TTFFTimer=a.setTimeout(b,c))},T)},_completeZoomingIfTimeout:function(){if(0===this._pointerCount){var b=this;(this._zoomInProgress||this._isBouncing)&&(b._completeZoomTimer=a.setTimeout(function(){b._completeZoom()},i._animationTimeAdjustment(ab)))}},_completeZoom:function(){if(!this._disposed){if(this._isBouncing)return this._zoomedOut?this._viewOut.endZoom(!0):this._viewIn.endZoom(!0),void(this._isBouncing=!1);if(this._zoomInProgress){g("WinJS.UI.SemanticZoom:CompleteZoom,info"),this._aligning=!1,this._alignViewsPromise&&this._alignViewsPromise.cancel(),this._clearTimeout(this._completeZoomTimer),this._clearTimeout(this._TTFFTimer),this._gestureEnding=!1,this[this._zoomingOut?"_opticalViewportOut":"_opticalViewportIn"].msContentZoomFactor=1,this._viewIn.endZoom(!this._zoomingOut),this._viewOut.endZoom(this._zoomingOut),this._canvasIn.style.opacity=this._zoomingOut&&!c.isPhone?0:1,this._canvasOut.style.opacity=this._zoomingOut?1:0,this._zoomInProgress=!1;var b=!1;if(this._zoomingOut!==this._zoomedOut&&(this._zoomedOut=!!this._zoomingOut,this._element.setAttribute("aria-checked",this._zoomedOut.toString()),b=!0),this._setVisibility(),b){var d=a.document.createEvent("CustomEvent");d.initCustomEvent(I,!0,!0,this._zoomedOut),this._element.dispatchEvent(d),this._isActive&&n._setActive(this._zoomedOut?this._elementOut:this._elementIn)}g("WinJS.UI.SemanticZoom:CompleteZoom_Custom,info")}}},_isActive:function(){var b=a.document.activeElement;return this._element===b||this._element.contains(b)},_setLayout:function(a,b,c){var d=a.style;d.position=b,d.overflow=c},_setupOpticalViewport:function(a){a.style["-ms-overflow-style"]="none",c.isPhone||(a.style["-ms-content-zooming"]="zoom",a.style["-ms-content-zoom-limit-min"]="99%",a.style["-ms-content-zoom-limit-max"]="101%",a.style["-ms-content-zoom-snap-points"]="snapList(100%)",a.style["-ms-content-zoom-snap-type"]="mandatory")},_setVisibility:function(){function a(a,b){a.style.visibility=b?"visible":"hidden"}a(this._opticalViewportIn,!this._zoomedOut||c.isPhone),a(this._opticalViewportOut,this._zoomedOut),this._opticalViewportIn.setAttribute("aria-hidden",!!this._zoomedOut),this._opticalViewportOut.setAttribute("aria-hidden",!this._zoomedOut)},_resetPointerRecords:function(){this._pinchedDirection=cb.none,this._pointerCount=0,this._pointerRecords={},this._resetPinchDistanceRecords()},_releasePointerCapture:function(a){var b=a.pointerId;try{n._releasePointerCapture(this._hiddenElement,b)}catch(c){}},_attemptRecordReset:function(){this._recordResetPromise&&this._recordResetPromise.cancel();var a=this;this._recordResetPromise=k.timeout(bb).then(function(){0===a._pointerCount&&(a._resetPointerRecords(),a._recordResetPromise=null)})},_resetPinchDistanceRecords:function(){this._lastPinchDirection=cb.none,this._lastPinchDistance=-1,this._lastLastPinchDistance=-1,this._pinchDistanceCount=0,this._currentMidPoint=null},_getPointerLocation:function(a){var b={left:0,top:0};try{b=this._element.getBoundingClientRect()}catch(c){}var d=n._getComputedStyle(this._element,null),e=v(this._element,d.paddingLeft),f=v(this._element,d.paddingTop),g=v(this._element,d.borderLeftWidth);return{x:+a.clientX===a.clientX?a.clientX-b.left-e-g:0,y:+a.clientY===a.clientY?a.clientY-b.top-f-f:0}},_playBounce:function(a,b){if(i.isAnimationEnabled()&&this._isBouncingIn!==a){this._clearTimeout(this._completeZoomTimer),this._clearTimeout(this._TTFFTimer),this._isBouncing=!0,this._isBouncingIn=a,a?this._bounceCenter=b:this._aligned=!0;var c=this._zoomedOut?this._canvasOut:this._canvasIn,d=this._zoomedOut?this._canvasLeftOut:this._canvasLeftIn,e=this._zoomedOut?this._canvasTopOut:this._canvasTopIn;c.style[z["transform-origin"].scriptName]=d+this._bounceCenter.x+"px "+(e+this._bounceCenter.y)+"px",c.style[Y]=a?t():u(),this._zoomedOut?this._viewOut.beginZoom():this._viewIn.beginZoom();var f=a?this._zoomedOut?2-J:J:1;w(c,f),this.setTimeoutAfterTTFF(this._onBounceAnimationComplete.bind(this),i._animationTimeAdjustment(S))}},_rtl:function(){return"rtl"===n._getComputedStyle(this._element,null).direction},_pinching:{set:function(a){this._viewIn.pinching=a,this._viewOut.pinching=a}}});return b.Class.mix(hb,e.createEventProperties("zoomchanged")),b.Class.mix(hb,l.DOMEventMixin),hb})})}),d("WinJS/Controls/Pivot/_Constants",["require","exports"],function(a,b){b._ClassNames={pivot:"win-pivot",pivotCustomHeaders:"win-pivot-customheaders",pivotLocked:"win-pivot-locked",pivotTitle:"win-pivot-title",pivotHeaderArea:"win-pivot-header-area",pivotHeaderLeftCustom:"win-pivot-header-leftcustom",pivotHeaderRightCustom:"win-pivot-header-rightcustom",pivotHeaderItems:"win-pivot-header-items",pivotHeaders:"win-pivot-headers",pivotHeader:"win-pivot-header",pivotHeaderSelected:"win-pivot-header-selected",pivotViewport:"win-pivot-viewport",pivotSurface:"win-pivot-surface",pivotNoSnap:"win-pivot-nosnap",pivotNavButton:"win-pivot-navbutton",pivotNavButtonPrev:"win-pivot-navbutton-prev",pivotNavButtonNext:"win-pivot-navbutton-next",pivotShowNavButtons:"win-pivot-shownavbuttons",pivotInputTypeMouse:"win-pivot-mouse",pivotInputTypeTouch:"win-pivot-touch",pivotDisableContentSwipeNavigation:"win-pivot-disablecontentswipenavigation"}}),d("WinJS/Controls/Pivot/_Item",["exports","../../Core/_Global","../../Core/_Base","../../Core/_BaseUtils","../../Core/_ErrorFromName","../../Core/_Resources","../../ControlProcessor","../../Promise","../../Scheduler","../../Utilities/_Control","../../Utilities/_Dispose","../../Utilities/_ElementUtilities","./_Constants"],function(a,b,c,d,e,f,g,h,i,j,k,l,m){"use strict";c.Namespace._moduleDefine(a,"WinJS.UI",{PivotItem:c.Namespace._lazy(function(){var a={get duplicateConstruction(){return"Invalid argument: Controls may only be instantiated one time for each DOM element"}},f=c.Class.define(function(c,d){if(c=c||b.document.createElement("DIV"),d=d||{},c.winControl)throw new e("WinJS.UI.PivotItem.DuplicateConstruction",a.duplicateConstruction);c.winControl=this,this._element=c,l.addClass(this.element,f._ClassName.pivotItem),l.addClass(this.element,"win-disposable"),this._element.setAttribute("role","tabpanel"),this._contentElement=b.document.createElement("DIV"),this._contentElement.className=f._ClassName.pivotItemContent,c.appendChild(this._contentElement);for(var h=this.element.firstChild;h!==this._contentElement;){var i=h.nextSibling;this._contentElement.appendChild(h),h=i}this._processors=[g.processAll],j.setOptions(this,d)},{element:{get:function(){return this._element}},contentElement:{get:function(){return this._contentElement}},header:{get:function(){return this._header},set:function(a){this._header=a,this._parentPivot&&this._parentPivot._headersState.handleHeaderChanged(this)}},_parentPivot:{get:function(){for(var a=this._element;a&&!l.hasClass(a,m._ClassNames.pivot);)a=a.parentNode;return a&&a.winControl}},_process:function(){var a=this;return this._processors&&this._processors.push(function(){return i.schedulePromiseAboveNormal()}),this._processed=(this._processors||[]).reduce(function(b,c){return b.then(function(){return c(a.contentElement)})},this._processed||h.as()),this._processors=null,this._processed},dispose:function(){this._disposed||(this._disposed=!0,this._processors=null,k.disposeSubTree(this.contentElement))}},{_ClassName:{pivotItem:"win-pivot-item",pivotItemContent:"win-pivot-item-content"},isDeclarativeControlContainer:d.markSupportedForProcessing(function(a,b){b!==g.processAll&&(a._processors=a._processors||[],a._processors.push(b),a._processed&&a._process())})});return f})})}),d("require-style!less/styles-pivot",[],function(){}),d("require-style!less/colors-pivot",[],function(){});var e=this.__extends||function(a,b){function c(){this.constructor=a}for(var d in b)b.hasOwnProperty(d)&&(a[d]=b[d]);c.prototype=b.prototype,a.prototype=new c};d("WinJS/Controls/Pivot/_Pivot",["require","exports","../../Core/_Global","../../Animations","../../BindingList","../../ControlProcessor","../../Promise","../../Scheduler","../../Core/_Base","../../Core/_BaseUtils","../../Utilities/_Control","../../Utilities/_Dispose","../../Utilities/_ElementUtilities","../../Core/_ErrorFromName","../../Core/_Events","../../Utilities/_Hoverable","../../Utilities/_KeyboardBehavior","../../Core/_Log","../../Core/_Resources","../../Utilities/_TabContainer","../../Animations/_TransitionAnimation","../../Core/_WriteProfilerMark","./_Constants"],function(a,b,c,d,f,g,h,i,j,k,l,m,n,o,p,q,r,s,t,u,v,w,x){function y(a){var b=c.document.createTextNode("object"==typeof a.header?JSON.stringify(a.header):""+a.header);return b}q.isHoverable,a(["require-style!less/styles-pivot"]),a(["require-style!less/colors-pivot"]);var z={selectionChanged:"selectionchanged",itemAnimationStart:"itemanimationstart",itemAnimationEnd:"itemanimationend"},A={get duplicateConstruction(){return"Invalid argument: Controls may only be instantiated one time for each DOM element" },get duplicateItem(){return t._getWinJSString("ui/duplicateItem").value},get invalidContent(){return"Invalid content: Pivot content must be made up of PivotItems."},get pivotAriaLabel(){return t._getWinJSString("ui/pivotAriaLabel").value},get pivotViewportAriaLabel(){return t._getWinJSString("ui/pivotViewportAriaLabel").value}},B=!!(n._supportsSnapPoints&&"inertiaDestinationX"in c.MSManipulationEvent.prototype),C=n._MSPointerEvent.MSPOINTER_TYPE_MOUSE||"mouse",D=n._MSPointerEvent.MSPOINTER_TYPE_TOUCH||"touch",E=n.Key,F=250,G=-1,H=function(){function a(a,b){if(void 0===b&&(b={}),this._disposed=!1,this._firstLoad=!0,this._hidePivotItemAnimation=h.wrap(),this._loadPromise=h.wrap(),this._pendingRefresh=!1,this._selectedIndex=0,this._showPivotItemAnimation=h.wrap(),this._slideHeadersAnimation=h.wrap(),a=a||c.document.createElement("DIV"),a.winControl)throw new o("WinJS.UI.Pivot.DuplicateConstruction",A.duplicateConstruction);this._handleItemChanged=this._handleItemChanged.bind(this),this._handleItemInserted=this._handleItemInserted.bind(this),this._handleItemMoved=this._handleItemMoved.bind(this),this._handleItemRemoved=this._handleItemRemoved.bind(this),this._handleItemReload=this._handleItemReload.bind(this),this._resizeHandler=this._resizeHandler.bind(this),this._updatePointerType=this._updatePointerType.bind(this),this._id=a.id||n._uniqueID(a),this._writeProfilerMark("constructor,StartTM"),a.winControl=this,this._element=a,this._element.setAttribute("role","tablist"),this._element.getAttribute("aria-label")||this._element.setAttribute("aria-label",A.pivotAriaLabel),n.addClass(this.element,x._ClassNames.pivot),n.addClass(this.element,"win-disposable"),n._addEventListener(this.element,"pointerenter",this._updatePointerType),n._addEventListener(this.element,"pointerout",this._updatePointerType),this._titleElement=c.document.createElement("DIV"),this._titleElement.style.display="none",n.addClass(this._titleElement,x._ClassNames.pivotTitle),this._element.appendChild(this._titleElement),this._headerAreaElement=c.document.createElement("DIV"),n.addClass(this._headerAreaElement,x._ClassNames.pivotHeaderArea),this._element.appendChild(this._headerAreaElement),this._headerItemsElement=c.document.createElement("DIV"),n.addClass(this._headerItemsElement,x._ClassNames.pivotHeaderItems),this._headerAreaElement.appendChild(this._headerItemsElement),this._headerItemsElWidth=null,this._headersContainerElement=c.document.createElement("DIV"),this._headersContainerElement.tabIndex=0,n.addClass(this._headersContainerElement,x._ClassNames.pivotHeaders),this._headersContainerElement.addEventListener("keydown",this._headersKeyDown.bind(this)),n._addEventListener(this._headersContainerElement,"pointerenter",this._showNavButtons.bind(this)),n._addEventListener(this._headersContainerElement,"pointerout",this._hideNavButtons.bind(this)),this._headerItemsElement.appendChild(this._headersContainerElement),this._element.addEventListener("click",this._elementClickedHandler.bind(this)),this._winKeyboard=new r._WinKeyboard(this._headersContainerElement),this._tabContainer=new u.TabContainer(this._headersContainerElement),this._customLeftHeader=c.document.createElement("DIV"),n.addClass(this._customLeftHeader,x._ClassNames.pivotHeaderLeftCustom),this._headerAreaElement.insertBefore(this._customLeftHeader,this._headerAreaElement.children[0]),this._customRightHeader=c.document.createElement("DIV"),n.addClass(this._customRightHeader,x._ClassNames.pivotHeaderRightCustom),this._headerAreaElement.appendChild(this._customRightHeader),this._viewportElement=c.document.createElement("DIV"),this._viewportElement.className=x._ClassNames.pivotViewport,this._element.appendChild(this._viewportElement),this._viewportElement.setAttribute("role","group"),this._viewportElement.setAttribute("aria-label",A.pivotViewportAriaLabel),this.element.addEventListener("mselementresize",this._resizeHandler),n._resizeNotifier.subscribe(this.element,this._resizeHandler),this._viewportElWidth=null,this._surfaceElement=c.document.createElement("DIV"),this._surfaceElement.className=x._ClassNames.pivotSurface,this._viewportElement.appendChild(this._surfaceElement),this._headersState=new I(this),B?this._viewportElement.addEventListener("MSManipulationStateChanged",this._MSManipulationStateChangedHandler.bind(this)):(n.addClass(this.element,x._ClassNames.pivotNoSnap),n._addEventListener(this._element,"pointerdown",this._elementPointerDownHandler.bind(this)),n._addEventListener(this._element,"pointerup",this._elementPointerUpHandler.bind(this))),this._parse(),b=k._shallowCopy(b),b.items&&(this.items=b.items,delete b.items),l.setOptions(this,b),this._refresh(),this._writeProfilerMark("constructor,StopTM")}return Object.defineProperty(a.prototype,"element",{get:function(){return this._element},enumerable:!0,configurable:!0}),Object.defineProperty(a.prototype,"customLeftHeader",{get:function(){return this._customLeftHeader.firstElementChild},set:function(a){n.empty(this._customLeftHeader),a?(this._customLeftHeader.appendChild(a),n.addClass(this._element,x._ClassNames.pivotCustomHeaders)):this._customLeftHeader.children.length||this._customRightHeader.childNodes.length||n.removeClass(this._element,x._ClassNames.pivotCustomHeaders),this.forceLayout()},enumerable:!0,configurable:!0}),Object.defineProperty(a.prototype,"customRightHeader",{get:function(){return this._customRightHeader.firstElementChild},set:function(a){n.empty(this._customRightHeader),a?(this._customRightHeader.appendChild(a),n.addClass(this._element,x._ClassNames.pivotCustomHeaders)):this._customLeftHeader.children.length||this._customRightHeader.childNodes.length||n.removeClass(this._element,x._ClassNames.pivotCustomHeaders),this.forceLayout()},enumerable:!0,configurable:!0}),Object.defineProperty(a.prototype,"locked",{get:function(){return n.hasClass(this.element,x._ClassNames.pivotLocked)},set:function(a){n[a?"addClass":"removeClass"](this.element,x._ClassNames.pivotLocked),a&&this._hideNavButtons()},enumerable:!0,configurable:!0}),Object.defineProperty(a.prototype,"items",{get:function(){return this._pendingItems?this._pendingItems:this._items},set:function(a){this._pendingItems=a,this._refresh()},enumerable:!0,configurable:!0}),Object.defineProperty(a.prototype,"title",{get:function(){return this._titleElement.textContent},set:function(a){a?(this._titleElement.style.display="block",this._titleElement.textContent=a):(this._titleElement.style.display="none",this._titleElement.textContent="")},enumerable:!0,configurable:!0}),Object.defineProperty(a.prototype,"selectedIndex",{get:function(){return 0===this.items.length?-1:this._selectedIndex},set:function(a){a>=0&&a<this.items.length&&(this._pendingRefresh?this._selectedIndex=a:this._loadItem(a))},enumerable:!0,configurable:!0}),Object.defineProperty(a.prototype,"selectedItem",{get:function(){return this.items.getAt(this.selectedIndex)},set:function(a){var b=this.items.indexOf(a);-1!==b&&(this.selectedIndex=b)},enumerable:!0,configurable:!0}),a.prototype.dispose=function(){if(!this._disposed){this._disposed=!0,this._updateEvents(this._items,null),n._resizeNotifier.unsubscribe(this.element,this._resizeHandler),this._headersState.exit(),m._disposeElement(this._headersContainerElement);for(var a=0,b=this.items.length;b>a;a++)this.items.getAt(a).dispose()}},a.prototype.forceLayout=function(){this._disposed||this._resizeHandler()},a.prototype._applyProperties=function(){function a(a){for(var b=0,c=a.items.length;c>b;b++){var d=a._items.getAt(b);if(d.element.parentNode===a._surfaceElement)throw new o("WinJS.UI.Pivot.DuplicateItem",A.duplicateItem);d.element.style.display="none",a._surfaceElement.appendChild(d.element)}}if(!this._disposed){if(this._pendingItems){for(this._updateEvents(this._items,this._pendingItems),this._items=this._pendingItems,this._pendingItems=null;this.element.firstElementChild!==this._titleElement;){var b=this.element.firstElementChild;b.parentNode.removeChild(b)}n.empty(this._surfaceElement)}a(this),this._rtl="rtl"===n._getComputedStyle(this._element,null).direction,this._headersState.refreshHeadersState(!0),this._pendingRefresh=!1,this._firstLoad=!0,this.selectedIndex=this._selectedIndex,this._firstLoad=!1,this._recenterViewport()}},a.prototype._parse=function(){for(var a=[],b=this.element.firstElementChild;b!==this._titleElement;){g.processAll(b);var c=b.winControl;if(!c)throw new o("WinJS.UI.Pivot.InvalidContent",A.invalidContent);a.push(c);var d=b.nextElementSibling;b=d}this.items=new f.List(a)},a.prototype._refresh=function(){this._pendingRefresh||(this._pendingRefresh=!0,i.schedule(this._applyProperties.bind(this),i.Priority.high))},a.prototype._resizeHandler=function(){if(!this._disposed&&!this._pendingRefresh){var a=this._getViewportWidth(),b=this._getHeaderItemsWidth();this._invalidateMeasures(),a!==this._getViewportWidth()||b!==this._getHeaderItemsWidth()?(s.log&&s.log("_resizeHandler, viewport from:"+a+" to: "+this._getViewportWidth()),s.log&&s.log("_resizeHandler, headers from:"+b+" to: "+this._getHeaderItemsWidth()),this._hidePivotItemAnimation&&this._hidePivotItemAnimation.cancel(),this._showPivotItemAnimation&&this._showPivotItemAnimation.cancel(),this._slideHeadersAnimation&&this._slideHeadersAnimation.cancel(),this._recenterViewport(),this._headersState.handleResize()):s.log&&s.log("_resizeHandler worthless resize")}},a.prototype._activateHeader=function(a){if(!this.locked){var b=this._items.indexOf(a._item);b!==this.selectedIndex?this._headersState.activateHeader(a):n._setActiveFirstFocusableElement(this.selectedItem.element)}},a.prototype._goNext=function(){this.selectedIndex<this._items.length-1?this.selectedIndex++:this.selectedIndex=0},a.prototype._goPrevious=function(){this._animateToPrevious=!0,this.selectedIndex>0?this.selectedIndex--:this.selectedIndex=this._items.length-1,this._animateToPrevious=!1},a.prototype._loadItem=function(a){var b=this;this._rtl="rtl"===n._getComputedStyle(this._element,null).direction,this._hidePivotItemAnimation.cancel(),this._showPivotItemAnimation.cancel(),this._slideHeadersAnimation.cancel();var c=this._animateToPrevious,d=this._items.getAt(a),e=this._firstLoad,f=this._loadPromise=this._loadPromise.then(function(){var g=b._items.getAt(b.selectedIndex);g&&b._hidePivotItem(g.element,c,e);var i=b._selectedIndex;b._selectedIndex=a;var j={index:a,direction:c?"backwards":"forward",item:d};return b._fireEvent(z.selectionChanged,!0,!1,j),b._headersState.handleNavigation(c,a,i),h.join([d._process(),b._hidePivotItemAnimation,h.timeout()]).then(function(){return b._disposed||b._loadPromise!==f?void 0:(b._recenterViewport(),b._showPivotItem(d.element,c,e).then(function(){b._disposed||b._loadPromise!==f||(b._loadPromise=h.wrap(),b._writeProfilerMark("itemAnimationStop,info"),b._fireEvent(z.itemAnimationEnd,!0,!1,null))}))})})},a.prototype._recenterViewport=function(){n.setScrollPosition(this._viewportElement,{scrollLeft:this._getViewportWidth()}),this.selectedItem&&(this.selectedItem.element.style[this._getDirectionAccessor()]=this._getViewportWidth()+"px")},a.prototype._fireEvent=function(a,b,d,e){var f=c.document.createEvent("CustomEvent");return f.initCustomEvent(a,!!b,!!d,e),this.element.dispatchEvent(f)},a.prototype._getDirectionAccessor=function(){return this._rtl?"right":"left"},a.prototype._getHeaderItemsWidth=function(){return this._headerItemsElWidth||(this._headerItemsElWidth=parseFloat(n._getComputedStyle(this._headerItemsElement).width)),this._headerItemsElWidth||G},a.prototype._getViewportWidth=function(){return this._viewportElWidth||(this._viewportElWidth=parseFloat(n._getComputedStyle(this._viewportElement).width),B&&(this._viewportElement.style[k._browserStyleEquivalents["scroll-snap-points-x"].scriptName]="snapInterval(0%, "+Math.ceil(this._viewportElWidth)+"px)")),this._viewportElWidth||G},a.prototype._invalidateMeasures=function(){this._viewportElWidth=this._headerItemsElWidth=null},a.prototype._updateEvents=function(a,b){a&&(a.removeEventListener("itemchanged",this._handleItemChanged),a.removeEventListener("iteminserted",this._handleItemInserted),a.removeEventListener("itemmoved",this._handleItemMoved),a.removeEventListener("itemremoved",this._handleItemRemoved),a.removeEventListener("reload",this._handleItemReload)),b&&(b.addEventListener("itemchanged",this._handleItemChanged),b.addEventListener("iteminserted",this._handleItemInserted),b.addEventListener("itemmoved",this._handleItemMoved),b.addEventListener("itemremoved",this._handleItemRemoved),b.addEventListener("reload",this._handleItemReload))},a.prototype._writeProfilerMark=function(a){var b="WinJS.UI.Pivot:"+this._id+":"+a;w(b),s.log&&s.log(b,null,"pivotprofiler")},a.prototype._handleItemChanged=function(a){if(!this._pendingItems){var b=a.detail.index,c=a.detail.newValue,d=a.detail.oldValue;if(c.element!==d.element){if(c.element.parentNode===this._surfaceElement)throw new o("WinJS.UI.Pivot.DuplicateItem",A.duplicateItem);c.element.style.display="none",this._surfaceElement.insertBefore(c.element,d.element),this._surfaceElement.removeChild(d.element),b===this.selectedIndex&&(this.selectedIndex=b)}this._headersState.render(),this._headersState.refreshHeadersState(!0)}},a.prototype._handleItemInserted=function(a){if(!this._pendingItems){var b=a.detail.index,c=a.detail.value;if(c.element.parentNode===this._surfaceElement)throw new o("WinJS.UI.Pivot.DuplicateItem",A.duplicateItem);c.element.style.display="none",b<this.items.length-1?this._surfaceElement.insertBefore(c.element,this.items.getAt(b+1).element):this._surfaceElement.appendChild(c.element),b<=this.selectedIndex&&this._selectedIndex++,1===this._items.length&&(this.selectedIndex=0),this._headersState.render(),this._headersState.refreshHeadersState(!0)}},a.prototype._handleItemMoved=function(a){if(!this._pendingItems){var b=a.detail.oldIndex,c=a.detail.newIndex,d=a.detail.value;c<this.items.length-1?this._surfaceElement.insertBefore(d.element,this.items.getAt(c+1).element):this._surfaceElement.appendChild(d.element),b<this.selectedIndex&&c>=this.selectedIndex?this._selectedIndex--:c>this.selectedIndex&&b<=this.selectedIndex?this._selectedIndex++:b===this.selectedIndex&&(this.selectedIndex=this.selectedIndex),this._headersState.render(),this._headersState.refreshHeadersState(!0)}},a.prototype._handleItemReload=function(){this.items=this.items},a.prototype._handleItemRemoved=function(a){if(!this._pendingItems){var b=a.detail.value,c=a.detail.index;this._surfaceElement.removeChild(b.element),c<this.selectedIndex?this._selectedIndex--:c===this._selectedIndex&&(this.selectedIndex=Math.min(this.items.length-1,this._selectedIndex)),this._headersState.render(),this._headersState.refreshHeadersState(!0)}},a.prototype._elementClickedHandler=function(a){if(this.locked||this._navigationHandled)return void(this._navigationHandled=!1);var b,c=a.target;if(n.hasClass(c,x._ClassNames.pivotHeader))b=c;else{var d=!1,e=n._elementsFromPoint(a.clientX,a.clientY);if(e&&e[0]===this._viewportElement)for(var f=0,g=e.length;g>f;f++)e[f]===c&&(d=!0),n.hasClass(e[f],x._ClassNames.pivotHeader)&&(b=e[f]);d||(b=null)}b&&this._activateHeader(b)},a.prototype._elementPointerDownHandler=function(a){if(!B){var b=a.target;this._elementPointerDownPoint={x:a.clientX,y:a.clientY,type:a.pointerType||"mouse",time:Date.now(),inHeaders:this._headersContainerElement.contains(b)}}},a.prototype._elementPointerUpHandler=function(a){if(!this._elementPointerDownPoint||this.locked)return void(this._elementPointerDownPoint=null);var b=a.target,c=32,d=.4,e=Math.abs(a.clientY-this._elementPointerDownPoint.y),f=a.clientX-this._elementPointerDownPoint.x,g=Math.abs(f*d),h=g>e&&Math.abs(f)>c&&(!n._supportsTouchDetection||this._elementPointerDownPoint.type===a.pointerType&&a.pointerType===D)&&(!this.element.classList.contains(x._ClassNames.pivotDisableContentSwipeNavigation)||this._elementPointerDownPoint.inHeaders&&this._headersContainerElement.contains(b));if(this._navigationHandled=!1,h){var i=Date.now()-this._elementPointerDownPoint.time;f*=Math.max(1,Math.pow(350/i,2)),f=this._rtl?-f:f;var j=this._getViewportWidth()/4;-j>f?(this._goNext(),this._navigationHandled=!0):f>j&&(this._goPrevious(),this._navigationHandled=!0)}if(!this._navigationHandled){for(;null!==b&&!n.hasClass(b,x._ClassNames.pivotHeader);)b=b.parentElement;null!==b&&(this._activateHeader(b),this._navigationHandled=!0)}this._elementPointerDownPoint=null},a.prototype._headersKeyDown=function(a){this.locked||(a.keyCode===E.leftArrow||a.keyCode===E.pageUp?(this._rtl?this._goNext():this._goPrevious(),a.preventDefault()):(a.keyCode===E.rightArrow||a.keyCode===E.pageDown)&&(this._rtl?this._goPrevious():this._goNext(),a.preventDefault()))},a.prototype._hideNavButtons=function(a){a&&this._headersContainerElement.contains(a.relatedTarget)||n.removeClass(this._headersContainerElement,x._ClassNames.pivotShowNavButtons)},a.prototype._hidePivotItem=function(a,b,c){return c||!v.isAnimationEnabled()?(a.style.display="none",this._hidePivotItemAnimation=h.wrap(),this._hidePivotItemAnimation):(this._hidePivotItemAnimation=v.executeTransition(a,{property:"opacity",delay:0,duration:67,timing:"linear",from:"",to:"0"}).then(function(){a.style.display="none"}),this._hidePivotItemAnimation)},a.prototype._MSManipulationStateChangedHandler=function(a){if(a.target===this._viewportElement&&a.currentState===n._MSManipulationEvent.MS_MANIPULATION_STATE_INERTIA){var b=a.inertiaDestinationX-this._getViewportWidth();b>0?this._goNext():0>b&&this._goPrevious()}},a.prototype._updatePointerType=function(a){this._pointerType!==(a.pointerType||C)&&(this._pointerType=a.pointerType||C,this._pointerType===D?(n.removeClass(this.element,x._ClassNames.pivotInputTypeMouse),n.addClass(this.element,x._ClassNames.pivotInputTypeTouch),this._hideNavButtons()):(n.removeClass(this.element,x._ClassNames.pivotInputTypeTouch),n.addClass(this.element,x._ClassNames.pivotInputTypeMouse)))},a.prototype._showNavButtons=function(a){this.locked||a&&a.pointerType===D||n.addClass(this._headersContainerElement,x._ClassNames.pivotShowNavButtons)},a.prototype._showPivotItem=function(a,b,c){function e(a){var b=a.getBoundingClientRect();return b.top<g.bottom&&b.bottom>g.top}if(this._writeProfilerMark("itemAnimationStart,info"),this._fireEvent(z.itemAnimationStart,!0,!1,null),a.style.display="",c||!v.isAnimationEnabled())return a.style.opacity="",this._showPivotItemAnimation=h.wrap(),this._showPivotItemAnimation;var f=this._rtl?!b:b,g=this._viewportElement.getBoundingClientRect(),i=a.querySelectorAll(".win-pivot-slide1"),j=a.querySelectorAll(".win-pivot-slide2"),l=a.querySelectorAll(".win-pivot-slide3");return i=Array.prototype.filter.call(i,e),j=Array.prototype.filter.call(j,e),l=Array.prototype.filter.call(l,e),this._showPivotItemAnimation=h.join([v.executeTransition(a,{property:"opacity",delay:0,duration:333,timing:"cubic-bezier(0.1,0.9,0.2,1)",from:"0",to:""}),v.executeTransition(a,{property:k._browserStyleEquivalents.transform.cssName,delay:0,duration:767,timing:"cubic-bezier(0.1,0.9,0.2,1)",from:"translateX("+(f?"-20px":"20px")+")",to:""}),d[f?"slideRightIn":"slideLeftIn"](null,i,j,l)]),this._showPivotItemAnimation},a.supportedForProcessing=!0,a._ClassNames=x._ClassNames,a._EventNames=z,a}();b.Pivot=H;var I=function(){function a(a){this.pivot=a}return a.prototype.exit=function(){},a.prototype.render=function(){},a.prototype.activateHeader=function(){},a.prototype.handleNavigation=function(){},a.prototype.handleResize=function(){},a.prototype.handleHeaderChanged=function(){},a.prototype.getCumulativeHeaderWidth=function(b){if(0===b)return 0;for(var c=this.pivot._headersContainerElement.children.length,d=0;b>d;d++){var e=this.renderHeader(d,!1);this.pivot._headersContainerElement.appendChild(e)}var f=0,g=this.pivot._rtl?this.pivot._headersContainerElement.lastElementChild:this.pivot._headersContainerElement.children[c],h=this.pivot._rtl?this.pivot._headersContainerElement.children[c]:this.pivot._headersContainerElement.lastElementChild;f=h.offsetLeft+h.offsetWidth-g.offsetLeft,f+=2*a.headerHorizontalMargin;for(var d=0;b>d;d++)this.pivot._headersContainerElement.removeChild(this.pivot._headersContainerElement.lastElementChild);return f},a.prototype.refreshHeadersState=function(a){a&&(this.cachedHeaderWidth=0);var b=this.cachedHeaderWidth||this.getCumulativeHeaderWidth(this.pivot.items.length);this.cachedHeaderWidth=b,b>this.pivot._getHeaderItemsWidth()&&!(this.pivot._headersState instanceof K)?(this.exit(),this.pivot._headersState=new K(this.pivot)):b<=this.pivot._getHeaderItemsWidth()&&!(this.pivot._headersState instanceof J)&&(this.exit(),this.pivot._headersState=new J(this.pivot))},a.prototype.renderHeader=function(b,d){function e(){f.pivot._disposed||f.pivot._headersContainerElement.contains(i)&&b!==f.pivot.selectedIndex&&"true"===i.getAttribute("aria-selected")&&(f.pivot.selectedIndex=b)}var f=this,g=n._syncRenderer(y),h=this.pivot.items.getAt(b),i=c.document.createElement("BUTTON");return i.setAttribute("type","button"),i.style.marginLeft=i.style.marginRight=a.headerHorizontalMargin+"px",n.addClass(i,x._ClassNames.pivotHeader),i._item=h,i._pivotItemIndex=b,g(h,i),d&&(i.setAttribute("aria-selected",""+(b===this.pivot.selectedIndex)),i.setAttribute("role","tab"),new n._MutationObserver(e).observe(i,{attributes:!0,attributeFilter:["aria-selected"]})),i},a.prototype.updateHeader=function(a){var b=this.pivot.items.indexOf(a),c=this.pivot._headersContainerElement.children[b];c.innerHTML="";var d=n._syncRenderer(y);d(a,c)},a.prototype.setActiveHeader=function(a){var b=!1,d=this.pivot._headersContainerElement.querySelector("."+x._ClassNames.pivotHeaderSelected);d&&(d.classList.remove(x._ClassNames.pivotHeaderSelected),d.setAttribute("aria-selected","false"),b=this.pivot._headersContainerElement.contains(c.document.activeElement)),a.classList.add(x._ClassNames.pivotHeaderSelected),a.setAttribute("aria-selected","true"),b&&this.pivot._headersContainerElement.focus()},a.headersContainerLeadingMargin=12,a.headerHorizontalMargin=12,a}(),J=function(a){function b(b){if(a.call(this,b),this._firstRender=!0,this._transitionAnimation=h.wrap(),b._headersContainerElement.children.length&&v.isAnimationEnabled()){var c=b._headersContainerElement.querySelector("."+x._ClassNames.pivotHeaderSelected),d=0,e=0;b._rtl?(d=c.offsetLeft+c.offsetWidth+I.headerHorizontalMargin,e=b._getHeaderItemsWidth()-this.getCumulativeHeaderWidth(b.selectedIndex)-I.headersContainerLeadingMargin,e+=parseFloat(b._headersContainerElement.style.marginLeft)):(d=c.offsetLeft,d+=parseFloat(b._headersContainerElement.style.marginLeft),e=this.getCumulativeHeaderWidth(b.selectedIndex)+I.headersContainerLeadingMargin+I.headerHorizontalMargin);var f=d-e;this.render();for(var g=k._browserStyleEquivalents.transform.cssName,i="translateX("+f+"px)",j=0,l=b._headersContainerElement.children.length;l>j;j++)b._headersContainerElement.children[j].style[g]=i;this._transitionAnimation=v.executeTransition(b._headersContainerElement.querySelectorAll("."+x._ClassNames.pivotHeader),{property:g,delay:0,duration:F,timing:"ease-out",to:""})}else this.render()}return e(b,a),b.prototype.exit=function(){this._transitionAnimation.cancel()},b.prototype.render=function(){var a=this.pivot;if(!a._pendingRefresh&&a._items){if(m._disposeElement(a._headersContainerElement),n.empty(a._headersContainerElement),a._rtl?(a._headersContainerElement.style.marginLeft="0px",a._headersContainerElement.style.marginRight=I.headersContainerLeadingMargin+"px"):(a._headersContainerElement.style.marginLeft=I.headersContainerLeadingMargin+"px",a._headersContainerElement.style.marginRight="0px"),a._viewportElement.style.overflow=1===a.items.length?"hidden":"",a.items.length){for(var b=0;b<a.items.length;b++){var c=this.renderHeader(b,!0);a._headersContainerElement.appendChild(c),b===a.selectedIndex&&c.classList.add(x._ClassNames.pivotHeaderSelected)}a._tabContainer.childFocus=a._headersContainerElement.children[a.selectedIndex]}this._firstRender=!1}},b.prototype.activateHeader=function(a){this.setActiveHeader(a),this.pivot._animateToPrevious=a._pivotItemIndex<this.pivot.selectedIndex,this.pivot.selectedIndex=a._pivotItemIndex,this.pivot._animateToPrevious=!1},b.prototype.handleNavigation=function(a,b){this._firstRender&&this.render(),this.setActiveHeader(this.pivot._headersContainerElement.children[b]),this.pivot._tabContainer.childFocus=this.pivot._headersContainerElement.children[b]},b.prototype.handleResize=function(){this.refreshHeadersState(!1)},b.prototype.handleHeaderChanged=function(a){this.updateHeader(a),this.refreshHeadersState(!0)},b}(I),K=function(a){function b(b){if(a.call(this,b),this._blocked=!1,this._firstRender=!0,this._transitionAnimation=h.wrap(),b._slideHeadersAnimation=h.wrap(),b._headersContainerElement.children.length&&v.isAnimationEnabled()){var c=this,d=function(){c._blocked=!1,c.render()};this._blocked=!0;var e=b._headersContainerElement.querySelector("."+x._ClassNames.pivotHeaderSelected),f=0,g=0;b._rtl?(f=b._getHeaderItemsWidth()-I.headersContainerLeadingMargin,g=e.offsetLeft,g+=I.headerHorizontalMargin,g+=e.offsetWidth,g+=parseFloat(b._headersContainerElement.style.marginLeft)):(f=I.headersContainerLeadingMargin,g=e.offsetLeft,g-=I.headerHorizontalMargin,g+=parseFloat(b._headersContainerElement.style.marginLeft));for(var i=f-g,j=0;j<b.selectedIndex;j++)b._headersContainerElement.appendChild(b._headersContainerElement.children[j].cloneNode(!0));var l=k._browserStyleEquivalents.transform.cssName;this._transitionAnimation=v.executeTransition(b._headersContainerElement.querySelectorAll("."+x._ClassNames.pivotHeader),{property:l,delay:0,duration:F,timing:"ease-out",to:"translateX("+i+"px)"}).then(d,d)}else this.render()}return e(b,a),b.prototype.exit=function(){this._transitionAnimation.cancel(),this.pivot._slideHeadersAnimation.cancel()},b.prototype.render=function(a){var b=this.pivot;if(!this._blocked&&!b._pendingRefresh&&b._items){var d=b._headersContainerElement.contains(c.document.activeElement);if(m._disposeElement(b._headersContainerElement),n.empty(b._headersContainerElement),1===b._items.length){var e=this.renderHeader(0,!0);e.classList.add(x._ClassNames.pivotHeaderSelected),b._headersContainerElement.appendChild(e),b._viewportElement.style.overflow="hidden",b._headersContainerElement.style.marginLeft="0px",b._headersContainerElement.style.marginRight="0px"}else if(b._items.length>1){var f=b._items.length+(a?2:1),g=.8*b._getHeaderItemsWidth(),h=b.selectedIndex-1;b._viewportElement.style.overflow&&(b._viewportElement.style.overflow="");for(var i=0;f>i;i++){-1===h?h=b._items.length-1:h===b._items.length&&(h=0);var e=this.renderHeader(h,!0);b._headersContainerElement.appendChild(e),e.offsetWidth>g&&(e.style.textOverflow="ellipsis",e.style.width=g+"px"),h===b.selectedIndex&&e.classList.add(x._ClassNames.pivotHeaderSelected),h++}if(!b._firstLoad&&!this._firstRender){var j,l;a?(j="",l="0"):(j="0",l="");var o=b._headersContainerElement.children[f-1];o.style.opacity=j;var p=.167;o.style[k._browserStyleEquivalents.transition.scriptName]="opacity "+v._animationTimeAdjustment(p)+"s",n._getComputedStyle(o).opacity,o.style.opacity=l}b._headersContainerElement.children[0].setAttribute("aria-hidden","true"),b._headersContainerElement.style.marginLeft="0px",b._headersContainerElement.style.marginRight="0px";var q=b._rtl?"marginRight":"marginLeft",r=b._headersContainerElement.children[0],s=n.getTotalWidth(r)-I.headersContainerLeadingMargin;if(r!==b._headersContainerElement.children[0])return;b._headersContainerElement.style[q]=-1*s+"px",b._prevButton=c.document.createElement("button"),b._prevButton.setAttribute("type","button"),n.addClass(b._prevButton,x._ClassNames.pivotNavButton),n.addClass(b._prevButton,x._ClassNames.pivotNavButtonPrev),b._prevButton.addEventListener("click",function(){b.locked||(b._rtl?b._goNext():b._goPrevious())}),b._headersContainerElement.appendChild(b._prevButton),b._prevButton.style.left=b._rtl?"0px":s+"px",b._nextButton=c.document.createElement("button"),b._nextButton.setAttribute("type","button"),n.addClass(b._nextButton,x._ClassNames.pivotNavButton),n.addClass(b._nextButton,x._ClassNames.pivotNavButtonNext),b._nextButton.addEventListener("click",function(){b.locked||(b._rtl?b._goPrevious():b._goNext())}),b._headersContainerElement.appendChild(b._nextButton),b._nextButton.style.right=b._rtl?s+"px":"0px"}var t=b._headersContainerElement.children.length>1?1:0;b._tabContainer.childFocus=b._headersContainerElement.children[t],d&&b._headersContainerElement.focus(),this._firstRender=!1}},b.prototype.activateHeader=function(a){a.previousSibling&&(this.pivot.selectedIndex=a._pivotItemIndex)},b.prototype.handleNavigation=function(a,b,c){function d(a){return j?a.offsetParent.offsetWidth-a.offsetLeft-a.offsetWidth:a.offsetLeft}function e(){g._disposed||(f.render(a),g._slideHeadersAnimation=h.wrap())}var f=this,g=this.pivot;if(this._blocked||0>b||g._firstLoad)return void this.render(a);var i;if(a?i=g._headersContainerElement.children[0]:(c>b&&(b+=g._items.length),i=g._headersContainerElement.children[1+b-c]),!i)return void this.render(a);n.removeClass(g._headersContainerElement.children[1],x._ClassNames.pivotHeaderSelected),n.addClass(i,x._ClassNames.pivotHeaderSelected);var j=g._rtl,l=d(g._headersContainerElement.children[1])-d(i);j&&(l*=-1);var m;m=v.isAnimationEnabled()?v.executeTransition(g._headersContainerElement.querySelectorAll("."+x._ClassNames.pivotHeader),{property:k._browserStyleEquivalents.transform.cssName,delay:0,duration:F,timing:"ease-out",to:"translateX("+l+"px)"}):h.wrap(),g._slideHeadersAnimation=m.then(e,e)},b.prototype.handleResize=function(){this.refreshHeadersState(!1)},b.prototype.handleHeaderChanged=function(){this.render(),this.refreshHeadersState(!0)},b}(I);j.Class.mix(H,p.createEventProperties(z.itemAnimationEnd,z.itemAnimationStart,z.selectionChanged)),j.Class.mix(H,l.DOMEventMixin)}),d("WinJS/Controls/Pivot",["require","exports","../Core/_Base","./Pivot/_Item"],function(a,b,c,d){d.touch;var e=null;c.Namespace.define("WinJS.UI",{Pivot:{get:function(){return e||a(["./Pivot/_Pivot"],function(a){e=a}),e.Pivot}}})}),d("WinJS/Controls/Hub/_Section",["exports","../../Core/_Global","../../Core/_Base","../../Core/_BaseUtils","../../Core/_ErrorFromName","../../Core/_Resources","../../ControlProcessor","../../Promise","../../Utilities/_Control","../../Utilities/_Dispose","../../Utilities/_ElementUtilities","../../Utilities/_KeyboardBehavior"],function(a,b,c,d,e,f,g,h,i,j,k,l){"use strict";c.Namespace._moduleDefine(a,"WinJS.UI",{HubSection:c.Namespace._lazy(function(){var a={get duplicateConstruction(){return"Invalid argument: Controls may only be instantiated one time for each DOM element"},get seeMore(){return f._getWinJSString("ui/seeMore").value}},m=c.Class.define(function(c,d){if(c=c||b.document.createElement("DIV"),d=d||{},c.winControl)throw new e("WinJS.UI.HubSection.DuplicateConstruction",a.duplicateConstruction);c.winControl=this,this._element=c,k.addClass(this.element,m._ClassName.hubSection),k.addClass(this.element,"win-disposable"),this._headerElement=b.document.createElement("DIV"),this._headerElement.className=m._ClassName.hubSectionHeader,this._headerElement.innerHTML='<button type="button" role="link" class="'+m._ClassName.hubSectionInteractive+" "+m._ClassName.hubSectionHeaderTabStop+'"><div class="'+m._ClassName.hubSectionHeaderWrapper+'" tabindex="-1"><h2 class="win-type-subheader '+m._ClassName.hubSectionHeaderContent+'"></h2><span class="'+m._ClassName.hubSectionHeaderChevron+' win-type-body">'+a.seeMore+"</span></div></button>",this._headerTabStopElement=this._headerElement.firstElementChild,this._headerWrapperElement=this._headerTabStopElement.firstElementChild,this._headerContentElement=this._headerWrapperElement.firstElementChild,this._headerChevronElement=this._headerWrapperElement.lastElementChild,c.appendChild(this._headerElement),this._winKeyboard=new l._WinKeyboard(this._headerElement),this._contentElement=b.document.createElement("DIV"),this._contentElement.className=m._ClassName.hubSectionContent,this._contentElement.style.visibility="hidden",c.appendChild(this._contentElement); for(var f=this.element.firstChild;f!==this._headerElement;){var h=f.nextSibling;this._contentElement.appendChild(f),f=h}this._processors=[g.processAll],i.setOptions(this,d)},{element:{get:function(){return this._element}},isHeaderStatic:{get:function(){return this._isHeaderStatic},set:function(a){this._isHeaderStatic=a,this._isHeaderStatic?(this._headerTabStopElement.setAttribute("role","heading"),k.removeClass(this._headerTabStopElement,m._ClassName.hubSectionInteractive)):(this._headerTabStopElement.setAttribute("role","link"),k.addClass(this._headerTabStopElement,m._ClassName.hubSectionInteractive))}},contentElement:{get:function(){return this._contentElement}},header:{get:function(){return this._header},set:function(a){this._header=a,this._renderHeader()}},_setHeaderTemplate:function(a){this._template=k._syncRenderer(a),this._renderHeader()},_renderHeader:function(){this._template&&(j._disposeElement(this._headerContentElement),k.empty(this._headerContentElement),this._template(this,this._headerContentElement))},_process:function(){var a=this;return this._processed=(this._processors||[]).reduce(function(b,c){return b.then(function(){return c(a.contentElement)})},this._processed||h.as()),this._processors=null,this._processed},dispose:function(){this._disposed||(this._disposed=!0,this._processors=null,j._disposeElement(this._headerContentElement),j.disposeSubTree(this.contentElement))}},{_ClassName:{hubSection:"win-hub-section",hubSectionHeader:"win-hub-section-header",hubSectionHeaderTabStop:"win-hub-section-header-tabstop",hubSectionHeaderWrapper:"win-hub-section-header-wrapper",hubSectionInteractive:"win-hub-section-header-interactive",hubSectionHeaderContent:"win-hub-section-header-content",hubSectionHeaderChevron:"win-hub-section-header-chevron",hubSectionContent:"win-hub-section-content"},isDeclarativeControlContainer:d.markSupportedForProcessing(function(a,b){b!==g.processAll&&(a._processors=a._processors||[],a._processors.push(b),a._processed&&a._process())})});return m})})}),d("require-style!less/styles-hub",[],function(){}),d("require-style!less/colors-hub",[],function(){}),d("WinJS/Controls/Hub",["../Core/_Global","../Core/_Base","../Core/_BaseUtils","../Core/_ErrorFromName","../Core/_Events","../Core/_Log","../Core/_Resources","../Core/_WriteProfilerMark","../_Accents","../Animations","../Animations/_TransitionAnimation","../BindingList","../ControlProcessor","../Promise","../_Signal","../Scheduler","../Utilities/_Control","../Utilities/_ElementUtilities","../Utilities/_Hoverable","../Utilities/_UI","./Hub/_Section","require-style!less/styles-hub","require-style!less/colors-hub"],function(a,b,c,d,e,f,g,h,i,j,k,l,m,n,o,p,q,r,s,t,u){"use strict";i.createAccentRule(".win-semanticzoom-zoomedoutview .win-hub-section-header-interactive .win-hub-section-header-content, .win-hub-section-header-interactive .win-hub-section-header-chevron",[{name:"color",value:i.ColorTypes.accent}]),b.Namespace.define("WinJS.UI",{Hub:b.Namespace._lazy(function(){function i(b){var c=a.document.createTextNode("object"==typeof b.header?JSON.stringify(b.header):""+b.header);return c}var s=r.Key,v=e._createEventProperty,w={contentAnimating:"contentanimating",headerInvoked:"headerinvoked",loadingStateChanged:"loadingstatechanged"},x=500,y={scrollPos:"scrollTop",scrollSize:"scrollHeight",offsetPos:"offsetTop",offsetSize:"offsetHeight",oppositeOffsetSize:"offsetWidth",marginStart:"marginTop",marginEnd:"marginBottom",borderStart:"borderTopWidth",borderEnd:"borderBottomWidth",paddingStart:"paddingTop",paddingEnd:"paddingBottom"},z={scrollPos:"scrollLeft",scrollSize:"scrollWidth",offsetPos:"offsetLeft",offsetSize:"offsetWidth",oppositeOffsetSize:"offsetHeight",marginStart:"marginRight",marginEnd:"marginLeft",borderStart:"borderRightWidth",borderEnd:"borderLeftWidth",paddingStart:"paddingRight",paddingEnd:"paddingLeft"},A={scrollPos:"scrollLeft",scrollSize:"scrollWidth",offsetPos:"offsetLeft",offsetSize:"offsetWidth",oppositeOffsetSize:"offsetHeight",marginStart:"marginLeft",marginEnd:"marginRight",borderStart:"borderLeftWidth",borderEnd:"borderRightWidth",paddingStart:"paddingLeft",paddingEnd:"paddingRight"},B=b.Class.define(function(b,c){if(b=b||a.document.createElement("DIV"),c=c||{},b.winControl)throw new d("WinJS.UI.Hub.DuplicateConstruction",D.duplicateConstruction);this._id=b.id||r._uniqueID(b),this._writeProfilerMark("constructor,StartTM"),this._windowKeyDownHandlerBound=this._windowKeyDownHandler.bind(this),a.addEventListener("keydown",this._windowKeyDownHandlerBound),b.winControl=this,this._element=b,r.addClass(this.element,B._ClassName.hub),r.addClass(this.element,"win-disposable"),this._viewportElement=a.document.createElement("DIV"),this._viewportElement.className=B._ClassName.hubViewport,this._element.appendChild(this._viewportElement),this._viewportElement.setAttribute("role","group"),this._viewportElement.setAttribute("aria-label",D.hubViewportAriaLabel),this._surfaceElement=a.document.createElement("DIV"),this._surfaceElement.className=B._ClassName.hubSurface,this._viewportElement.appendChild(this._surfaceElement),this._visible=!1,this._viewportElement.style.opacity=0,c.orientation||(this._orientation=t.Orientation.horizontal,r.addClass(this.element,B._ClassName.hubHorizontal)),this._fireEntrance=!0,this._animateEntrance=!0,this._loadId=0,this.runningAnimations=new n.wrap,this._currentIndexForSezo=0,this._parse(),q.setOptions(this,c),r._addEventListener(this.element,"focusin",this._focusin.bind(this),!1),this.element.addEventListener("keydown",this._keyDownHandler.bind(this)),this.element.addEventListener("click",this._clickHandler.bind(this)),this._resizeHandlerBound=this._resizeHandler.bind(this),this.element.addEventListener("mselementresize",this._resizeHandlerBound),r._resizeNotifier.subscribe(this.element,this._resizeHandlerBound),this._viewportElement.addEventListener("scroll",this._scrollHandler.bind(this)),this._surfaceElement.addEventListener("mselementresize",this._contentResizeHandler.bind(this)),this._handleSectionChangedBind=this._handleSectionChanged.bind(this),this._handleSectionInsertedBind=this._handleSectionInserted.bind(this),this._handleSectionMovedBind=this._handleSectionMoved.bind(this),this._handleSectionRemovedBind=this._handleSectionRemoved.bind(this),this._handleSectionReloadBind=this._handleSectionReload.bind(this),this._refresh(),this._writeProfilerMark("constructor,StopTM")},{element:{get:function(){return this._element}},orientation:{get:function(){return this._orientation},set:function(a){if(a!==this._orientation){if(this._measured=!1,this._names){var b={};b[this._names.scrollPos]=0,r.setScrollPosition(this._viewportElement,b)}a===t.Orientation.vertical?(r.removeClass(this.element,B._ClassName.hubHorizontal),r.addClass(this.element,B._ClassName.hubVertical)):(a=t.Orientation.horizontal,r.removeClass(this.element,B._ClassName.hubVertical),r.addClass(this.element,B._ClassName.hubHorizontal)),this._orientation=a,p.schedule(this._updateSnapList.bind(this),p.Priority.idle)}}},sections:{get:function(){return this._pendingSections?this._pendingSections:this._sections},set:function(a){var b=!this._pendingSections;this._pendingSections=a,this._refresh(),b&&(this.scrollPosition=0)}},headerTemplate:{get:function(){return this._pendingHeaderTemplate?this._pendingHeaderTemplate:(this._headerTemplate||(this._headerTemplate=i),this._headerTemplate)},set:function(a){this._pendingHeaderTemplate=a||i,this._refresh()}},scrollPosition:{get:function(){return+this._pendingScrollLocation===this._pendingScrollLocation?this._pendingScrollLocation:(this._measure(),this._scrollPosition)},set:function(a){if(a=Math.max(0,a),this._pendingRefresh)this._pendingScrollLocation=a,this._pendingSectionOnScreen=null;else{this._measure();var b=Math.max(0,Math.min(this._scrollLength-this._viewportSize,a));this._scrollPosition=b;var c={};c[this._names.scrollPos]=b,r.setScrollPosition(this._viewportElement,c)}}},sectionOnScreen:{get:function(){if(+this._pendingSectionOnScreen===this._pendingSectionOnScreen)return this._pendingSectionOnScreen;this._measure();for(var a=0;a<this._sectionSizes.length;a++){var b=this._sectionSizes[a];if(b.offset+b.size-b.borderEnd-b.paddingEnd>this._scrollPosition+this._startSpacer+b.borderStart+b.paddingStart)return a}return-1},set:function(a){a=Math.max(0,a),this._pendingRefresh?(this._pendingSectionOnScreen=a,this._pendingScrollLocation=null):(this._measure(),a>=0&&a<this._sectionSizes.length&&this._scrollToSection(a))}},indexOfFirstVisible:{get:function(){this._measure();for(var a=0;a<this._sectionSizes.length;a++){var b=this._sectionSizes[a];if(b.offset+b.size-b.borderEnd-b.paddingEnd>this._scrollPosition)return a}return-1}},indexOfLastVisible:{get:function(){this._measure();for(var a=this._sectionSizes.length-1;a>=0;a--){var b=this._sectionSizes[a];if(b.offset+b.paddingStart+b.borderStart<this._scrollPosition+this._viewportSize)return a}return-1}},onheaderinvoked:v(w.headerInvoked),onloadingstatechanged:v(w.loadingStateChanged),oncontentanimating:v(w.contentAnimating),_refresh:function(){this._pendingRefresh||(this._loadId++,this._setState(B.LoadingState.loading),this._pendingRefresh=!0,p.schedule(this._refreshImpl.bind(this),p.Priority.high))},_refreshImpl:function(){if(!this._disposed){var a=n.wrap();if(this._pendingSections&&(this._animateEntrance=!0,this._fireEntrance=!this._visible,!this._fireEntrance&&(this._visible=!1,this._viewportElement.style.opacity=0,k.isAnimationEnabled()))){var b=this._fireEvent(B._EventName.contentAnimating,{type:B.AnimationType.contentTransition});b&&(this._viewportElement.style["-ms-overflow-style"]="none",a=j.fadeOut(this._viewportElement).then(function(){this._viewportElement.style["-ms-overflow-style"]=""}.bind(this))),this._animateEntrance=b}a.done(this._applyProperties.bind(this))}},_applyProperties:function(){if(!this._disposed){this._pendingRefresh=!1;var a=!1;if(this._pendingSections){for(a=!0,this._updateEvents(this._sections,this._pendingSections),this._sections=this._pendingSections,this._pendingSections=null;this.element.firstElementChild!==this._viewportElement;){var b=this.element.firstElementChild;b.parentNode.removeChild(b)}r.empty(this._surfaceElement)}this._pendingHeaderTemplate&&(this._headerTemplate=this._pendingHeaderTemplate,this._pendingHeaderTemplate=null),this._assignHeaderTemplate(),a&&this._attachSections(),+this._pendingSectionOnScreen===this._pendingSectionOnScreen?this.sectionOnScreen=this._pendingSectionOnScreen:this.scrollPosition=+this._pendingScrollLocation===this._pendingScrollLocation?this._pendingScrollLocation:0,this._pendingSectionOnScreen=null,this._pendingScrollLocation=null,this._setState(B.LoadingState.loading),this._loadSections()}},_handleSectionChanged:function(a){if(!this._pendingSections){var b=a.detail.newValue,c=a.detail.oldValue;if(b._setHeaderTemplate(this.headerTemplate),b.element!==c.element){if(b.element.parentNode===this._surfaceElement)throw new d("WinJS.UI.Hub.DuplicateSection",D.duplicateSection);this._surfaceElement.insertBefore(b.element,c.element),this._surfaceElement.removeChild(c.element),this._measured=!1,this._setState(B.LoadingState.loading),this._loadSections()}}},_handleSectionInserted:function(a){if(!this._pendingSections){var b=a.detail.index,c=a.detail.value;c._animation&&c._animation.cancel();var e,f=this._fireEvent(B._EventName.contentAnimating,{type:B.AnimationType.insert,index:b,section:c});if(f){for(var g=[],h=b+1;h<this.sections.length;h++)g.push(this.sections.getAt(h).element);e=new j._createUpdateListAnimation([c.element],[],g)}if(c.element.parentNode===this._surfaceElement)throw new d("WinJS.UI.Hub.DuplicateSection",D.duplicateSection);if(c._setHeaderTemplate(this.headerTemplate),b<this.sections.length-1?this._surfaceElement.insertBefore(c.element,this.sections.getAt(b+1).element):this._surfaceElement.appendChild(c.element),this._measured=!1,e){var i=e.execute();this.runningAnimations=n.join([this.runningAnimations,i])}this._setState(B.LoadingState.loading),this._loadSections()}},_handleSectionMoved:function(a){if(!this._pendingSections){var b=a.detail.newIndex,c=a.detail.value;b<this.sections.length-1?this._surfaceElement.insertBefore(c.element,this.sections.getAt(b+1).element):this._surfaceElement.appendChild(c.element),this._measured=!1,this._setState(B.LoadingState.loading),this._loadSections()}},_handleSectionRemoved:function(a){if(!this._pendingSections){var b=a.detail.value,c=a.detail.index,d=n.wrap(),e=this._fireEvent(B._EventName.contentAnimating,{type:B.AnimationType.remove,index:c,section:b});if(e){for(var f=[],g=c;g<this.sections.length;g++)f.push(this.sections.getAt(g).element);var h=new j._createUpdateListAnimation([],[b.element],f);this._measure();var i=b.element.offsetTop,k=b.element.offsetLeft;b.element.style.position="absolute",b.element.style.top=i,b.element.style.left=k,b.element.style.opacity=0,this._measured=!1,d=h.execute().then(function(){b.element.style.position="",b.element.style.top="",b.element.style.left="",b.element.style.opacity=1}.bind(this))}d.done(function(){this._disposed||(this._surfaceElement.removeChild(b.element),this._measured=!1)}.bind(this)),b._animation=d,this.runningAnimations=n.join([this.runningAnimations,d]),this._setState(B.LoadingState.loading),this._loadSections()}},_handleSectionReload:function(){this.sections=this.sections},_updateEvents:function(a,b){a&&(a.removeEventListener("itemchanged",this._handleSectionChangedBind),a.removeEventListener("iteminserted",this._handleSectionInsertedBind),a.removeEventListener("itemmoved",this._handleSectionMovedBind),a.removeEventListener("itemremoved",this._handleSectionRemovedBind),a.removeEventListener("reload",this._handleSectionReloadBind)),b&&(b.addEventListener("itemchanged",this._handleSectionChangedBind),b.addEventListener("iteminserted",this._handleSectionInsertedBind),b.addEventListener("itemmoved",this._handleSectionMovedBind),b.addEventListener("itemremoved",this._handleSectionRemovedBind),b.addEventListener("reload",this._handleSectionReloadBind))},_attachSections:function(){this._measured=!1;for(var a=0;a<this.sections.length;a++){var b=this._sections.getAt(a);if(b._animation&&b._animation.cancel(),b.element.parentNode===this._surfaceElement)throw new d("WinJS.UI.Hub.DuplicateSection",D.duplicateSection);this._surfaceElement.appendChild(b.element)}},_assignHeaderTemplate:function(){this._measured=!1;for(var a=0;a<this.sections.length;a++){var b=this._sections.getAt(a);b._setHeaderTemplate(this.headerTemplate)}},_loadSection:function(a){var b=this._sections.getAt(a);return b._process().then(function(){var a=b.contentElement.style;""!==a.visibility&&(a.visibility="")})},_loadSections:function(){function b(a){a.then(function(){p.schedule(c,p.Priority.idle)})}function c(){if(d===e._loadId&&!e._disposed)if(g.length){var a=g.shift(),c=e._loadSection(a);b(c)}else i.complete()}this._loadId++;var d=this._loadId,e=this,f=n.wrap(),g=[],h=n.wrap();if(this._showProgressPromise||(this._showProgressPromise=n.timeout(x).then(function(){this._disposed||(this._progressBar||(this._progressBar=a.document.createElement("progress"),r.addClass(this._progressBar,B._ClassName.hubProgress),this._progressBar.max=100),this._progressBar.parentNode||this.element.insertBefore(this._progressBar,this._viewportElement),this._showProgressPromise=null)}.bind(this),function(){this._showProgressPromise=null}.bind(this))),this.sections.length){var i=new o;h=i.promise;for(var l=[],m=Math.max(0,this.indexOfFirstVisible),q=Math.max(0,this.indexOfLastVisible),s=m;q>=s;s++)l.push(this._loadSection(s));for(m--,q++;m>=0||q<this.sections.length;)q<this.sections.length&&(g.push(q),q++),m>=0&&(g.push(m),m--);var t=n.join(l);t.done(function(){d!==this._loadId||e._disposed||(this._showProgressPromise&&this._showProgressPromise.cancel(),this._progressBar&&this._progressBar.parentNode&&this._progressBar.parentNode.removeChild(this._progressBar),p.schedule(function(){if(d===this._loadId&&!e._disposed&&!this._visible){if(this._visible=!0,this._viewportElement.style.opacity=1,this._animateEntrance&&k.isAnimationEnabled()){var b={type:B.AnimationType.entrance};(!this._fireEntrance||this._fireEvent(B._EventName.contentAnimating,b))&&(this._viewportElement.style["-ms-overflow-style"]="none",f=j.enterContent(this._viewportElement).then(function(){this._viewportElement.style["-ms-overflow-style"]="",this._viewportElement.onmousewheel=function(){}}.bind(this)))}this._element===a.document.activeElement&&this._moveFocusIn(this.sectionOnScreen)}},p.Priority.high,this,"WinJS.UI.Hub.entranceAnimation"))}.bind(this)),b(t)}else this._showProgressPromise&&this._showProgressPromise.cancel(),this._progressBar&&this._progressBar.parentNode&&this._progressBar.parentNode.removeChild(this._progressBar);n.join([this.runningAnimations,f,h]).done(function(){d!==this._loadId||e._disposed||(this.runningAnimations=n.wrap(),this._measured&&this._scrollLength!==this._viewportElement[this._names.scrollSize]&&(this._measured=!1),this._setState(B.LoadingState.complete),p.schedule(this._updateSnapList.bind(this),p.Priority.idle))}.bind(this))},loadingState:{get:function(){return this._loadingState}},_setState:function(b){if(b!==this._loadingState){this._writeProfilerMark("loadingStateChanged:"+b+",info"),this._loadingState=b;var c=a.document.createEvent("CustomEvent");c.initCustomEvent(B._EventName.loadingStateChanged,!0,!1,{loadingState:b}),this._element.dispatchEvent(c)}},_parse:function(){for(var a=[],b=this.element.firstElementChild;b!==this._viewportElement;){m.processAll(b);var c=b.winControl;if(!c)throw new d("WinJS.UI.Hub.InvalidContent",D.invalidContent);a.push(c);var e=b.nextElementSibling;b=e}this.sections=new l.List(a)},_fireEvent:function(b,c){var d=a.document.createEvent("CustomEvent");return d.initCustomEvent(b,!0,!0,c),this.element.dispatchEvent(d)},_findHeaderTabStop:function(a){if(a.parentNode&&r._matchesSelector(a,".win-hub-section-header-tabstop, .win-hub-section-header-tabstop *")){for(;!r.hasClass(a,"win-hub-section-header-tabstop");)a=a.parentElement;return a}return null},_isInteractive:function(b){for(;b&&b!==a.document.body;){if(r.hasClass(b,"win-interactive"))return!0;b=b.parentElement}return!1},_clickHandler:function(a){var b=this._findHeaderTabStop(a.target);if(b&&!this._isInteractive(a.target)){var c=b.parentElement.parentElement.winControl;if(!c.isHeaderStatic){var d=this.sections.indexOf(c);this._fireEvent(B._EventName.headerInvoked,{index:d,section:c})}}},_resizeHandler:function(){this._measured=!1,p.schedule(this._updateSnapList.bind(this),p.Priority.idle)},_contentResizeHandler:function(){this._measured=!1,p.schedule(this._updateSnapList.bind(this),p.Priority.idle)},_scrollHandler:function(){this._measured=!1,this._pendingSections||(this._pendingScrollLocation=null,this._pendingSectionOnScreen=null,this._pendingScrollHandler||(this._pendingScrollHandler=c._requestAnimationFrame(function(){this._pendingScrollHandler=null,this._pendingSections||this.loadingState!==B.LoadingState.complete&&this._loadSections()}.bind(this))))},_measure:function(){if(!this._measured||0===this._scrollLength){this._writeProfilerMark("measure,StartTM"),this._measured=!0,this._rtl="rtl"===r._getComputedStyle(this._element,null).direction,this._names=this.orientation===t.Orientation.vertical?y:this._rtl?z:A,this._viewportSize=this._viewportElement[this._names.offsetSize],this._viewportOppositeSize=this._viewportElement[this._names.oppositeOffsetSize],this._scrollPosition=r.getScrollPosition(this._viewportElement)[this._names.scrollPos],this._scrollLength=this._viewportElement[this._names.scrollSize];var a=r._getComputedStyle(this._surfaceElement);this._startSpacer=parseFloat(a[this._names.marginStart])+parseFloat(a[this._names.borderStart])+parseFloat(a[this._names.paddingStart]),this._endSpacer=parseFloat(a[this._names.marginEnd])+parseFloat(a[this._names.borderEnd])+parseFloat(a[this._names.paddingEnd]),this._sectionSizes=[];for(var b=0;b<this.sections.length;b++){var c=this.sections.getAt(b),d=r._getComputedStyle(c.element);this._sectionSizes[b]={offset:c.element[this._names.offsetPos],size:c.element[this._names.offsetSize],marginStart:parseFloat(d[this._names.marginStart]),marginEnd:parseFloat(d[this._names.marginEnd]),borderStart:parseFloat(d[this._names.borderStart]),borderEnd:parseFloat(d[this._names.borderEnd]),paddingStart:parseFloat(d[this._names.paddingStart]),paddingEnd:parseFloat(d[this._names.paddingEnd])},this._rtl&&this.orientation===t.Orientation.horizontal&&(this._sectionSizes[b].offset=this._viewportSize-(this._sectionSizes[b].offset+this._sectionSizes[b].size))}this._writeProfilerMark("measure,StopTM")}},_updateSnapList:function(){this._writeProfilerMark("updateSnapList,StartTM"),this._measure();for(var a="snapList(",b=0;b<this._sectionSizes.length;b++){b>0&&(a+=",");var c=this._sectionSizes[b];a+=c.offset-c.marginStart-this._startSpacer+"px"}a+=")";var d="",e="";this.orientation===t.Orientation.vertical?d=a:e=a,this._lastSnapPointY!==d&&(this._lastSnapPointY=d,this._viewportElement.style["-ms-scroll-snap-points-y"]=d),this._lastSnapPointX!==e&&(this._lastSnapPointX=e,this._viewportElement.style["-ms-scroll-snap-points-x"]=e),this._writeProfilerMark("updateSnapList,StopTM")},_scrollToSection:function(a,b){this._measure();var c=this._sectionSizes[a],d=Math.min(this._scrollLength-this._viewportSize,c.offset-c.marginStart-this._startSpacer);this._scrollTo(d,b)},_ensureVisible:function(a,b){this._measure();var c=this._ensureVisibleMath(a,this._scrollPosition);this._scrollTo(c,b)},_ensureVisibleMath:function(a,b){this._measure();var c=this._sectionSizes[a],d=Math.min(this._scrollLength-this._viewportSize,c.offset-c.marginStart-this._startSpacer),e=Math.max(0,c.offset+c.size+c.marginEnd+this._endSpacer-this._viewportSize+1);return b>d?b=d:e>b&&(b=Math.min(d,e)),b},_scrollTo:function(a,b){if(this._scrollPosition=a,b)this.orientation===t.Orientation.vertical?r._zoomTo(this._viewportElement,{contentX:0,contentY:this._scrollPosition,viewportX:0,viewportY:0}):r._zoomTo(this._viewportElement,{contentX:this._scrollPosition,contentY:0,viewportX:0,viewportY:0});else{var c={};c[this._names.scrollPos]=this._scrollPosition,r.setScrollPosition(this._viewportElement,c)}},_windowKeyDownHandler:function(a){if(a.keyCode===s.tab){this._tabSeenLast=!0;var b=this;c._yieldForEvents(function(){b._tabSeenLast=!1})}},_focusin:function(a){if(this._tabSeenLast){var b=this._findHeaderTabStop(a.target);if(b&&!this._isInteractive(a.target)){var c=this.sections.indexOf(b.parentElement.parentElement.winControl);c>-1&&this._ensureVisible(c,!0)}}for(var d=a.target;d&&!r.hasClass(d,u.HubSection._ClassName.hubSection);)d=d.parentElement;if(d){var c=this.sections.indexOf(d.winControl);c>-1&&(this._currentIndexForSezo=c)}if(a.target===this.element){var e;+this._sectionToFocus===this._sectionToFocus&&this._sectionToFocus>=0&&this._sectionToFocus<this.sections.length?(e=this._sectionToFocus,this._sectionToFocus=null):e=this.sectionOnScreen,this._moveFocusIn(e)}},_moveFocusIn:function(a){if(a>=0){for(var b=a;b<this.sections.length;b++){var c=this.sections.getAt(b),d=r._trySetActive(c._headerTabStopElement,this._viewportElement);if(d)return;if(r._setActiveFirstFocusableElement(c.contentElement,this._viewportElement))return}for(var b=a-1;b>=0;b--){var c=this.sections.getAt(b);if(r._setActiveFirstFocusableElement(c.contentElement,this._viewportElement))return;var d=r._trySetActive(c._headerTabStopElement,this._viewportElement);if(d)return}}},_keyDownHandler:function(a){if(!this._isInteractive(a.target)&&!r._hasCursorKeysBehaviors(a.target)){var b=this._rtl?s.rightArrow:s.leftArrow,c=this._rtl?s.leftArrow:s.rightArrow;if(a.keyCode===s.upArrow||a.keyCode===s.downArrow||a.keyCode===s.leftArrow||a.keyCode===s.rightArrow||a.keyCode===s.pageUp||a.keyCode===s.pageDown){var d=this._findHeaderTabStop(a.target);if(d){var e,f=this.sections.indexOf(d.parentElement.parentElement.winControl),g=!1;if(a.keyCode===s.pageDown||this.orientation===t.Orientation.horizontal&&a.keyCode===c||this.orientation===t.Orientation.vertical&&a.keyCode===s.downArrow){for(var h=f+1;h<this.sections.length;h++)if(this._tryFocus(h)){e=h;break}}else if(a.keyCode===s.pageUp||this.orientation===t.Orientation.horizontal&&a.keyCode===b||this.orientation===t.Orientation.vertical&&a.keyCode===s.upArrow)for(var h=f-1;h>=0;h--)if(this._tryFocus(h)){e=h;break}(a.keyCode===s.upArrow||a.keyCode===s.downArrow||a.keyCode===s.leftArrow||a.keyCode===s.rightArrow)&&(g=!0),+e===e&&(g?this._ensureVisible(e,!0):this._scrollToSection(e,!0),a.preventDefault())}}else if(a.keyCode===s.home||a.keyCode===s.end){this._measure();var i=Math.max(0,this._scrollLength-this._viewportSize);this._scrollTo(a.keyCode===s.home?0:i,!0),a.preventDefault()}}},_tryFocus:function(b){var c=this.sections.getAt(b);return r._setActive(c._headerTabStopElement,this._viewportElement),a.document.activeElement===c._headerTabStopElement},zoomableView:{get:function(){return this._zoomableView||(this._zoomableView=new C(this)),this._zoomableView}},_getPanAxis:function(){return this.orientation===t.Orientation.horizontal?"horizontal":"vertical"},_configureForZoom:function(){},_setCurrentItem:function(a,b){var c;c=this.orientation===t.Orientation.horizontal?a:b,this._measure(),c+=this._scrollPosition,this._currentIndexForSezo=this._sectionSizes.length-1;for(var d=1;d<this._sectionSizes.length;d++){var e=this._sectionSizes[d];if(e.offset-e.marginStart>c){this._currentIndexForSezo=d-1;break}}},_getCurrentItem:function(){var a;if(this._sectionSizes.length>0){this._measure();var b=Math.max(0,Math.min(this._currentIndexForSezo,this._sectionSizes.length)),c=this._sectionSizes[b];a=this.orientation===t.Orientation.horizontal?{left:Math.max(0,c.offset-c.marginStart-this._scrollPosition),top:0,width:c.size,height:this._viewportOppositeSize}:{left:0,top:Math.max(0,c.offset-c.marginStart-this._scrollPosition),width:this._viewportOppositeSize,height:c.size};var d=this.sections.getAt(b);return n.wrap({item:{data:d,index:b,groupIndexHint:b},position:a})}},_beginZoom:function(){this._viewportElement.style["-ms-overflow-style"]="none"},_positionItem:function(a,b){if(a.index>=0&&a.index<this._sectionSizes.length){this._measure();var c,d=this._sectionSizes[a.index];c=this.orientation===t.Orientation.horizontal?b.left:b.top,this._sectionToFocus=a.index;var e=d.offset-c,e=this._ensureVisibleMath(a.index,e);this._scrollPosition=e;var f={};f[this._names.scrollPos]=this._scrollPosition,r.setScrollPosition(this._viewportElement,f)}},_endZoom:function(){this._viewportElement.style["-ms-overflow-style"]=""},_writeProfilerMark:function(a){var b="WinJS.UI.Hub:"+this._id+":"+a;h(b),f.log&&f.log(b,null,"hubprofiler")},dispose:function(){if(!this._disposed){this._disposed=!0,a.removeEventListener("keydown",this._windowKeyDownHandlerBound),r._resizeNotifier.unsubscribe(this.element,this._resizeHandlerBound),this._updateEvents(this._sections);for(var b=0;b<this.sections.length;b++)this.sections.getAt(b).dispose()}}},{AnimationType:{entrance:"entrance",contentTransition:"contentTransition",insert:"insert",remove:"remove"},LoadingState:{loading:"loading",complete:"complete"},_ClassName:{hub:"win-hub",hubSurface:"win-hub-surface",hubProgress:"win-hub-progress",hubViewport:"win-hub-viewport",hubVertical:"win-hub-vertical",hubHorizontal:"win-hub-horizontal"},_EventName:{contentAnimating:w.contentAnimating,headerInvoked:w.headerInvoked,loadingStateChanged:w.loadingStateChanged}});b.Class.mix(B,q.DOMEventMixin);var C=b.Class.define(function(a){this._hub=a},{getPanAxis:function(){return this._hub._getPanAxis()},configureForZoom:function(a,b,c,d){this._hub._configureForZoom(a,b,c,d)},setCurrentItem:function(a,b){this._hub._setCurrentItem(a,b)},getCurrentItem:function(){return this._hub._getCurrentItem()},beginZoom:function(){this._hub._beginZoom()},positionItem:function(a,b){return this._hub._positionItem(a,b)},endZoom:function(a){this._hub._endZoom(a)}}),D={get duplicateConstruction(){return"Invalid argument: Controls may only be instantiated one time for each DOM element"},get duplicateSection(){return"Hub duplicate sections: Each HubSection must be unique"},get invalidContent(){return"Invalid content: Hub content must be made up of HubSections."},get hubViewportAriaLabel(){return g._getWinJSString("ui/hubViewportAriaLabel").value}};return B})})}),d("require-style!less/styles-lightdismissservice",[],function(){});var e=this.__extends||function(a,b){function c(){this.constructor=a}for(var d in b)b.hasOwnProperty(d)&&(a[d]=b[d]);c.prototype=b.prototype,a.prototype=new c};d("WinJS/_LightDismissService",["require","exports","./Application","./Core/_Base","./Core/_BaseUtils","./Utilities/_ElementUtilities","./Core/_Global","./Utilities/_KeyboardBehavior","./Core/_Log","./Core/_Resources"],function(a,b,c,d,f,g,h,i,j,k){a(["require-style!less/styles-lightdismissservice"]);var l=1e3,m={get closeOverlay(){return k._getWinJSString("ui/closeOverlay").value}};b._ClassNames={_clickEater:"win-clickeater"};b.LightDismissalReasons={tap:"tap",lostFocus:"lostFocus",escape:"escape",hardwareBackButton:"hardwareBackButton",windowResize:"windowResize",windowBlur:"windowBlur"},b.DismissalPolicies={light:function(a){switch(a.reason){case b.LightDismissalReasons.tap:case b.LightDismissalReasons.escape:return a.active?!0:(a.stopPropagation(),!1);case b.LightDismissalReasons.hardwareBackButton:return a.active?(a.preventDefault(),!0):(a.stopPropagation(),!1);case b.LightDismissalReasons.lostFocus:case b.LightDismissalReasons.windowResize:case b.LightDismissalReasons.windowBlur:return!0}},modal:function(a){switch(a.stopPropagation(),a.reason){case b.LightDismissalReasons.tap:case b.LightDismissalReasons.lostFocus:case b.LightDismissalReasons.windowResize:case b.LightDismissalReasons.windowBlur:return!1;case b.LightDismissalReasons.escape:return a.active;case b.LightDismissalReasons.hardwareBackButton:return a.preventDefault(),a.active}},sticky:function(a){return a.stopPropagation(),!1}};var n={keyDown:"keyDown",keyUp:"keyUp",keyPress:"keyPress"},o=function(){function a(a){this.element=a.element,this.element.tabIndex=a.tabIndex,this.onLightDismiss=a.onLightDismiss,a.onTakeFocus&&(this.onTakeFocus=a.onTakeFocus),a.onShouldLightDismiss&&(this.onShouldLightDismiss=a.onShouldLightDismiss),this._ldeOnKeyDownBound=this._ldeOnKeyDown.bind(this),this._ldeOnKeyUpBound=this._ldeOnKeyUp.bind(this),this._ldeOnKeyPressBound=this._ldeOnKeyPress.bind(this)}return a.prototype.restoreFocus=function(){var a=h.document.activeElement;if(a&&this.containsElement(a))return this._ldeCurrentFocus=a,!0;var b=!i._keyboardSeenLast;return this._ldeCurrentFocus&&this.containsElement(this._ldeCurrentFocus)&&g._tryFocusOnAnyElement(this._ldeCurrentFocus,b)},a.prototype._ldeOnKeyDown=function(a){this._ldeService.keyDown(this,a)},a.prototype._ldeOnKeyUp=function(a){this._ldeService.keyUp(this,a)},a.prototype._ldeOnKeyPress=function(a){this._ldeService.keyPress(this,a)},a.prototype.setZIndex=function(a){this.element.style.zIndex=a},a.prototype.getZIndexCount=function(){return 1},a.prototype.containsElement=function(a){return this.element.contains(a)},a.prototype.onTakeFocus=function(a){this.restoreFocus()||g._focusFirstFocusableElement(this.element,a)||g._tryFocusOnAnyElement(this.element,a)},a.prototype.onFocus=function(a){this._ldeCurrentFocus=a},a.prototype.onShow=function(a){this._ldeService=a,this.element.addEventListener("keydown",this._ldeOnKeyDownBound),this.element.addEventListener("keyup",this._ldeOnKeyUpBound),this.element.addEventListener("keypress",this._ldeOnKeyPressBound)},a.prototype.onHide=function(){this._ldeCurrentFocus=null,this._ldeService=null,this.element.removeEventListener("keydown",this._ldeOnKeyDownBound),this.element.removeEventListener("keyup",this._ldeOnKeyUpBound),this.element.removeEventListener("keypress",this._ldeOnKeyPressBound)},a.prototype.onKeyInStack=function(){},a.prototype.onShouldLightDismiss=function(){return!1 },a.prototype.onLightDismiss=function(){},a}(),p=function(a){function c(){a.apply(this,arguments)}return e(c,a),c.prototype.onKeyInStack=function(){},c.prototype.onShouldLightDismiss=function(a){return b.DismissalPolicies.light(a)},c}(o);b.LightDismissableElement=p;var q=function(a){function c(){a.apply(this,arguments)}return e(c,a),c.prototype.onKeyInStack=function(a){a.stopPropagation()},c.prototype.onShouldLightDismiss=function(a){return b.DismissalPolicies.modal(a)},c}(o);b.ModalElement=q;var r=function(){function a(){}return a.prototype.setZIndex=function(){},a.prototype.getZIndexCount=function(){return 1},a.prototype.containsElement=function(a){return h.document.body.contains(a)},a.prototype.onTakeFocus=function(a){this.currentFocus&&this.containsElement(this.currentFocus)&&g._tryFocusOnAnyElement(this.currentFocus,a)},a.prototype.onFocus=function(a){this.currentFocus=a},a.prototype.onShow=function(){},a.prototype.onHide=function(){this.currentFocus=null},a.prototype.onKeyInStack=function(){},a.prototype.onShouldLightDismiss=function(){return!1},a.prototype.onLightDismiss=function(){},a}(),s=function(){function a(){this._debug=!1,this._clients=[],this._notifying=!1,this._bodyClient=new r,this._updateDom_rendered={serviceActive:!1},this._clickEaterEl=this._createClickEater(),this._onBeforeRequestingFocusOnKeyboardInputBound=this._onBeforeRequestingFocusOnKeyboardInput.bind(this),this._onFocusInBound=this._onFocusIn.bind(this),this._onKeyDownBound=this._onKeyDown.bind(this),this._onWindowResizeBound=this._onWindowResize.bind(this),this._onClickEaterPointerUpBound=this._onClickEaterPointerUp.bind(this),this._onClickEaterPointerCancelBound=this._onClickEaterPointerCancel.bind(this),c.addEventListener("backclick",this._onBackClick.bind(this)),h.window.addEventListener("blur",this._onWindowBlur.bind(this)),this.shown(this._bodyClient)}return a.prototype.shown=function(a){var b=this._clients.indexOf(a);-1===b&&(this._clients.push(a),a.onShow(this),this._updateDom())},a.prototype.hidden=function(a){var b=this._clients.indexOf(a);-1!==b&&(this._clients.splice(b,1),a.setZIndex(""),a.onHide(),this._updateDom())},a.prototype.updated=function(){this._updateDom()},a.prototype.keyDown=function(a,b){b.keyCode===g.Key.escape?this._escapePressed(b):this._dispatchKeyboardEvent(a,n.keyDown,b)},a.prototype.keyUp=function(a,b){this._dispatchKeyboardEvent(a,n.keyUp,b)},a.prototype.keyPress=function(a,b){this._dispatchKeyboardEvent(a,n.keyPress,b)},a.prototype.isShown=function(a){return-1!==this._clients.indexOf(a)},a.prototype.isTopmost=function(a){return a===this._clients[this._clients.length-1]},a.prototype._setDebug=function(a){this._debug=a},a.prototype._updateDom=function(a){a=a||{};var b=!!a.activeDismissableNeedsFocus,d=this._updateDom_rendered;if(!this._notifying){var e=this._clients.length>1;if(e!==d.serviceActive){if(e)c.addEventListener("beforerequestingfocusonkeyboardinput",this._onBeforeRequestingFocusOnKeyboardInputBound),g._addEventListener(h.document.documentElement,"focusin",this._onFocusInBound),h.document.documentElement.addEventListener("keydown",this._onKeyDownBound),h.window.addEventListener("resize",this._onWindowResizeBound),this._bodyClient.currentFocus=h.document.activeElement,h.document.body.appendChild(this._clickEaterEl);else{c.removeEventListener("beforerequestingfocusonkeyboardinput",this._onBeforeRequestingFocusOnKeyboardInputBound),g._removeEventListener(h.document.documentElement,"focusin",this._onFocusInBound),h.document.documentElement.removeEventListener("keydown",this._onKeyDownBound),h.window.removeEventListener("resize",this._onWindowResizeBound);var f=this._clickEaterEl.parentNode;f&&f.removeChild(this._clickEaterEl)}d.serviceActive=e}var j=0,k=l+1;this._clients.forEach(function(a){var b=k+j;a.setZIndex(""+b),k=b,j=a.getZIndexCount()+1}),e&&(this._clickEaterEl.style.zIndex=""+(k-1));var m=this._clients.length>0?this._clients[this._clients.length-1]:null;if(this._activeDismissable!==m&&(this._activeDismissable=m,b=!0),b){var n=!i._keyboardSeenLast;this._activeDismissable&&this._activeDismissable.onTakeFocus(n)}}},a.prototype._dispatchKeyboardEvent=function(a,b,c){var d=this._clients.indexOf(a);if(-1!==d)for(var e={type:b,keyCode:c.keyCode,propagationStopped:!1,stopPropagation:function(){this.propagationStopped=!0,c.stopPropagation()}},f=this._clients.slice(0,d+1),g=f.length-1;g>=0&&!e.propagationStopped;g--)f[g].onKeyInStack(e)},a.prototype._dispatchLightDismiss=function(a,b,c){if(this._notifying)return void(j.log&&j.log('_LightDismissService ignored dismiss trigger to avoid re-entrancy: "'+a+'"',"winjs _LightDismissService","warning"));if(b=b||this._clients.slice(0),0!==b.length){this._notifying=!0;for(var d={reason:a,active:!1,_stop:!1,stopPropagation:function(){this._stop=!0},_doDefault:!0,preventDefault:function(){this._doDefault=!1}},e=b.length-1;e>=0&&!d._stop;e--)d.active=this._activeDismissable===b[e],b[e].onShouldLightDismiss(d)&&b[e].onLightDismiss(d);return this._notifying=!1,this._updateDom(c),d._doDefault}},a.prototype._onBeforeRequestingFocusOnKeyboardInput=function(){return!0},a.prototype._clickEaterTapped=function(){this._dispatchLightDismiss(b.LightDismissalReasons.tap)},a.prototype._onFocusIn=function(a){for(var c=a.target,d=this._clients.length-1;d>=0&&!this._clients[d].containsElement(c);d--);-1!==d&&this._clients[d].onFocus(c),d+1<this._clients.length&&this._dispatchLightDismiss(b.LightDismissalReasons.lostFocus,this._clients.slice(d+1),{activeDismissableNeedsFocus:!0})},a.prototype._onKeyDown=function(a){a.keyCode===g.Key.escape&&this._escapePressed(a)},a.prototype._escapePressed=function(a){a.preventDefault(),a.stopPropagation(),this._dispatchLightDismiss(b.LightDismissalReasons.escape)},a.prototype._onBackClick=function(){var a=this._dispatchLightDismiss(b.LightDismissalReasons.hardwareBackButton);return!a},a.prototype._onWindowResize=function(){this._dispatchLightDismiss(b.LightDismissalReasons.windowResize)},a.prototype._onWindowBlur=function(){if(!this._debug)if(h.document.hasFocus()){var a=h.document.activeElement;a&&"IFRAME"===a.tagName&&!a.msLightDismissBlur&&(a.addEventListener("blur",this._onWindowBlur.bind(this),!1),a.msLightDismissBlur=!0)}else this._dispatchLightDismiss(b.LightDismissalReasons.windowBlur)},a.prototype._createClickEater=function(){var a=h.document.createElement("section");return a.className=b._ClassNames._clickEater,g._addEventListener(a,"pointerdown",this._onClickEaterPointerDown.bind(this),!0),a.addEventListener("click",this._onClickEaterClick.bind(this),!0),a.setAttribute("role","menuitem"),a.setAttribute("aria-label",m.closeOverlay),a.setAttribute("unselectable","on"),a},a.prototype._onClickEaterPointerDown=function(a){a.stopPropagation(),a.preventDefault(),this._clickEaterPointerId=a.pointerId,this._registeredClickEaterCleanUp||(g._addEventListener(h.window,"pointerup",this._onClickEaterPointerUpBound),g._addEventListener(h.window,"pointercancel",this._onClickEaterPointerCancelBound),this._registeredClickEaterCleanUp=!0)},a.prototype._onClickEaterPointerUp=function(a){var b=this;if(a.stopPropagation(),a.preventDefault(),a.pointerId===this._clickEaterPointerId){this._resetClickEaterPointerState();var c=h.document.elementFromPoint(a.clientX,a.clientY);c===this._clickEaterEl&&(this._skipClickEaterClick=!0,f._yieldForEvents(function(){b._skipClickEaterClick=!1}),this._clickEaterTapped())}},a.prototype._onClickEaterClick=function(a){a.stopPropagation(),a.preventDefault(),this._skipClickEaterClick||this._clickEaterTapped()},a.prototype._onClickEaterPointerCancel=function(a){a.pointerId===this._clickEaterPointerId&&this._resetClickEaterPointerState()},a.prototype._resetClickEaterPointerState=function(){this._registeredClickEaterCleanUp&&(g._removeEventListener(h.window,"pointerup",this._onClickEaterPointerUpBound),g._removeEventListener(h.window,"pointercancel",this._onClickEaterPointerCancelBound)),this._clickEaterPointerId=null,this._registeredClickEaterCleanUp=!1},a}(),t=new s;b.shown=t.shown.bind(t),b.hidden=t.hidden.bind(t),b.updated=t.updated.bind(t),b.isShown=t.isShown.bind(t),b.isTopmost=t.isTopmost.bind(t),b.keyDown=t.keyDown.bind(t),b.keyUp=t.keyUp.bind(t),b.keyPress=t.keyPress.bind(t),b._clickEaterTapped=t._clickEaterTapped.bind(t),b._onBackClick=t._onBackClick.bind(t),b._setDebug=t._setDebug.bind(t),d.Namespace.define("WinJS.UI._LightDismissService",{shown:b.shown,hidden:b.hidden,updated:b.updated,isShown:b.isShown,isTopmost:b.isTopmost,keyDown:b.keyDown,keyUp:b.keyUp,keyPress:b.keyPress,_clickEaterTapped:b._clickEaterTapped,_onBackClick:b._onBackClick,_setDebug:b._setDebug,LightDismissableElement:p,DismissalPolicies:b.DismissalPolicies,LightDismissalReasons:b.LightDismissalReasons,_ClassNames:b._ClassNames,_service:t})}),d("WinJS/Controls/_LegacyAppBar/_Constants",["exports","../../Core/_Base"],function(a,b){"use strict";b.Namespace._moduleDefine(a,null,{appBarClass:"win-navbar",firstDivClass:"win-firstdiv",finalDivClass:"win-finaldiv",invokeButtonClass:"win-navbar-invokebutton",ellipsisClass:"win-navbar-ellipsis",primaryCommandsClass:"win-primarygroup",secondaryCommandsClass:"win-secondarygroup",commandLayoutClass:"win-commandlayout",menuLayoutClass:"win-menulayout",topClass:"win-top",bottomClass:"win-bottom",showingClass:"win-navbar-opening",shownClass:"win-navbar-opened",hidingClass:"win-navbar-closing",hiddenClass:"win-navbar-closed",compactClass:"win-navbar-compact",minimalClass:"win-navbar-minimal",menuContainerClass:"win-navbar-menu",appBarPlacementTop:"top",appBarPlacementBottom:"bottom",appBarLayoutCustom:"custom",appBarLayoutCommands:"commands",appBarLayoutMenu:"menu",appBarInvokeButtonWidth:32,typeSeparator:"separator",typeContent:"content",typeButton:"button",typeToggle:"toggle",typeFlyout:"flyout",appBarCommandClass:"win-command",appBarCommandGlobalClass:"win-global",appBarCommandSelectionClass:"win-selection",commandHiddenClass:"win-command-hidden",sectionSelection:"selection",sectionGlobal:"global",sectionPrimary:"primary",sectionSecondary:"secondary",menuCommandClass:"win-command",menuCommandButtonClass:"win-command-button",menuCommandToggleClass:"win-command-toggle",menuCommandFlyoutClass:"win-command-flyout",menuCommandFlyoutActivatedClass:"win-command-flyout-activated",menuCommandSeparatorClass:"win-command-separator",_menuCommandInvokedEvent:"_invoked",menuClass:"win-menu",menuContainsToggleCommandClass:"win-menu-containstogglecommand",menuContainsFlyoutCommandClass:"win-menu-containsflyoutcommand",menuMouseSpacingClass:"win-menu-mousespacing",menuTouchSpacingClass:"win-menu-touchspacing",menuCommandHoverDelay:400,overlayClass:"win-overlay",flyoutClass:"win-flyout",flyoutLightClass:"win-ui-light",settingsFlyoutClass:"win-settingsflyout",scrollsClass:"win-scrolls",pinToRightEdge:-1,pinToBottomEdge:-1,separatorWidth:34,buttonWidth:68,narrowClass:"win-narrow",wideClass:"win-wide",_visualViewportClass:"win-visualviewport-space",commandPropertyMutated:"_commandpropertymutated",commandVisibilityChanged:"commandvisibilitychanged"})}),d("WinJS/Utilities/_KeyboardInfo",["require","exports","../Core/_BaseCoreUtils","../Core/_Global","../Core/_WinRT"],function(a,b,c,d,e){"use strict";var f={visualViewportClass:"win-visualviewport-space",scrollTimeout:150};b._KeyboardInfo,b._KeyboardInfo={get _visible(){try{return e.Windows.UI.ViewManagement.InputPane&&e.Windows.UI.ViewManagement.InputPane.getForCurrentView().occludedRect.height>0}catch(a){return!1}},get _extraOccluded(){var a=0;return!b._KeyboardInfo._isResized&&e.Windows.UI.ViewManagement.InputPane&&(a=e.Windows.UI.ViewManagement.InputPane.getForCurrentView().occludedRect.height),a},get _isResized(){var a=d.document.documentElement.clientHeight/d.innerHeight,b=d.document.documentElement.clientWidth/d.innerWidth;return.99>b/a},get _visibleDocBottom(){return b._KeyboardInfo._visibleDocTop+b._KeyboardInfo._visibleDocHeight},get _visibleDocHeight(){return b._KeyboardInfo._visualViewportHeight-b._KeyboardInfo._extraOccluded},get _visibleDocTop(){return 0},get _visibleDocBottomOffset(){return b._KeyboardInfo._extraOccluded},get _visualViewportHeight(){var a=b._KeyboardInfo._visualViewportSpace;return a.height},get _visualViewportWidth(){var a=b._KeyboardInfo._visualViewportSpace;return a.width},get _visualViewportSpace(){var a=d.document.body.querySelector("."+f.visualViewportClass);return a||(a=d.document.createElement("DIV"),a.className=f.visualViewportClass,d.document.body.appendChild(a)),a.getBoundingClientRect()},get _animationShowLength(){if(c.hasWinRT){if(e.Windows.UI.Core.AnimationMetrics){for(var a=e.Windows.UI.Core.AnimationMetrics,b=new a.AnimationDescription(a.AnimationEffect.showPanel,a.AnimationEffectTarget.primary),d=b.animations,f=0,g=0;g<d.size;g++){var h=d[g];f=Math.max(f,h.delay+h.duration)}return f}var i=300,j=50;return j+i}return 0},get _scrollTimeout(){return f.scrollTimeout},get _layoutViewportCoords(){var a=d.window.pageYOffset-d.document.documentElement.scrollTop,b=d.document.documentElement.clientHeight-(a+this._visibleDocHeight);return{visibleDocTop:a,visibleDocBottom:b}}}}),d("require-style!less/styles-overlay",[],function(){}),d("require-style!less/colors-overlay",[],function(){}),d("WinJS/Controls/Flyout/_Overlay",["exports","../../Core/_Global","../../Core/_WinRT","../../Core/_Base","../../Core/_BaseUtils","../../Core/_ErrorFromName","../../Core/_Events","../../Core/_Resources","../../Core/_WriteProfilerMark","../../_Accents","../../Animations","../../Application","../../ControlProcessor","../../Promise","../../Scheduler","../../Utilities/_Control","../../Utilities/_ElementUtilities","../../Utilities/_KeyboardInfo","../_LegacyAppBar/_Constants","require-style!less/styles-overlay","require-style!less/colors-overlay"],function(a,b,c,d,e,f,g,h,i,j,k,l,m,n,o,p,q,r,s){"use strict";j.createAccentRule("button[aria-checked=true].win-command:before, .win-menu-containsflyoutcommand button.win-command-flyout-activated:before",[{name:"background-color",value:j.ColorTypes.accent},{name:"border-color",value:j.ColorTypes.accent}]),j.createAccentRule(".win-flyout, .win-settingsflyout",[{name:"border-color",value:j.ColorTypes.accent}]),d.Namespace._moduleDefine(a,"WinJS.UI",{_Overlay:d.Namespace._lazy(function(){function a(a,c,d){var e=b.document.querySelectorAll("."+s.overlayClass);if(e)for(var f=e.length,g=0;f>g;g++){var h=e[g],i=h.winControl;if(!i._disposed&&i){var j=i[c](a);if(d&&j)return j}}}function e(a){if(!a)return[];"string"!=typeof a&&a&&a.length||(a=[a]);var c,d=[];for(c=0;c<a.length;c++)if(a[c])if("string"==typeof a[c]){var e=b.document.getElementById(a[c]);e&&d.push(e)}else d.push(a[c].element?a[c].element:a[c]);return d}var g=d.Class.define(function(){this._currentState=g.states.off,this._inputPaneShowing=this._inputPaneShowing.bind(this),this._inputPaneHiding=this._inputPaneHiding.bind(this),this._documentScroll=this._documentScroll.bind(this),this._windowResized=this._windowResized.bind(this)},{initialize:function(){this._toggleListeners(g.states.on)},reset:function(){this._toggleListeners(g.states.off),this._toggleListeners(g.states.on)},_inputPaneShowing:function(b){i(g.profilerString+"_showingKeyboard,StartTM"),a(b,"_showingKeyboard"),i(g.profilerString+"_showingKeyboard,StopTM")},_inputPaneHiding:function(b){i(g.profilerString+"_hidingKeyboard,StartTM"),a(b,"_hidingKeyboard"),i(g.profilerString+"_hidingKeyboard,StopTM")},_documentScroll:function(b){i(g.profilerString+"_checkScrollPosition,StartTM"),a(b,"_checkScrollPosition"),i(g.profilerString+"_checkScrollPosition,StopTM")},_windowResized:function(b){i(g.profilerString+"_baseResize,StartTM"),a(b,"_baseResize"),i(g.profilerString+"_baseResize,StopTM")},_toggleListeners:function(a){var d;if(this._currentState!==a){if(a===g.states.on?d="addEventListener":a===g.states.off&&(d="removeEventListener"),c.Windows.UI.ViewManagement.InputPane){var e=c.Windows.UI.ViewManagement.InputPane.getForCurrentView();e[d]("showing",this._inputPaneShowing,!1),e[d]("hiding",this._inputPaneHiding,!1),b.document[d]("scroll",this._documentScroll,!1)}b.addEventListener("resize",this._windowResized,!1),this._currentState=a}}},{profilerString:{get:function(){return"WinJS.UI._Overlay Global Listener:"}},states:{get:function(){return{off:0,on:1}}}}),j={get duplicateConstruction(){return"Invalid argument: Controls may only be instantiated one time for each DOM element"},get mustContainCommands(){return"Invalid HTML: AppBars/Menus must contain only AppBarCommands/MenuCommands"},get closeOverlay(){return h._getWinJSString("ui/closeOverlay").value}},l=d.Class.define(function(a,b){this._baseOverlayConstructor(a,b)},{_baseOverlayConstructor:function(a,c){this._disposed=!1,a||(a=b.document.createElement("div"));var d=a.winControl;if(d)throw new f("WinJS.UI._Overlay.DuplicateConstruction",j.duplicateConstruction);this._element||(this._element=a),this._element.hasAttribute("tabIndex")||(this._element.tabIndex=-1),this._sticky=!1,this._doNext="",this._element.style.visibility="hidden",this._element.style.opacity=0,a.winControl=this,q.addClass(this._element,s.overlayClass),q.addClass(this._element,"win-disposable");var e=this._element.getAttribute("unselectable");(null===e||void 0===e)&&this._element.setAttribute("unselectable","on"),this._currentAnimateIn=this._baseAnimateIn,this._currentAnimateOut=this._baseAnimateOut,this._animationPromise=n.as(),this._queuedToShow=[],this._queuedToHide=[],this._queuedCommandAnimation=!1,c&&p.setOptions(this,c),l._globalEventListeners.initialize()},element:{get:function(){return this._element}},dispose:function(){this._disposed||(this._disposed=!0,this._dispose())},_dispose:function(){},_show:function(){this._baseShow()},_hide:function(){this._baseHide()},hidden:{get:function(){return"hidden"===this._element.style.visibility||"hiding"===this._element.winAnimating||"hide"===this._doNext},set:function(a){var b=this.hidden;!a&&b?this.show():a&&!b&&this.hide()}},addEventListener:function(a,b,c){return this._element.addEventListener(a,b,c)},removeEventListener:function(a,b,c){return this._element.removeEventListener(a,b,c)},_baseShow:function(){if(this._animating||this._needToHandleHidingKeyboard)return this._doNext="show",!1;if("visible"!==this._element.style.visibility){this._element.winAnimating="showing",this._element.style.display="",this._element.style.visibility="hidden",this._queuedCommandAnimation&&(this._showAndHideFast(this._queuedToShow,this._queuedToHide),this._queuedToShow=[],this._queuedToHide=[]),this._beforeShow(),this._sendEvent(l.beforeShow),this._ensurePosition();var a=this;return this._animationPromise=this._currentAnimateIn().then(function(){a._baseEndShow()},function(){a._baseEndShow()}),!0}return!1},_beforeShow:function(){},_ensurePosition:function(){},_baseEndShow:function(){this._disposed||(this._element.setAttribute("aria-hidden","false"),this._element.winAnimating="","show"===this._doNext&&(this._doNext=""),this._sendEvent(l.afterShow),this._writeProfilerMark("show,StopTM"),o.schedule(this._checkDoNext,o.Priority.normal,this,"WinJS.UI._Overlay._checkDoNext"))},_baseHide:function(){if(this._animating)return this._doNext="hide",!1;if(this._needToHandleHidingKeyboard&&(this._element.style.visibility=""),"hidden"!==this._element.style.visibility){if(this._element.winAnimating="hiding",this._element.setAttribute("aria-hidden","true"),this._sendEvent(l.beforeHide),""===this._element.style.visibility)this._element.style.opacity=0,this._baseEndHide();else{var a=this;this._animationPromise=this._currentAnimateOut().then(function(){a._baseEndHide()},function(){a._baseEndHide()})}return!0}return!1},_baseEndHide:function(){this._disposed||(this._beforeEndHide(),this._element.style.visibility="hidden",this._element.style.display="none",this._element.winAnimating="",this._queuedCommandAnimation&&(this._showAndHideFast(this._queuedToShow,this._queuedToHide),this._queuedToShow=[],this._queuedToHide=[]),"hide"===this._doNext&&(this._doNext=""),this._afterHide(),this._sendEvent(l.afterHide),this._writeProfilerMark("hide,StopTM"),o.schedule(this._checkDoNext,o.Priority.normal,this,"WinJS.UI._Overlay._checkDoNext"))},_beforeEndHide:function(){},_afterHide:function(){},_checkDoNext:function(){this._animating||this._needToHandleHidingKeyboard||this._disposed||("hide"===this._doNext?(this._hide(),this._doNext=""):this._queuedCommandAnimation?this._showAndHideQueue():"show"===this._doNext&&(this._show(),this._doNext=""))},_baseAnimateIn:function(){return this._element.style.opacity=0,this._element.style.visibility="visible",q._getComputedStyle(this._element,null).opacity,k.fadeIn(this._element)},_baseAnimateOut:function(){return this._element.style.opacity=1,q._getComputedStyle(this._element,null).opacity,k.fadeOut(this._element)},_animating:{get:function(){return!!this._element.winAnimating}},_sendEvent:function(a,c){if(!this._disposed){var d=b.document.createEvent("CustomEvent");d.initEvent(a,!0,!0,c||{}),this._element.dispatchEvent(d)}},_showCommands:function(a,b){var c=this._resolveCommands(a);this._showAndHideCommands(c.commands,[],b)},_hideCommands:function(a,b){var c=this._resolveCommands(a);this._showAndHideCommands([],c.commands,b)},_showOnlyCommands:function(a,b){var c=this._resolveCommands(a);this._showAndHideCommands(c.commands,c.others,b)},_showAndHideCommands:function(a,b,c){c||this.hidden&&!this._animating?(this._showAndHideFast(a,b),this._removeFromQueue(a,this._queuedToShow),this._removeFromQueue(b,this._queuedToHide)):(this._updateAnimateQueue(a,this._queuedToShow,this._queuedToHide),this._updateAnimateQueue(b,this._queuedToHide,this._queuedToShow))},_removeFromQueue:function(a,b){var c;for(c=0;c<a.length;c++){var d;for(d=0;d<b.length;d++)if(b[d]===a[c]){b.splice(d,1);break}}},_updateAnimateQueue:function(a,b,c){if(!this._disposed){var d;for(d=0;d<a.length;d++){var e;for(e=0;e<b.length&&b[e]!==a[d];e++);for(e===b.length&&(b[e]=a[d]),e=0;e<c.length;e++)if(c[e]===a[d]){c.splice(e,1);break}}this._queuedCommandAnimation||(this._animating||o.schedule(this._checkDoNext,o.Priority.normal,this,"WinJS.UI._Overlay._checkDoNext"),this._queuedCommandAnimation=!0)}},_showAndHideFast:function(a,b){var c,d;for(c=0;c<a.length;c++)d=a[c],d&&d.style&&(d.style.visibility="",d.style.display="");for(c=0;c<b.length;c++)d=b[c],d&&d.style&&(d.style.visibility="hidden",d.style.display="none");this._commandsUpdated()},_showAndHideQueue:function(){if(this._queuedCommandAnimation=!1,this.hidden)this._showAndHideFast(this._queuedToShow,this._queuedToHide),o.schedule(this._checkDoNext,o.Priority.normal,this,"WinJS.UI._Overlay._checkDoNext");else{var a,c=this._queuedToShow,d=this._queuedToHide,e=this._findSiblings(c.concat(d));for(a=0;a<c.length;a++)c[a]&&c[a].style&&b.document.body.contains(c[a])?"hidden"!==c[a].style.visibility&&"0"!==c[a].style.opacity&&(e.push(c[a]),c.splice(a,1),a--):(c.splice(a,1),a--);for(a=0;a<d.length;a++)d[a]&&d[a].style&&b.document.body.contains(d[a])&&"hidden"!==d[a].style.visibility&&"0"!==d[a].style.opacity||(d.splice(a,1),a--);var f=this._baseBeginAnimateCommands(c,d,e),g=this;f?f.done(function(){g._baseEndAnimateCommands(d)},function(){g._baseEndAnimateCommands(d)}):o.schedule(function(){g._baseEndAnimateCommands([])},o.Priority.normal,null,"WinJS.UI._Overlay._endAnimateCommandsWithoutAnimation")}this._queuedToShow=[],this._queuedToHide=[]},_baseBeginAnimateCommands:function(a,b,c){this._beginAnimateCommands(a,b,this._getVisibleCommands(c));var d=null,e=null;b.length>0&&(e=k.createDeleteFromListAnimation(b,0===a.length?c:void 0)),a.length>0&&(d=k.createAddToListAnimation(a,c));for(var f=0,g=b.length;g>f;f++){var h=b[f].getBoundingClientRect(),i=q._getComputedStyle(b[f]);b[f].style.top=h.top-parseFloat(i.marginTop)+"px",b[f].style.left=h.left-parseFloat(i.marginLeft)+"px",b[f].style.opacity=0,b[f].style.position="fixed"}this._element.winAnimating="rearranging";var j=null;for(e&&(j=e.execute()),f=0;f<a.length;f++)a[f].style.visibility="",a[f].style.display="",a[f].style.opacity=1;if(d){var l=d.execute();j=j?n.join([j,l]):l}return j},_beginAnimateCommands:function(){},_getVisibleCommands:function(a){var b,c=a,d=[];c||(c=this.element.querySelectorAll(".win-command"));for(var e=0,f=c.length;f>e;e++)b=c[e].winControl||c[e],b.hidden||d.push(b);return d},_baseEndAnimateCommands:function(a){if(!this._disposed){var b;for(b=0;b<a.length;b++)a[b].style.position="",a[b].style.top="",a[b].style.left="",a[b].getBoundingClientRect(),a[b].style.visibility="hidden",a[b].style.display="none",a[b].style.opacity=1;this._element.winAnimating="",this._endAnimateCommands(),this._checkDoNext()}},_endAnimateCommands:function(){},_resolveCommands:function(a){a=e(a);var b={};b.commands=[],b.others=[];var c,d,f=this.element.querySelectorAll(".win-command");for(c=0;c<f.length;c++){var g=!1;for(d=0;d<a.length;d++)if(a[d]===f[c]){b.commands.push(f[c]),a.splice(d,1),g=!0;break}g||b.others.push(f[c])}return b},_findSiblings:function(a){var b,c,d=[],e=this.element.querySelectorAll(".win-command");for(b=0;b<e.length;b++){var f=!1;for(c=0;c<a.length;c++)if(a[c]===e[b]){a.splice(c,1),f=!0;break}f||d.push(e[b])}return d},_baseResize:function(a){this._resize(a)},_hideOrDismiss:function(){var a=this._element;a&&q.hasClass(a,s.settingsFlyoutClass)?this._dismiss():a&&q.hasClass(a,s.appBarClass)?this.close():this.hide()},_resize:function(){},_commandsUpdated:function(){},_checkScrollPosition:function(){},_showingKeyboard:function(){},_hidingKeyboard:function(){},_verifyCommandsOnly:function(a,b){for(var c=a.children,d=new Array(c.length),e=0;e<c.length;e++){if(!q.hasClass(c[e],"win-command")&&c[e].getAttribute("data-win-control")!==b)throw new f("WinJS.UI._Overlay.MustContainCommands",j.mustContainCommands);m.processAll(c[e]),d[e]=c[e].winControl}return d},_focusOnLastFocusableElementOrThis:function(){this._focusOnLastFocusableElement()||l._trySetActive(this._element)},_focusOnLastFocusableElement:function(){if(this._element.firstElementChild){var a=this._element.firstElementChild.tabIndex,c=this._element.lastElementChild.tabIndex;this._element.firstElementChild.tabIndex=-1,this._element.lastElementChild.tabIndex=-1;var d=q._focusLastFocusableElement(this._element);return d&&l._trySelect(b.document.activeElement),this._element.firstElementChild.tabIndex=a,this._element.lastElementChild.tabIndex=c,d}return!1},_focusOnFirstFocusableElementOrThis:function(){this._focusOnFirstFocusableElement()||l._trySetActive(this._element)},_focusOnFirstFocusableElement:function(a,c){if(this._element.firstElementChild){var d=this._element.firstElementChild.tabIndex,e=this._element.lastElementChild.tabIndex;this._element.firstElementChild.tabIndex=-1,this._element.lastElementChild.tabIndex=-1;var f=q._focusFirstFocusableElement(this._element,a,c);return f&&l._trySelect(b.document.activeElement),this._element.firstElementChild.tabIndex=d,this._element.lastElementChild.tabIndex=e,f}return!1},_writeProfilerMark:function(a){i("WinJS.UI._Overlay:"+this._id+":"+a)}},{_isFlyoutVisible:function(){for(var a=b.document.querySelectorAll("."+s.flyoutClass),c=0;c<a.length;c++){var d=a[c].winControl;if(d&&!d.hidden)return!0}return!1},_trySetActive:function(a,c){return a&&b.document.body&&b.document.body.contains(a)&&q._setActive(a,c)?a===b.document.activeElement:!1},_trySelect:function(a){try{a&&a.select&&a.select()}catch(b){}},_sizeOfDocument:function(){return{width:b.document.documentElement.offsetWidth,height:b.document.documentElement.offsetHeight}},_getParentControlUsingClassName:function(a,c){for(;a&&a!==b.document.body;){if(q.hasClass(a,c))return a.winControl;a=a.parentNode}return null},_globalEventListeners:new g,_hideAppBars:function(a){var b=a.map(function(a){return a.close(),a._animationPromise});return n.join(b)},_showAppBars:function(a){var b=a.map(function(a){return a._show(),a._animationPromise});return n.join(b)},_keyboardInfo:r._KeyboardInfo,_scrollTimeout:r._KeyboardInfo._scrollTimeout,beforeShow:"beforeshow",beforeHide:"beforehide",afterShow:"aftershow",afterHide:"afterhide",commonstrings:{get cannotChangeCommandsWhenVisible(){return"Invalid argument: You must call hide() before changing {0} commands"},get cannotChangeHiddenProperty(){return"Unable to set hidden property while parent {0} is visible."}}});return d.Class.mix(l,p.DOMEventMixin),l})})}),d("WinJS/Controls/Flyout",["exports","../Core/_Global","../Core/_Base","../Core/_BaseUtils","../Core/_ErrorFromName","../Core/_Events","../Core/_Log","../Core/_Resources","../Core/_WriteProfilerMark","../Animations","../_Signal","../_LightDismissService","../Utilities/_Dispose","../Utilities/_ElementUtilities","../Utilities/_KeyboardBehavior","../Utilities/_Hoverable","./_LegacyAppBar/_Constants","./Flyout/_Overlay"],function(a,b,c,d,e,f,g,h,i,j,k,l,m,n,o,p,q,r){"use strict";c.Namespace._moduleDefine(a,"WinJS.UI",{Flyout:c.Namespace._lazy(function(){function a(a,b){return n.convertToPixels(a,n._getComputedStyle(a,null)[b])}function p(b){return{marginTop:a(b,"marginTop"),marginBottom:a(b,"marginBottom"),marginLeft:a(b,"marginLeft"),marginRight:a(b,"marginRight"),totalWidth:n.getTotalWidth(b),totalHeight:n.getTotalHeight(b),contentWidth:n.getContentWidth(b),contentHeight:n.getContentHeight(b)}}var s=n.Key,t={get ariaLabel(){return h._getWinJSString("ui/flyoutAriaLabel").value},get noAnchor(){return"Invalid argument: Flyout anchor element not found in DOM."},get badPlacement(){return"Invalid argument: Flyout placement should be 'top' (default), 'bottom', 'left', 'right', 'auto', 'autohorizontal', or 'autovertical'."},get badAlignment(){return"Invalid argument: Flyout alignment should be 'center' (default), 'left', or 'right'."},get noCoordinates(){return"Invalid argument: Flyout coordinates must contain a valid x,y pair."}},u=f._createEventProperty,v=c.Class.define(function(a){this._onLightDismiss=a,this._currentlyFocusedClient=null,this._clients=[]},{shown:function(a){a._focusable=!0;var b=this._clients.indexOf(a);-1===b&&(this._clients.push(a),a.onShow(this),l.isShown(this)?(l.updated(this),this._activateTopFocusableClientIfNeeded()):l.shown(this))},hiding:function(a){var b=this._clients.indexOf(a);-1!==b&&(this._clients[b]._focusable=!1,this._activateTopFocusableClientIfNeeded())},hidden:function(a){var b=this._clients.indexOf(a);-1!==b&&(this._clients.splice(b,1),a.setZIndex(""),a.onHide(),0===this._clients.length?l.hidden(this):(l.updated(this),this._activateTopFocusableClientIfNeeded()))},keyDown:function(a,b){l.keyDown(this,b)},keyUp:function(a,b){l.keyUp(this,b)},keyPress:function(a,b){l.keyPress(this,b)},clients:{get:function(){return this._clients}},_clientForElement:function(a){for(var b=this._clients.length-1;b>=0;b--)if(this._clients[b].containsElement(a))return this._clients[b];return null},_focusableClientForElement:function(a){for(var b=this._clients.length-1;b>=0;b--)if(this._clients[b]._focusable&&this._clients[b].containsElement(a))return this._clients[b];return null},_getTopmostFocusableClient:function(){for(var a=this._clients.length-1;a>=0;a--){var b=this._clients[a];if(b&&b._focusable)return b}return null},_activateTopFocusableClientIfNeeded:function(){var a=this._getTopmostFocusableClient();if(a&&l.isTopmost(this)){var b=!o._keyboardSeenLast;a.onTakeFocus(b)}},setZIndex:function(a){this._clients.forEach(function(b,c){b.setZIndex(a+c)},this)},getZIndexCount:function(){return this._clients.length},containsElement:function(a){return!!this._clientForElement(a)},onTakeFocus:function(a){var c=this._focusableClientForElement(b.document.activeElement);!c&&-1!==this._clients.indexOf(this._currentlyFocusedClient)&&this._currentlyFocusedClient._focusable&&(c=this._currentlyFocusedClient),c||(c=this._getTopmostFocusableClient()),this._currentlyFocusedClient=c,c&&c.onTakeFocus(a)},onFocus:function(a){this._currentlyFocusedClient=this._clientForElement(a),this._currentlyFocusedClient&&this._currentlyFocusedClient.onFocus(a)},onShow:function(){},onHide:function(){this._currentlyFocusedClient=null},onKeyInStack:function(a){var b=this._clients.indexOf(this._currentlyFocusedClient); if(-1!==b)for(var c=this._clients.slice(0,b+1),d=c.length-1;d>=0&&!a.propagationStopped;d--)c[d]._focusable&&c[d].onKeyInStack(a)},onShouldLightDismiss:function(a){return l.DismissalPolicies.light(a)},onLightDismiss:function(a){this._onLightDismiss(a)}}),w=c.Class.define(function(){var a=this;this._dismissableLayer=new v(function(b){b.reason===l.LightDismissalReasons.escape?a.collapseFlyout(a.getAt(a.length-1)):a.collapseAll()}),this._cascadingStack=[],this._handleKeyDownInCascade_bound=this._handleKeyDownInCascade.bind(this),this._inputType=null},{appendFlyout:function(a){if(g.log&&this.reentrancyLock&&g.log("_CascadeManager is attempting to append a Flyout through reentrancy.","winjs _CascadeManager","error"),this.indexOf(a)<0){var b=this.collapseAll;if(a._positionRequest instanceof y.AnchorPositioning){var c=this.indexOfElement(a._positionRequest.anchor);c>=0&&(b=function(){this.collapseFlyout(this.getAt(c+1))})}b.call(this),a.element.addEventListener("keydown",this._handleKeyDownInCascade_bound,!1),this._cascadingStack.push(a)}},collapseFlyout:function(a){if(!this.reentrancyLock&&a&&this.indexOf(a)>=0){this.reentrancyLock=!0;var b=new k;this.unlocked=b.promise;for(var c;this.length&&a!==c;)c=this._cascadingStack.pop(),c.element.removeEventListener("keydown",this._handleKeyDownInCascade_bound,!1),c._hide();0===this._cascadingStack.length&&(this._inputType=null),this.reentrancyLock=!1,this.unlocked=null,b.complete()}},flyoutShown:function(a){this._dismissableLayer.shown(a._dismissable)},flyoutHiding:function(a){this._dismissableLayer.hiding(a._dismissable)},flyoutHidden:function(a){this._dismissableLayer.hidden(a._dismissable)},collapseAll:function(){var a=this.getAt(0);a&&this.collapseFlyout(a)},indexOf:function(a){return this._cascadingStack.indexOf(a)},indexOfElement:function(a){for(var b=-1,c=0,d=this.length;d>c;c++){var e=this.getAt(c);if(e.element.contains(a)){b=c;break}}return b},length:{get:function(){return this._cascadingStack.length}},getAt:function(a){return this._cascadingStack[a]},handleFocusIntoFlyout:function(a){var b=this.indexOfElement(a.target);if(b>=0){var c=this.getAt(b+1);this.collapseFlyout(c)}},inputType:{get:function(){return this._inputType||(this._inputType=o._lastInputType),this._inputType}},dismissableLayer:{get:function(){return this._dismissableLayer}},_handleKeyDownInCascade:function(a){var b="rtl"===n._getComputedStyle(a.target).direction,c=b?s.rightArrow:s.leftArrow,d=a.target;if(a.keyCode===c){var e=this.indexOfElement(d);if(e>=1){var f=this.getAt(e);this.collapseFlyout(f),a.preventDefault()}}else(a.keyCode===s.alt||a.keyCode===s.F10)&&this.collapseAll()}}),x={top:{top:"50px",left:"0px",keyframe:"WinJS-showFlyoutTop"},bottom:{top:"-50px",left:"0px",keyframe:"WinJS-showFlyoutBottom"},left:{top:"0px",left:"50px",keyframe:"WinJS-showFlyoutLeft"},right:{top:"0px",left:"-50px",keyframe:"WinJS-showFlyoutRight"}},y={AnchorPositioning:c.Class.define(function(a,c,d){if("string"==typeof a?a=b.document.getElementById(a):a&&a.element&&(a=a.element),!a)throw new e("WinJS.UI.Flyout.NoAnchor",t.noAnchor);this.anchor=a,this.placement=c,this.alignment=d},{getTopLeft:function(a,b){function c(a){h(a)?(z=f(a)-y,u=r._Overlay._keyboardInfo._visibleDocTop,w=x.top):(z=g(a)-y,u=q.pinToBottomEdge,w=x.bottom),v=!0}function d(a,b){return(r._Overlay._keyboardInfo._visibleDocHeight-a.height)/2>=b.totalHeight}function f(a){return a.top-r._Overlay._keyboardInfo._visibleDocTop}function g(a){return r._Overlay._keyboardInfo._visibleDocBottom-a.bottom}function h(a){return f(a)>g(a)}function i(a,b){return u=a-b.totalHeight,w=x.top,u>=r._Overlay._keyboardInfo._visibleDocTop&&u+b.totalHeight<=r._Overlay._keyboardInfo._visibleDocBottom}function j(a,b){return u=a,w=x.bottom,u>=r._Overlay._keyboardInfo._visibleDocTop&&u+b.totalHeight<=r._Overlay._keyboardInfo._visibleDocBottom}function k(a,b){return s=a-b.totalWidth,w=x.left,s>=0&&s+b.totalWidth<=r._Overlay._keyboardInfo._visualViewportWidth}function l(a,b){return s=a,w=x.right,s>=0&&s+b.totalWidth<=r._Overlay._keyboardInfo._visualViewportWidth}function m(a,b){u=a.top+a.height/2-b.totalHeight/2,u<r._Overlay._keyboardInfo._visibleDocTop?u=r._Overlay._keyboardInfo._visibleDocTop:u+b.totalHeight>=r._Overlay._keyboardInfo._visibleDocBottom&&(u=q.pinToBottomEdge)}function n(a,b,c){if("center"===c)s=a.left+a.width/2-b.totalWidth/2;else if("left"===c)s=a.left;else{if("right"!==c)throw new e("WinJS.UI.Flyout.BadAlignment",t.badAlignment);s=a.right-b.totalWidth}0>s?s=0:s+b.totalWidth>=r._Overlay._keyboardInfo._visualViewportWidth&&(s=q.pinToRightEdge)}var o;try{o=this.anchor.getBoundingClientRect()}catch(p){throw new e("WinJS.UI.Flyout.NoAnchor",t.noAnchor)}var s,u,v,w,y=a.totalHeight-a.contentHeight,z=a.contentHeight,A=this.alignment;switch(this.placement){case"top":i(o.top,a)||(u=r._Overlay._keyboardInfo._visibleDocTop,v=!0,z=f(o)-y),n(o,a,A);break;case"bottom":j(o.bottom,a)||(u=q.pinToBottomEdge,v=!0,z=g(o)-y),n(o,a,A);break;case"left":k(o.left,a)||(s=0),m(o,a);break;case"right":l(o.right,a)||(s=q.pinToRightEdge),m(o,a);break;case"autovertical":i(o.top,a)||j(o.bottom,a)||c(o),n(o,a,A);break;case"autohorizontal":k(o.left,a)||l(o.right,a)||(s=q.pinToRightEdge),m(o,a);break;case"auto":d(o,a)?(i(o.top,a)||j(o.bottom,a),n(o,a,A)):k(o.left,a)||l(o.right,a)?m(o,a):(c(o),n(o,a,A));break;case"_cascade":j(o.top-a.marginTop,a)||i(o.bottom+a.marginBottom,a)||m(o,a);var B=3,C=o.right-a.marginLeft-B,D=o.left+a.marginRight+B;b?k(D,a)||l(C,a)||(s=0,w=x.left):l(C,a)||k(D,a)||(s=q.pinToRightEdge,w=x.right);break;default:throw new e("WinJS.UI.Flyout.BadPlacement",t.badPlacement)}return{left:s,top:u,animOffset:w,doesScroll:v,contentHeight:z,verticalMarginBorderPadding:y}}}),CoordinatePositioning:c.Class.define(function(a){if(a.clientX===+a.clientX&&a.clientY===+a.clientY){var b=a;a={x:b.clientX,y:b.clientY}}else if(a.x!==+a.x||a.y!==+a.y)throw new e("WinJS.UI.Flyout.NoCoordinates",t.noCoordinates);this.coordinates=a},{getTopLeft:function(a,b){var c=this.coordinates,d=a.totalWidth-a.marginLeft-a.marginRight,e=b?d:0,f=a.totalHeight-a.contentHeight,g=a.contentHeight,h=c.y-a.marginTop,i=c.x-a.marginLeft-e;return 0>h?h=0:h+a.totalHeight>r._Overlay._keyboardInfo._visibleDocBottom&&(h=q.pinToBottomEdge),0>i?i=0:i+a.totalWidth>r._Overlay._keyboardInfo._visualViewportWidth&&(i=q.pinToRightEdge),{left:i,top:h,verticalMarginBorderPadding:f,contentHeight:g,doesScroll:!1,animOffset:x.top}}})},z=c.Class.derive(r._Overlay,function(a,c){c=c||{},this._element=a||b.document.createElement("div"),this._id=this._element.id||n._uniqueID(this._element),this._writeProfilerMark("constructor,StartTM"),this._baseFlyoutConstructor(this._element,c);var d=this._element.getElementsByTagName("*"),e=this._addFirstDiv();e.tabIndex=n._getLowestTabIndexInList(d);var f=this._addFinalDiv();return f.tabIndex=n._getHighestTabIndexInList(d),this._element.addEventListener("keydown",this._handleKeyDown,!0),this._writeProfilerMark("constructor,StopTM"),this},{_lastMaxHeight:null,_baseFlyoutConstructor:function(a,b){this._placement="auto",this._alignment="center",this._baseOverlayConstructor(a,b),this._element.style.visibilty="hidden",this._element.style.display="none",n.addClass(this._element,q.flyoutClass);var c=this;this._dismissable=new l.LightDismissableElement({element:this._element,tabIndex:this._element.hasAttribute("tabIndex")?this._element.tabIndex:-1,onLightDismiss:function(){c.hide()},onTakeFocus:function(){c._dismissable.restoreFocus()||(n.hasClass(c.element,q.menuClass)?r._Overlay._trySetActive(c._element):c._focusOnFirstFocusableElementOrThis())}});var d=this._element.getAttribute("role");(null===d||""===d||void 0===d)&&(n.hasClass(this._element,q.menuClass)?this._element.setAttribute("role","menu"):this._element.setAttribute("role","dialog"));var e=this._element.getAttribute("aria-label");(null===e||""===e||void 0===e)&&this._element.setAttribute("aria-label",t.ariaLabel),this._currentAnimateIn=this._flyoutAnimateIn,this._currentAnimateOut=this._flyoutAnimateOut,n._addEventListener(this.element,"focusin",this._handleFocusIn.bind(this),!1)},anchor:{get:function(){return this._anchor},set:function(a){this._anchor=a}},placement:{get:function(){return this._placement},set:function(a){if("top"!==a&&"bottom"!==a&&"left"!==a&&"right"!==a&&"auto"!==a&&"autohorizontal"!==a&&"autovertical"!==a)throw new e("WinJS.UI.Flyout.BadPlacement",t.badPlacement);this._placement=a}},alignment:{get:function(){return this._alignment},set:function(a){if("right"!==a&&"left"!==a&&"center"!==a)throw new e("WinJS.UI.Flyout.BadAlignment",t.badAlignment);this._alignment=a}},disabled:{get:function(){return!!this._element.disabled},set:function(a){a=!!a;var b=!!this._element.disabled;b!==a&&(this._element.disabled=a,!this.hidden&&this._element.disabled&&this.hide())}},onbeforeshow:u(r._Overlay.beforeShow),onaftershow:u(r._Overlay.afterShow),onbeforehide:u(r._Overlay.beforeHide),onafterhide:u(r._Overlay.afterHide),_dispose:function(){m.disposeSubTree(this.element),this._hide(),z._cascadeManager.flyoutHidden(this),this.anchor=null},show:function(a,b,c){this._writeProfilerMark("show,StartTM"),this._positionRequest=new y.AnchorPositioning(a||this._anchor,b||this._placement,c||this._alignment),this._show()},_show:function(){this._baseFlyoutShow()},showAt:function(a){this._writeProfilerMark("show,StartTM"),this._positionRequest=new y.CoordinatePositioning(a),this._show()},hide:function(){this._writeProfilerMark("hide,StartTM"),this._hide()},_hide:function(){z._cascadeManager.collapseFlyout(this),this._baseHide()&&z._cascadeManager.flyoutHiding(this)},_beforeEndHide:function(){z._cascadeManager.flyoutHidden(this)},_baseFlyoutShow:function(){if(!this.disabled&&!this._disposed)if(z._cascadeManager.appendFlyout(this),this._element.winAnimating)this._doNext="show";else if(z._cascadeManager.reentrancyLock){this._doNext="show";var a=this;z._cascadeManager.unlocked.then(function(){a._checkDoNext()})}else if(this._baseShow()){if(!n.hasClass(this.element,"win-menu")){var b=this._element.getElementsByTagName("*"),c=this.element.querySelectorAll(".win-first");this.element.children.length&&!n.hasClass(this.element.children[0],q.firstDivClass)&&(c&&c.length>0&&c.item(0).parentNode.removeChild(c.item(0)),c=this._addFirstDiv()),c.tabIndex=n._getLowestTabIndexInList(b);var d=this.element.querySelectorAll(".win-final");n.hasClass(this.element.children[this.element.children.length-1],q.finalDivClass)||(d&&d.length>0&&d.item(0).parentNode.removeChild(d.item(0)),d=this._addFinalDiv()),d.tabIndex=n._getHighestTabIndexInList(b)}z._cascadeManager.flyoutShown(this)}},_lightDismiss:function(){z._cascadeManager.collapseAll()},_ensurePosition:function(){this._keyboardMovedUs=!1,this._clearAdjustedStyles(),this._setAlignment();var a=p(this._element),b="rtl"===n._getComputedStyle(this._element).direction;this._currentPosition=this._positionRequest.getTopLeft(a,b),this._currentPosition.top<0?(this._element.style.bottom=r._Overlay._keyboardInfo._visibleDocBottomOffset+"px",this._element.style.top="auto"):(this._element.style.top=this._currentPosition.top+"px",this._element.style.bottom="auto"),this._currentPosition.left<0?(this._element.style.right="0px",this._element.style.left="auto"):(this._element.style.left=this._currentPosition.left+"px",this._element.style.right="auto"),this._currentPosition.doesScroll&&(n.addClass(this._element,q.scrollsClass),this._lastMaxHeight=this._element.style.maxHeight,this._element.style.maxHeight=this._currentPosition.contentHeight+"px"),r._Overlay._keyboardInfo._visible&&(this._checkKeyboardFit(),this._keyboardMovedUs&&this._adjustForKeyboard())},_clearAdjustedStyles:function(){this._element.style.top="0px",this._element.style.bottom="auto",this._element.style.left="0px",this._element.style.right="auto",n.removeClass(this._element,q.scrollsClass),null!==this._lastMaxHeight&&(this._element.style.maxHeight=this._lastMaxHeight,this._lastMaxHeight=null),n.removeClass(this._element,"win-rightalign"),n.removeClass(this._element,"win-leftalign")},_setAlignment:function(){switch(this._positionRequest.alignment){case"left":n.addClass(this._element,"win-leftalign");break;case"right":n.addClass(this._element,"win-rightalign")}},_showingKeyboard:function(a){if(!this.hidden&&(a.ensuredFocusedElementInView=!0,this._checkKeyboardFit(),this._keyboardMovedUs)){this._element.style.opacity=0;var c=this;b.setTimeout(function(){c._adjustForKeyboard(),c._baseAnimateIn()},r._Overlay._keyboardInfo._animationShowLength)}},_resize:function(){if((!this.hidden||this._animating)&&this._needToHandleHidingKeyboard){var a=this;d._setImmediate(function(){(!a.hidden||a._animating)&&a._ensurePosition()}),this._needToHandleHidingKeyboard=!1}},_checkKeyboardFit:function(){var a=!1,b=r._Overlay._keyboardInfo._visibleDocHeight,c=this._currentPosition.contentHeight+this._currentPosition.verticalMarginBorderPadding;c>b?(a=!0,this._currentPosition.top=q.pinToBottomEdge,this._currentPosition.contentHeight=b-this._currentPosition.verticalMarginBorderPadding,this._currentPosition.doesScroll=!0):this._currentPosition.top>=0&&this._currentPosition.top+c>r._Overlay._keyboardInfo._visibleDocBottom?(this._currentPosition.top=q.pinToBottomEdge,a=!0):this._currentPosition.top===q.pinToBottomEdge&&(a=!0),this._keyboardMovedUs=a},_adjustForKeyboard:function(){this._currentPosition.doesScroll&&(this._lastMaxHeight||(n.addClass(this._element,q.scrollsClass),this._lastMaxHeight=this._element.style.maxHeight),this._element.style.maxHeight=this._currentPosition.contentHeight+"px"),this._checkScrollPosition(!0)},_hidingKeyboard:function(){if(!this.hidden||this._animating)if(r._Overlay._keyboardInfo._isResized)this._needToHandleHidingKeyboard=!0;else{var a=this;d._setImmediate(function(){(!a.hidden||a._animating)&&a._ensurePosition()})}},_checkScrollPosition:function(a){(!this.hidden||a)&&(this._currentPosition.top<0?(this._element.style.bottom=r._Overlay._keyboardInfo._visibleDocBottomOffset+"px",this._element.style.top="auto"):(this._element.style.top=this._currentPosition.top+"px",this._element.style.bottom="auto"))},_flyoutAnimateIn:function(){return this._keyboardMovedUs?this._baseAnimateIn():(this._element.style.opacity=1,this._element.style.visibility="visible",j.showPopup(this._element,this._currentPosition.animOffset))},_flyoutAnimateOut:function(){return this._keyboardMovedUs?this._baseAnimateOut():(this._element.style.opacity=0,j.hidePopup(this._element,this._currentPosition.animOffset))},_hideAllOtherFlyouts:function(a){for(var c=b.document.querySelectorAll("."+q.flyoutClass),d=0;d<c.length;d++){var e=c[d].winControl;e&&!e.hidden&&e!==a&&e.hide()}},_handleKeyDown:function(a){a.keyCode!==s.space&&a.keyCode!==s.enter||this!==b.document.activeElement?!a.shiftKey||a.keyCode!==s.tab||this!==b.document.activeElement||a.altKey||a.ctrlKey||a.metaKey||(a.preventDefault(),a.stopPropagation(),this.winControl._focusOnLastFocusableElementOrThis()):(a.preventDefault(),a.stopPropagation(),this.winControl.hide())},_handleFocusIn:function(a){this.element.contains(a.relatedTarget)||z._cascadeManager.handleFocusIntoFlyout(a)},_addFirstDiv:function(){var a=b.document.createElement("div");a.className=q.firstDivClass,a.style.display="inline",a.setAttribute("role","menuitem"),a.setAttribute("aria-hidden","true"),this._element.children[0]?this._element.insertBefore(a,this._element.children[0]):this._element.appendChild(a);var c=this;return n._addEventListener(a,"focusin",function(){c._focusOnLastFocusableElementOrThis()},!1),a},_addFinalDiv:function(){var a=b.document.createElement("div");a.className=q.finalDivClass,a.style.display="inline",a.setAttribute("role","menuitem"),a.setAttribute("aria-hidden","true"),this._element.appendChild(a);var c=this;return n._addEventListener(a,"focusin",function(){c._focusOnFirstFocusableElementOrThis()},!1),a},_writeProfilerMark:function(a){i("WinJS.UI.Flyout:"+this._id+":"+a)}},{_cascadeManager:new w});return z})})}),d("WinJS/Controls/CommandingSurface/_Constants",["require","exports"],function(a,b){b.ClassNames={controlCssClass:"win-commandingsurface",disposableCssClass:"win-disposable",tabStopClass:"win-commandingsurface-tabstop",contentClass:"win-commandingsurface-content",actionAreaCssClass:"win-commandingsurface-actionarea",actionAreaContainerCssClass:"win-commandingsurface-actionareacontainer",overflowButtonCssClass:"win-commandingsurface-overflowbutton",spacerCssClass:"win-commandingsurface-spacer",ellipsisCssClass:"win-commandingsurface-ellipsis",overflowAreaCssClass:"win-commandingsurface-overflowarea",overflowAreaContainerCssClass:"win-commandingsurface-overflowareacontainer",contentFlyoutCssClass:"win-commandingsurface-contentflyout",menuCssClass:"win-menu",menuContainsToggleCommandClass:"win-menu-containstogglecommand",insetOutlineClass:"win-commandingsurface-insetoutline",openingClass:"win-commandingsurface-opening",openedClass:"win-commandingsurface-opened",closingClass:"win-commandingsurface-closing",closedClass:"win-commandingsurface-closed",noneClass:"win-commandingsurface-closeddisplaynone",minimalClass:"win-commandingsurface-closeddisplayminimal",compactClass:"win-commandingsurface-closeddisplaycompact",fullClass:"win-commandingsurface-closeddisplayfull",overflowTopClass:"win-commandingsurface-overflowtop",overflowBottomClass:"win-commandingsurface-overflowbottom",commandHiddenClass:"win-commandingsurface-command-hidden",commandPrimaryOverflownPolicyClass:"win-commandingsurface-command-primary-overflown",commandSecondaryOverflownPolicyClass:"win-commandingsurface-command-secondary-overflown",commandSeparatorHiddenPolicyClass:"win-commandingsurface-command-separator-hidden"},b.EventNames={beforeOpen:"beforeopen",afterOpen:"afteropen",beforeClose:"beforeclose",afterClose:"afterclose",commandPropertyMutated:"_commandpropertymutated"},b.actionAreaCommandWidth=68,b.actionAreaSeparatorWidth=34,b.actionAreaOverflowButtonWidth=32,b.overflowCommandHeight=44,b.overflowSeparatorHeight=12,b.controlMinWidth=b.actionAreaOverflowButtonWidth,b.overflowAreaMaxWidth=480,b.heightOfMinimal=24,b.heightOfCompact=48,b.contentMenuCommandDefaultLabel="Custom content",b.defaultClosedDisplayMode="compact",b.defaultOpened=!1,b.defaultOverflowDirection="bottom",b.typeSeparator="separator",b.typeContent="content",b.typeButton="button",b.typeToggle="toggle",b.typeFlyout="flyout",b.commandSelector=".win-command",b.primaryCommandSection="primary",b.secondaryCommandSection="secondary"}),d("WinJS/Controls/ToolBar/_Constants",["require","exports","../CommandingSurface/_Constants"],function(a,b,c){b.ClassNames={controlCssClass:"win-toolbar",disposableCssClass:"win-disposable",actionAreaCssClass:"win-toolbar-actionarea",overflowButtonCssClass:"win-toolbar-overflowbutton",spacerCssClass:"win-toolbar-spacer",ellipsisCssClass:"win-toolbar-ellipsis",overflowAreaCssClass:"win-toolbar-overflowarea",contentFlyoutCssClass:"win-toolbar-contentflyout",emptytoolbarCssClass:"win-toolbar-empty",menuCssClass:"win-menu",menuContainsToggleCommandClass:"win-menu-containstogglecommand",openedClass:"win-toolbar-opened",closedClass:"win-toolbar-closed",compactClass:"win-toolbar-closeddisplaycompact",fullClass:"win-toolbar-closeddisplayfull",overflowTopClass:"win-toolbar-overflowtop",overflowBottomClass:"win-toolbar-overflowbottom",placeHolderCssClass:"win-toolbar-placeholder"},b.EventNames={beforeOpen:"beforeopen",afterOpen:"afteropen",beforeClose:"beforeclose",afterClose:"afterclose"},b.OverflowDirection={top:"top",bottom:"bottom"},b.overflowAreaMaxWidth=c.overflowAreaMaxWidth,b.controlMinWidth=c.controlMinWidth,b.defaultClosedDisplayMode="compact",b.defaultOpened=!1,b.typeSeparator="separator",b.typeContent="content",b.typeButton="button",b.typeToggle="toggle",b.typeFlyout="flyout",b.commandSelector=".win-command",b.primaryCommandSection="primary",b.secondaryCommandSection="secondary"}),d("WinJS/Controls/AppBar/_Icon",["exports","../../Core/_Base","../../Core/_Resources"],function(a,b,c){"use strict";var d=["previous","next","play","pause","edit","save","clear","delete","remove","add","cancel","accept","more","redo","undo","home","up","forward","right","back","left","favorite","camera","settings","video","sync","download","mail","find","help","upload","emoji","twopage","leavechat","mailforward","clock","send","crop","rotatecamera","people","closepane","openpane","world","flag","previewlink","globe","trim","attachcamera","zoomin","bookmarks","document","protecteddocument","page","bullets","comment","mail2","contactinfo","hangup","viewall","mappin","phone","videochat","switch","contact","rename","pin","musicinfo","go","keyboard","dockleft","dockright","dockbottom","remote","refresh","rotate","shuffle","list","shop","selectall","orientation","import","importall","browsephotos","webcam","pictures","savelocal","caption","stop","showresults","volume","repair","message","page2","calendarday","calendarweek","calendar","characters","mailreplyall","read","link","accounts","showbcc","hidebcc","cut","attach","paste","filter","copy","emoji2","important","mailreply","slideshow","sort","manage","allapps","disconnectdrive","mapdrive","newwindow","openwith","contactpresence","priority","uploadskydrive","gototoday","font","fontcolor","contact2","folder","audio","placeholder","view","setlockscreen","settile","cc","stopslideshow","permissions","highlight","disableupdates","unfavorite","unpin","openlocal","mute","italic","underline","bold","movetofolder","likedislike","dislike","like","alignright","aligncenter","alignleft","zoom","zoomout","openfile","otheruser","admin","street","map","clearselection","fontdecrease","fontincrease","fontsize","cellphone","reshare","tag","repeatone","repeatall","outlinestar","solidstar","calculator","directions","target","library","phonebook","memo","microphone","postupdate","backtowindow","fullscreen","newfolder","calendarreply","unsyncfolder","reporthacked","syncfolder","blockcontact","switchapps","addfriend","touchpointer","gotostart","zerobars","onebar","twobars","threebars","fourbars","scan","preview","hamburger"],e=d.reduce(function(a,b){return a[b]={get:function(){return c._getWinJSString("ui/appBarIcons/"+b).value}},a},{});b.Namespace._moduleDefine(a,"WinJS.UI.AppBarIcon",e)}),d("WinJS/Controls/AppBar/_Command",["exports","../../Core/_Global","../../Core/_WinRT","../../Core/_Base","../../Core/_BaseUtils","../../Core/_ErrorFromName","../../Core/_Events","../../Core/_Resources","../../Utilities/_Control","../../Utilities/_Dispose","../../Utilities/_ElementUtilities","../Flyout/_Overlay","../Tooltip","../_LegacyAppBar/_Constants","./_Icon"],function(a,b,c,d,e,f,g,h,i,j,k,l,m,n,o){"use strict";d.Namespace._moduleDefine(a,"WinJS.UI",{AppBarCommand:d.Namespace._lazy(function(){function a(a){var c=this.winControl;if(c){if(c._type===n.typeToggle)c.selected=!c.selected;else if(c._type===n.typeFlyout&&c._flyout){var d=c._flyout;"string"==typeof d&&(d=b.document.getElementById(d)),d.show||(d=d.winControl),d&&d.show&&d.show(this,"autovertical")}c.onclick&&c.onclick(a)}}function p(a,b){var c=a[b],d=a.constructor.prototype,e=q(d,b)||{},f=e.get.bind(a)||function(){return c},g=e.set.bind(a)||function(a){c=a};Object.defineProperty(a,b,{get:function(){return f()},set:function(c){var d=f();g(c);var e=f();this._disposed||d===c||d===e||a._disposed||a._propertyMutations.dispatchEvent(n.commandPropertyMutated,{command:a,propertyName:b,oldValue:d,newValue:e})}})}function q(a,b){for(var c=null;a&&!c;)c=Object.getOwnPropertyDescriptor(a,b),a=Object.getPrototypeOf(a);return c}var r=d.Class.define(function(){this._observer=e._merge({},g.eventMixin)},{bind:function(a){this._observer.addEventListener(n.commandPropertyMutated,a)},unbind:function(a){this._observer.removeEventListener(n.commandPropertyMutated,a)},dispatchEvent:function(a,b){this._observer.dispatchEvent(a,b)}}),s={get ariaLabel(){return h._getWinJSString("ui/appBarCommandAriaLabel").value},get duplicateConstruction(){return"Invalid argument: Controls may only be instantiated one time for each DOM element"},get badClick(){return"Invalid argument: The onclick property for an {0} must be a function"},get badDivElement(){return"Invalid argument: For a content command, the element must be null or a div element"},get badHrElement(){return"Invalid argument: For a separator, the element must be null or an hr element"},get badButtonElement(){return"Invalid argument: For a button, toggle, or flyout command, the element must be null or a button element"},get badPriority(){return"Invalid argument: the priority of an {0} must be a non-negative integer"}},t=d.Class.define(function(b,c){if(b&&b.winControl)throw new f("WinJS.UI.AppBarCommand.DuplicateConstruction",s.duplicateConstruction);if(this._disposed=!1,c||(c={}),c.type||(this._type=n.typeButton),c.section=c.section||n.sectionPrimary,this._element=b,c.type===n.typeContent?this._createContent():c.type===n.typeSeparator?this._createSeparator():this._createButton(),k.addClass(this._element,"win-disposable"),this._element.winControl=this,k.addClass(this._element,n.appBarCommandClass),c.onclick&&(this.onclick=c.onclick),c.onclick=a,i.setOptions(this,c),this._type!==n.typeToggle||c.selected||(this.selected=!1),this._type!==n.typeSeparator){var d=this._element.getAttribute("role");(null===d||""===d||void 0===d)&&(d=this._type===n.typeToggle?"menuitemcheckbox":this._type===n.typeContent?"group":"menuitem",this._element.setAttribute("role",d),this._type===n.typeFlyout&&this._element.setAttribute("aria-haspopup",!0));var e=this._element.getAttribute("aria-label");(null===e||""===e||void 0===e)&&this._element.setAttribute("aria-label",s.ariaLabel)}this._propertyMutations=new r;var g=this;u.forEach(function(a){p(g,a)})},{id:{get:function(){return this._element.id},set:function(a){a&&!this._element.id&&(this._element.id=a)}},type:{get:function(){return this._type},set:function(a){this._type||(this._type=a!==n.typeContent&&a!==n.typeFlyout&&a!==n.typeToggle&&a!==n.typeSeparator?n.typeButton:a)}},label:{get:function(){return this._label},set:function(a){this._label=a,this._labelSpan&&(this._labelSpan.textContent=this.label),!this.tooltip&&this._tooltipControl&&(this._tooltip=this.label,this._tooltipControl.innerHTML=this.label),this._element.setAttribute("aria-label",this.label),this._testIdenticalTooltip()}},icon:{get:function(){return this._icon},set:function(a){this._icon=o[a]||a,this._imageSpan&&(this._icon&&1===this._icon.length?(this._imageSpan.textContent=this._icon,this._imageSpan.style.backgroundImage="",this._imageSpan.style.msHighContrastAdjust="",k.addClass(this._imageSpan,"win-commandglyph")):(this._imageSpan.textContent="",this._imageSpan.style.backgroundImage=this._icon,this._imageSpan.style.msHighContrastAdjust="none",k.removeClass(this._imageSpan,"win-commandglyph")))}},onclick:{get:function(){return this._onclick},set:function(a){if(a&&"function"!=typeof a)throw new f("WinJS.UI.AppBarCommand.BadClick",h._formatString(s.badClick,"AppBarCommand"));this._onclick=a}},priority:{get:function(){return this._priority},set:function(a){if(!(void 0===a||"number"==typeof a&&a>=0))throw new f("WinJS.UI.AppBarCommand.BadPriority",h._formatString(s.badPriority,"AppBarCommand"));this._priority=a}},flyout:{get:function(){var a=this._flyout;return"string"==typeof a&&(a=b.document.getElementById(a)),a&&!a.element&&a.winControl&&(a=a.winControl),a},set:function(a){var b=a;b&&"string"!=typeof b&&(b.element&&(b=b.element),b&&(b.id?b=b.id:(b.id=k._uniqueID(b),b=b.id))),"string"==typeof b&&this._element.setAttribute("aria-owns",b),this._flyout=a}},section:{get:function(){return this._section},set:function(a){(!this._section||c.Windows.ApplicationModel.DesignMode.designModeEnabled)&&this._setSection(a)}},tooltip:{get:function(){return this._tooltip},set:function(a){this._tooltip=a,this._tooltipControl&&(this._tooltipControl.innerHTML=this._tooltip),this._testIdenticalTooltip()}},selected:{get:function(){return"true"===this._element.getAttribute("aria-checked")},set:function(a){this._element.setAttribute("aria-checked",a)}},element:{get:function(){return this._element}},disabled:{get:function(){return!!this._element.disabled},set:function(a){this._element.disabled=a}},hidden:{get:function(){return k.hasClass(this._element,n.commandHiddenClass)},set:function(a){if(a!==this.hidden){var b=this.hidden;a?k.addClass(this._element,n.commandHiddenClass):k.removeClass(this._element,n.commandHiddenClass),this._sendEvent(n.commandVisibilityChanged)||(b?k.addClass(this._element,n.commandHiddenClass):k.removeClass(this._element,n.commandHiddenClass))}}},firstElementFocus:{get:function(){return this._firstElementFocus||this._lastElementFocus||this._element},set:function(a){this._firstElementFocus=a===this.element?null:a,this._updateTabStop()}},lastElementFocus:{get:function(){return this._lastElementFocus||this._firstElementFocus||this._element},set:function(a){this._lastElementFocus=a===this.element?null:a,this._updateTabStop()}},dispose:function(){this._disposed||(this._disposed=!0,this._tooltipControl&&this._tooltipControl.dispose(),this._type===n.typeContent&&j.disposeSubTree(this.element))},addEventListener:function(a,b,c){return this._element.addEventListener(a,b,c)},removeEventListener:function(a,b,c){return this._element.removeEventListener(a,b,c)},extraClass:{get:function(){return this._extraClass},set:function(a){this._extraClass&&k.removeClass(this._element,this._extraClass),this._extraClass=a,k.addClass(this._element,this._extraClass)}},_testIdenticalTooltip:function(){this._hideIfFullSize=this._label===this._tooltip},_createContent:function(){if(this._element){if("DIV"!==this._element.tagName)throw new f("WinJS.UI.AppBarCommand.BadDivElement",s.badDivElement)}else this._element=b.document.createElement("div");parseInt(this._element.getAttribute("tabIndex"),10)!==this._element.tabIndex&&(this._element.tabIndex=0)},_createSeparator:function(){if(this._element){if("HR"!==this._element.tagName)throw new f("WinJS.UI.AppBarCommand.BadHrElement",s.badHrElement)}else this._element=b.document.createElement("hr")},_createButton:function(){if(this._element){if("BUTTON"!==this._element.tagName)throw new f("WinJS.UI.AppBarCommand.BadButtonElement",s.badButtonElement);var a=this._element.getAttribute("type");(null===a||""===a||void 0===a)&&this._element.setAttribute("type","button"),this._element.innerHTML=""}else this._element=b.document.createElement("button");this._element.type="button",this._iconSpan=b.document.createElement("span"),this._iconSpan.setAttribute("aria-hidden","true"),this._iconSpan.className="win-commandicon",this._iconSpan.tabIndex=-1,this._element.appendChild(this._iconSpan),this._imageSpan=b.document.createElement("span"),this._imageSpan.setAttribute("aria-hidden","true"),this._imageSpan.className="win-commandimage",this._imageSpan.tabIndex=-1,this._iconSpan.appendChild(this._imageSpan),this._labelSpan=b.document.createElement("span"),this._labelSpan.setAttribute("aria-hidden","true"),this._labelSpan.className="win-label",this._labelSpan.tabIndex=-1,this._element.appendChild(this._labelSpan),this._tooltipControl=new m.Tooltip(this._element);var c=this;this._tooltipControl.addEventListener("beforeopen",function(){c._hideIfFullSize&&!l._Overlay._getParentControlUsingClassName(c._element.parentElement,n.reducedClass)&&c._tooltipControl.close()},!1)},_setSection:function(a){a||(a=n.sectionPrimary),this._section&&(this._section===n.sectionGlobal?k.removeClass(this._element,n.appBarCommandGlobalClass):this.section===n.sectionSelection&&k.removeClass(this._element,n.appBarCommandSelectionClass)),this._section=a,a===n.sectionGlobal?k.addClass(this._element,n.appBarCommandGlobalClass):a===n.sectionSelection&&k.addClass(this._element,n.appBarCommandSelectionClass)},_updateTabStop:function(){this.element.tabIndex=this._firstElementFocus||this._lastElementFocus?-1:0},_isFocusable:function(){return!this.hidden&&this._type!==n.typeSeparator&&!this.element.disabled&&(this.firstElementFocus.tabIndex>=0||this.lastElementFocus.tabIndex>=0) },_sendEvent:function(a,c){if(!this._disposed){var d=b.document.createEvent("CustomEvent");return d.initCustomEvent(a,!0,!0,c||{}),this._element.dispatchEvent(d)}}}),u=["label","disabled","flyout","extraClass","selected","onclick","hidden"];return t})}),d.Namespace._moduleDefine(a,"WinJS.UI",{Command:d.Namespace._lazy(function(){return a.AppBarCommand})})}),d("WinJS/Controls/Menu/_Command",["exports","../../Core/_Global","../../Core/_Base","../../Core/_ErrorFromName","../../Core/_Resources","../../Promise","../../Utilities/_Control","../../Utilities/_ElementUtilities","../_LegacyAppBar/_Constants","../Flyout/_Overlay"],function(a,b,c,d,e,f,g,h,i,j){"use strict";c.Namespace._moduleDefine(a,"WinJS.UI",{MenuCommand:c.Namespace._lazy(function(){var a={get ariaLabel(){return e._getWinJSString("ui/menuCommandAriaLabel").value},get duplicateConstruction(){return"Invalid argument: Controls may only be instantiated one time for each DOM element"},get badClick(){return"Invalid argument: The onclick property for an {0} must be a function"},get badHrElement(){return"Invalid argument: For a separator, the element must be null or an hr element"},get badButtonElement(){return"Invalid argument: For a button, toggle, or flyout command, the element must be null or a button element"}},k=c.Class.define(function(b,c){if(b&&b.winControl)throw new d("WinJS.UI.MenuCommand.DuplicateConstruction",a.duplicateConstruction);if(this._disposed=!1,c||(c={}),c.type||(this._type=i.typeButton),this._element=b,c.type===i.typeSeparator?this._createSeparator():this._createButton(),h.addClass(this._element,"win-disposable"),this._element.winControl=this,h.addClass(this._element,i.menuCommandClass),c.selected||c.type!==i.typeToggle||(this.selected=!1),c.onclick&&(this.onclick=c.onclick),c.onclick=this._handleClick.bind(this),g.setOptions(this,c),this._type!==i.typeSeparator){var e=this._element.getAttribute("role");(null===e||""===e||void 0===e)&&(e="menuitem",this._type===i.typeToggle&&(e="menuitemcheckbox"),this._element.setAttribute("role",e),this._type===i.typeFlyout&&this._element.setAttribute("aria-haspopup",!0));var f=this._element.getAttribute("aria-label");(null===f||""===f||void 0===f)&&this._element.setAttribute("aria-label",a.ariaLabel)}},{id:{get:function(){return this._element.id},set:function(a){this._element.id||(this._element.id=a)}},type:{get:function(){return this._type},set:function(a){this._type||(a!==i.typeButton&&a!==i.typeFlyout&&a!==i.typeToggle&&a!==i.typeSeparator&&(a=i.typeButton),this._type=a,a===i.typeButton?h.addClass(this.element,i.menuCommandButtonClass):a===i.typeFlyout?(h.addClass(this.element,i.menuCommandFlyoutClass),this.element.addEventListener("keydown",this._handleKeyDown.bind(this),!1)):a===i.typeSeparator?h.addClass(this.element,i.menuCommandSeparatorClass):a===i.typeToggle&&h.addClass(this.element,i.menuCommandToggleClass))}},label:{get:function(){return this._label},set:function(a){this._label=a||"",this._labelSpan&&(this._labelSpan.textContent=this.label),this._element.setAttribute("aria-label",this.label)}},onclick:{get:function(){return this._onclick},set:function(b){if(b&&"function"!=typeof b)throw new d("WinJS.UI.MenuCommand.BadClick",e._formatString(a.badClick,"MenuCommand"));this._onclick=b}},flyout:{get:function(){var a=this._flyout;return"string"==typeof a&&(a=b.document.getElementById(a)),a&&!a.element&&(a=a.winControl),a},set:function(a){var b=a;b&&"string"!=typeof b&&(b.element&&(b=b.element),b&&(b.id?b=b.id:(b.id=h._uniqueID(b),b=b.id))),"string"==typeof b&&this._element.setAttribute("aria-owns",b),this._flyout!==a&&k._deactivateFlyoutCommand(this),this._flyout=a}},selected:{get:function(){return"true"===this._element.getAttribute("aria-checked")},set:function(a){this._element.setAttribute("aria-checked",!!a)}},element:{get:function(){return this._element}},disabled:{get:function(){return!!this._element.disabled},set:function(a){a=!!a,a&&this.type===i.typeFlyout&&k._deactivateFlyoutCommand(this),this._element.disabled=a}},hidden:{get:function(){return"hidden"===this._element.style.visibility},set:function(a){var b=j._Overlay._getParentControlUsingClassName(this._element,i.menuClass);if(b&&!b.hidden)throw new d("WinJS.UI.MenuCommand.CannotChangeHiddenProperty",e._formatString(j._Overlay.commonstrings.cannotChangeHiddenProperty,"Menu"));var c=this._element.style;a?(this.type===i.typeFlyout&&k._deactivateFlyoutCommand(this),c.visibility="hidden",c.display="none"):(c.visibility="",c.display="block")}},extraClass:{get:function(){return this._extraClass},set:function(a){this._extraClass&&h.removeClass(this._element,this._extraClass),this._extraClass=a,h.addClass(this._element,this._extraClass)}},dispose:function(){this._disposed||(this._disposed=!0)},addEventListener:function(a,b,c){return this._element.addEventListener(a,b,c)},removeEventListener:function(a,b,c){return this._element.removeEventListener(a,b,c)},_createSeparator:function(){if(this._element){if("HR"!==this._element.tagName)throw new d("WinJS.UI.MenuCommand.BadHrElement",a.badHrElement)}else this._element=b.document.createElement("hr")},_createButton:function(){if(this._element){if("BUTTON"!==this._element.tagName)throw new d("WinJS.UI.MenuCommand.BadButtonElement",a.badButtonElement)}else this._element=b.document.createElement("button");this._element.innerHTML='<div class="win-menucommand-liner"><span class="win-toggleicon" aria-hidden="true"></span><span class="win-label" aria-hidden="true"></span><span class="win-flyouticon" aria-hidden="true"></span></div>',this._element.type="button",this._menuCommandLiner=this._element.firstElementChild,this._toggleSpan=this._menuCommandLiner.firstElementChild,this._labelSpan=this._toggleSpan.nextElementSibling,this._flyoutSpan=this._labelSpan.nextElementSibling},_sendEvent:function(a,c){if(!this._disposed){var d=b.document.createEvent("CustomEvent");d.initCustomEvent(a,!0,!0,c||{}),this._element.dispatchEvent(d)}},_invoke:function(a){this.hidden||this.disabled||this._disposed||(this._type===i.typeToggle?this.selected=!this.selected:this._type===i.typeFlyout&&k._activateFlyoutCommand(this),a&&"click"===a.type&&this.onclick&&this.onclick(a),this._sendEvent(i._menuCommandInvokedEvent,{command:this}))},_handleClick:function(a){this._invoke(a)},_handleKeyDown:function(a){var b=h.Key,c="rtl"===h._getComputedStyle(this.element).direction,d=c?b.leftArrow:b.rightArrow;a.keyCode===d&&this.type===i.typeFlyout&&(this._invoke(a),a.preventDefault())}},{_activateFlyoutCommand:function(a){return new f(function(b,c){a=a.winControl||a;var d=a.flyout;d&&d.hidden&&d.show?(h.addClass(a.element,i.menuCommandFlyoutActivatedClass),d.addEventListener("beforehide",function e(){d.removeEventListener("beforehide",e,!1),h.removeClass(a.element,i.menuCommandFlyoutActivatedClass)},!1),d.addEventListener("aftershow",function f(){d.removeEventListener("aftershow",f,!1),b()},!1),d.show(a,"_cascade")):c()})},_deactivateFlyoutCommand:function(a){return new f(function(b){a=a.winControl||a,h.removeClass(a.element,i.menuCommandFlyoutActivatedClass);var c=a.flyout;c&&!c.hidden&&c.hide?(c.addEventListener("afterhide",function d(){c.removeEventListener("afterhide",d,!1),b()},!1),c.hide()):b()})}});return k})})});var e=this.__extends||function(a,b){function c(){this.constructor=a}for(var d in b)b.hasOwnProperty(d)&&(a[d]=b[d]);c.prototype=b.prototype,a.prototype=new c};return d("WinJS/Controls/CommandingSurface/_MenuCommand",["require","exports","../Menu/_Command"],function(a,b,c){var d=function(a){function b(b,c){c&&c.beforeInvoke&&(this._beforeInvoke=c.beforeInvoke),a.call(this,b,c)}return e(b,a),b.prototype._invoke=function(b){this._beforeInvoke&&this._beforeInvoke(b),a.prototype._invoke.call(this,b)},b}(c.MenuCommand);b._MenuCommand=d}),d("WinJS/Utilities/_OpenCloseMachine",["require","exports","../Core/_Global","../Promise","../_Signal"],function(a,b,c,d,e){"use strict";function f(a){return d._cancelBlocker(a,function(){a.cancel()})}function g(){}function h(a,b){a._interruptibleWorkPromises=a._interruptibleWorkPromises||[];var c=new e;a._interruptibleWorkPromises.push(b(c.promise)),c.complete()}function i(){(this._interruptibleWorkPromises||[]).forEach(function(a){a.cancel()})}var j={beforeOpen:"beforeopen",afterOpen:"afteropen",beforeClose:"beforeclose",afterClose:"afterclose",_openCloseStateSettled:"_openCloseStateSettled"},k=function(){function a(a){this._control=a,this._initializedSignal=new e,this._disposed=!1,this._setState(l.Init)}return a.prototype.exitInit=function(){this._initializedSignal.complete()},a.prototype.updateDom=function(){this._state.updateDom()},a.prototype.open=function(){this._state.open()},a.prototype.close=function(){this._state.close()},Object.defineProperty(a.prototype,"opened",{get:function(){return this._state.opened},set:function(a){a?this.open():this.close()},enumerable:!0,configurable:!0}),a.prototype.dispose=function(){this._setState(l.Disposed),this._disposed=!0,this._control=null},a.prototype._setState=function(a,b){this._disposed||(this._state&&this._state.exit(),this._state=new a,this._state.machine=this,this._state.enter(b))},a.prototype._fireEvent=function(a,b){b=b||{};var d=b.detail||null,e=!!b.cancelable,f=c.document.createEvent("CustomEvent");return f.initCustomEvent(a,!0,e,d),this._control.eventElement.dispatchEvent(f)},a.prototype._fireBeforeOpen=function(){return this._fireEvent(j.beforeOpen,{cancelable:!0})},a.prototype._fireBeforeClose=function(){return this._fireEvent(j.beforeClose,{cancelable:!0})},a}();b.OpenCloseMachine=k;var l;!function(a){function b(){this.machine._control.onUpdateDom()}var c=function(){function a(){this.name="Init",this.exit=i,this.updateDom=g}return a.prototype.enter=function(){var a=this;h(this,function(b){return b.then(function(){return a.machine._initializedSignal.promise}).then(function(){a.machine._control.onUpdateDomWithIsOpened(a._opened),a.machine._setState(a._opened?l:d)})})},Object.defineProperty(a.prototype,"opened",{get:function(){return this._opened},enumerable:!0,configurable:!0}),a.prototype.open=function(){this._opened=!0},a.prototype.close=function(){this._opened=!1},a}();a.Init=c;var d=function(){function a(){this.name="Closed",this.exit=g,this.opened=!1,this.close=g,this.updateDom=b}return a.prototype.enter=function(a){a=a||{},a.openIsPending&&this.open(),this.machine._fireEvent(j._openCloseStateSettled)},a.prototype.open=function(){this.machine._setState(e)},a}(),e=function(){function a(){this.name="BeforeOpen",this.exit=i,this.opened=!1,this.open=g,this.close=g,this.updateDom=b}return a.prototype.enter=function(){var a=this;h(this,function(b){return b.then(function(){return a.machine._fireBeforeOpen()}).then(function(b){a.machine._setState(b?k:d)})})},a}(),k=function(){function a(){this.name="Opening",this.exit=i,this.updateDom=g}return a.prototype.enter=function(){var a=this;h(this,function(b){return b.then(function(){return a._closeIsPending=!1,f(a.machine._control.onOpen())}).then(function(){a.machine._fireEvent(j.afterOpen)}).then(function(){a.machine._control.onUpdateDom(),a.machine._setState(l,{closeIsPending:a._closeIsPending})})})},Object.defineProperty(a.prototype,"opened",{get:function(){return!this._closeIsPending},enumerable:!0,configurable:!0}),a.prototype.open=function(){this._closeIsPending=!1},a.prototype.close=function(){this._closeIsPending=!0},a}(),l=function(){function a(){this.name="Opened",this.exit=g,this.opened=!0,this.open=g,this.updateDom=b}return a.prototype.enter=function(a){a=a||{},a.closeIsPending&&this.close(),this.machine._fireEvent(j._openCloseStateSettled)},a.prototype.close=function(){this.machine._setState(m)},a}(),m=function(){function a(){this.name="BeforeClose",this.exit=i,this.opened=!0,this.open=g,this.close=g,this.updateDom=b}return a.prototype.enter=function(){var a=this;h(this,function(b){return b.then(function(){return a.machine._fireBeforeClose()}).then(function(b){a.machine._setState(b?n:l)})})},a}(),n=function(){function a(){this.name="Closing",this.exit=i,this.updateDom=g}return a.prototype.enter=function(){var a=this;h(this,function(b){return b.then(function(){return a._openIsPending=!1,f(a.machine._control.onClose())}).then(function(){a.machine._fireEvent(j.afterClose)}).then(function(){a.machine._control.onUpdateDom(),a.machine._setState(d,{openIsPending:a._openIsPending})})})},Object.defineProperty(a.prototype,"opened",{get:function(){return this._openIsPending},enumerable:!0,configurable:!0}),a.prototype.open=function(){this._openIsPending=!0},a.prototype.close=function(){this._openIsPending=!1},a}(),o=function(){function a(){this.name="Disposed",this.enter=g,this.exit=g,this.opened=!1,this.open=g,this.close=g,this.updateDom=g}return a}();a.Disposed=o}(l||(l={}))}),d("require-style!less/styles-commandingsurface",[],function(){}),d("require-style!less/colors-commandingsurface",[],function(){}),d("WinJS/Controls/CommandingSurface/_CommandingSurface",["require","exports","../../Animations","../../Core/_Base","../../Core/_BaseUtils","../../BindingList","../../ControlProcessor","../CommandingSurface/_Constants","../AppBar/_Command","../CommandingSurface/_MenuCommand","../../Utilities/_Control","../../Utilities/_Dispose","../../Utilities/_ElementUtilities","../../Core/_ErrorFromName","../../Core/_Events","../../Controls/Flyout","../../Core/_Global","../../Utilities/_Hoverable","../../Utilities/_KeyboardBehavior","../../Core/_Log","../../Promise","../../Core/_Resources","../../Scheduler","../../Utilities/_OpenCloseMachine","../../_Signal","../../Core/_WriteProfilerMark"],function(a,b,c,d,e,f,g,h,i,j,k,l,m,n,o,p,q,r,s,t,u,v,w,x,y,z){function A(a,b){b&&m.addClass(a,b)}function B(a,b){b&&m.removeClass(a,b)}function C(a,b){return a.filter(function(a){return b.indexOf(a)<0})}function D(a,b){return a.filter(function(a){return-1!==b.indexOf(a)})}a(["require-style!less/styles-commandingsurface"]),a(["require-style!less/colors-commandingsurface"]);var E={get overflowButtonAriaLabel(){return v._getWinJSString("ui/commandingSurfaceOverflowButtonAriaLabel").value},get badData(){return"Invalid argument: The data property must an instance of a WinJS.Binding.List"},get mustContainCommands(){return"The commandingSurface can only contain WinJS.UI.Command or WinJS.UI.AppBarCommand controls"},get duplicateConstruction(){return"Invalid argument: Controls may only be instantiated one time for each DOM element"}},F={bottom:"bottom",top:"top"},G={};G[F.top]=h.ClassNames.overflowTopClass,G[F.bottom]=h.ClassNames.overflowBottomClass;var H={none:"none",minimal:"minimal",compact:"compact",full:"full"},I={};I[H.none]=h.ClassNames.noneClass,I[H.minimal]=h.ClassNames.minimalClass,I[H.compact]=h.ClassNames.compactClass,I[H.full]=h.ClassNames.fullClass;var J=function(){function a(a,b){var c=this;if(void 0===b&&(b={}),this._hoverable=r.isHoverable,this._dataChangedEvents=["itemchanged","iteminserted","itemmoved","itemremoved","reload"],this._updateDomImpl=function(){var a={closedDisplayMode:void 0,isOpenedMode:void 0,overflowDirection:void 0,overflowAlignmentOffset:void 0},b=function(){var b=a,d=c._dom;if(b.isOpenedMode!==c._isOpenedMode&&(c._isOpenedMode?(B(d.root,h.ClassNames.closedClass),A(d.root,h.ClassNames.openedClass),d.firstTabStop.tabIndex=0,d.finalTabStop.tabIndex=0,d.firstTabStop.setAttribute("x-ms-aria-flowfrom",d.finalTabStop.id),d.finalTabStop.setAttribute("aria-flowto",d.firstTabStop.id)):(B(d.root,h.ClassNames.openedClass),A(d.root,h.ClassNames.closedClass),d.firstTabStop.tabIndex=-1,d.finalTabStop.tabIndex=-1,d.firstTabStop.removeAttribute("x-ms-aria-flowfrom"),d.finalTabStop.removeAttribute("aria-flowto")),b.isOpenedMode=c._isOpenedMode),b.closedDisplayMode!==c.closedDisplayMode&&(B(d.root,I[b.closedDisplayMode]),A(d.root,I[c.closedDisplayMode]),b.closedDisplayMode=c.closedDisplayMode),b.overflowDirection!==c.overflowDirection&&(B(d.root,G[b.overflowDirection]),A(d.root,G[c.overflowDirection]),b.overflowDirection=c.overflowDirection),c._overflowAlignmentOffset!==b.overflowAlignmentOffset){var e=c._rtl?"left":"right",f=c._overflowAlignmentOffset+"px";d.overflowAreaContainer.style[e]=f}},d={newDataStage:3,measuringStage:2,layoutStage:1,idle:0},e=d.idle,f=function(){c._writeProfilerMark("_updateDomImpl_updateCommands,info");for(var a=e;a!==d.idle;){var b=a,f=!1;switch(a){case d.newDataStage:a=d.measuringStage,f=c._processNewData();break;case d.measuringStage:a=d.layoutStage,f=c._measure();break;case d.layoutStage:a=d.idle,f=c._layoutCommands()}if(!f){a=b;break}}e=a,a===d.idle?c._layoutCompleteCallback&&c._layoutCompleteCallback():c._minimalLayout()};return{get renderedState(){return{get closedDisplayMode(){return a.closedDisplayMode},get isOpenedMode(){return a.isOpenedMode},get overflowDirection(){return a.overflowDirection},get overflowAlignmentOffset(){return a.overflowAlignmentOffset}}},update:function(){b(),f()},dataDirty:function(){e=Math.max(d.newDataStage,e)},measurementsDirty:function(){e=Math.max(d.measuringStage,e)},layoutDirty:function(){e=Math.max(d.layoutStage,e)},get _currentLayoutStage(){return e}}}(),this._writeProfilerMark("constructor,StartTM"),a){if(a.winControl)throw new n("WinJS.UI._CommandingSurface.DuplicateConstruction",E.duplicateConstruction);b.data||(b=e._shallowCopy(b),b.data=b.data||this._getDataFromDOMElements(a))}this._initializeDom(a||q.document.createElement("div")),this._machine=b.openCloseMachine||new x.OpenCloseMachine({eventElement:this._dom.root,onOpen:function(){return c.synchronousOpen(),u.wrap()},onClose:function(){return c.synchronousClose(),u.wrap()},onUpdateDom:function(){c._updateDomImpl.update()},onUpdateDomWithIsOpened:function(a){a?c.synchronousOpen():c.synchronousClose()}}),this._disposed=!1,this._primaryCommands=[],this._secondaryCommands=[],this._refreshBound=this._refresh.bind(this),this._resizeHandlerBound=this._resizeHandler.bind(this),this._winKeyboard=new s._WinKeyboard(this._dom.root),this._refreshPending=!1,this._rtl=!1,this._initializedSignal=new y,this._isOpenedMode=h.defaultOpened,this._menuCommandProjections=[],this.overflowDirection=h.defaultOverflowDirection,this.closedDisplayMode=h.defaultClosedDisplayMode,this.opened=this._isOpenedMode,k.setOptions(this,b),m._resizeNotifier.subscribe(this._dom.root,this._resizeHandlerBound),this._dom.root.addEventListener("keydown",this._keyDownHandler.bind(this)),m._addEventListener(this._dom.firstTabStop,"focusin",function(){c._focusLastFocusableElementOrThis(!1)}),m._addEventListener(this._dom.finalTabStop,"focusin",function(){c._focusFirstFocusableElementOrThis(!1)}),m._inDom(this._dom.root).then(function(){c._rtl="rtl"===m._getComputedStyle(c._dom.root).direction,b.openCloseMachine||c._machine.exitInit(),c._initializedSignal.complete(),c._writeProfilerMark("constructor,StopTM")})}return Object.defineProperty(a.prototype,"element",{get:function(){return this._dom.root},enumerable:!0,configurable:!0}),Object.defineProperty(a.prototype,"data",{get:function(){return this._data},set:function(a){if(this._writeProfilerMark("set_data,info"),a!==this.data){if(!(a instanceof f.List))throw new n("WinJS.UI._CommandingSurface.BadData",E.badData);this._data&&this._removeDataListeners(),this._data=a,this._addDataListeners(),this._dataUpdated()}},enumerable:!0,configurable:!0}),Object.defineProperty(a.prototype,"closedDisplayMode",{get:function(){return this._closedDisplayMode},set:function(a){this._writeProfilerMark("set_closedDisplayMode,info");var b=a!==this._closedDisplayMode;H[a]&&b&&(this._updateDomImpl.layoutDirty(),this._closedDisplayMode=a,this._machine.updateDom())},enumerable:!0,configurable:!0}),Object.defineProperty(a.prototype,"overflowDirection",{get:function(){return this._overflowDirection},set:function(a){var b=a!==this._overflowDirection;F[a]&&b&&(this._overflowDirection=a,this._machine.updateDom())},enumerable:!0,configurable:!0}),Object.defineProperty(a.prototype,"opened",{get:function(){return this._machine.opened},set:function(a){this._machine.opened=a},enumerable:!0,configurable:!0}),a.prototype.open=function(){this._machine.open()},a.prototype.close=function(){this._machine.close()},a.prototype.dispose=function(){this._disposed||(this._disposed=!0,this._machine.dispose(),m._resizeNotifier.unsubscribe(this._dom.root,this._resizeHandlerBound),this._contentFlyout&&(this._contentFlyout.dispose(),this._contentFlyout.element.parentNode.removeChild(this._contentFlyout.element)),l.disposeSubTree(this._dom.root))},a.prototype.forceLayout=function(){this._updateDomImpl.measurementsDirty(),this._machine.updateDom()},a.prototype.getBoundingRects=function(){return{commandingSurface:this._dom.root.getBoundingClientRect(),overflowArea:this._dom.overflowArea.getBoundingClientRect()}},a.prototype.getCommandById=function(a){if(this._data)for(var b=0,c=this._data.length;c>b;b++){var d=this._data.getAt(b);if(d.id===a)return d}return null},a.prototype.showOnlyCommands=function(a){if(this._data){for(var b=0,c=this._data.length;c>b;b++)this._data.getAt(b).hidden=!0;for(var b=0,c=a.length;c>b;b++){var d="string"==typeof a[b]?this.getCommandById(a[b]):a[b];d&&(d.hidden=!1)}}},a.prototype.takeFocus=function(a){this._focusFirstFocusableElementOrThis(a)},a.prototype._focusFirstFocusableElementOrThis=function(a){m._focusFirstFocusableElement(this._dom.content,a)||m._tryFocusOnAnyElement(this.element,a)},a.prototype._focusLastFocusableElementOrThis=function(a){m._focusLastFocusableElement(this._dom.content,a)||m._tryFocusOnAnyElement(this.element,a)},a.prototype.deferredDomUpate=function(){this._machine.updateDom()},a.prototype.createOpenAnimation=function(a){t.log&&this._updateDomImpl.renderedState.isOpenedMode&&t.log("The CommandingSurface should only attempt to create an open animation when it's not already opened");var b=this;return{execute:function(){m.addClass(b.element,h.ClassNames.openingClass);var d=b.getBoundingRects();return b._dom.overflowAreaContainer.style.width=d.overflowArea.width+"px",b._dom.overflowAreaContainer.style.height=d.overflowArea.height+"px",c._commandingSurfaceOpenAnimation({actionAreaClipper:b._dom.actionAreaContainer,actionArea:b._dom.actionArea,overflowAreaClipper:b._dom.overflowAreaContainer,overflowArea:b._dom.overflowArea,oldHeight:a,newHeight:d.commandingSurface.height,overflowAreaHeight:d.overflowArea.height,menuPositionedAbove:b.overflowDirection===F.top}).then(function(){m.removeClass(b.element,h.ClassNames.openingClass),b._clearAnimation()})}}},a.prototype.createCloseAnimation=function(a){t.log&&!this._updateDomImpl.renderedState.isOpenedMode&&t.log("The CommandingSurface should only attempt to create an closed animation when it's not already closed");var b=this.getBoundingRects().commandingSurface.height,d=this._dom.overflowArea.offsetHeight,e=(this._dom.overflowArea.offsetTop,this);return{execute:function(){return m.addClass(e.element,h.ClassNames.closingClass),c._commandingSurfaceCloseAnimation({actionAreaClipper:e._dom.actionAreaContainer,actionArea:e._dom.actionArea,overflowAreaClipper:e._dom.overflowAreaContainer,overflowArea:e._dom.overflowArea,oldHeight:b,newHeight:a,overflowAreaHeight:d,menuPositionedAbove:e.overflowDirection===F.top}).then(function(){m.removeClass(e.element,h.ClassNames.closingClass),e._clearAnimation()})}}},Object.defineProperty(a.prototype,"initialized",{get:function(){return this._initializedSignal.promise},enumerable:!0,configurable:!0}),a.prototype._writeProfilerMark=function(a){z("WinJS.UI._CommandingSurface:"+this._id+":"+a)},a.prototype._initializeDom=function(a){var b=this;this._writeProfilerMark("_intializeDom,info"),a.winControl=this,this._id=a.id||m._uniqueID(a),a.hasAttribute("tabIndex")||(a.tabIndex=-1),m.addClass(a,h.ClassNames.controlCssClass),m.addClass(a,h.ClassNames.disposableCssClass);var c=q.document.createElement("div");m.addClass(c,h.ClassNames.contentClass),a.appendChild(c);var d=q.document.createElement("div");m.addClass(d,h.ClassNames.actionAreaCssClass);var e=document.createElement("div");m.addClass(e,h.ClassNames.insetOutlineClass);var f=q.document.createElement("div");m.addClass(f,h.ClassNames.actionAreaContainerCssClass),f.appendChild(d),f.appendChild(e),c.appendChild(f);var g=q.document.createElement("div");m.addClass(g,h.ClassNames.spacerCssClass),g.tabIndex=-1,d.appendChild(g);var i=q.document.createElement("button");i.tabIndex=0,i.innerHTML="<span class='"+h.ClassNames.ellipsisCssClass+"'></span>",m.addClass(i,h.ClassNames.overflowButtonCssClass),d.appendChild(i),i.addEventListener("click",function(){b.opened=!b.opened});var j=q.document.createElement("div");m.addClass(j,h.ClassNames.overflowAreaCssClass),m.addClass(j,h.ClassNames.menuCssClass);var k=q.document.createElement("DIV");m.addClass(k,h.ClassNames.insetOutlineClass);var l=q.document.createElement("div");m.addClass(l,h.ClassNames.overflowAreaContainerCssClass),l.appendChild(j),l.appendChild(k),c.appendChild(l);var n=q.document.createElement("div");m.addClass(n,h.ClassNames.spacerCssClass),n.tabIndex=-1,j.appendChild(n);var o=q.document.createElement("div");m.addClass(o,h.ClassNames.tabStopClass),m._ensureId(o),a.insertBefore(o,a.children[0]);var p=q.document.createElement("div");m.addClass(p,h.ClassNames.tabStopClass),m._ensureId(p),a.appendChild(p),this._dom={root:a,content:c,actionArea:d,actionAreaContainer:f,actionAreaSpacer:g,overflowButton:i,overflowArea:j,overflowAreaContainer:l,overflowAreaSpacer:n,firstTabStop:o,finalTabStop:p}},a.prototype._getFocusableElementsInfo=function(){var a=this,b={elements:[],focusedIndex:-1},c=Array.prototype.slice.call(this._dom.actionArea.children);return this._updateDomImpl.renderedState.isOpenedMode&&(c=c.concat(Array.prototype.slice.call(this._dom.overflowArea.children))),c.forEach(function(c){a._isElementFocusable(c)&&(b.elements.push(c),c.contains(q.document.activeElement)&&(b.focusedIndex=b.elements.length-1))}),b},a.prototype._dataUpdated=function(){var a=this;this._primaryCommands=[],this._secondaryCommands=[],this.data.length>0&&this.data.forEach(function(b){"secondary"===b.section?a._secondaryCommands.push(b):a._primaryCommands.push(b)}),this._updateDomImpl.dataDirty(),this._machine.updateDom()},a.prototype._refresh=function(){var a=this;this._refreshPending||(this._refreshPending=!0,this._batchDataUpdates(function(){a._refreshPending&&!a._disposed&&(a._refreshPending=!1,a._dataUpdated())}))},a.prototype._batchDataUpdates=function(a){w.schedule(function(){a()},w.Priority.high,null,"WinJS.UI._CommandingSurface._refresh")},a.prototype._addDataListeners=function(){var a=this;this._dataChangedEvents.forEach(function(b){a._data.addEventListener(b,a._refreshBound,!1)})},a.prototype._removeDataListeners=function(){var a=this;this._dataChangedEvents.forEach(function(b){a._data.removeEventListener(b,a._refreshBound,!1)})},a.prototype._isElementFocusable=function(a){var b=!1;if(a){var c=a.winControl;b=c?!this._hasAnyHiddenClasses(c)&&c.type!==h.typeSeparator&&!c.hidden&&!c.disabled&&(!c.firstElementFocus||c.firstElementFocus.tabIndex>=0||c.lastElementFocus.tabIndex>=0):"none"!==a.style.display&&"hidden"!==m._getComputedStyle(a).visibility&&a.tabIndex>=0}return b},a.prototype._clearHiddenPolicyClasses=function(a){m.removeClass(a.element,h.ClassNames.commandPrimaryOverflownPolicyClass),m.removeClass(a.element,h.ClassNames.commandSecondaryOverflownPolicyClass),m.removeClass(a.element,h.ClassNames.commandSeparatorHiddenPolicyClass)},a.prototype._hasHiddenPolicyClasses=function(a){return m.hasClass(a.element,h.ClassNames.commandPrimaryOverflownPolicyClass)||m.hasClass(a.element,h.ClassNames.commandSecondaryOverflownPolicyClass)||m.hasClass(a.element,h.ClassNames.commandSeparatorHiddenPolicyClass)},a.prototype._hasAnyHiddenClasses=function(a){return m.hasClass(a.element,h.ClassNames.commandHiddenClass)||this._hasHiddenPolicyClasses(a)},a.prototype._isCommandInActionArea=function(a){return a&&a.winControl&&a.parentElement===this._dom.actionArea},a.prototype._getLastElementFocus=function(a){return this._isCommandInActionArea(a)?a.winControl.lastElementFocus:a},a.prototype._getFirstElementFocus=function(a){return this._isCommandInActionArea(a)?a.winControl.firstElementFocus:a},a.prototype._keyDownHandler=function(a){if(!a.altKey){if(m._matchesSelector(a.target,".win-interactive, .win-interactive *"))return;var b,c=m.Key,d=this._getFocusableElementsInfo();if(d.elements.length)switch(a.keyCode){case this._rtl?c.rightArrow:c.leftArrow:case c.upArrow:var e=Math.max(0,d.focusedIndex-1);b=this._getLastElementFocus(d.elements[e%d.elements.length]);break;case this._rtl?c.leftArrow:c.rightArrow:case c.downArrow:var e=Math.min(d.focusedIndex+1,d.elements.length-1);b=this._getFirstElementFocus(d.elements[e]);break;case c.home:var e=0;b=this._getFirstElementFocus(d.elements[e]);break;case c.end:var e=d.elements.length-1;b=this._getLastElementFocus(d.elements[e])}b&&b!==q.document.activeElement&&(b.focus(),a.preventDefault())}},a.prototype._getDataFromDOMElements=function(a){this._writeProfilerMark("_getDataFromDOMElements,info"),g.processAll(a,!0);for(var b,c=[],d=a.children.length,e=0;d>e;e++){if(b=a.children[e],!(b.winControl&&b.winControl instanceof i.AppBarCommand))throw new n("WinJS.UI._CommandingSurface.MustContainCommands",E.mustContainCommands);c.push(b.winControl)}return new f.List(c)},a.prototype._canMeasure=function(){return(this._updateDomImpl.renderedState.isOpenedMode||this._updateDomImpl.renderedState.closedDisplayMode===H.compact||this._updateDomImpl.renderedState.closedDisplayMode===H.full)&&q.document.body.contains(this._dom.root)&&this._dom.actionArea.offsetWidth>0},a.prototype._resizeHandler=function(){if(this._canMeasure()){var a=m._getPreciseContentWidth(this._dom.actionArea);this._cachedMeasurements&&this._cachedMeasurements.actionAreaContentBoxWidth!==a&&(this._cachedMeasurements.actionAreaContentBoxWidth=a,this._updateDomImpl.layoutDirty(),this._machine.updateDom())}else this._updateDomImpl.measurementsDirty()},a.prototype.synchronousOpen=function(){this._overflowAlignmentOffset=0,this._isOpenedMode=!0,this._updateDomImpl.update(),this._overflowAlignmentOffset=this._computeAdjustedOverflowAreaOffset(),this._updateDomImpl.update()},a.prototype._computeAdjustedOverflowAreaOffset=function(){t.log&&(!this._updateDomImpl.renderedState.isOpenedMode&&t.log("The CommandingSurface should only attempt to compute adjusted overflowArea offset when it has been rendered opened"),0!==this._updateDomImpl.renderedState.overflowAlignmentOffset&&t.log("The CommandingSurface should only attempt to compute adjusted overflowArea offset when it has been rendered with an overflowAlignementOffset of 0"));var a=(this._dom.overflowArea,this.getBoundingRects()),b=0;if(this._rtl){var c=window.innerWidth,d=a.overflowArea.right;b=Math.min(c-d,0)}else{var e=a.overflowArea.left;b=Math.min(0,e)}return b},a.prototype.synchronousClose=function(){this._isOpenedMode=!1,this._updateDomImpl.update()},a.prototype.updateDom=function(){this._updateDomImpl.update()},a.prototype._getDataChangeInfo=function(){var a=this,b=[],c=[],d=[],e=[],f=[],g=[],i=[],j=[],k=[],l=[];return Array.prototype.forEach.call(this._dom.actionArea.querySelectorAll(h.commandSelector),function(b){a._hasAnyHiddenClasses(b.winControl)||e.push(b),f.push(b)}),this.data.forEach(function(b){var c=b.hidden,d=c&&!m.hasClass(b.element,h.ClassNames.commandHiddenClass),e=!c&&m.hasClass(b.element,h.ClassNames.commandHiddenClass),f=m.hasClass(b.element,h.ClassNames.commandPrimaryOverflownPolicyClass);a._hasAnyHiddenClasses(b.element.winControl)||g.push(b.element),f?j.push(b.element):d?k.push(b.element):e&&l.push(b.element),i.push(b.element)}),c=C(f,i),d=D(e,g),b=C(i,f),{nextElements:i,prevElements:f,added:b,deleted:c,unchanged:d,hiding:k,showing:l,overflown:j}},a.prototype._processNewData=function(){var a=this;this._writeProfilerMark("_processNewData,info");var b=this._getDataChangeInfo(),d=c._createUpdateListAnimation(b.added.concat(b.showing).concat(b.overflown),b.deleted.concat(b.hiding),b.unchanged);return b.deleted.forEach(function(b){var c=b.winControl;c&&c._propertyMutations&&c._propertyMutations.unbind(a._refreshBound) }),b.added.forEach(function(b){var c=b.winControl;c&&c._propertyMutations&&c._propertyMutations.bind(a._refreshBound)}),b.prevElements.forEach(function(a){a.parentElement&&a.parentElement.removeChild(a)}),b.nextElements.forEach(function(b){a._dom.actionArea.appendChild(b)}),b.hiding.forEach(function(a){m.addClass(a,h.ClassNames.commandHiddenClass)}),b.showing.forEach(function(a){m.removeClass(a,h.ClassNames.commandHiddenClass)}),this._dom.actionArea.appendChild(this._dom.overflowButton),d.execute(),!0},a.prototype._measure=function(){var a=this;if(this._writeProfilerMark("_measure,info"),this._canMeasure()){var b=this._dom.overflowButton.style.display;this._dom.overflowButton.style.display="";var c=m._getPreciseTotalWidth(this._dom.overflowButton);this._dom.overflowButton.style.display=b;var d=m._getPreciseContentWidth(this._dom.actionArea),e=0,f=0,g={};return this._primaryCommands.forEach(function(b){var c=b.element.style.display;b.element.style.display="inline-block",b.type===h.typeContent?g[a._commandUniqueId(b)]=m._getPreciseTotalWidth(b.element):b.type===h.typeSeparator?e||(e=m._getPreciseTotalWidth(b.element)):f||(f=m._getPreciseTotalWidth(b.element)),b.element.style.display=c}),this._cachedMeasurements={contentCommandWidths:g,separatorWidth:e,standardCommandWidth:f,overflowButtonWidth:c,actionAreaContentBoxWidth:d},!0}return!1},a.prototype._layoutCommands=function(){var a=this;this._writeProfilerMark("_layoutCommands,StartTM");var b=[],c=[],d=[],e=[];this.data.forEach(function(d){a._clearHiddenPolicyClasses(d),d.hidden||(d.section===h.secondaryCommandSection?b.push(d):c.push(d))});var f=b.length>0,g=this._getVisiblePrimaryCommandsLocation(c,f);d=g.commandsForActionArea,e=g.commandsForOverflowArea,e.forEach(function(a){return m.addClass(a.element,h.ClassNames.commandPrimaryOverflownPolicyClass)}),b.forEach(function(a){return m.addClass(a.element,h.ClassNames.commandSecondaryOverflownPolicyClass)}),this._hideSeparatorsIfNeeded(d),m.empty(this._dom.overflowArea),this._menuCommandProjections.map(function(a){a.dispose()});var i=function(a){return a.type===h.typeContent},k=e.some(i)||b.some(i);k&&!this._contentFlyout&&(this._contentFlyoutInterior=q.document.createElement("div"),m.addClass(this._contentFlyoutInterior,h.ClassNames.contentFlyoutCssClass),this._contentFlyout=new p.Flyout,this._contentFlyout.element.appendChild(this._contentFlyoutInterior),q.document.body.appendChild(this._contentFlyout.element),this._contentFlyout.onbeforeshow=function(){m.empty(a._contentFlyoutInterior),m._reparentChildren(a._chosenCommand.element,a._contentFlyoutInterior)},this._contentFlyout.onafterhide=function(){m._reparentChildren(a._contentFlyoutInterior,a._chosenCommand.element)});var l=!1,n=[];if(e.forEach(function(b){b.type===h.typeToggle&&(l=!0),n.push(a._projectAsMenuCommand(b))}),e.length>0&&b.length>0){var o=new j._MenuCommand(null,{type:h.typeSeparator});n.push(o)}b.forEach(function(b){b.type===h.typeToggle&&(l=!0),n.push(a._projectAsMenuCommand(b))}),this._hideSeparatorsIfNeeded(n),n.forEach(function(b){a._dom.overflowArea.appendChild(b.element)}),this._menuCommandProjections=n,m[l?"addClass":"removeClass"](this._dom.overflowArea,h.ClassNames.menuContainsToggleCommandClass),n.length>0&&this._dom.overflowArea.appendChild(this._dom.overflowAreaSpacer);var r=this._needsOverflowButton(d.length>0,n.length>0);return this._dom.overflowButton.style.display=r?"":"none",this._writeProfilerMark("_layoutCommands,StopTM"),!0},a.prototype._getVisiblePrimaryCommandsInfo=function(a){for(var b=0,c=[],d=0,e=0,f=a.length-1;f>=0;f--){var g=a[f];d=void 0===g.priority?e--:g.priority,b=this._getCommandWidth(g),c.unshift({command:g,width:b,priority:d})}return c},a.prototype._getVisiblePrimaryCommandsLocation=function(a,b){for(var c=[],d=[],e=this._getVisiblePrimaryCommandsInfo(a),f=e.slice(0).sort(function(a,b){return a.priority-b.priority}),g=Number.MAX_VALUE,h=this._cachedMeasurements.actionAreaContentBoxWidth,i=this._needsOverflowButton(a.length>0,b),j=0,k=f.length;k>j;j++){h-=f[j].width;var l=i||j!==k-1?this._cachedMeasurements.overflowButtonWidth:0;if(l>h){g=f[j].priority-1;break}}return e.forEach(function(a){a.priority<=g?c.push(a.command):d.push(a.command)}),{commandsForActionArea:c,commandsForOverflowArea:d}},a.prototype._needsOverflowButton=function(a,b){return b?!0:this._hasExpandableActionArea()&&a?!0:!1},a.prototype._minimalLayout=function(){if(this.closedDisplayMode===H.minimal){var a=function(a){return!a.hidden},b=this.data.some(a);this._dom.overflowButton.style.display=b?"":"none"}},a.prototype._commandUniqueId=function(a){return m._uniqueID(a.element)},a.prototype._getCommandWidth=function(a){return a.type===h.typeContent?this._cachedMeasurements.contentCommandWidths[this._commandUniqueId(a)]:a.type===h.typeSeparator?this._cachedMeasurements.separatorWidth:this._cachedMeasurements.standardCommandWidth},a.prototype._projectAsMenuCommand=function(a){var b=this,c=new j._MenuCommand(null,{label:a.label,type:(a.type===h.typeContent?h.typeFlyout:a.type)||h.typeButton,disabled:a.disabled,flyout:a.flyout,beforeInvoke:function(){b._chosenCommand=c._originalICommand,b._chosenCommand.type===h.typeToggle&&(b._chosenCommand.selected=!b._chosenCommand.selected)}});return a.selected&&(c.selected=!0),a.extraClass&&(c.extraClass=a.extraClass),a.type===h.typeContent?(c.label||(c.label=h.contentMenuCommandDefaultLabel),c.flyout=this._contentFlyout):c.onclick=a.onclick,c._originalICommand=a,c},a.prototype._hideSeparatorsIfNeeded=function(a){var b,c=h.typeSeparator,d=a.length;a.forEach(function(a){a.type===h.typeSeparator&&c===h.typeSeparator&&m.addClass(a.element,h.ClassNames.commandSeparatorHiddenPolicyClass),c=a.type});for(var e=d-1;e>=0&&(b=a[e],b.type===h.typeSeparator);e--)m.addClass(b.element,h.ClassNames.commandSeparatorHiddenPolicyClass)},a.prototype._hasExpandableActionArea=function(){switch(this.closedDisplayMode){case H.none:case H.minimal:case H.compact:return!0;case H.full:default:return!1}},a.prototype._clearAnimation=function(){var a=e._browserStyleEquivalents.transform.scriptName;this._dom.actionAreaContainer.style[a]="",this._dom.actionArea.style[a]="",this._dom.overflowAreaContainer.style[a]="",this._dom.overflowArea.style[a]=""},a.ClosedDisplayMode=H,a.OverflowDirection=F,a.supportedForProcessing=!0,a}();b._CommandingSurface=J,d.Class.mix(J,o.createEventProperties(h.EventNames.beforeOpen,h.EventNames.afterOpen,h.EventNames.beforeClose,h.EventNames.afterClose)),d.Class.mix(J,k.DOMEventMixin)}),d("WinJS/Controls/CommandingSurface",["require","exports"],function(a){function b(){return c||a(["./CommandingSurface/_CommandingSurface"],function(a){c=a}),c._CommandingSurface}var c=null,d=Object.create({},{_CommandingSurface:{get:function(){return b()}}});return d}),d("require-style!less/styles-toolbar",[],function(){}),d("WinJS/Controls/ToolBar/_ToolBar",["require","exports","../../Core/_Base","../ToolBar/_Constants","../CommandingSurface","../../Utilities/_Control","../../Utilities/_Dispose","../../Utilities/_ElementUtilities","../../Core/_ErrorFromName","../../Core/_Events","../../Core/_Global","../../_LightDismissService","../../Core/_Resources","../../Utilities/_OpenCloseMachine","../../Core/_WriteProfilerMark"],function(a,b,c,d,e,f,g,h,i,j,k,l,m,n,o){function p(a,b){b&&h.addClass(a,b)}function q(a,b){b&&h.removeClass(a,b)}a(["require-style!less/styles-toolbar"]);var r={get ariaLabel(){return m._getWinJSString("ui/toolbarAriaLabel").value},get overflowButtonAriaLabel(){return m._getWinJSString("ui/toolbarOverflowButtonAriaLabel").value},get mustContainCommands(){return"The toolbar can only contain WinJS.UI.Command or WinJS.UI.AppBarCommand controls"},get duplicateConstruction(){return"Invalid argument: Controls may only be instantiated one time for each DOM element"}},s={compact:"compact",full:"full"},t={};t[s.compact]=d.ClassNames.compactClass,t[s.full]=d.ClassNames.fullClass;var u=function(){function a(a,b){var c=this;if(void 0===b&&(b={}),this._updateDomImpl_renderedState={isOpenedMode:void 0,closedDisplayMode:void 0,prevInlineWidth:void 0},this._writeProfilerMark("constructor,StartTM"),a&&a.winControl)throw new i("WinJS.UI.ToolBar.DuplicateConstruction",r.duplicateConstruction);this._initializeDom(a||k.document.createElement("div"));var g=new n.OpenCloseMachine({eventElement:this.element,onOpen:function(){var a=c._commandingSurface.createOpenAnimation(c._getClosedHeight());return c._synchronousOpen(),a.execute()},onClose:function(){var a=c._commandingSurface.createCloseAnimation(c._getClosedHeight());return a.execute().then(function(){c._synchronousClose()})},onUpdateDom:function(){c._updateDomImpl()},onUpdateDomWithIsOpened:function(a){c._isOpenedMode=a,c._updateDomImpl()}});this._handleShowingKeyboardBound=this._handleShowingKeyboard.bind(this),h._inputPaneListener.addEventListener(this._dom.root,"showing",this._handleShowingKeyboardBound),this._disposed=!1,this._cachedClosedHeight=null,this._commandingSurface=new e._CommandingSurface(this._dom.commandingSurfaceEl,{openCloseMachine:g}),p(this._dom.commandingSurfaceEl.querySelector(".win-commandingsurface-actionarea"),d.ClassNames.actionAreaCssClass),p(this._dom.commandingSurfaceEl.querySelector(".win-commandingsurface-overflowarea"),d.ClassNames.overflowAreaCssClass),p(this._dom.commandingSurfaceEl.querySelector(".win-commandingsurface-overflowbutton"),d.ClassNames.overflowButtonCssClass),p(this._dom.commandingSurfaceEl.querySelector(".win-commandingsurface-ellipsis"),d.ClassNames.ellipsisCssClass),this._isOpenedMode=d.defaultOpened,this._dismissable=new l.LightDismissableElement({element:this._dom.root,tabIndex:this._dom.root.hasAttribute("tabIndex")?this._dom.root.tabIndex:-1,onLightDismiss:function(){c.close()},onTakeFocus:function(a){c._dismissable.restoreFocus()||c._commandingSurface.takeFocus(a)}}),this.closedDisplayMode=d.defaultClosedDisplayMode,this.opened=this._isOpenedMode,f.setOptions(this,b),h._inDom(this.element).then(function(){return c._commandingSurface.initialized}).then(function(){g.exitInit(),c._writeProfilerMark("constructor,StopTM")})}return Object.defineProperty(a.prototype,"element",{get:function(){return this._dom.root},enumerable:!0,configurable:!0}),Object.defineProperty(a.prototype,"data",{get:function(){return this._commandingSurface.data},set:function(a){this._commandingSurface.data=a},enumerable:!0,configurable:!0}),Object.defineProperty(a.prototype,"closedDisplayMode",{get:function(){return this._commandingSurface.closedDisplayMode},set:function(a){s[a]&&(this._commandingSurface.closedDisplayMode=a,this._cachedClosedHeight=null)},enumerable:!0,configurable:!0}),Object.defineProperty(a.prototype,"opened",{get:function(){return this._commandingSurface.opened},set:function(a){this._commandingSurface.opened=a},enumerable:!0,configurable:!0}),a.prototype.open=function(){this._commandingSurface.open()},a.prototype.close=function(){this._commandingSurface.close()},a.prototype.dispose=function(){this._disposed||(this._disposed=!0,l.hidden(this._dismissable),this._commandingSurface.dispose(),this._synchronousClose(),h._inputPaneListener.removeEventListener(this._dom.root,"showing",this._handleShowingKeyboardBound),g.disposeSubTree(this.element))},a.prototype.forceLayout=function(){this._commandingSurface.forceLayout()},a.prototype.getCommandById=function(a){return this._commandingSurface.getCommandById(a)},a.prototype.showOnlyCommands=function(a){return this._commandingSurface.showOnlyCommands(a)},a.prototype._writeProfilerMark=function(a){o("WinJS.UI.ToolBar:"+this._id+":"+a)},a.prototype._initializeDom=function(a){this._writeProfilerMark("_intializeDom,info"),a.winControl=this,this._id=a.id||h._uniqueID(a),h.addClass(a,d.ClassNames.controlCssClass),h.addClass(a,d.ClassNames.disposableCssClass);var b=a.getAttribute("role");b||a.setAttribute("role","menubar");var c=a.getAttribute("aria-label");c||a.setAttribute("aria-label",r.ariaLabel);var e=document.createElement("DIV");h._reparentChildren(a,e),a.appendChild(e);var f=k.document.createElement("DIV");h.addClass(f,d.ClassNames.placeHolderCssClass),g.markDisposable(f,this.dispose.bind(this)),this._dom={root:a,commandingSurfaceEl:e,placeHolder:f}},a.prototype._handleShowingKeyboard=function(){this.close()},a.prototype._synchronousOpen=function(){this._isOpenedMode=!0,this._updateDomImpl()},a.prototype._synchronousClose=function(){this._isOpenedMode=!1,this._updateDomImpl()},a.prototype._updateDomImpl=function(){var a=this._updateDomImpl_renderedState;a.isOpenedMode!==this._isOpenedMode&&(this._isOpenedMode?this._updateDomImpl_renderOpened():this._updateDomImpl_renderClosed(),a.isOpenedMode=this._isOpenedMode),a.closedDisplayMode!==this.closedDisplayMode&&(q(this._dom.root,t[a.closedDisplayMode]),p(this._dom.root,t[this.closedDisplayMode]),a.closedDisplayMode=this.closedDisplayMode),this._commandingSurface.updateDom()},a.prototype._getClosedHeight=function(){if(null===this._cachedClosedHeight){var a=this._isOpenedMode;this._isOpenedMode&&this._synchronousClose(),this._cachedClosedHeight=this._commandingSurface.getBoundingRects().commandingSurface.height,a&&this._synchronousOpen()}return this._cachedClosedHeight},a.prototype._updateDomImpl_renderOpened=function(){var a=this;this._updateDomImpl_renderedState.prevInlineWidth=this._dom.root.style.width;var b=this._dom.root.getBoundingClientRect(),c=h._getPreciseContentWidth(this._dom.root),e=h._getPreciseContentHeight(this._dom.root),f=h._getComputedStyle(this._dom.root),g=h._convertToPrecisePixels(f.paddingTop),i=h._convertToPrecisePixels(f.borderTopWidth),j=h._getPreciseMargins(this._dom.root),m=b.top+i+g,n=m+e,o=this._dom.placeHolder,p=o.style;p.width=b.width+"px",p.height=b.height+"px",p.marginTop=j.top+"px",p.marginRight=j.right+"px",p.marginBottom=j.bottom+"px",p.marginLeft=j.left+"px",h._maintainFocus(function(){a._dom.root.parentElement.insertBefore(o,a._dom.root),k.document.body.appendChild(a._dom.root),a._dom.root.style.width=c+"px",a._dom.root.style.left=b.left-j.left+"px";var e=0,f=k.innerHeight,g=m-e,i=f-n;g>i?(a._commandingSurface.overflowDirection=d.OverflowDirection.top,a._dom.root.style.bottom=f-b.bottom-j.bottom+"px"):(a._commandingSurface.overflowDirection=d.OverflowDirection.bottom,a._dom.root.style.top=e+b.top-j.top+"px"),h.addClass(a._dom.root,d.ClassNames.openedClass),h.removeClass(a._dom.root,d.ClassNames.closedClass)}),this._commandingSurface.synchronousOpen(),l.shown(this._dismissable)},a.prototype._updateDomImpl_renderClosed=function(){var a=this;h._maintainFocus(function(){if(a._dom.placeHolder.parentElement){var b=a._dom.placeHolder;b.parentElement.insertBefore(a._dom.root,b),b.parentElement.removeChild(b)}a._dom.root.style.top="",a._dom.root.style.right="",a._dom.root.style.bottom="",a._dom.root.style.left="",a._dom.root.style.width=a._updateDomImpl_renderedState.prevInlineWidth,h.addClass(a._dom.root,d.ClassNames.closedClass),h.removeClass(a._dom.root,d.ClassNames.openedClass)}),this._commandingSurface.synchronousClose(),l.hidden(this._dismissable)},a.ClosedDisplayMode=s,a.supportedForProcessing=!0,a}();b.ToolBar=u,c.Class.mix(u,j.createEventProperties(d.EventNames.beforeOpen,d.EventNames.afterOpen,d.EventNames.beforeClose,d.EventNames.afterClose)),c.Class.mix(u,f.DOMEventMixin)}),d("WinJS/Controls/ToolBar",["require","exports","../Core/_Base"],function(a,b,c){var d=null;c.Namespace.define("WinJS.UI",{ToolBar:{get:function(){return d||a(["./ToolBar/_ToolBar"],function(a){d=a}),d.ToolBar}}})}),d("WinJS/Controls/_LegacyAppBar/_Layouts",["exports","../../Animations/_TransitionAnimation","../../BindingList","../../Core/_BaseUtils","../../Core/_Global","../../Core/_Base","../../Core/_ErrorFromName","../../Core/_Resources","../../Core/_WriteProfilerMark","../../Controls/ToolBar","../../Controls/ToolBar/_Constants","../../Promise","../../Scheduler","../../Utilities/_Control","../../Utilities/_Dispose","../../Utilities/_ElementUtilities","../AppBar/_Command","./_Constants"],function(a,b,c,d,e,f,g,h,i,j,k,l,m,n,o,p,q,r){"use strict";f.Namespace._moduleDefine(a,"WinJS.UI",{_AppBarBaseLayout:f.Namespace._lazy(function(){var a=r.appBarLayoutCustom,b={get nullCommand(){return"Invalid argument: command must not be null"}},c=f.Class.define(function(a,b){this._disposed=!1,b=b||{},n.setOptions(this,b),a&&this.connect(a)},{className:{get:function(){return this._className}},type:{get:function(){return this._type||a}},commandsInOrder:{get:function(){var a=this.appBarEl.querySelectorAll("."+r.appBarCommandClass);return Array.prototype.map.call(a,function(a){return a.winControl})}},connect:function(a){this.className&&p.addClass(a,this.className),this.appBarEl=a},disconnect:function(){this.className&&p.removeClass(this.appBarEl,this.className),this.appBarEl=null,this.dispose()},layout:function(a){for(var b=a.length,c=0;b>c;c++){var d=this.sanitizeCommand(a[c]);this.appBarEl.appendChild(d._element)}},showCommands:function(a){this.appBarEl.winControl._showCommands(a)},showOnlyCommands:function(a){this.appBarEl.winControl._showOnlyCommands(a)},hideCommands:function(a){this.appBarEl.winControl._hideCommands(a)},sanitizeCommand:function(a){if(!a)throw new g("WinJS.UI.AppBar.NullCommand",b.nullCommand);return a=a.winControl||a,a._element||(a=new q.AppBarCommand(null,a)),a._element.parentElement&&a._element.parentElement.removeChild(a._element),a},dispose:function(){this._disposed=!0},disposeChildren:function(){var a=this.appBarEl.querySelectorAll("."+r.firstDivClass);a=a.length>=1?a[0]:null;var b=this.appBarEl.querySelectorAll("."+r.finalDivClass);b=b.length>=1?b[0]:null;for(var c=this.appBarEl.children,d=c.length,e=0;d>e;e++){var f=c[e];f!==a&&f!==b&&o.disposeSubTree(f)}},handleKeyDown:function(){},commandsUpdated:function(){},beginAnimateCommands:function(){},endAnimateCommands:function(){},scale:function(){},resize:function(){},positionChanging:function(){return l.wrap()},setFocusOnShow:function(){this.appBarEl.winControl._setFocusToAppBar()}});return c})}),f.Namespace._moduleDefine(a,"WinJS.UI",{_AppBarCommandsLayout:f.Namespace._lazy(function(){var b=r.commandLayoutClass,c=r.appBarLayoutCommands,d=f.Class.derive(a._AppBarBaseLayout,function(d){a._AppBarBaseLayout.call(this,d,{_className:b,_type:c}),this._commandLayoutsInit(d)},{commandsInOrder:{get:function(){return this._originalCommands.filter(function(a){return this.appBarEl.contains(a.element)},this)}},layout:function(a){p.empty(this._primaryCommands),p.empty(this._secondaryCommands),this._originalCommands=[];for(var b=0,c=a.length;c>b;b++){var d=this.sanitizeCommand(a[b]);this._originalCommands.push(d),"primary"===d.section||"global"===d.section?this._primaryCommands.appendChild(d._element):this._secondaryCommands.appendChild(d._element)}this.appBarEl.appendChild(this._secondaryCommands),this.appBarEl.appendChild(this._primaryCommands),this._needToMeasureNewCommands=!0,m.schedule(function(){this._needToMeasureNewCommands&&!this._disposed&&this.scale()}.bind(this),m.Priority.idle,this,"WinJS._commandLayoutsMixin._scaleNewCommands")},disposeChildren:function(){o.disposeSubTree(this._primaryCommands),o.disposeSubTree(this._secondaryCommands)},handleKeyDown:function(a){var b=p.Key;if(!p._matchesSelector(a.target,".win-interactive, .win-interactive *")){var c="rtl"===p._getComputedStyle(this.appBarEl).direction,d=c?b.rightArrow:b.leftArrow,f=c?b.leftArrow:b.rightArrow;if(a.keyCode===d||a.keyCode===f||a.keyCode===b.home||a.keyCode===b.end){var g,h=this._primaryCommands.contains(e.document.activeElement),i=this._getFocusableCommandsInLogicalOrder(h);if(i.length)switch(a.keyCode){case d:var j=Math.max(-1,i.focusedIndex-1)+i.length;g=i[j%i.length].winControl.lastElementFocus;break;case f:var j=i.focusedIndex+1+i.length;g=i[j%i.length].winControl.firstElementFocus;break;case b.home:var j=0;g=i[j].winControl.firstElementFocus;break;case b.end:var j=i.length-1;g=i[j].winControl.lastElementFocus}g&&g!==e.document.activeElement&&(g.focus(),a.preventDefault())}}},commandsUpdated:function(a){var b=a?a:this.commandsInOrder.filter(function(a){return!a.hidden});this._fullSizeWidthOfLastKnownVisibleCommands=this._getWidthOfFullSizeCommands(b)},beginAnimateCommands:function(a,b,c){this._scaleAfterAnimations=!1;var d=this._getWidthOfFullSizeCommands(a)-this._getWidthOfFullSizeCommands(b);if(d>0){var e=c.concat(a);this.commandsUpdated(e),this.scale()}else 0>d&&(this._scaleAfterAnimations=!0)},endAnimateCommands:function(){this._scaleAfterAnimations&&(this.commandsUpdated(),this.scale())},resize:function(){this._disposed||(this._appBarTotalKnownWidth=null,this.appBarEl.winControl.opened&&this.scale())},disconnect:function(){a._AppBarBaseLayout.prototype.disconnect.call(this)},_getWidthOfFullSizeCommands:function(a){this._needToMeasureNewCommands&&this._measureContentCommands();var b=0,c=0,d=0;if(!a)return this._fullSizeWidthOfLastKnownVisibleCommands;for(var e,f=0,g=a.length;g>f;f++)e=a[f].winControl||a[f],e._type===r.typeSeparator?c++:e._type!==r.typeContent?d++:b+=e._fullSizeWidth;return b+=c*r.separatorWidth+d*r.buttonWidth},_getFocusableCommandsInLogicalOrder:function(){var a=this._secondaryCommands.children,b=this._primaryCommands.children,c=-1,d=function(a){for(var b=[],d=0,f=a.length;f>d;d++){var g=a[d];if(p.hasClass(g,r.appBarCommandClass)&&g.winControl){var h=g.contains(e.document.activeElement);(g.winControl._isFocusable()||h)&&(b.push(g),h&&(c=b.length-1))}}return b},f=Array.prototype.slice.call(a).concat(Array.prototype.slice.call(b)),g=d(f);return g.focusedIndex=c,g},_commandLayoutsInit:function(){this._primaryCommands=e.document.createElement("DIV"),this._secondaryCommands=e.document.createElement("DIV"),p.addClass(this._primaryCommands,r.primaryCommandsClass),p.addClass(this._secondaryCommands,r.secondaryCommandsClass)},_scaleHelper:function(){var a="minimal"===this.appBarEl.winControl.closedDisplayMode?r.appBarInvokeButtonWidth:0;return e.document.documentElement.clientWidth-a},_measureContentCommands:function(){if(e.document.body.contains(this.appBarEl)){this._needToMeasureNewCommands=!1;var a=p.hasClass(this.appBarEl,"win-navbar-closed");p.removeClass(this.appBarEl,"win-navbar-closed");var b=this.appBarEl.style.display;this.appBarEl.style.display="";for(var c,d,f=this.appBarEl.querySelectorAll("div."+r.appBarCommandClass),g=0,h=f.length;h>g;g++)d=f[g],d.winControl&&d.winControl._type===r.typeContent&&(c=d.style.display,d.style.display="",d.winControl._fullSizeWidth=p.getTotalWidth(d)||0,d.style.display=c);this.appBarEl.style.display=b,a&&p.addClass(this.appBarEl,"win-navbar-closed"),this.commandsUpdated()}}});return d})}),f.Namespace._moduleDefine(a,"WinJS.UI",{_AppBarMenuLayout:f.Namespace._lazy(function(){function g(a,c){var f=c.duration*b._animationFactor,g=d._browserStyleEquivalents.transition.scriptName;a.style[g]=f+"ms "+t.cssName+" "+c.timing,a.style[t.scriptName]=c.to;var h;return new l(function(b){var c=function(b){b.target===a&&b.propertyName===t.cssName&&h()},i=!1;h=function(){i||(e.clearTimeout(j),a.removeEventListener(d._browserEventEquivalents.transitionEnd,c),a.style[g]="",i=!0),b()};var j=e.setTimeout(function(){j=e.setTimeout(h,f)},50);a.addEventListener(d._browserEventEquivalents.transitionEnd,c)},function(){h()})}function h(a,b,c){var d=c.anchorTrailingEdge?c.to.total-c.from.total:c.from.total-c.to.total,e="width"===c.dimension?"translateX":"translateY",f=c.dimension,h=c.duration||367,i=c.timing||"cubic-bezier(0.1, 0.9, 0.2, 1)";a.style[f]=c.to.total+"px",a.style[t.scriptName]=e+"("+d+"px)",b.style[f]=c.to.content+"px",b.style[t.scriptName]=e+"("+-d+"px)",p._getComputedStyle(a).opacity,p._getComputedStyle(b).opacity;var j={duration:h,timing:i,to:""};return l.join([g(a,j),g(b,j)])}function m(a,b,c){var e=c.anchorTrailingEdge?c.from.total-c.to.total:c.to.total-c.from.total,f="width"===c.dimension?"translateX":"translateY",h=c.duration||367,i=c.timing||"cubic-bezier(0.1, 0.9, 0.2, 1)";a.style[t.scriptName]="",b.style[t.scriptName]="",p._getComputedStyle(a).opacity,p._getComputedStyle(b).opacity;var j={duration:h,timing:i},k=d._merge(j,{to:f+"("+e+"px)"}),m=d._merge(j,{to:f+"("+-e+"px)"});return l.join([g(a,k),g(b,m)])}function n(a,b,c){return c.to.total>c.from.total?h(a,b,c):c.to.total<c.from.total?m(a,b,c):l.as()}var q=r.menuLayoutClass,s=r.appBarLayoutMenu,t=d._browserStyleEquivalents.transform,u=f.Class.derive(a._AppBarBaseLayout,function(b){a._AppBarBaseLayout.call(this,b,{_className:q,_type:s}),this._tranformNames=d._browserStyleEquivalents.transform,this._animationCompleteBound=this._animationComplete.bind(this),this._positionToolBarBound=this._positionToolBar.bind(this)},{commandsInOrder:{get:function(){return this._originalCommands}},layout:function(a){this._writeProfilerMark("layout,info"),a=a||[],this._originalCommands=[];var b=this;a.forEach(function(a){b._originalCommands.push(b.sanitizeCommand(a))}),this._displayedCommands=this._originalCommands.slice(0),this._menu?p.empty(this._menu):(this._menu=e.document.createElement("div"),p.addClass(this._menu,r.menuContainerClass)),this.appBarEl.appendChild(this._menu),this._toolbarEl=e.document.createElement("div"),this._menu.appendChild(this._toolbarEl),this._createToolBar(a)},showCommands:function(a){var b=this._getCommandsElements(a),c=[],d=[],e=this;this._originalCommands.forEach(function(a){(b.indexOf(a.element)>=0||e._displayedCommands.indexOf(a)>=0)&&(d.push(a),c.push(a))}),this._displayedCommands=d,this._updateData(c)},showOnlyCommands:function(a){this._displayedCommands=[],this.showCommands(a)},hideCommands:function(a){var b=this._getCommandsElements(a),c=[],d=[],e=this;this._originalCommands.forEach(function(a){-1===b.indexOf(a.element)&&e._displayedCommands.indexOf(a)>=0&&(d.push(a),c.push(a))}),this._displayedCommands=d,this._updateData(c)},connect:function(b){this._writeProfilerMark("connect,info"),a._AppBarBaseLayout.prototype.connect.call(this,b),this._id=p._uniqueID(b)},resize:function(){this._writeProfilerMark("resize,info"),this._initialized&&(this._forceLayoutPending=!0)},positionChanging:function(a,b){return this._writeProfilerMark("positionChanging from:"+a+" to: "+b+",info"),this._animationPromise=this._animationPromise||l.wrap(),this._animating&&this._animationPromise.cancel(),this._animating=!0,"shown"===b||"shown"!==a&&"compact"===b?(this._positionToolBar(),this._animationPromise=this._animateToolBarEntrance()):this._animationPromise="minimal"===a||"compact"===a||"hidden"===a?l.wrap():this._animateToolBarExit(),this._animationPromise.then(this._animationCompleteBound,this._animationCompleteBound),this._animationPromise},disposeChildren:function(){this._writeProfilerMark("disposeChildren,info"),this._toolbar&&o.disposeSubTree(this._toolbarEl),this._originalCommands=[],this._displayedCommands=[]},setFocusOnShow:function(){this.appBarEl.winControl._setFocusToAppBar(!0,this._menu)},_updateData:function(a){var b=p.hasClass(this.appBarEl,"win-navbar-closed"),d=p.hasClass(this.appBarEl,"win-navbar-opened");p.removeClass(this.appBarEl,"win-navbar-closed");var e=this.appBarEl.style.display;this.appBarEl.style.display="",this._toolbar.data=new c.List(a),b&&this._positionToolBar(),this.appBarEl.style.display=e,b&&p.addClass(this.appBarEl,"win-navbar-closed"),d&&(this._positionToolBar(),this._animateToolBarEntrance())},_getCommandsElements:function(a){if(!a)return[];"string"!=typeof a&&a&&a.length||(a=[a]);for(var b=[],c=0,d=a.length;d>c;c++)if(a[c])if("string"==typeof a[c]){var f=e.document.getElementById(a[c]);if(f)b.push(f);else for(var g=0,h=this._originalCommands.length;h>g;g++){var f=this._originalCommands[g].element;f.id===a[c]&&b.push(f)}}else b.push(a[c].element?a[c].element:a[c]);return b},_animationComplete:function(){this._disposed||(this._animating=!1)},_createToolBar:function(){this._writeProfilerMark("_createToolBar,info");var a=p.hasClass(this.appBarEl,"win-navbar-closed");p.removeClass(this.appBarEl,"win-navbar-closed");var b=this.appBarEl.style.display;this.appBarEl.style.display="",this._toolbar=new j.ToolBar(this._toolbarEl,{data:new c.List(this._originalCommands),shownDisplayMode:"full"});var d=this;this._appbarInvokeButton=this.appBarEl.querySelector("."+r.invokeButtonClass),this._overflowButton=this._toolbarEl.querySelector("."+k.overflowButtonCssClass),this._overflowButton.addEventListener("click",function(){d._appbarInvokeButton.click()}),this._positionToolBar(),this.appBarEl.style.display=b,a&&p.addClass(this.appBarEl,"win-navbar-closed")},_positionToolBar:function(){this._disposed||(this._writeProfilerMark("_positionToolBar,info"),this._initialized=!0)},_animateToolBarEntrance:function(){this._writeProfilerMark("_animateToolBarEntrance,info"),this._forceLayoutPending&&(this._forceLayoutPending=!1,this._toolbar.forceLayout(),this._positionToolBar());var a=this._isMinimal()?0:this.appBarEl.offsetHeight;if(this._isBottom()){var b=this._menu.offsetHeight-a;return this._executeTranslate(this._menu,"translateY("+-b+"px)")}return n(this._menu,this._toolbarEl,{from:{content:a,total:a},to:{content:this._menu.offsetHeight,total:this._menu.offsetHeight},dimension:"height",duration:400,timing:"ease-in"})},_animateToolBarExit:function(){this._writeProfilerMark("_animateToolBarExit,info");var a=this._isMinimal()?0:this.appBarEl.offsetHeight;return this._isBottom()?this._executeTranslate(this._menu,"none"):n(this._menu,this._toolbarEl,{from:{content:this._menu.offsetHeight,total:this._menu.offsetHeight},to:{content:a,total:a},dimension:"height",duration:400,timing:"ease-in"})},_executeTranslate:function(a,c){return b.executeTransition(a,{property:this._tranformNames.cssName,delay:0,duration:400,timing:"ease-in",to:c})},_isMinimal:function(){return"minimal"===this.appBarEl.winControl.closedDisplayMode},_isBottom:function(){return"bottom"===this.appBarEl.winControl.placement},_writeProfilerMark:function(a){i("WinJS.UI._AppBarMenuLayout:"+this._id+":"+a)}});return u})})}),d("WinJS/Controls/_LegacyAppBar",["exports","../Core/_Global","../Core/_WinRT","../Core/_Base","../Core/_BaseUtils","../Core/_ErrorFromName","../Core/_Events","../Core/_Resources","../Core/_WriteProfilerMark","../Animations","../Promise","../Scheduler","../_LightDismissService","../Utilities/_Control","../Utilities/_Dispose","../Utilities/_ElementUtilities","../Utilities/_Hoverable","../Utilities/_KeyboardBehavior","./_LegacyAppBar/_Constants","./_LegacyAppBar/_Layouts","./AppBar/_Command","./AppBar/_Icon","./Flyout/_Overlay","../Application"],function(a,b,c,d,e,f,g,h,i,j,k,l,m,n,o,p,q,r,s,t,u,v,w){"use strict";d.Namespace._moduleDefine(a,"WinJS.UI",{_LegacyAppBar:d.Namespace._lazy(function(){function a(a){var c=b.document.querySelectorAll("."+s.appBarClass);if(c)for(var d=c.length,e=0;d>e;e++){var f=c[e],g=f.winControl;g&&!f.disabled&&g._manipulationChanged(a)}}var q={beforeOpen:"beforeopen",afterOpen:"afteropen",beforeClose:"beforeclose",afterClose:"afterclose"},u=g._createEventProperty,v={none:0,hidden:0,minimal:25,compact:48},x={none:"hidden",hidden:"hidden",minimal:"minimal",shown:"shown",compact:"compact"},y={none:"none",minimal:"minimal",compact:"compact"},z="shown",A="hidden",B=!1,C={get ariaLabel(){return h._getWinJSString("ui/appBarAriaLabel").value},get requiresCommands(){return"Invalid argument: commands must not be empty"},get cannotChangePlacementWhenVisible(){return"Invalid argument: The placement property cannot be set when the AppBar is visible, call hide() first"},get cannotChangeLayoutWhenVisible(){return"Invalid argument: The layout property cannot be set when the AppBar is visible, call hide() first"}},D=d.Class.derive(w._Overlay,function(c,d){this._initializing=!0,d=d||{},this._element=c||b.document.createElement("div"),this._id=this._element.id||p._uniqueID(this._element),this._writeProfilerMark("constructor,StartTM"),p.addClass(this._element,s.appBarClass);var e=this;this._dismissable=new m.LightDismissableElement({element:this._element,tabIndex:this._element.hasAttribute("tabIndex")?this._element.tabIndex:-1,onLightDismiss:function(){e.close()},onTakeFocus:function(){e._dismissable.restoreFocus()||e._layoutImpl.setFocusOnShow() }});var f=this._element.getAttribute("role");f||this._element.setAttribute("role","menubar");var g=this._element.getAttribute("aria-label");g||this._element.setAttribute("aria-label",C.ariaLabel),this._baseOverlayConstructor(this._element),this._lastPositionVisited=x.none,p.addClass(this._element,s.hiddenClass),this._invokeButton=b.document.createElement("button"),this._invokeButton.tabIndex=0,this._invokeButton.setAttribute("type","button"),this._invokeButton.innerHTML="<span class='"+s.ellipsisClass+"'></span>",p.addClass(this._invokeButton,s.invokeButtonClass),this._element.appendChild(this._invokeButton),this._invokeButton.addEventListener("click",function(){e.opened?e._hide():e._show()},!1),this._layout=s.appBarLayoutCustom,delete d._layout,this.placement=d.placement||s.appBarPlacementBottom,this.closedDisplayMode=d.closedDisplayMode||y.compact,n.setOptions(this,d);var h=this._commandsUpdated.bind(this);return this._element.addEventListener(s.commandVisibilityChanged,function(a){e._disposed||(e.opened&&a.preventDefault(),h())}),this._initializing=!1,this._setFocusToAppBarBound=this._setFocusToAppBar.bind(this),this._element.addEventListener("keydown",this._handleKeyDown.bind(this),!1),B||(b.document.addEventListener("MSManipulationStateChanged",a,!1),B=!0),this.closedDisplayMode===y.none&&this.layout===s.appBarLayoutCommands&&(this._element.style.display="none"),this._winKeyboard=new r._WinKeyboard(this._element),this._writeProfilerMark("constructor,StopTM"),this},{placement:{get:function(){return this._placement},set:function(a){var b=!1;if(c.Windows.ApplicationModel.DesignMode.designModeEnabled&&(this._hide(),b=!0),this.opened)throw new f("WinJS.UI._LegacyAppBar.CannotChangePlacementWhenVisible",C.cannotChangePlacementWhenVisible);this._placement=a===s.appBarPlacementTop?s.appBarPlacementTop:s.appBarPlacementBottom,this._placement===s.appBarPlacementTop?(p.addClass(this._element,s.topClass),p.removeClass(this._element,s.bottomClass)):this._placement===s.appBarPlacementBottom&&(p.removeClass(this._element,s.topClass),p.addClass(this._element,s.bottomClass)),this._ensurePosition(),b&&this._show()}},_layout:{get:function(){return this._layoutImpl.type},set:function(a){a!==s.appBarLayoutCommands&&a!==s.appBarLayoutCustom&&a!==s.appBarLayoutMenu;var b=!1;if(c.Windows.ApplicationModel.DesignMode.designModeEnabled&&(this._hide(),b=!0),this.opened)throw new f("WinJS.UI._LegacyAppBar.CannotChangeLayoutWhenVisible",C.cannotChangeLayoutWhenVisible);var d;this._initializing||(d=this._layoutImpl.commandsInOrder,this._layoutImpl.disconnect()),this._layoutImpl=a===s.appBarLayoutCommands?new t._AppBarCommandsLayout:a===s.appBarLayoutMenu?new t._AppBarMenuLayout:new t._AppBarBaseLayout,this._layoutImpl.connect(this._element),d&&d.length&&this._layoutCommands(d),b&&this._show()},configurable:!0},commands:{set:function(a){if(this.opened)throw new f("WinJS.UI._LegacyAppBar.CannotChangeCommandsWhenVisible",h._formatString(w._Overlay.commonstrings.cannotChangeCommandsWhenVisible,"_LegacyAppBar"));this._initializing||this._disposeChildren(),this._layoutCommands(a)}},_layoutCommands:function(a){p.empty(this._element),this._element.appendChild(this._invokeButton),Array.isArray(a)||(a=[a]),this._layoutImpl.layout(a)},closedDisplayMode:{get:function(){return this._closedDisplayMode},set:function(a){var b=this._closedDisplayMode;if(b!==a){var c=p.hasClass(this._element,s.hiddenClass)||p.hasClass(this._element,s.hidingClass);a===y.none?(this._closedDisplayMode=y.none,c&&b||(p.removeClass(this._element,s.minimalClass),p.removeClass(this._element,s.compactClass))):a===y.minimal?(this._closedDisplayMode=y.minimal,c&&b&&b!==y.none||(p.addClass(this._element,s.minimalClass),p.removeClass(this._element,s.compactClass))):(this._closedDisplayMode=y.compact,p.addClass(this._element,s.compactClass),p.removeClass(this._element,s.minimalClass)),this._layoutImpl.resize(),c&&this._changeVisiblePosition(x[this._closedDisplayMode])}}},opened:{get:function(){return!p.hasClass(this._element,s.hiddenClass)&&!p.hasClass(this._element,s.hidingClass)&&this._doNext!==x.minimal&&this._doNext!==x.compact&&this._doNext!==x.none},set:function(a){var b=this.opened;a&&!b?this._show():!a&&b&&this._hide()}},onbeforeopen:u(q.beforeOpen),onafteropen:u(q.afterOpen),onbeforeclose:u(q.beforeClose),onafterclose:u(q.afterClose),getCommandById:function(a){var b=this._layoutImpl.commandsInOrder.filter(function(b){return b.id===a||b.element.id===a});return 1===b.length?b[0]:0===b.length?null:b},showCommands:function(a){if(!a)throw new f("WinJS.UI._LegacyAppBar.RequiresCommands",C.requiresCommands);this._layoutImpl.showCommands(a)},hideCommands:function(a){if(!a)throw new f("WinJS.UI._LegacyAppBar.RequiresCommands",C.requiresCommands);this._layoutImpl.hideCommands(a)},showOnlyCommands:function(a){if(!a)throw new f("WinJS.UI._LegacyAppBar.RequiresCommands",C.requiresCommands);this._layoutImpl.showOnlyCommands(a)},open:function(){this._writeProfilerMark("show,StartTM"),this._show()},_show:function(){var a=x.shown,b=null;this.disabled||!p.hasClass(this._element,s.hiddenClass)&&!p.hasClass(this._element,s.hidingClass)||(b=z),this._changeVisiblePosition(a,b),b&&(this._updateFirstAndFinalDiv(),m.shown(this._dismissable))},close:function(){this._writeProfilerMark("hide,StartTM"),this._hide()},_hide:function(a){var a=a||x[this.closedDisplayMode],b=null;p.hasClass(this._element,s.hiddenClass)||p.hasClass(this._element,s.hidingClass)||(b=A),this._changeVisiblePosition(a,b)},_dispose:function(){o.disposeSubTree(this.element),m.hidden(this._dismissable),this._layoutImpl.dispose(),this.disabled=!0,this.close()},_disposeChildren:function(){this._layoutImpl.disposeChildren()},_handleKeyDown:function(a){this._invokeButton.contains(b.document.activeElement)||this._layoutImpl.handleKeyDown(a)},_visiblePixels:{get:function(){return{hidden:v.hidden,minimal:v.minimal,compact:Math.max(this._heightWithoutLabels||0,v.compact),shown:this._element.offsetHeight}}},_visiblePosition:{get:function(){return this._animating&&x[this._element.winAnimating]?this._element.winAnimating:this._lastPositionVisited}},_visible:{get:function(){return this._visiblePosition!==x.none}},_changeVisiblePosition:function(a,b){if(this._visiblePosition===a&&!this._keyboardObscured||this.disabled&&a!==x.disabled)this._afterPositionChange(null);else if(this._animating||this._needToHandleShowingKeyboard||this._needToHandleHidingKeyboard)this._doNext=a,this._afterPositionChange(null);else{this._element.winAnimating=a;var c=this._initializing?!1:!0,d=this._lastPositionVisited;this._element.style.display="";var e=a===x.hidden;this._keyboardObscured&&(e?c=!1:d=x.hidden,this._keyboardObscured=!1),b===z?this._beforeShow():b===A&&this._beforeHide(),this._ensurePosition(),this._element.style.opacity=1,this._element.style.visibility="visible",this._animationPromise=c?this._animatePositionChange(d,a):k.wrap(),this._animationPromise.then(function(){this._afterPositionChange(a,b)}.bind(this),function(){this._afterPositionChange(a,b)}.bind(this))}},_afterPositionChange:function(a,b){if(!this._disposed){if(a){a===x.minimal&&(p.addClass(this._element,s.minimalClass),p.removeClass(this._element,s.compactClass)),a===x.hidden&&this.closedDisplayMode===y.none&&(p.removeClass(this._element,s.minimalClass),p.removeClass(this._element,s.compactClass)),this._element.winAnimating="",this._lastPositionVisited=a,this._doNext===this._lastPositionVisited&&(this._doNext=""),b===A&&m.hidden(this._dismissable),a===x.hidden&&(this._element.style.visibility="hidden",this._element.style.display="none");var c=e._browserStyleEquivalents.transform.scriptName;this._element.style[c]="",b===z?this._afterShow():b===A&&this._afterHide(),l.schedule(this._checkDoNext,l.Priority.normal,this,"WinJS.UI._LegacyAppBar._checkDoNext")}this._afterPositionChangeCallBack()}},_afterPositionChangeCallBack:function(){},_beforeShow:function(){this._queuedCommandAnimation&&(this._showAndHideFast(this._queuedToShow,this._queuedToHide),this._queuedToShow=[],this._queuedToHide=[]),this._layoutImpl.scale(),this.closedDisplayMode===y.compact&&(this._heightWithoutLabels=this._element.offsetHeight),p.removeClass(this._element,s.hiddenClass),p.addClass(this._element,s.showingClass),this._sendEvent(q.beforeOpen)},_afterShow:function(){p.removeClass(this._element,s.showingClass),p.addClass(this._element,s.shownClass),this._sendEvent(q.afterOpen),this._writeProfilerMark("show,StopTM")},_beforeHide:function(){p.removeClass(this._element,s.shownClass),p.addClass(this._element,s.hidingClass),this._sendEvent(q.beforeClose)},_afterHide:function(){this._queuedCommandAnimation&&(this._showAndHideFast(this._queuedToShow,this._queuedToHide),this._queuedToShow=[],this._queuedToHide=[]),p.removeClass(this._element,s.hidingClass),p.addClass(this._element,s.hiddenClass),this._sendEvent(q.afterClose),this._writeProfilerMark("hide,StopTM")},_animatePositionChange:function(a,b){var c,d=this._layoutImpl.positionChanging(a,b),e=this._visiblePixels[a],f=this._visiblePixels[b],g=Math.abs(f-e),h=this._placement===s.appBarPlacementTop?-g:g;if(this._placement===s.appBarPlacementTop&&(a===x.shown&&b===x.compact||a===x.compact&&b===x.shown)&&(h=0),f>e){var i={top:h+"px",left:"0px"};c=j.showEdgeUI(this._element,i,{mechanism:"transition"})}else{var l={top:h+"px",left:"0px"};c=j.hideEdgeUI(this._element,l,{mechanism:"transition"})}return k.join([d,c])},_checkDoNext:function(){this._animating||this._needToHandleShowingKeyboard||this._needToHandleHidingKeyboard||this._disposed||(this._doNext===x.disabled||this._doNext===x.hidden||this._doNext===x.minimal||this._doNext===x.compact?(this._hide(this._doNext),this._doNext=""):this._queuedCommandAnimation?this._showAndHideQueue():this._doNext===x.shown&&(this._show(),this._doNext=""))},_setFocusToAppBar:function(a,b){this._focusOnFirstFocusableElement(a,b)||w._Overlay._trySetActive(this._element,b)},_commandsUpdated:function(){this._initializing||(this._layoutImpl.commandsUpdated(),this._layoutImpl.scale())},_beginAnimateCommands:function(a,b,c){this._layoutImpl.beginAnimateCommands(a,b,c)},_endAnimateCommands:function(){this._layoutImpl.endAnimateCommands(),this._endAnimateCommandsCallBack()},_endAnimateCommandsCallBack:function(){},_getTopOfVisualViewport:function(){return w._Overlay._keyboardInfo._visibleDocTop},_getAdjustedBottom:function(){return w._Overlay._keyboardInfo._visibleDocBottomOffset},_showingKeyboard:function(a){if(this._keyboardObscured=!1,this._needToHandleHidingKeyboard=!1,!w._Overlay._keyboardInfo._visible||!this._alreadyInPlace()){this._needToHandleShowingKeyboard=!0,this.opened&&this._element.contains(b.document.activeElement)&&(a.ensuredFocusedElementInView=!0),this._visible&&this._placement!==s.appBarPlacementTop&&w._Overlay._isFlyoutVisible()?this._keyboardObscured=!0:this._scrollHappened=!1;var c=this;b.setTimeout(function(a){c._checkKeyboardTimer(a)},w._Overlay._keyboardInfo._animationShowLength+w._Overlay._scrollTimeout)}},_hidingKeyboard:function(){this._keyboardObscured=!1,this._needToHandleShowingKeyboard=!1,this._needToHandleHidingKeyboard=!0,w._Overlay._keyboardInfo._isResized||((this._visible||this._animating)&&(this._checkScrollPosition(),this._element.style.display=""),this._needToHandleHidingKeyboard=!1)},_resize:function(a){this._needToHandleShowingKeyboard?this._visible&&(this._placement===s.appBarPlacementTop||this._keyboardObscured||(this._element.style.display="none")):this._needToHandleHidingKeyboard&&(this._needToHandleHidingKeyboard=!1,(this._visible||this._animating)&&(this._checkScrollPosition(),this._element.style.display="")),this._initializing||this._layoutImpl.resize(a)},_checkKeyboardTimer:function(){this._scrollHappened||this._mayEdgeBackIn()},_manipulationChanged:function(a){0===a.currentState&&this._scrollHappened&&this._mayEdgeBackIn()},_mayEdgeBackIn:function(){if(this._needToHandleShowingKeyboard)if(this._needToHandleShowingKeyboard=!1,this._keyboardObscured||this._placement===s.appBarPlacementTop&&0===w._Overlay._keyboardInfo._visibleDocTop)this._checkDoNext();else{var a=this._visiblePosition;this._lastPositionVisited=x.hidden,this._changeVisiblePosition(a,!1)}this._scrollHappened=!1},_ensurePosition:function(){var a=this._computePositionOffset();this._element.style.bottom=a.bottom,this._element.style.top=a.top},_computePositionOffset:function(){var a={};return this._placement===s.appBarPlacementBottom?(a.bottom=this._getAdjustedBottom()+"px",a.top=""):this._placement===s.appBarPlacementTop&&(a.bottom="",a.top=this._getTopOfVisualViewport()+"px"),a},_checkScrollPosition:function(){return this._needToHandleShowingKeyboard?void(this._scrollHappened=!0):void((this._visible||this._animating)&&(this._ensurePosition(),this._checkDoNext()))},_alreadyInPlace:function(){var a=this._computePositionOffset();return a.top===this._element.style.top&&a.bottom===this._element.style.bottom},_updateFirstAndFinalDiv:function(){var a=this._element.querySelectorAll("."+s.firstDivClass);a=a.length>=1?a[0]:null;var c=this._element.querySelectorAll("."+s.finalDivClass);c=c.length>=1?c[0]:null,a&&this._element.children[0]!==a&&(a.parentNode.removeChild(a),a=null),c&&this._element.children[this._element.children.length-1]!==c&&(c.parentNode.removeChild(c),c=null),a||(a=b.document.createElement("div"),a.style.display="inline",a.className=s.firstDivClass,a.tabIndex=-1,a.setAttribute("aria-hidden","true"),p._addEventListener(a,"focusin",this._focusOnLastFocusableElementOrThis.bind(this),!1),this._element.children[0]?this._element.insertBefore(a,this._element.children[0]):this._element.appendChild(a)),c||(c=b.document.createElement("div"),c.style.display="inline",c.className=s.finalDivClass,c.tabIndex=-1,c.setAttribute("aria-hidden","true"),p._addEventListener(c,"focusin",this._focusOnFirstFocusableElementOrThis.bind(this),!1),this._element.appendChild(c)),this._element.children[this._element.children.length-2]!==this._invokeButton&&this._element.insertBefore(this._invokeButton,c);var d=this._element.getElementsByTagName("*"),e=p._getHighestTabIndexInList(d);this._invokeButton.tabIndex=e,a&&(a.tabIndex=p._getLowestTabIndexInList(d)),c&&(c.tabIndex=e)},_writeProfilerMark:function(a){i("WinJS.UI._LegacyAppBar:"+this._id+":"+a)}},{_Events:q});return D})})}),d("WinJS/Controls/Menu",["exports","../Core/_Global","../Core/_Base","../Core/_BaseUtils","../Core/_ErrorFromName","../Core/_Resources","../Core/_WriteProfilerMark","../Promise","../Utilities/_ElementUtilities","../Utilities/_Hoverable","../Utilities/_KeyboardBehavior","./_LegacyAppBar/_Constants","./Flyout","./Flyout/_Overlay","./Menu/_Command"],function(a,b,c,d,e,f,g,h,i,j,k,l,m,n,o){"use strict";c.Namespace._moduleDefine(a,"WinJS.UI",{Menu:c.Namespace._lazy(function(){function a(a){var b=a.element||a;return i._matchesSelector(b,"."+l.menuClass+" ."+l.menuCommandClass)}var j=i.Key,p={get ariaLabel(){return f._getWinJSString("ui/menuAriaLabel").value},get requiresCommands(){return"Invalid argument: commands must not be empty"},get nullCommand(){return"Invalid argument: command must not be null"}},q=c.Class.derive(m.Flyout,function(a,c){c=c||{},this._element=a||b.document.createElement("div"),this._id=this._element.id||i._uniqueID(this._element),this._writeProfilerMark("constructor,StartTM"),!c.commands&&this._element&&(c=d._shallowCopy(c),c.commands=this._verifyCommandsOnly(this._element,"WinJS.UI.MenuCommand"));var e=this._element?this._element.getAttribute("role"):null,f=this._element?this._element.getAttribute("aria-label"):null;this._baseFlyoutConstructor(this._element,c),(null===e||""===e||void 0===e)&&this._element.setAttribute("role","menu"),(null===f||""===f||void 0===f)&&this._element.setAttribute("aria-label",p.ariaLabel),this._element.addEventListener("keydown",this._handleKeyDown.bind(this),!0),this._element.addEventListener(l._menuCommandInvokedEvent,this._handleCommandInvoked.bind(this),!1),this._element.addEventListener("mouseover",this._handleMouseOver.bind(this),!1),this._element.addEventListener("mouseout",this._handleMouseOut.bind(this),!1),i.addClass(this._element,l.menuClass),this._winKeyboard=new k._WinKeyboard(this._element),this.hide(),this._writeProfilerMark("constructor,StopTM")},{commands:{set:function(a){if(!this.hidden)throw new e("WinJS.UI.Menu.CannotChangeCommandsWhenVisible",f._formatString(n._Overlay.commonstrings.cannotChangeCommandsWhenVisible,"Menu"));i.empty(this._element),Array.isArray(a)||(a=[a]);for(var b=a.length,c=0;b>c;c++)this._addCommand(a[c])}},getCommandById:function(a){for(var b=this.element.querySelectorAll("#"+a),c=[],d=0,e=b.length;e>d;d++)b[d].winControl&&c.push(b[d].winControl);return 1===c.length?c[0]:0===c.length?null:c},showCommands:function(a){if(!a)throw new e("WinJS.UI.Menu.RequiresCommands",p.requiresCommands);this._showCommands(a,!0)},hideCommands:function(a){if(!a)throw new e("WinJS.UI.Menu.RequiresCommands",p.requiresCommands);this._hideCommands(a,!0)},showOnlyCommands:function(a){if(!a)throw new e("WinJS.UI.Menu.RequiresCommands",p.requiresCommands);this._showOnlyCommands(a,!0)},_hide:function(){this._hoverPromise&&this._hoverPromise.cancel(),m.Flyout.prototype._hide.call(this)},_afterHide:function(){i.removeClass(this.element,l.menuMouseSpacingClass),i.removeClass(this.element,l.menuTouchSpacingClass)},_beforeShow:function(){i.hasClass(this.element,l.menuMouseSpacingClass)||i.hasClass(this.element,l.menuTouchSpacingClass)||i.addClass(this.element,m.Flyout._cascadeManager.inputType===k._InputTypes.mouse||m.Flyout._cascadeManager.inputType===k._InputTypes.keyboard?l.menuMouseSpacingClass:l.menuTouchSpacingClass),this._checkMenuCommands()},_addCommand:function(a){if(!a)throw new e("WinJS.UI.Menu.NullCommand",p.nullCommand);a._element||(a=new o.MenuCommand(null,a)),a._element.parentElement&&a._element.parentElement.removeChild(a._element),this._element.appendChild(a._element)},_dispose:function(){this._hoverPromise&&this._hoverPromise.cancel(),m.Flyout.prototype._dispose.call(this)},_commandsUpdated:function(){this.hidden||this._checkMenuCommands()},_checkMenuCommands:function(){var a=this._element.querySelectorAll(".win-command"),b=!1,c=!1;if(a)for(var d=0,e=a.length;e>d;d++){var f=a[d].winControl;f&&!f.hidden&&(b||f.type!==l.typeToggle||(b=!0),c||f.type!==l.typeFlyout||(c=!0))}i[b?"addClass":"removeClass"](this._element,l.menuContainsToggleCommandClass),i[c?"addClass":"removeClass"](this._element,l.menuContainsFlyoutCommandClass)},_handleKeyDown:function(a){a.keyCode===j.upArrow?(q._focusOnPreviousElement(this.element),a.preventDefault()):a.keyCode===j.downArrow?(q._focusOnNextElement(this.element),a.preventDefault()):a.keyCode!==j.space&&a.keyCode!==j.enter||this.element!==b.document.activeElement?a.keyCode===j.tab&&a.preventDefault():(a.preventDefault(),this.hide())},_handleFocusIn:function(b){var c=b.target;if(a(c)){var d=c.winControl;if(i.hasClass(d.element,l.menuCommandFlyoutActivatedClass))d.flyout.element.focus();else{var e=this.element.querySelector("."+l.menuCommandFlyoutActivatedClass);e&&o.MenuCommand._deactivateFlyoutCommand(e)}}else c===this.element&&m.Flyout.prototype._handleFocusIn.call(this,b)},_handleCommandInvoked:function(a){this._hoverPromise&&this._hoverPromise.cancel();var b=a.detail.command;b._type!==l.typeFlyout&&b._type!==l.typeSeparator&&this._lightDismiss()},_hoverPromise:null,_handleMouseOver:function(b){var c=b.target;if(a(c)){var d=c.winControl,e=this;c.focus&&(c.focus(),i.removeClass(c,"win-keyboard"),d.type===l.typeFlyout&&d.flyout&&d.flyout.hidden&&(this._hoverPromise=this._hoverPromise||h.timeout(l.menuCommandHoverDelay).then(function(){e.hidden||e._disposed||d._invoke(b),e._hoverPromise=null},function(){e._hoverPromise=null})))}},_handleMouseOut:function(c){var d=c.target;a(d)&&!d.contains(c.relatedTarget)&&(d===b.document.activeElement&&this.element.focus(),this._hoverPromise&&this._hoverPromise.cancel())},_writeProfilerMark:function(a){g("WinJS.UI.Menu:"+this._id+":"+a)}});return q._focusOnNextElement=function(a){var c=b.document.activeElement;do c=c===a?c.firstElementChild:c.nextElementSibling,c?c.focus():c=a;while(c!==b.document.activeElement)},q._focusOnPreviousElement=function(a){var c=b.document.activeElement;do c=c===a?c.lastElementChild:c.previousElementSibling,c?c.focus():c=a;while(c!==b.document.activeElement)},q})})}),d("WinJS/Controls/AutoSuggestBox/_SearchSuggestionManagerShim",["exports","../../_Signal","../../Core/_Base","../../Core/_BaseUtils","../../Core/_Events","../../BindingList"],function(a,b,c,d,e){"use strict";var f={reset:0,itemInserted:1,itemRemoved:2,itemChanged:3},g={Query:0,Result:1,Separator:2},h=c.Class.derive(Array,function(){},{reset:function(){this.length=0,this.dispatchEvent("vectorchanged",{collectionChange:f.reset,index:0})},insert:function(a,b){this.splice(a,0,b),this.dispatchEvent("vectorchanged",{collectionChange:f.itemInserted,index:a})},remove:function(a){this.splice(a,1),this.dispatchEvent("vectorchanged",{collectionChange:f.itemRemoved,index:a})}});c.Class.mix(h,e.eventMixin);var i=c.Class.define(function(){this._data=[]},{size:{get:function(){return this._data.length}},appendQuerySuggestion:function(a){this._data.push({kind:g.Query,text:a})},appendQuerySuggestions:function(a){a.forEach(this.appendQuerySuggestion.bind(this))},appendResultSuggestion:function(a,b,c,d,e){this._data.push({kind:g.Result,text:a,detailText:b,tag:c,imageUrl:d,imageAlternateText:e,image:null})},appendSearchSeparator:function(a){this._data.push({kind:g.Separator,text:a})}}),j=c.Class.define(function(a,b,c){this._queryText=a,this._language=b,this._linguisticDetails=c,this._searchSuggestionCollection=new i},{language:{get:function(){return this._language}},linguisticDetails:{get:function(){return this._linguisticDetails}},queryText:{get:function(){return this._queryText}},searchSuggestionCollection:{get:function(){return this._searchSuggestionCollection}},getDeferral:function(){return this._deferralSignal||(this._deferralSignal=new b)},_deferralSignal:null}),k=c.Class.define(function(){this._updateVector=this._updateVector.bind(this),this._suggestionVector=new h,this._query="",this._history={"":[]},this._dataSource=[],this.searchHistoryContext="",this.searchHistoryEnabled=!0},{addToHistory:function(a){if(a&&a.trim()){for(var b=this._history[this.searchHistoryContext],c=-1,d=0,e=b.length;e>d;d++){var f=b[d];if(f.text.toLowerCase()===a.toLowerCase()){c=d;break}}c>=0&&b.splice(c,1),b.splice(0,0,{text:a,kind:g.Query}),this._updateVector()}},clearHistory:function(){this._history[this.searchHistoryContext]=[],this._updateVector()},setLocalContentSuggestionSettings:function(){},setQuery:function(a){function b(a){c._dataSource=a,c._updateVector()}var c=this;this._query=a;var d=new j(a);this.dispatchEvent("suggestionsrequested",{request:d}),d._deferralSignal?d._deferralSignal.promise.then(b.bind(this,d.searchSuggestionCollection._data)):b(d.searchSuggestionCollection._data)},searchHistoryContext:{get:function(){return""+this._searchHistoryContext},set:function(a){a=""+a,this._history[a]||(this._history[a]=[]),this._searchHistoryContext=a}},searchHistoryEnabled:{get:function(){return this._searchHistoryEnabled},set:function(a){this._searchHistoryEnabled=a}},suggestions:{get:function(){return this._suggestionVector}},_updateVector:function(){for(this.suggestions.insert(this.suggestions.length,{text:"",kind:g.Query});this.suggestions.length>1;)this.suggestions.remove(0);var a=0,b={};if(this.searchHistoryEnabled){var c=this._query.toLowerCase();this._history[this.searchHistoryContext].forEach(function(d){var e=d.text.toLowerCase();0===e.indexOf(c)&&(this.suggestions.insert(a,d),b[e]=!0,a++)},this)}this._dataSource.forEach(function(c){c.kind===g.Query?b[c.text.toLowerCase()]||(this.suggestions.insert(a,c),a++):(this.suggestions.insert(a,c),a++)},this),this.suggestions.remove(this.suggestions.length-1)}});c.Class.mix(k,e.eventMixin),c.Namespace._moduleDefine(a,null,{_CollectionChange:f,_SearchSuggestionKind:g,_SearchSuggestionManagerShim:k})}),d("require-style!less/styles-autosuggestbox",[],function(){}),d("require-style!less/colors-autosuggestbox",[],function(){}),d("WinJS/Controls/AutoSuggestBox",["exports","../Core/_Global","../Core/_WinRT","../Core/_Base","../Core/_ErrorFromName","../Core/_Events","../Core/_Resources","../Utilities/_Control","../Utilities/_ElementListUtilities","../Utilities/_ElementUtilities","../Utilities/_Hoverable","../_Accents","../Animations","../BindingList","../Promise","./Repeater","./AutoSuggestBox/_SearchSuggestionManagerShim","require-style!less/styles-autosuggestbox","require-style!less/colors-autosuggestbox"],function(a,b,c,d,e,f,g,h,i,j,k,l,m,n,o,p,q){"use strict";l.createAccentRule("html.win-hoverable .win-autosuggestbox .win-autosuggestbox-suggestion-selected:hover",[{name:"background-color",value:l.ColorTypes.listSelectHover}]),l.createAccentRule(".win-autosuggestbox .win-autosuggestbox-suggestion-selected",[{name:"background-color",value:l.ColorTypes.listSelectRest}]),l.createAccentRule(".win-autosuggestbox .win-autosuggestbox-suggestion-selected.win-autosuggestbox-suggestion-selected:hover:active",[{name:"background-color",value:l.ColorTypes.listSelectPress}]);var r={asb:"win-autosuggestbox",asbDisabled:"win-autosuggestbox-disabled",asbFlyout:"win-autosuggestbox-flyout",asbFlyoutAbove:"win-autosuggestbox-flyout-above",asbBoxFlyoutHighlightText:"win-autosuggestbox-flyout-highlighttext",asbHitHighlightSpan:"win-autosuggestbox-hithighlight-span",asbInput:"win-autosuggestbox-input",asbInputFocus:"win-autosuggestbox-input-focus",asbSuggestionQuery:"win-autosuggestbox-suggestion-query",asbSuggestionResult:"win-autosuggestbox-suggestion-result",asbSuggestionResultText:"win-autosuggestbox-suggestion-result-text",asbSuggestionResultDetailedText:"win-autosuggestbox-suggestion-result-detailed-text",asbSuggestionSelected:"win-autosuggestbox-suggestion-selected",asbSuggestionSeparator:"win-autosuggestbox-suggestion-separator"};d.Namespace._moduleDefine(a,"WinJS.UI",{AutoSuggestBox:d.Namespace._lazy(function(){function a(a,c,d,e){function f(a,c,d){var e=b.document.createElement("span");return e.textContent=c,e.setAttribute("aria-hidden","true"),e.classList.add(r.asbHitHighlightSpan),a.insertBefore(e,d),e}if(d){i.query("."+r.asbHitHighlightSpan,a).forEach(function(a){a.parentNode.removeChild(a)});var g=a.firstChild,h=c.hits;!h&&e&&c.kind!==q._SearchSuggestionKind.Separator&&(h=e.find(d));for(var k=x._sortAndMergeHits(h),l=0,m=0;m<k.length;m++){var n=k[m];f(a,d.substring(l,n.startPosition),g),l=n.startPosition+n.length;var o=f(a,d.substring(n.startPosition,l),g);j.addClass(o,r.asbBoxFlyoutHighlightText)}l<d.length&&f(a,d.substring(l),g)}}function k(a){var b={ctrlKey:1,altKey:2,shiftKey:4},c=0;return a.ctrlKey&&(c|=b.ctrlKey),a.altKey&&(c|=b.altKey),a.shiftKey&&(c|=b.shiftKey),c}function l(c,d){function e(a){c._internalFocusMove=!0,c._inputElement.focus(),c._processSuggestionChosen(d,a)}var f=b.document.createElement("div"),h=new b.Image;h.style.opacity=0;var i=function(a){function b(){h.removeEventListener("load",b,!1),m.fadeIn(h)}h.addEventListener("load",b,!1),h.src=a};null!==d.image?d.image.openReadAsync().then(function(a){null!==a&&i(b.URL.createObjectURL(a,{oneTimeOnly:!0}))}):null!==d.imageUrl&&i(d.imageUrl),h.setAttribute("aria-hidden","true"),f.appendChild(h);var k=b.document.createElement("div");j.addClass(k,r.asbSuggestionResultText),a(k,d,d.text),k.title=d.text,k.setAttribute("aria-hidden","true"),f.appendChild(k);var l=b.document.createElement("br");k.appendChild(l);var n=b.document.createElement("span");j.addClass(n,r.asbSuggestionResultDetailedText),a(n,d,d.detailText),n.title=d.detailText,n.setAttribute("aria-hidden","true"),k.appendChild(n),j.addClass(f,r.asbSuggestionResult),j._addEventListener(f,"click",function(a){c._isFlyoutPointerDown||e(a)}),j._addEventListener(f,"pointerup",e),f.setAttribute("role","option");var o=g._formatString(w.ariaLabelResult,d.text,d.detailText);return f.setAttribute("aria-label",o),f}function s(c,d){function e(a){c._internalFocusMove=!0,c._inputElement.focus(),c._processSuggestionChosen(d,a)}var f=b.document.createElement("div");a(f,d,d.text),f.title=d.text,f.classList.add(r.asbSuggestionQuery),j._addEventListener(f,"click",function(a){c._isFlyoutPointerDown||e(a)}),j._addEventListener(f,"pointerup",e);var h=g._formatString(w.ariaLabelQuery,d.text);return f.setAttribute("role","option"),f.setAttribute("aria-label",h),f}function t(a){var c=b.document.createElement("div");if(a.text.length>0){var d=b.document.createElement("div");d.textContent=a.text,d.title=a.text,d.setAttribute("aria-hidden","true"),c.appendChild(d)}c.insertAdjacentHTML("beforeend","<hr/>"),j.addClass(c,r.asbSuggestionSeparator),c.setAttribute("role","separator");var e=g._formatString(w.ariaLabelSeparator,a.text);return c.setAttribute("aria-label",e),c}var u=j.Key,v={querychanged:"querychanged",querysubmitted:"querysubmitted",resultsuggestionchosen:"resultsuggestionchosen",suggestionsrequested:"suggestionsrequested"},w={get duplicateConstruction(){return"Invalid argument: Controls may only be instantiated one time for each DOM element"},get invalidSuggestionKind(){return"Error: Invalid suggestion kind."},get ariaLabel(){return g._getWinJSString("ui/autoSuggestBoxAriaLabel").value},get ariaLabelInputNoPlaceHolder(){return g._getWinJSString("ui/autoSuggestBoxAriaLabelInputNoPlaceHolder").value},get ariaLabelInputPlaceHolder(){return g._getWinJSString("ui/autoSuggestBoxAriaLabelInputPlaceHolder").value},get ariaLabelQuery(){return g._getWinJSString("ui/autoSuggestBoxAriaLabelQuery").value},get ariaLabelResult(){return g._getWinJSString("ui/autoSuggestBoxAriaLabelResult").value},get ariaLabelSeparator(){return g._getWinJSString("ui/autoSuggestBoxAriaLabelSeparator").value}},x=d.Class.define(function(a,c){if(a=a||b.document.createElement("div"),c=c||{},a.winControl)throw new e("WinJS.UI.AutoSuggestBox.DuplicateConstruction",w.duplicateConstruction);this._suggestionsChangedHandler=this._suggestionsChangedHandler.bind(this),this._suggestionsRequestedHandler=this._suggestionsRequestedHandler.bind(this),this._element=a,a.winControl=this,a.classList.add(r.asb),a.classList.add("win-disposable"),this._setupDOM(),this._setupSSM(),this._chooseSuggestionOnEnter=!1,this._currentFocusedIndex=-1,this._currentSelectedIndex=-1,this._flyoutOpenPromise=o.wrap(),this._lastKeyPressLanguage="",this._prevLinguisticDetails=this._getLinguisticDetails(),this._prevQueryText="",h.setOptions(this,c),this._hideFlyout()},{onresultsuggestionchosen:f._createEventProperty(v.resultsuggestionchosen),onquerychanged:f._createEventProperty(v.querychanged),onquerysubmitted:f._createEventProperty(v.querysubmitted),onsuggestionsrequested:f._createEventProperty(v.suggestionsrequested),element:{get:function(){return this._element}},chooseSuggestionOnEnter:{get:function(){return this._chooseSuggestionOnEnter},set:function(a){this._chooseSuggestionOnEnter=!!a}},disabled:{get:function(){return this._inputElement.disabled},set:function(a){this._inputElement.disabled!==!!a&&(a?this._disableControl():this._enableControl())}},placeholderText:{get:function(){return this._inputElement.placeholder},set:function(a){this._inputElement.placeholder=a,this._updateInputElementAriaLabel()}},queryText:{get:function(){return this._inputElement.value},set:function(a){this._inputElement.value="",this._inputElement.value=a}},searchHistoryDisabled:{get:function(){return!this._suggestionManager.searchHistoryEnabled},set:function(a){this._suggestionManager.searchHistoryEnabled=!a}},searchHistoryContext:{get:function(){return this._suggestionManager.searchHistoryContext},set:function(a){this._suggestionManager.searchHistoryContext=a}},dispose:function(){this._disposed||(this._flyoutOpenPromise.cancel(),this._suggestions.removeEventListener("vectorchanged",this._suggestionsChangedHandler),this._suggestionManager.removeEventListener("suggestionsrequested",this._suggestionsRequestedHandler),this._suggestionManager=null,this._suggestions=null,this._hitFinder=null,this._disposed=!0) },setLocalContentSuggestionSettings:function(a){this._suggestionManager.setLocalContentSuggestionSettings(a)},_setupDOM:function(){function a(a){return f._renderSuggestion(a)}var c=this._flyoutPointerReleasedHandler.bind(this),d=this._inputOrImeChangeHandler.bind(this);this._element.getAttribute("aria-label")||this._element.setAttribute("aria-label",w.ariaLabel),this._element.setAttribute("role","group"),this._inputElement=b.document.createElement("input"),this._inputElement.autocorrect="off",this._inputElement.type="search",this._inputElement.classList.add(r.asbInput),this._inputElement.classList.add("win-textbox"),this._inputElement.setAttribute("role","textbox"),this._inputElement.addEventListener("keydown",this._keyDownHandler.bind(this)),this._inputElement.addEventListener("keypress",this._keyPressHandler.bind(this)),this._inputElement.addEventListener("keyup",this._keyUpHandler.bind(this)),this._inputElement.addEventListener("focus",this._inputFocusHandler.bind(this)),this._inputElement.addEventListener("blur",this._inputBlurHandler.bind(this)),this._inputElement.addEventListener("input",d),this._inputElement.addEventListener("compositionstart",d),this._inputElement.addEventListener("compositionupdate",d),this._inputElement.addEventListener("compositionend",d),j._addEventListener(this._inputElement,"pointerdown",this._inputPointerDownHandler.bind(this)),this._updateInputElementAriaLabel(),this._element.appendChild(this._inputElement);var e=this._tryGetInputContext();e&&(e.addEventListener("MSCandidateWindowShow",this._msCandidateWindowShowHandler.bind(this)),e.addEventListener("MSCandidateWindowHide",this._msCandidateWindowHideHandler.bind(this))),this._flyoutElement=b.document.createElement("div"),this._flyoutElement.classList.add(r.asbFlyout),this._flyoutElement.addEventListener("blur",this._flyoutBlurHandler.bind(this)),j._addEventListener(this._flyoutElement,"pointerup",c),j._addEventListener(this._flyoutElement,"pointercancel",c),j._addEventListener(this._flyoutElement,"pointerout",c),j._addEventListener(this._flyoutElement,"pointerdown",this._flyoutPointerDownHandler.bind(this)),this._element.appendChild(this._flyoutElement);var f=this;this._suggestionsData=new n.List,this._repeaterElement=b.document.createElement("div"),this._repeater=new p.Repeater(this._repeaterElement,{data:this._suggestionsData,template:a}),j._ensureId(this._repeaterElement),this._repeaterElement.setAttribute("role","listbox"),this._repeaterElement.setAttribute("aria-live","polite"),this._flyoutElement.appendChild(this._repeaterElement)},_setupSSM:function(){this._suggestionManager=new q._SearchSuggestionManagerShim,this._suggestions=this._suggestionManager.suggestions,this._suggestions.addEventListener("vectorchanged",this._suggestionsChangedHandler),this._suggestionManager.addEventListener("suggestionsrequested",this._suggestionsRequestedHandler)},_hideFlyout:function(){this._isFlyoutShown()&&(this._flyoutElement.style.display="none")},_showFlyout:function(){var a=this._prevNumSuggestions||0;if(this._prevNumSuggestions=this._suggestionsData.length,(!this._isFlyoutShown()||a!==this._suggestionsData.length)&&0!==this._suggestionsData.length){this._flyoutElement.style.display="block";var c=this._inputElement.getBoundingClientRect(),d=this._flyoutElement.getBoundingClientRect(),e=b.document.documentElement.clientWidth,f=c.top,g=b.document.documentElement.clientHeight-c.bottom;this._flyoutBelowInput=g>=f,this._flyoutBelowInput?(this._flyoutElement.classList.remove(r.asbFlyoutAbove),this._flyoutElement.scrollTop=0):(this._flyoutElement.classList.add(r.asbFlyoutAbove),this._flyoutElement.scrollTop=this._flyoutElement.scrollHeight-this._flyoutElement.clientHeight),this._addFlyoutIMEPaddingIfRequired();var h;h="rtl"===j._getComputedStyle(this._flyoutElement).direction?c.right-d.width>=0||c.left+d.width>e:c.left+d.width>e&&c.right-d.width>=0,this._flyoutElement.style.left=h?c.width-d.width-this._element.clientLeft+"px":"-"+this._element.clientLeft+"px",this._flyoutElement.style.touchAction=this._flyoutElement.scrollHeight>d.height?"pan-y":"none",this._flyoutOpenPromise.cancel();var i=this._flyoutBelowInput?"WinJS-flyoutBelowASB-showPopup":"WinJS-flyoutAboveASB-showPopup";this._flyoutOpenPromise=m.showPopup(this._flyoutElement,{top:"0px",left:"0px",keyframe:i})}},_addFlyoutIMEPaddingIfRequired:function(){var a=this._tryGetInputContext();if(a&&this._isFlyoutShown()&&this._flyoutBelowInput){var b=this._flyoutElement.getBoundingClientRect(),c=a.getCandidateWindowClientRect(),d=this._inputElement.getBoundingClientRect(),e=d.bottom,f=d.bottom+b.height;if(!(c.top>f||c.bottom<e)){var g=m.createRepositionAnimation(this._flyoutElement);c.width<.45*d.width?this._flyoutElement.style.marginLeft=c.width+"px":this._flyoutElement.style.marginTop=c.bottom-c.top+4+"px",g.execute()}}},_findNextSuggestionElementIndex:function(a){for(var b=0>a?0:a+1,c=b;c<this._suggestionsData.length;c++)if(this._repeater.elementFromIndex(c)&&this._isSuggestionSelectable(this._suggestionsData.getAt(c)))return c;return-1},_findPreviousSuggestionElementIndex:function(a){for(var b=a>=this._suggestionsData.length?this._suggestionsData.length-1:a-1,c=b;c>=0;c--)if(this._repeater.elementFromIndex(c)&&this._isSuggestionSelectable(this._suggestionsData.getAt(c)))return c;return-1},_isFlyoutShown:function(){return"none"!==this._flyoutElement.style.display},_isSuggestionSelectable:function(a){return a.kind===q._SearchSuggestionKind.Query||a.kind===q._SearchSuggestionKind.Result},_processSuggestionChosen:function(a,b){this.queryText=a.text,a.kind===q._SearchSuggestionKind.Query?this._submitQuery(a.text,!1,b):a.kind===q._SearchSuggestionKind.Result&&this._fireEvent(v.resultsuggestionchosen,{tag:a.tag,keyModifiers:k(b),storageFile:null}),this._hideFlyout()},_selectSuggestionAtIndex:function(a){function b(a){var b=c._flyoutElement.getBoundingClientRect().bottom-c._flyoutElement.getBoundingClientRect().top;if(a.offsetTop+a.offsetHeight>c._flyoutElement.scrollTop+b){var d=a.offsetTop+a.offsetHeight-(c._flyoutElement.scrollTop+b);j._zoomTo(c._flyoutElement,{contentX:0,contentY:c._flyoutElement.scrollTop+d,viewportX:0,viewportY:0})}else a.offsetTop<c._flyoutElement.scrollTop&&j._zoomTo(c._flyoutElement,{contentX:0,contentY:a.offsetTop,viewportX:0,viewportY:0})}for(var c=this,d=null,e=0;e<this._suggestionsData.length;e++)d=this._repeater.elementFromIndex(e),e!==a?(d.classList.remove(r.asbSuggestionSelected),d.setAttribute("aria-selected","false")):(d.classList.add(r.asbSuggestionSelected),b(d),d.setAttribute("aria-selected","true"));this._currentSelectedIndex=a,d?this._inputElement.setAttribute("aria-activedescendant",this._repeaterElement.id+a):this._inputElement.hasAttribute("aria-activedescendant")&&this._inputElement.removeAttribute("aria-activedescendant")},_updateFakeFocus:function(){var a;a=this._isFlyoutShown()&&this._chooseSuggestionOnEnter?this._findNextSuggestionElementIndex(-1):-1,this._selectSuggestionAtIndex(a)},_updateQueryTextWithSuggestionText:function(a){a>=0&&a<this._suggestionsData.length&&(this.queryText=this._suggestionsData.getAt(a).text)},_disableControl:function(){this._isFlyoutShown()&&this._hideFlyout(),this._element.disabled=!0,this._element.classList.add(r.asbDisabled),this._inputElement.disabled=!0},_enableControl:function(){this._element.disabled=!1,this._element.classList.remove(r.asbDisabled),this._inputElement.disabled=!1,b.document.activeElement===this._element&&j._setActive(this._inputElement)},_fireEvent:function(a,c){var d=b.document.createEvent("CustomEvent");return d.initCustomEvent(a,!0,!0,c),this._element.dispatchEvent(d)},_getLinguisticDetails:function(a,b){function d(a,b,d,e,f){for(var g=null,h=[],i=0;i<a.length;i++)h[i]=e+a[i]+f;if(c.Windows.ApplicationModel.Search.SearchQueryLinguisticDetails)try{g=new c.Windows.ApplicationModel.Search.SearchQueryLinguisticDetails(h,b,d)}catch(j){}return g||(g={queryTextAlternatives:h,queryTextCompositionStart:b,queryTextCompositionLength:d}),g}var e=null;if(this._inputElement.value===this._prevQueryText&&a&&this._prevLinguisticDetails&&b)e=this._prevLinguisticDetails;else{var f=[],g=0,h=0,i="",j="";if(b){var k=this._tryGetInputContext();k&&k.getCompositionAlternatives&&(f=k.getCompositionAlternatives(),g=k.compositionStartOffset,h=k.compositionEndOffset-k.compositionStartOffset,this._inputElement.value!==this._prevQueryText||0===this._prevCompositionLength||h>0?(i=this._inputElement.value.substring(0,g),j=this._inputElement.value.substring(g+h)):(i=this._inputElement.value.substring(0,this._prevCompositionStart),j=this._inputElement.value.substring(this._prevCompositionStart+this._prevCompositionLength)))}e=d(f,g,h,i,j)}return e},_isElementInSearchControl:function(a){return this.element.contains(a)||this.element===a},_renderSuggestion:function(a){var b=null;if(!a)return b;if(a.kind===q._SearchSuggestionKind.Query)b=s(this,a);else if(a.kind===q._SearchSuggestionKind.Separator)b=t(a);else{if(a.kind!==q._SearchSuggestionKind.Result)throw new e("WinJS.UI.AutoSuggestBox.invalidSuggestionKind",w.invalidSuggestionKind);b=l(this,a)}return b},_shouldIgnoreInput:function(){var a=this._isProcessingDownKey||this._isProcessingUpKey||this._isProcessingTabKey||this._isProcessingEnterKey;return a||this._isFlyoutPointerDown},_submitQuery:function(a,b,d){this._disposed||(c.Windows.Globalization.Language&&(this._lastKeyPressLanguage=c.Windows.Globalization.Language.currentInputMethodLanguageTag),this._fireEvent(v.querysubmitted,{language:this._lastKeyPressLanguage,linguisticDetails:this._getLinguisticDetails(!0,b),queryText:a,keyModifiers:k(d)}),this._suggestionManager&&this._suggestionManager.addToHistory(this._inputElement.value,this._lastKeyPressLanguage))},_tryGetInputContext:function(){if(this._inputElement.msGetInputContext)try{return this._inputElement.msGetInputContext()}catch(a){return null}return null},_updateInputElementAriaLabel:function(){this._inputElement.setAttribute("aria-label",this._inputElement.placeholder?g._formatString(w.ariaLabelInputPlaceHolder,this._inputElement.placeholder):w.ariaLabelInputNoPlaceHolder)},_flyoutBlurHandler:function(){this._isElementInSearchControl(b.document.activeElement)?this._internalFocusMove=!0:(this._element.classList.remove(r.asbInputFocus),this._hideFlyout())},_flyoutPointerDownHandler:function(a){function b(){if(d)for(var a=0;a<c._suggestionsData.length;a++)if(c._repeater.elementFromIndex(a)===d)return a;return-1}var c=this,d=a.target;for(this._isFlyoutPointerDown=!0;d&&d.parentNode!==this._repeaterElement;)d=d.parentNode;var e=b();e>=0&&e<this._suggestionsData.length&&this._currentFocusedIndex!==e&&this._isSuggestionSelectable(this._suggestionsData.getAt(e))&&(this._currentFocusedIndex=e,this._selectSuggestionAtIndex(e),this._updateQueryTextWithSuggestionText(this._currentFocusedIndex)),a.preventDefault()},_flyoutPointerReleasedHandler:function(){if(this._isFlyoutPointerDown=!1,this._reflowImeOnPointerRelease){this._reflowImeOnPointerRelease=!1;var a=m.createRepositionAnimation(this._flyoutElement);this._flyoutElement.style.marginTop="",this._flyoutElement.style.marginLeft="",a.execute()}},_inputBlurHandler:function(){this._isElementInSearchControl(b.document.activeElement)||(this._element.classList.remove(r.asbInputFocus),this._hideFlyout()),this.queryText=this._prevQueryText,this._isProcessingDownKey=!1,this._isProcessingUpKey=!1,this._isProcessingTabKey=!1,this._isProcessingEnterKey=!1},_inputFocusHandler:function(a){this._inputElement.value!==this._prevQueryText&&c.Windows.Data.Text.SemanticTextQuery&&(this._hitFinder=""!==this._inputElement.value?new c.Windows.Data.Text.SemanticTextQuery(this._inputElement.value,this._inputElement.lang):null),a.target!==this._inputElement||this._internalFocusMove||(this._showFlyout(),-1!==this._currentFocusedIndex?this._selectSuggestionAtIndex(this._currentFocusedIndex):this._updateFakeFocus(),this._suggestionManager.setQuery(this._inputElement.value,this._lastKeyPressLanguage,this._getLinguisticDetails(!0,!0))),this._internalFocusMove=!1,this._element.classList.add(r.asbInputFocus)},_inputOrImeChangeHandler:function(){function a(a){var c=!1;return(b._prevLinguisticDetails.queryTextCompositionStart!==a.queryTextCompositionStart||b._prevLinguisticDetails.queryTextCompositionLength!==a.queryTextCompositionLength||b._prevLinguisticDetails.queryTextAlternatives.length!==a.queryTextAlternatives.length)&&(c=!0),b._prevLinguisticDetails=a,c}var b=this;if(!this._shouldIgnoreInput()){var d=this._getLinguisticDetails(!1,!0),a=a(d);if((this._inputElement.value!==this._prevQueryText||0===this._prevCompositionLength||d.queryTextCompositionLength>0)&&(this._prevCompositionStart=d.queryTextCompositionStart,this._prevCompositionLength=d.queryTextCompositionLength),this._prevQueryText===this._inputElement.value&&!a)return;this._prevQueryText=this._inputElement.value,c.Windows.Globalization.Language&&(this._lastKeyPressLanguage=c.Windows.Globalization.Language.currentInputMethodLanguageTag),c.Windows.Data.Text.SemanticTextQuery&&(this._hitFinder=""!==this._inputElement.value?new c.Windows.Data.Text.SemanticTextQuery(this._inputElement.value,this._lastKeyPressLanguage):null),this._fireEvent(v.querychanged,{language:this._lastKeyPressLanguage,queryText:this._inputElement.value,linguisticDetails:d}),this._suggestionManager.setQuery(this._inputElement.value,this._lastKeyPressLanguage,d)}},_inputPointerDownHandler:function(){b.document.activeElement===this._inputElement&&-1!==this._currentSelectedIndex&&(this._currentFocusedIndex=-1,this._selectSuggestionAtIndex(this._currentFocusedIndex))},_keyDownHandler:function(a){function b(b){c._currentFocusedIndex=b,c._selectSuggestionAtIndex(b),a.preventDefault(),a.stopPropagation()}var c=this;if(this._lastKeyPressLanguage=a.locale,a.keyCode===u.tab?this._isProcessingTabKey=!0:a.keyCode===u.upArrow?this._isProcessingUpKey=!0:a.keyCode===u.downArrow?this._isProcessingDownKey=!0:a.keyCode===u.enter&&"ko"===a.locale&&(this._isProcessingEnterKey=!0),a.keyCode!==u.IME)if(a.keyCode===u.tab){var d=!0;a.shiftKey?-1!==this._currentFocusedIndex&&(b(-1),d=!1):-1===this._currentFocusedIndex&&(this._currentFocusedIndex=this._flyoutBelowInput?this._findNextSuggestionElementIndex(this._currentFocusedIndex):this._findPreviousSuggestionElementIndex(this._suggestionsData.length),-1!==this._currentFocusedIndex&&(b(this._currentFocusedIndex),this._updateQueryTextWithSuggestionText(this._currentFocusedIndex),d=!1)),d&&this._hideFlyout()}else if(a.keyCode===u.escape)-1!==this._currentFocusedIndex?(this.queryText=this._prevQueryText,b(-1)):""!==this.queryText&&(this.queryText="",this._inputOrImeChangeHandler(null),a.preventDefault(),a.stopPropagation());else if(this._flyoutBelowInput&&a.keyCode===u.upArrow||!this._flyoutBelowInput&&a.keyCode===u.downArrow){var e;-1!==this._currentSelectedIndex?(e=this._findPreviousSuggestionElementIndex(this._currentSelectedIndex),-1===e&&(this.queryText=this._prevQueryText)):e=this._findPreviousSuggestionElementIndex(this._suggestionsData.length),b(e),this._updateQueryTextWithSuggestionText(this._currentFocusedIndex)}else if(this._flyoutBelowInput&&a.keyCode===u.downArrow||!this._flyoutBelowInput&&a.keyCode===u.upArrow){var f=this._findNextSuggestionElementIndex(this._currentSelectedIndex);-1!==this._currentSelectedIndex&&-1===f&&(this.queryText=this._prevQueryText),b(f),this._updateQueryTextWithSuggestionText(this._currentFocusedIndex)}else a.keyCode===u.enter&&(-1===this._currentSelectedIndex?this._submitQuery(this._inputElement.value,!0,a):this._processSuggestionChosen(this._suggestionsData.getAt(this._currentSelectedIndex),a),this._hideFlyout())},_keyUpHandler:function(a){a.keyCode===u.tab?this._isProcessingTabKey=!1:a.keyCode===u.upArrow?this._isProcessingUpKey=!1:a.keyCode===u.downArrow?this._isProcessingDownKey=!1:a.keyCode===u.enter&&(this._isProcessingEnterKey=!1)},_keyPressHandler:function(a){this._lastKeyPressLanguage=a.locale},_msCandidateWindowHideHandler:function(){if(this._isFlyoutPointerDown)this._reflowImeOnPointerRelease=!0;else{var a=m.createRepositionAnimation(this._flyoutElement);this._flyoutElement.style.marginTop="",this._flyoutElement.style.marginLeft="",a.execute()}},_msCandidateWindowShowHandler:function(){this._addFlyoutIMEPaddingIfRequired(),this._reflowImeOnPointerRelease=!1},_suggestionsChangedHandler:function(c){var d=c.collectionChange||c.detail.collectionChange,e=+c.index===c.index?c.index:c.detail.index,f=q._CollectionChange;if(d===f.reset)this._isFlyoutShown()&&this._hideFlyout(),this._suggestionsData.splice(0,this._suggestionsData.length);else if(d===f.itemInserted){var g=this._suggestions[e];this._suggestionsData.splice(e,0,g),this._showFlyout()}else if(d===f.itemRemoved)1===this._suggestionsData.length&&(j._setActive(this._inputElement),this._hideFlyout()),this._suggestionsData.splice(e,1);else if(d===f.itemChanged){var g=this._suggestions[e];if(g!==this._suggestionsData.getAt(e))this._suggestionsData.setAt(e,g);else{var h=this._repeater.elementFromIndex(e);if(j.hasClass(h,r.asbSuggestionQuery))a(h,g,g.text);else{var i=h.querySelector("."+r.asbSuggestionResultText);if(i){a(i,g,g.text);var k=h.querySelector("."+r.asbSuggestionResultDetailedText);k&&a(k,g,g.detailText)}}}}b.document.activeElement===this._inputElement&&this._updateFakeFocus()},_suggestionsRequestedHandler:function(a){c.Windows.Globalization.Language&&(this._lastKeyPressLanguage=c.Windows.Globalization.Language.currentInputMethodLanguageTag);var b,d=a.request||a.detail.request;this._fireEvent(v.suggestionsrequested,{setPromise:function(a){b=d.getDeferral(),a.then(function(){b.complete()})},searchSuggestionCollection:d.searchSuggestionCollection,language:this._lastKeyPressLanguage,linguisticDetails:this._getLinguisticDetails(!0,!0),queryText:this._inputElement.value})}},{createResultSuggestionImage:function(a){return c.Windows.Foundation.Uri&&c.Windows.Storage.Streams.RandomAccessStreamReference?c.Windows.Storage.Streams.RandomAccessStreamReference.createFromUri(new c.Windows.Foundation.Uri(a)):a},_EventNames:v,_sortAndMergeHits:function(a){function b(a,b){var c=0;return a.startPosition<b.startPosition?c=-1:a.startPosition>b.startPosition&&(c=1),c}function c(a,b,c){if(0===c)a.push(b);else{var d=a[a.length-1],e=d.startPosition+d.length;if(b.startPosition<=e){var f=b.startPosition+b.length;f>e&&(d.length=f-d.startPosition)}else a.push(b)}return a}var d=[];if(a){for(var e=new Array(a.length),f=0;f<a.length;f++)e.push({startPosition:a[f].startPosition,length:a[f].length});e.sort(b),e.reduce(c,d)}return d}});return d.Class.mix(x,h.DOMEventMixin),x})}),a.ClassNames=r}),d("require-style!less/styles-searchbox",[],function(){}),d("require-style!less/colors-searchbox",[],function(){}),d("WinJS/Controls/SearchBox",["../Core/_Global","../Core/_WinRT","../Core/_Base","../Core/_ErrorFromName","../Core/_Events","../Core/_Resources","./AutoSuggestBox","../_Accents","../Utilities/_Control","../Utilities/_ElementUtilities","./AutoSuggestBox/_SearchSuggestionManagerShim","../Application","require-style!less/styles-searchbox","require-style!less/colors-searchbox"],function(a,b,c,d,e,f,g,h,i,j,k,l){"use strict";h.createAccentRule("html.win-hoverable .win-searchbox-button:not(.win-searchbox-button-disabled):hover",[{name:"color",value:h.ColorTypes.accent}]),h.createAccentRule(".win-searchbox-button.win-searchbox-button:not(.win-searchbox-button-disabled):hover:active",[{name:"background-color",value:h.ColorTypes.accent}]),c.Namespace.define("WinJS.UI",{SearchBox:c.Namespace._lazy(function(){var d={searchBox:"win-searchbox",searchBoxDisabled:"win-searchbox-disabled",searchBoxInput:"win-searchbox-input",searchBoxInputFocus:"win-searchbox-input-focus",searchBoxButton:"win-searchbox-button",searchBoxFlyout:"win-searchbox-flyout",searchBoxFlyoutHighlightText:"win-searchbox-flyout-highlighttext",searchBoxHitHighlightSpan:"win-searchbox-hithighlight-span",searchBoxSuggestionResult:"win-searchbox-suggestion-result",searchBoxSuggestionResultText:"win-searchbox-suggestion-result-text",searchBoxSuggestionResultDetailedText:"win-searchbox-suggestion-result-detailed-text",searchBoxSuggestionSelected:"win-searchbox-suggestion-selected",searchBoxSuggestionQuery:"win-searchbox-suggestion-query",searchBoxSuggestionSeparator:"win-searchbox-suggestion-separator",searchBoxButtonInputFocus:"win-searchbox-button-input-focus",searchBoxButtonDisabled:"win-searchbox-button-disabled"},e={receivingfocusonkeyboardinput:"receivingfocusonkeyboardinput"},h={get invalidSearchBoxSuggestionKind(){return"Error: Invalid search suggestion kind."},get ariaLabel(){return f._getWinJSString("ui/searchBoxAriaLabel").value},get ariaLabelInputNoPlaceHolder(){return f._getWinJSString("ui/searchBoxAriaLabelInputNoPlaceHolder").value},get ariaLabelInputPlaceHolder(){return f._getWinJSString("ui/searchBoxAriaLabelInputPlaceHolder").value},get searchBoxDeprecated(){return"SearchBox is deprecated and may not be available in future releases. Instead use AutoSuggestBox."}},m=c.Class.derive(g.AutoSuggestBox,function(b,c){j._deprecated(h.searchBoxDeprecated),this._requestingFocusOnKeyboardInputHandlerBind=this._requestingFocusOnKeyboardInputHandler.bind(this),this._buttonElement=a.document.createElement("div"),this._focusOnKeyboardInput=!1,g.AutoSuggestBox.call(this,b,c),this.element.classList.add(d.searchBox),this._flyoutElement.classList.add(d.searchBoxFlyout),this._inputElement.classList.add(d.searchBoxInput),this._inputElement.addEventListener("blur",this._searchboxInputBlurHandler.bind(this)),this._inputElement.addEventListener("focus",this._searchboxInputFocusHandler.bind(this)),this._buttonElement.tabIndex=-1,this._buttonElement.classList.add(d.searchBoxButton),this._buttonElement.addEventListener("click",this._buttonClickHandler.bind(this)),j._addEventListener(this._buttonElement,"pointerdown",this._buttonPointerDownHandler.bind(this)),this.element.appendChild(this._buttonElement)},{focusOnKeyboardInput:{get:function(){return this._focusOnKeyboardInput},set:function(a){this._focusOnKeyboardInput&&!a?l._applicationListener.removeEventListener(this.element,"requestingfocusonkeyboardinput",this._requestingFocusOnKeyboardInputHandlerBind):!this._focusOnKeyboardInput&&a&&l._applicationListener.addEventListener(this.element,"requestingfocusonkeyboardinput",this._requestingFocusOnKeyboardInputHandlerBind),this._focusOnKeyboardInput=!!a}},dispose:function(){this._disposed||(g.AutoSuggestBox.prototype.dispose.call(this),this._focusOnKeyboardInput&&l._applicationListener.removeEventListener(this.element,"requestingfocusonkeyboardinput",this._requestingFocusOnKeyboardInputHandlerBind))},_disableControl:function(){g.AutoSuggestBox.prototype._disableControl.call(this),this._buttonElement.disabled=!0,this._buttonElement.classList.add(d.searchBoxButtonDisabled),this.element.classList.add(d.searchBoxDisabled)},_enableControl:function(){g.AutoSuggestBox.prototype._enableControl.call(this),this._buttonElement.disabled=!1,this._buttonElement.classList.remove(d.searchBoxButtonDisabled),this.element.classList.remove(d.searchBoxDisabled)},_renderSuggestion:function(a){var b=g.AutoSuggestBox.prototype._renderSuggestion.call(this,a);if(a.kind===k._SearchSuggestionKind.Query)b.classList.add(d.searchBoxSuggestionQuery);else if(a.kind===k._SearchSuggestionKind.Separator)b.classList.add(d.searchBoxSuggestionSeparator);else{b.classList.add(d.searchBoxSuggestionResult);var c=b.querySelector("."+g.ClassNames.asbSuggestionResultText);c.classList.add(d.searchBoxSuggestionResultText);var e=b.querySelector("."+g.ClassNames.asbSuggestionResultDetailedText);e.classList.add(d.searchBoxSuggestionResultDetailedText);for(var f=b.querySelectorAll("."+g.ClassNames.asbHitHighlightSpan),h=0,i=f.length;i>h;h++)f[h].classList.add(d.searchBoxHitHighlightSpan);for(var j=b.querySelectorAll("."+g.ClassNames.asbBoxFlyoutHighlightText),h=0,i=j.length;i>h;h++)j[h].classList.add(d.searchBoxFlyoutHighlightText)}return b},_selectSuggestionAtIndex:function(a){g.AutoSuggestBox.prototype._selectSuggestionAtIndex.call(this,a);var b=this.element.querySelector("."+d.searchBoxSuggestionSelected);b&&b.classList.remove(d.searchBoxSuggestionSelected);var c=this.element.querySelector("."+g.ClassNames.asbSuggestionSelected);c&&c.classList.add(d.searchBoxSuggestionSelected)},_shouldIgnoreInput:function(){var a=g.AutoSuggestBox.prototype._shouldIgnoreInput(),b=j._matchesSelector(this._buttonElement,":active");return a||b},_updateInputElementAriaLabel:function(){this._inputElement.setAttribute("aria-label",this._inputElement.placeholder?f._formatString(h.ariaLabelInputPlaceHolder,this._inputElement.placeholder):h.ariaLabelInputNoPlaceHolder)},_buttonPointerDownHandler:function(a){this._inputElement.focus(),a.preventDefault()},_buttonClickHandler:function(a){this._inputElement.focus(),this._submitQuery(this._inputElement.value,!0,a),this._hideFlyout()},_searchboxInputBlurHandler:function(){j.removeClass(this.element,d.searchBoxInputFocus),j.removeClass(this._buttonElement,d.searchBoxButtonInputFocus)},_searchboxInputFocusHandler:function(){j.addClass(this.element,d.searchBoxInputFocus),j.addClass(this._buttonElement,d.searchBoxButtonInputFocus)},_requestingFocusOnKeyboardInputHandler:function(){if(this._fireEvent(e.receivingfocusonkeyboardinput,null),a.document.activeElement!==this._inputElement)try{this._inputElement.focus()}catch(b){}}},{createResultSuggestionImage:function(a){return j._deprecated(h.searchBoxDeprecated),b.Windows.Foundation.Uri&&b.Windows.Storage.Streams.RandomAccessStreamReference?b.Windows.Storage.Streams.RandomAccessStreamReference.createFromUri(new b.Windows.Foundation.Uri(a)):a},_getKeyModifiers:function(a){var b={ctrlKey:1,altKey:2,shiftKey:4},c=0;return a.ctrlKey&&(c|=b.ctrlKey),a.altKey&&(c|=b.altKey),a.shiftKey&&(c|=b.shiftKey),c},_isTypeToSearchKey:function(a){return a.shiftKey||a.ctrlKey||a.altKey?!1:!0}});return c.Class.mix(m,i.DOMEventMixin),m})})}),d("WinJS/Controls/SettingsFlyout",["../Core/_Global","../Core/_WinRT","../Core/_Base","../Core/_BaseUtils","../Core/_ErrorFromName","../Core/_Events","../Core/_Resources","../Core/_WriteProfilerMark","../Animations","../Pages","../Promise","../_LightDismissService","../Utilities/_Dispose","../Utilities/_ElementUtilities","../Utilities/_ElementListUtilities","../Utilities/_Hoverable","./_LegacyAppBar/_Constants","./Flyout/_Overlay"],function(a,b,c,d,e,f,g,h,i,j,k,l,m,n,o,p,q,r){"use strict";c.Namespace.define("WinJS.UI",{SettingsFlyout:c.Namespace._lazy(function(){function d(){if(b.Windows.UI.ApplicationSettings.SettingsEdgeLocation){var a=b.Windows.UI.ApplicationSettings;return a.SettingsPane.edge===a.SettingsEdgeLocation.left}return!1}function p(a,b){for(var c,d,e=a.querySelectorAll("."+q.settingsFlyoutClass),f=0;f<e.length;f++)if(d=e[f].winControl){if(d.settingsCommandId===b){c=d;break}e[f].id===b&&(c=c||d)}return c}var s,t=n.Key,u=f._createEventProperty,v="narrow",w="wide",x=c.Class.derive(r._Overlay,function(b,c){n._deprecated(z.settingsFlyoutIsDeprecated),this._element=b||a.document.createElement("div"),this._id=this._element.id||n._uniqueID(this._element),this._writeProfilerMark("constructor,StartTM"),this._baseOverlayConstructor(this._element,c),this._addFirstDiv(),this._addFinalDiv(),this._element.addEventListener("keydown",this._handleKeyDown,!0),this._element.style.visibilty="hidden",this._element.style.display="none",n.addClass(this._element,q.settingsFlyoutClass);var d=this;this._dismissable=new l.LightDismissableElement({element:this._element,tabIndex:this._element.hasAttribute("tabIndex")?this._element.tabIndex:-1,onLightDismiss:function(){d.hide()},onTakeFocus:function(a){if(!d._dismissable.restoreFocus()){var b=d.element.querySelector("."+q.firstDivClass);b&&(b.msSettingsFlyoutFocusOut||(n._addEventListener(b,"focusout",function(){s=1},!1),b.msSettingsFlyoutFocusOut=!0),s=0,n._tryFocus(b,a))}}}),o.query("div.win-content",this._element).forEach(function(a){n._matchesSelector(a,".win-ui-dark, .win-ui-dark *")||n.addClass(a,q.flyoutLightClass)});var e=this._element.getAttribute("role");(null===e||""===e||void 0===e)&&this._element.setAttribute("role","dialog");var f=this._element.getAttribute("aria-label");(null===f||""===f||void 0===f)&&this._element.setAttribute("aria-label",z.ariaLabel),this._currentAnimateIn=this._animateSlideIn,this._currentAnimateOut=this._animateSlideOut,this._writeProfilerMark("constructor,StopTM")},{width:{get:function(){return this._width},set:function(a){n._deprecated(z.widthDeprecationMessage),a!==this._width&&(this._width===v?n.removeClass(this._element,q.narrowClass):this._width===w&&n.removeClass(this._element,q.wideClass),this._width=a,this._width===v?n.addClass(this._element,q.narrowClass):this._width===w&&n.addClass(this._element,q.wideClass))}},settingsCommandId:{get:function(){return this._settingsCommandId},set:function(a){this._settingsCommandId=a}},disabled:{get:function(){return!!this._element.disabled},set:function(a){a=!!a;var b=!!this._element.disabled;b!==a&&(this._element.disabled=a,!this.hidden&&this._element.disabled&&this._dismiss())}},onbeforeshow:u(r._Overlay.beforeShow),onaftershow:u(r._Overlay.afterShow),onbeforehide:u(r._Overlay.beforeHide),onafterhide:u(r._Overlay.afterHide),show:function(){this.disabled||(this._writeProfilerMark("show,StartTM"),this._show())},_dispose:function(){l.hidden(this._dismissable),m.disposeSubTree(this.element),this._dismiss()},_show:function(){if(this._baseShow()){if(!n.hasClass(this.element.children[0],q.firstDivClass)){var a=this.element.querySelectorAll("."+q.firstDivClass);a&&a.length>0&&a.item(0).parentNode.removeChild(a.item(0)),this._addFirstDiv()}if(!n.hasClass(this.element.children[this.element.children.length-1],q.finalDivClass)){var b=this.element.querySelectorAll("."+q.finalDivClass);b&&b.length>0&&b.item(0).parentNode.removeChild(b.item(0)),this._addFinalDiv()}this._setBackButtonsAriaLabel(),l.shown(this._dismissable)}},_setBackButtonsAriaLabel:function(){for(var a,b=this.element.querySelectorAll(".win-backbutton"),c=0;c<b.length;c++)a=b[c].getAttribute("aria-label"),(null===a||""===a||void 0===a)&&b[c].setAttribute("aria-label",z.backbuttonAriaLabel)},hide:function(){this._writeProfilerMark("hide,StartTM"),this._hide()},_hide:function(){this._baseHide()},_beforeEndHide:function(){l.hidden(this._dismissable)},_animateSlideIn:function(){var a=d(),b=a?"-100px":"100px";o.query("div.win-content",this._element).forEach(function(a){i.enterPage(a,{left:b})});var c,e=this._element.offsetWidth;return a?(c={top:"0px",left:"-"+e+"px"},this._element.style.right="auto",this._element.style.left="0px"):(c={top:"0px",left:e+"px"},this._element.style.right="0px",this._element.style.left="auto"),this._element.style.opacity=1,this._element.style.visibility="visible",i.showPanel(this._element,c)},_animateSlideOut:function(){var a,b=this._element.offsetWidth;return d()?(a={top:"0px",left:b+"px"},this._element.style.right="auto",this._element.style.left="-"+b+"px"):(a={top:"0px",left:"-"+b+"px"},this._element.style.right="-"+b+"px",this._element.style.left="auto"),i.showPanel(this._element,a)},_fragmentDiv:{get:function(){return this._fragDiv},set:function(a){this._fragDiv=a}},_unloadPage:function(b){var c=b.currentTarget.winControl;c.removeEventListener(r._Overlay.afterHide,this._unloadPage,!1),k.as().then(function(){c._fragmentDiv&&(a.document.body.removeChild(c._fragmentDiv),c._fragmentDiv=null)})},_dismiss:function(){this.addEventListener(r._Overlay.afterHide,this._unloadPage,!1),this._hide()},_handleKeyDown:function(b){if(b.keyCode!==t.space&&b.keyCode!==t.enter||this.children[0]!==a.document.activeElement){if(b.shiftKey&&b.keyCode===t.tab&&this.children[0]===a.document.activeElement){b.preventDefault(),b.stopPropagation();for(var c=this.getElementsByTagName("*"),d=c.length-2;d>=0&&(c[d].focus(),c[d]!==a.document.activeElement);d--);}}else b.preventDefault(),b.stopPropagation(),this.winControl._dismiss()},_focusOnLastFocusableElementFromParent:function(){var b=a.document.activeElement; if(s&&b&&n.hasClass(b,q.firstDivClass)){var c=this.parentElement.getElementsByTagName("*");if(!(c.length<=2)){var d,e=c[c.length-1].tabIndex;if(e){for(d=c.length-2;d>0;d--)if(c[d].tabIndex===e){c[d].focus();break}}else for(d=c.length-2;d>0&&("DIV"===c[d].tagName&&null===c[d].getAttribute("tabIndex")||(c[d].focus(),c[d]!==a.document.activeElement));d--);}}},_focusOnFirstFocusableElementFromParent:function(){var b=a.document.activeElement;if(b&&n.hasClass(b,q.finalDivClass)){var c=this.parentElement.getElementsByTagName("*");if(!(c.length<=2)){var d,e=c[0].tabIndex;if(e){for(d=1;d<c.length-1;d++)if(c[d].tabIndex===e){c[d].focus();break}}else for(d=1;d<c.length-1&&("DIV"===c[d].tagName&&null===c[d].getAttribute("tabIndex")||(c[d].focus(),c[d]!==a.document.activeElement));d++);}}},_addFirstDiv:function(){for(var b=this._element.getElementsByTagName("*"),c=0,d=0;d<b.length;d++)0<b[d].tabIndex&&(0===c||b[d].tabIndex<c)&&(c=b[d].tabIndex);var e=a.document.createElement("div");e.className=q.firstDivClass,e.style.display="inline",e.setAttribute("role","menuitem"),e.setAttribute("aria-hidden","true"),e.tabIndex=c,n._addEventListener(e,"focusin",this._focusOnLastFocusableElementFromParent,!1),this._element.children[0]?this._element.insertBefore(e,this._element.children[0]):this._element.appendChild(e)},_addFinalDiv:function(){for(var b=this._element.getElementsByTagName("*"),c=0,d=0;d<b.length;d++)b[d].tabIndex>c&&(c=b[d].tabIndex);var e=a.document.createElement("div");e.className=q.finalDivClass,e.style.display="inline",e.setAttribute("role","menuitem"),e.setAttribute("aria-hidden","true"),e.tabIndex=c,n._addEventListener(e,"focusin",this._focusOnFirstFocusableElementFromParent,!1),this._element.appendChild(e)},_writeProfilerMark:function(a){h("WinJS.UI.SettingsFlyout:"+this._id+":"+a)}});x.show=function(){b.Windows.UI.ApplicationSettings.SettingsPane&&b.Windows.UI.ApplicationSettings.SettingsPane.show();for(var c=a.document.querySelectorAll('div[data-win-control="WinJS.UI.SettingsFlyout"]'),d=c.length,e=0;d>e;e++){var f=c[e].winControl;f&&f._dismiss()}};var y={event:void 0};x.populateSettings=function(a){if(y.event=a.detail,y.event.applicationcommands){var c=b.Windows.UI.ApplicationSettings;Object.keys(y.event.applicationcommands).forEach(function(a){var b=y.event.applicationcommands[a];b.title||(b.title=a);var d=new c.SettingsCommand(a,b.title,x._onSettingsCommand);y.event.e.request.applicationCommands.append(d)})}},x._onSettingsCommand=function(a){var b=a.id;y.event.applicationcommands&&y.event.applicationcommands[b]&&x.showSettings(b,y.event.applicationcommands[b].href)},x.showSettings=function(b,c){var d=p(a.document,b);if(d)d.show();else{if(!c)throw new e("WinJS.UI.SettingsFlyout.BadReference",z.badReference);var f=a.document.createElement("div");f=a.document.body.appendChild(f),j.render(c,f).then(function(){d=p(f,b),d?(d._fragmentDiv=f,d.show()):a.document.body.removeChild(f)})}};var z={get ariaLabel(){return g._getWinJSString("ui/settingsFlyoutAriaLabel").value},get badReference(){return"Invalid argument: Invalid href to settings flyout fragment"},get backbuttonAriaLabel(){return g._getWinJSString("ui/backbuttonarialabel").value},get widthDeprecationMessage(){return"SettingsFlyout.width may be altered or unavailable in future versions. Instead, style the CSS width property on elements with the .win-settingsflyout class."},get settingsFlyoutIsDeprecated(){return"SettingsFlyout is deprecated and may not be available in future releases. Instead, put settings on their own page within the app."}};return x})})}),d("require-style!less/styles-splitviewcommand",[],function(){}),d("require-style!less/colors-splitviewcommand",[],function(){}),d("WinJS/Controls/SplitView/Command",["exports","../../Core/_Global","../../Core/_Base","../../Core/_ErrorFromName","../../Core/_Events","../../ControlProcessor","../../Utilities/_Control","../../Utilities/_ElementUtilities","../../Utilities/_KeyboardBehavior","../AppBar/_Icon","require-style!less/styles-splitviewcommand","require-style!less/colors-splitviewcommand"],function(a,b,c,d,e,f,g,h,i,j){"use strict";c.Namespace._moduleDefine(a,"WinJS.UI",{_WinPressed:c.Namespace._lazy(function(){var a=c.Class.define(function(a){this._element=a,h._addEventListener(this._element,"pointerdown",this._MSPointerDownButtonHandler.bind(this))},{_MSPointerDownButtonHandler:function(c){this._pointerUpBound||(this._pointerUpBound=this._MSPointerUpHandler.bind(this),this._pointerCancelBound=this._MSPointerCancelHandler.bind(this),this._pointerOverBound=this._MSPointerOverHandler.bind(this),this._pointerOutBound=this._MSPointerOutHandler.bind(this)),c.isPrimary&&(this._pointerId&&this._resetPointer(),h._matchesSelector(c.target,".win-interactive, .win-interactive *")||(this._pointerId=c.pointerId,h._addEventListener(b,"pointerup",this._pointerUpBound,!0),h._addEventListener(b,"pointercancel",this._pointerCancelBound),!0,h._addEventListener(this._element,"pointerover",this._pointerOverBound,!0),h._addEventListener(this._element,"pointerout",this._pointerOutBound,!0),h.addClass(this._element,a.winPressed)))},_MSPointerOverHandler:function(b){this._pointerId===b.pointerId&&h.addClass(this._element,a.winPressed)},_MSPointerOutHandler:function(b){this._pointerId===b.pointerId&&h.removeClass(this._element,a.winPressed)},_MSPointerCancelHandler:function(a){this._pointerId===a.pointerId&&this._resetPointer()},_MSPointerUpHandler:function(a){this._pointerId===a.pointerId&&this._resetPointer()},_resetPointer:function(){this._pointerId=null,h._removeEventListener(b,"pointerup",this._pointerUpBound,!0),h._removeEventListener(b,"pointercancel",this._pointerCancelBound,!0),h._removeEventListener(this._element,"pointerover",this._pointerOverBound,!0),h._removeEventListener(this._element,"pointerout",this._pointerOutBound,!0),h.removeClass(this._element,a.winPressed)},dispose:function(){this._disposed||(this._disposed=!0,this._resetPointer())}},{winPressed:"win-pressed"});return a}),SplitViewCommand:c.Namespace._lazy(function(){var k=h.Key,l={get duplicateConstruction(){return"Invalid argument: Controls may only be instantiated one time for each DOM element"}},m={command:"win-splitviewcommand",commandButton:"win-splitviewcommand-button",commandButtonContent:"win-splitviewcommand-button-content",commandSplitButton:"win-splitviewcommand-splitbutton",commandSplitButtonOpened:"win-splitviewcommand-splitbutton-opened",commandIcon:"win-splitviewcommand-icon",commandLabel:"win-splitviewcommand-label"},n={invoked:"invoked",_splitToggle:"_splittoggle"},o=e._createEventProperty,p=c.Class.define(function(a,c){if(a=a||b.document.createElement("DIV"),c=c||{},a.winControl)throw new d("WinJS.UI.SplitViewCommand.DuplicateConstruction",l.duplicateConstruction);this._winKeyboard=new i._WinKeyboard(a),this._baseConstructor(a,c)},{_baseConstructor:function(a,b,c){this._classNames=c||m,a.winControl=this,this._element=a,h.addClass(this.element,this._classNames.command),h.addClass(this.element,"win-disposable"),this._tooltip=null,this._splitOpened=!1,this._buildDom(),a.addEventListener("keydown",this._keydownHandler.bind(this)),g.setOptions(this,b)},element:{get:function(){return this._element}},label:{get:function(){return this._label},set:function(a){this._label=a,this._labelEl.textContent=a}},tooltip:{get:function(){return this._tooltip},set:function(a){this._tooltip=a,this._tooltip||""===this._tooltip?this._element.setAttribute("title",this._tooltip):this._element.removeAttribute("title")}},icon:{get:function(){return this._icon},set:function(a){this._icon=j[a]||a,this._icon&&1===this._icon.length?(this._imageSpan.textContent=this._icon,this._imageSpan.style.backgroundImage="",this._imageSpan.style.msHighContrastAdjust="",this._imageSpan.style.display=""):this._icon&&this._icon.length>1?(this._imageSpan.textContent="",this._imageSpan.style.backgroundImage=this._icon,this._imageSpan.style.msHighContrastAdjust="none",this._imageSpan.style.display=""):(this._imageSpan.textContent="",this._imageSpan.style.backgroundImage="",this._imageSpan.style.msHighContrastAdjust="",this._imageSpan.style.display="none")}},oninvoked:o(n.invoked),_toggleSplit:function(){this._splitOpened=!this._splitOpened,this._splitOpened?(h.addClass(this._splitButtonEl,this._classNames.commandSplitButtonOpened),this._splitButtonEl.setAttribute("aria-expanded","true")):(h.removeClass(this._splitButtonEl,this._classNames.commandSplitButtonOpened),this._splitButtonEl.setAttribute("aria-expanded","false")),this._fireEvent(p._EventName._splitToggle)},_rtl:{get:function(){return"rtl"===h._getComputedStyle(this.element).direction}},_keydownHandler:function(a){if(!h._matchesSelector(a.target,".win-interactive, .win-interactive *")){var b=this._rtl?k.rightArrow:k.leftArrow,c=this._rtl?k.leftArrow:k.rightArrow;a.altKey||a.keyCode!==b&&a.keyCode!==k.home&&a.keyCode!==k.end||a.target!==this._splitButtonEl?a.altKey||a.keyCode!==c||!this.splitButton||a.target!==this._buttonEl&&!this._buttonEl.contains(a.target)?a.keyCode!==k.space&&a.keyCode!==k.enter||a.target!==this._buttonEl&&!this._buttonEl.contains(a.target)?a.keyCode!==k.space&&a.keyCode!==k.enter||a.target!==this._splitButtonEl||this._toggleSplit():this._invoke():(h._setActive(this._splitButtonEl),a.keyCode===c&&a.stopPropagation(),a.preventDefault()):(h._setActive(this._buttonEl),a.keyCode===b&&a.stopPropagation(),a.preventDefault())}},_getFocusInto:function(a){var b=this._rtl?k.rightArrow:k.leftArrow;return a===b&&this.splitButton?this._splitButtonEl:this._buttonEl},_buildDom:function(){var b='<div tabindex="0" role="button" class="'+this._classNames.commandButton+'"><div class="'+this._classNames.commandButtonContent+'"><div class="'+this._classNames.commandIcon+'"></div><div class="'+this._classNames.commandLabel+'"></div></div></div><div tabindex="-1" aria-expanded="false" class="'+this._classNames.commandSplitButton+'"></div>';this.element.insertAdjacentHTML("afterBegin",b),this._buttonEl=this.element.firstElementChild,this._buttonPressedBehavior=new a._WinPressed(this._buttonEl),this._contentEl=this._buttonEl.firstElementChild,this._imageSpan=this._contentEl.firstElementChild,this._imageSpan.style.display="none",this._labelEl=this._imageSpan.nextElementSibling,this._splitButtonEl=this._buttonEl.nextElementSibling,this._splitButtonPressedBehavior=new a._WinPressed(this._splitButtonEl),this._splitButtonEl.style.display="none",h._ensureId(this._buttonEl),this._splitButtonEl.setAttribute("aria-labelledby",this._buttonEl.id),this._buttonEl.addEventListener("click",this._handleButtonClick.bind(this));var c=new h._MutationObserver(this._splitButtonAriaExpandedPropertyChangeHandler.bind(this));c.observe(this._splitButtonEl,{attributes:!0,attributeFilter:["aria-expanded"]}),this._splitButtonEl.addEventListener("click",this._handleSplitButtonClick.bind(this));for(var d=this._splitButtonEl.nextSibling;d;)this._buttonEl.insertBefore(d,this._contentEl),"#text"!==d.nodeName&&f.processAll(d),d=this._splitButtonEl.nextSibling},_handleButtonClick:function(a){var b=a.target;h._matchesSelector(b,".win-interactive, .win-interactive *")||this._invoke()},_splitButtonAriaExpandedPropertyChangeHandler:function(){"true"===this._splitButtonEl.getAttribute("aria-expanded")!==this._splitOpened&&this._toggleSplit()},_handleSplitButtonClick:function(){this._toggleSplit()},_invoke:function(){this._fireEvent(p._EventName.invoked)},_fireEvent:function(a,c){var d=b.document.createEvent("CustomEvent");d.initCustomEvent(a,!0,!1,c),this.element.dispatchEvent(d)},dispose:function(){this._disposed||(this._disposed=!0,this._buttonPressedBehavior.dispose(),this._splitButtonPressedBehavior.dispose())}},{_ClassName:m,_EventName:n});return c.Class.mix(p,g.DOMEventMixin),p})})}),d("WinJS/Controls/NavBar/_Command",["exports","../../Core/_Global","../../Core/_Base","../../Core/_ErrorFromName","../../Navigation","../../Utilities/_ElementUtilities","../SplitView/Command"],function(a,b,c,d,e,f,g){"use strict";c.Namespace._moduleDefine(a,"WinJS.UI",{NavBarCommand:c.Namespace._lazy(function(){var a={get duplicateConstruction(){return"Invalid argument: Controls may only be instantiated one time for each DOM element"},get navBarCommandDeprecated(){return"NavBarCommand is deprecated and may not be available in future releases. If you were using a NavBarCommand inside of a SplitView, use SplitViewCommand instead."}},h={command:"win-navbarcommand",commandButton:"win-navbarcommand-button",commandButtonContent:"win-navbarcommand-button-content",commandSplitButton:"win-navbarcommand-splitbutton",commandSplitButtonOpened:"win-navbarcommand-splitbutton-opened",commandIcon:"win-navbarcommand-icon",commandLabel:"win-navbarcommand-label"},i=g.SplitViewCommand.prototype,j=c.Class.derive(g.SplitViewCommand,function(c,e){if(f._deprecated(a.navBarCommandDeprecated),c=c||b.document.createElement("DIV"),e=e||{},c.winControl)throw new d("WinJS.UI.NavBarCommand.DuplicateConstruction",a.duplicateConstruction);this._baseConstructor(c,e,h)},{element:{get:function(){return Object.getOwnPropertyDescriptor(i,"element").get.call(this)}},label:{get:function(){return Object.getOwnPropertyDescriptor(i,"label").get.call(this)},set:function(a){return Object.getOwnPropertyDescriptor(i,"label").set.call(this,a)}},tooltip:{get:function(){return Object.getOwnPropertyDescriptor(i,"tooltip").get.call(this)},set:function(a){return Object.getOwnPropertyDescriptor(i,"tooltip").set.call(this,a)}},icon:{get:function(){return Object.getOwnPropertyDescriptor(i,"icon").get.call(this)},set:function(a){return Object.getOwnPropertyDescriptor(i,"icon").set.call(this,a)}},location:{get:function(){return this._location},set:function(a){this._location=a}},oninvoked:{get:function(){return void 0},enumerable:!1},state:{get:function(){return this._state},set:function(a){this._state=a}},splitButton:{get:function(){return this._split},set:function(a){this._split=a,this._splitButtonEl.style.display=this._split?"":"none"}},splitOpened:{get:function(){return this._splitOpened},set:function(a){this._splitOpened!==!!a&&this._toggleSplit()}},dispose:function(){i.dispose.call(this)},_invoke:function(){this.location&&e.navigate(this.location,this.state),this._fireEvent(j._EventName._invoked)}},{_ClassName:h,_EventName:{_invoked:"_invoked",_splitToggle:"_splittoggle"}});return j})})}),d("WinJS/Controls/NavBar/_Container",["exports","../../Core/_Global","../../Core/_Base","../../Core/_BaseUtils","../../Core/_ErrorFromName","../../Core/_Events","../../Core/_Log","../../Core/_Resources","../../Core/_WriteProfilerMark","../../Animations","../../Animations/_TransitionAnimation","../../BindingList","../../ControlProcessor","../../Navigation","../../Promise","../../Scheduler","../../Utilities/_Control","../../Utilities/_ElementUtilities","../../Utilities/_KeyboardBehavior","../../Utilities/_UI","../_LegacyAppBar/_Constants","../Repeater","./_Command"],function(a,b,c,d,e,f,g,h,i,j,k,l,m,n,o,p,q,r,s,t,u,v,w){"use strict";function x(){return null===b.document.activeElement||b.document.activeElement===b.document.body}c.Namespace._moduleDefine(a,"WinJS.UI",{NavBarContainer:c.Namespace._lazy(function(){var a=r.Key,y=3e3,z=r._MSPointerEvent.MSPOINTER_TYPE_TOUCH||"touch",A=0,B=f._createEventProperty,C={invoked:"invoked",splittoggle:"splittoggle"},D={get duplicateConstruction(){return"Invalid argument: Controls may only be instantiated one time for each DOM element"},get navBarContainerViewportAriaLabel(){return h._getWinJSString("ui/navBarContainerViewportAriaLabel").value},get navBarContainerIsDeprecated(){return"NavBarContainer is deprecated and may not be available in future releases. Instead, use a WinJS SplitView to display navigation targets within the app."}},E=c.Class.define(function(a,c){if(r._deprecated(D.navBarContainerIsDeprecated),a=a||b.document.createElement("DIV"),this._id=a.id||r._uniqueID(a),this._writeProfilerMark("constructor,StartTM"),c=c||{},a.winControl)throw new e("WinJS.UI.NavBarContainer.DuplicateConstruction",D.duplicateConstruction);a.winControl=this,this._element=a,r.addClass(this.element,E._ClassName.navbarcontainer),r.addClass(this.element,"win-disposable"),a.getAttribute("tabIndex")||(a.tabIndex=-1),this._focusCurrentItemPassivelyBound=this._focusCurrentItemPassively.bind(this),this._closeSplitAndResetBound=this._closeSplitAndReset.bind(this),this._currentManipulationState=A,this._panningDisabled=!r._supportsSnapPoints,this._fixedSize=!1,this._maxRows=1,this._sizes={},this._setupTree(),this._duringConstructor=!0,this._dataChangingBound=this._dataChanging.bind(this),this._dataChangedBound=this._dataChanged.bind(this),n.addEventListener("navigated",this._closeSplitAndResetBound),this.layout=c.layout||t.Orientation.horizontal,c.maxRows&&(this.maxRows=c.maxRows),c.template&&(this.template=c.template),c.data&&(this.data=c.data),c.fixedSize&&(this.fixedSize=c.fixedSize),q._setOptions(this,c,!0),this._duringConstructor=!1,c.currentIndex&&(this.currentIndex=c.currentIndex),this._updatePageUI(),p.schedule(function(){this._updateAppBarReference()},p.Priority.normal,this,"WinJS.UI.NavBarContainer_async_initialize"),this._writeProfilerMark("constructor,StopTM")},{element:{get:function(){return this._element}},template:{get:function(){return this._template},set:function(a){if(this._template=a,this._repeater){var c=this.element.contains(b.document.activeElement);this._duringConstructor||this._closeSplitIfOpen(),this._repeater.template=this._repeater.template,this._duringConstructor||(this._measured=!1,this._sizes.itemMeasured=!1,this._reset(),c&&this._keyboardBehavior._focus(0))}}},_render:function(a){var c=b.document.createElement("div"),d=this._template;d&&(d.render?d.render(a,c):d.winControl&&d.winControl.render?d.winControl.render(a,c):c.appendChild(d(a)));var e=new w.NavBarCommand(c,a);return e._element},data:{get:function(){return this._repeater&&this._repeater.data},set:function(a){a||(a=new l.List),this._duringConstructor||this._closeSplitIfOpen(),this._removeDataChangingEvents(),this._removeDataChangedEvents();var c=this.element.contains(b.document.activeElement);this._repeater||(this._surfaceEl.innerHTML="",this._repeater=new v.Repeater(this._surfaceEl,{template:this._render.bind(this)})),this._addDataChangingEvents(a),this._repeater.data=a,this._addDataChangedEvents(a),this._duringConstructor||(this._measured=!1,this._sizes.itemMeasured=!1,this._reset(),c&&this._keyboardBehavior._focus(0))}},maxRows:{get:function(){return this._maxRows},set:function(a){a=+a===a?a:1,this._maxRows=Math.max(1,a),this._duringConstructor||(this._closeSplitIfOpen(),this._measured=!1,this._reset())}},layout:{get:function(){return this._layout},set:function(a){a===t.Orientation.vertical?(this._layout=t.Orientation.vertical,r.removeClass(this.element,E._ClassName.horizontal),r.addClass(this.element,E._ClassName.vertical)):(this._layout=t.Orientation.horizontal,r.removeClass(this.element,E._ClassName.vertical),r.addClass(this.element,E._ClassName.horizontal)),this._viewportEl.style.msScrollSnapType="",this._zooming=!1,this._duringConstructor||(this._measured=!1,this._sizes.itemMeasured=!1,this._ensureVisible(this._keyboardBehavior.currentIndex,!0),this._updatePageUI(),this._closeSplitIfOpen())}},currentIndex:{get:function(){return this._keyboardBehavior.currentIndex},set:function(a){if(a===+a){var c=this.element.contains(b.document.activeElement);this._keyboardBehavior.currentIndex=a,this._ensureVisible(this._keyboardBehavior.currentIndex,!0),c&&this._keyboardBehavior._focus()}}},fixedSize:{get:function(){return this._fixedSize},set:function(a){this._fixedSize=!!a,this._duringConstructor||(this._closeSplitIfOpen(),this._measured?this._surfaceEl.children.length>0&&this._updateGridStyles():this._measure())}},oninvoked:B(C.invoked),onsplittoggle:B(C.splittoggle),forceLayout:function(){this._resizeHandler(),this._measured&&(this._scrollPosition=r.getScrollPosition(this._viewportEl)[this.layout===t.Orientation.horizontal?"scrollLeft":"scrollTop"]),this._duringForceLayout=!0,this._ensureVisible(this._keyboardBehavior.currentIndex,!0),this._updatePageUI(),this._duringForceLayout=!1},_updateAppBarReference:function(){if(!this._appBarEl||!this._appBarEl.contains(this.element)){this._appBarEl&&(this._appBarEl.removeEventListener("beforeopen",this._closeSplitAndResetBound),this._appBarEl.removeEventListener("beforeopen",this._resizeImplBound),this._appBarEl.removeEventListener("afteropen",this._focusCurrentItemPassivelyBound));for(var a=this.element.parentNode;a&&!r.hasClass(a,u.appBarClass);)a=a.parentNode;this._appBarEl=a,this._appBarEl&&(this._appBarEl.addEventListener("beforeopen",this._closeSplitAndResetBound),this._appBarEl.addEventListener("afteropen",this._focusCurrentItemPassivelyBound))}},_closeSplitAndReset:function(){this._closeSplitIfOpen(),this._reset()},_dataChanging:function(a){this._elementHadFocus=b.document.activeElement,this._currentSplitNavItem&&this._currentSplitNavItem.splitOpened&&("itemremoved"===a.type?this._surfaceEl.children[a.detail.index].winControl===this._currentSplitNavItem&&this._closeSplitIfOpen():"itemchanged"===a.type?this._surfaceEl.children[a.detail.index].winControl===this._currentSplitNavItem&&this._closeSplitIfOpen():"itemmoved"===a.type?this._surfaceEl.children[a.detail.oldIndex].winControl===this._currentSplitNavItem&&this._closeSplitIfOpen():"reload"===a.type&&this._closeSplitIfOpen())},_dataChanged:function(a){this._measured=!1,"itemremoved"===a.type?a.detail.index<this._keyboardBehavior.currentIndex?this._keyboardBehavior.currentIndex--:a.detail.index===this._keyboardBehavior.currentIndex&&(this._keyboardBehavior.currentIndex=this._keyboardBehavior.currentIndex,x()&&this._elementHadFocus&&this._keyboardBehavior._focus()):"itemchanged"===a.type?a.detail.index===this._keyboardBehavior.currentIndex&&x()&&this._elementHadFocus&&this._keyboardBehavior._focus():"iteminserted"===a.type?a.detail.index<=this._keyboardBehavior.currentIndex&&this._keyboardBehavior.currentIndex++:"itemmoved"===a.type?a.detail.oldIndex===this._keyboardBehavior.currentIndex&&(this._keyboardBehavior.currentIndex=a.detail.newIndex,x()&&this._elementHadFocus&&this._keyboardBehavior._focus()):"reload"===a.type&&(this._keyboardBehavior.currentIndex=0,x()&&this._elementHadFocus&&this._keyboardBehavior._focus()),this._ensureVisible(this._keyboardBehavior.currentIndex,!0),this._updatePageUI()},_focusCurrentItemPassively:function(){this.element.contains(b.document.activeElement)&&this._keyboardBehavior._focus()},_reset:function(){this._keyboardBehavior.currentIndex=0,this.element.contains(b.document.activeElement)&&this._keyboardBehavior._focus(0),this._viewportEl.style.msScrollSnapType="",this._zooming=!1,this._ensureVisible(0,!0),this._updatePageUI()},_removeDataChangedEvents:function(){this._repeater&&(this._repeater.data.removeEventListener("itemchanged",this._dataChangedBound),this._repeater.data.removeEventListener("iteminserted",this._dataChangedBound),this._repeater.data.removeEventListener("itemmoved",this._dataChangedBound),this._repeater.data.removeEventListener("itemremoved",this._dataChangedBound),this._repeater.data.removeEventListener("reload",this._dataChangedBound))},_addDataChangedEvents:function(){this._repeater&&(this._repeater.data.addEventListener("itemchanged",this._dataChangedBound),this._repeater.data.addEventListener("iteminserted",this._dataChangedBound),this._repeater.data.addEventListener("itemmoved",this._dataChangedBound),this._repeater.data.addEventListener("itemremoved",this._dataChangedBound),this._repeater.data.addEventListener("reload",this._dataChangedBound))},_removeDataChangingEvents:function(){this._repeater&&(this._repeater.data.removeEventListener("itemchanged",this._dataChangingBound),this._repeater.data.removeEventListener("iteminserted",this._dataChangingBound),this._repeater.data.removeEventListener("itemmoved",this._dataChangingBound),this._repeater.data.removeEventListener("itemremoved",this._dataChangingBound),this._repeater.data.removeEventListener("reload",this._dataChangingBound))},_addDataChangingEvents:function(a){a.addEventListener("itemchanged",this._dataChangingBound),a.addEventListener("iteminserted",this._dataChangingBound),a.addEventListener("itemmoved",this._dataChangingBound),a.addEventListener("itemremoved",this._dataChangingBound),a.addEventListener("reload",this._dataChangingBound)},_mouseleave:function(){this._mouseInViewport&&(this._mouseInViewport=!1,this._updateArrows())},_MSPointerDown:function(a){a.pointerType===z&&this._mouseInViewport&&(this._mouseInViewport=!1,this._updateArrows())},_MSPointerMove:function(a){a.pointerType!==z&&(this._mouseInViewport||(this._mouseInViewport=!0,this._updateArrows()))},_setupTree:function(){this._animateNextPreviousButtons=o.wrap(),this._element.addEventListener("mouseleave",this._mouseleave.bind(this)),r._addEventListener(this._element,"pointerdown",this._MSPointerDown.bind(this)),r._addEventListener(this._element,"pointermove",this._MSPointerMove.bind(this)),r._addEventListener(this._element,"focusin",this._focusHandler.bind(this),!1),this._pageindicatorsEl=b.document.createElement("div"),r.addClass(this._pageindicatorsEl,E._ClassName.pageindicators),this._element.appendChild(this._pageindicatorsEl),this._ariaStartMarker=b.document.createElement("div"),this._element.appendChild(this._ariaStartMarker),this._viewportEl=b.document.createElement("div"),r.addClass(this._viewportEl,E._ClassName.viewport),this._element.appendChild(this._viewportEl),this._viewportEl.setAttribute("role","group"),this._viewportEl.setAttribute("aria-label",D.navBarContainerViewportAriaLabel),this._boundResizeHandler=this._resizeHandler.bind(this),r._resizeNotifier.subscribe(this._element,this._boundResizeHandler),this._viewportEl.addEventListener("mselementresize",this._resizeHandler.bind(this)),this._viewportEl.addEventListener("scroll",this._scrollHandler.bind(this)),this._viewportEl.addEventListener("MSManipulationStateChanged",this._MSManipulationStateChangedHandler.bind(this)),this._ariaEndMarker=b.document.createElement("div"),this._element.appendChild(this._ariaEndMarker),this._surfaceEl=b.document.createElement("div"),r.addClass(this._surfaceEl,E._ClassName.surface),this._viewportEl.appendChild(this._surfaceEl),this._surfaceEl.addEventListener(w.NavBarCommand._EventName._invoked,this._navbarCommandInvokedHandler.bind(this)),this._surfaceEl.addEventListener(w.NavBarCommand._EventName._splitToggle,this._navbarCommandSplitToggleHandler.bind(this)),r._addEventListener(this._surfaceEl,"focusin",this._itemsFocusHandler.bind(this),!1),this._surfaceEl.addEventListener("keydown",this._keyDownHandler.bind(this));for(var a=this.element.firstElementChild;a!==this._pageindicatorsEl;)this._surfaceEl.appendChild(a),m.process(a),a=this.element.firstElementChild;this._leftArrowEl=b.document.createElement("div"),r.addClass(this._leftArrowEl,E._ClassName.navleftarrow),r.addClass(this._leftArrowEl,E._ClassName.navarrow),this._element.appendChild(this._leftArrowEl),this._leftArrowEl.addEventListener("click",this._goLeft.bind(this)),this._leftArrowEl.style.opacity=0,this._leftArrowEl.style.visibility="hidden",this._leftArrowFadeOut=o.wrap(),this._rightArrowEl=b.document.createElement("div"),r.addClass(this._rightArrowEl,E._ClassName.navrightarrow),r.addClass(this._rightArrowEl,E._ClassName.navarrow),this._element.appendChild(this._rightArrowEl),this._rightArrowEl.addEventListener("click",this._goRight.bind(this)),this._rightArrowEl.style.opacity=0,this._rightArrowEl.style.visibility="hidden",this._rightArrowFadeOut=o.wrap(),this._keyboardBehavior=new s._KeyboardBehavior(this._surfaceEl,{scroller:this._viewportEl}),this._winKeyboard=new s._WinKeyboard(this._surfaceEl)},_goRight:function(){this._sizes.rtl?this._goPrev():this._goNext()},_goLeft:function(){this._sizes.rtl?this._goNext():this._goPrev()},_goNext:function(){this._measure();var a=this._sizes.rowsPerPage*this._sizes.columnsPerPage,b=Math.min(Math.floor(this._keyboardBehavior.currentIndex/a)+1,this._sizes.pages-1);this._keyboardBehavior.currentIndex=Math.min(a*b,this._surfaceEl.children.length),this._keyboardBehavior._focus()},_goPrev:function(){this._measure();var a=this._sizes.rowsPerPage*this._sizes.columnsPerPage,b=Math.max(0,Math.floor(this._keyboardBehavior.currentIndex/a)-1);this._keyboardBehavior.currentIndex=Math.max(a*b,0),this._keyboardBehavior._focus()},_currentPage:{get:function(){return this.layout===t.Orientation.horizontal&&(this._measure(),this._sizes.viewportOffsetWidth>0)?Math.min(this._sizes.pages-1,Math.round(this._scrollPosition/this._sizes.viewportOffsetWidth)):0}},_resizeHandler:function(){if(!this._disposed&&this._measured){var a=this.layout===t.Orientation.horizontal?this._sizes.viewportOffsetWidth!==parseFloat(r._getComputedStyle(this._viewportEl).width):this._sizes.viewportOffsetHeight!==parseFloat(r._getComputedStyle(this._viewportEl).height);a&&(this._measured=!1,this._pendingResize||(this._pendingResize=!0,this._resizeImplBound=this._resizeImplBound||this._resizeImpl.bind(this),this._updateAppBarReference(),this._appBarEl&&this._appBarEl.winControl&&!this._appBarEl.winControl.opened?(p.schedule(this._resizeImplBound,p.Priority.idle,null,"WinJS.UI.NavBarContainer._resizeImpl"),this._appBarEl.addEventListener("beforeopen",this._resizeImplBound)):this._resizeImpl()))}},_resizeImpl:function(){!this._disposed&&this._pendingResize&&(this._pendingResize=!1,this._appBarEl&&this._appBarEl.removeEventListener("beforeopen",this._resizeImplBound),this._keyboardBehavior.currentIndex=0,this.element.contains(b.document.activeElement)&&this._keyboardBehavior._focus(this._keyboardBehavior.currentIndex),this._closeSplitIfOpen(),this._ensureVisible(this._keyboardBehavior.currentIndex,!0),this._updatePageUI())},_keyDownHandler:function(c){var d=c.keyCode;if(!c.altKey&&(d===a.pageUp||d===a.pageDown)){var e=c.target;if(r._matchesSelector(e,".win-interactive, .win-interactive *"))return;var f=this._keyboardBehavior.currentIndex;this._measure();var g=this._sizes,h=Math.floor(f/(g.columnsPerPage*g.rowsPerPage)),i=null;if(d===a.pageUp){if(this.layout===t.Orientation.horizontal){var j=h*g.columnsPerPage*g.rowsPerPage;f===j&&this._surfaceEl.children[f].winControl._buttonEl===b.document.activeElement?f-=g.columnsPerPage*g.rowsPerPage:f=j}else{var k=this._surfaceEl.children[f],l=k.offsetTop,m=l+k.offsetHeight,n=this._zooming?this._zoomPosition:this._scrollPosition;if(l>=n&&m<n+g.viewportOffsetHeight)for(;f>0&&this._surfaceEl.children[f-1].offsetTop>n;)f--;if(this._keyboardBehavior.currentIndex===f){var o=m-g.viewportOffsetHeight;for(f=Math.max(0,f-1);f>0&&this._surfaceEl.children[f-1].offsetTop>o;)f--;i=f>0?this._surfaceEl.children[f].offsetTop-this._sizes.itemMarginTop:0}}f=Math.max(f,0),this._keyboardBehavior.currentIndex=f;var p=this._surfaceEl.children[f].winControl._buttonEl;null!==i&&this._scrollTo(i),r._setActive(p,this._viewportEl)}else{if(this.layout===t.Orientation.horizontal){var q=(h+1)*g.columnsPerPage*g.rowsPerPage-1;f===q?f+=g.columnsPerPage*g.rowsPerPage:f=q}else{var k=this._surfaceEl.children[this._keyboardBehavior.currentIndex],l=k.offsetTop,m=l+k.offsetHeight,n=this._zooming?this._zoomPosition:this._scrollPosition;if(l>=n&&m<n+g.viewportOffsetHeight)for(;f<this._surfaceEl.children.length-1&&this._surfaceEl.children[f+1].offsetTop+this._surfaceEl.children[f+1].offsetHeight<n+g.viewportOffsetHeight;)f++;if(f===this._keyboardBehavior.currentIndex){var s=l+g.viewportOffsetHeight;for(f=Math.min(this._surfaceEl.children.length-1,f+1);f<this._surfaceEl.children.length-1&&this._surfaceEl.children[f+1].offsetTop+this._surfaceEl.children[f+1].offsetHeight<s;)f++;i=f<this._surfaceEl.children.length-1?this._surfaceEl.children[f+1].offsetTop-this._sizes.viewportOffsetHeight:this._scrollLength-this._sizes.viewportOffsetHeight}}f=Math.min(f,this._surfaceEl.children.length-1),this._keyboardBehavior.currentIndex=f;var p=this._surfaceEl.children[f].winControl._buttonEl;null!==i&&this._scrollTo(i);try{r._setActive(p,this._viewportEl) }catch(u){}}}},_focusHandler:function(a){var b=a.target;this._surfaceEl.contains(b)||(this._skipEnsureVisible=!0,this._keyboardBehavior._focus(this._keyboardBehavior.currentIndex))},_itemsFocusHandler:function(a){var b=a.target;if(b!==this._surfaceEl){for(;b.parentNode!==this._surfaceEl;)b=b.parentNode;for(var c=-1;b;)c++,b=b.previousSibling;this._skipEnsureVisible?this._skipEnsureVisible=!1:this._ensureVisible(c)}},_ensureVisible:function(a,b){if(this._measure(),this.layout===t.Orientation.horizontal){var c=Math.floor(a/(this._sizes.rowsPerPage*this._sizes.columnsPerPage));this._scrollTo(c*this._sizes.viewportOffsetWidth,b)}else{var d,e=this._surfaceEl.children[a];d=a>0?e.offsetTop-this._sizes.itemMarginTop:0;var f;f=a<this._surfaceEl.children.length-1?this._surfaceEl.children[a+1].offsetTop-this._sizes.viewportOffsetHeight:this._scrollLength-this._sizes.viewportOffsetHeight;var g=this._zooming?this._zoomPosition:this._scrollPosition;g=Math.max(g,f),g=Math.min(g,d),this._scrollTo(g,b)}},_scrollTo:function(a,b){if(this._measure(),a=this.layout===t.Orientation.horizontal?Math.max(0,Math.min(this._scrollLength-this._sizes.viewportOffsetWidth,a)):Math.max(0,Math.min(this._scrollLength-this._sizes.viewportOffsetHeight,a)),b){if(Math.abs(this._scrollPosition-a)>1){this._zooming=!1,this._scrollPosition=a,this._updatePageUI(),this._duringForceLayout||this._closeSplitIfOpen();var c={};c[this.layout===t.Orientation.horizontal?"scrollLeft":"scrollTop"]=a,r.setScrollPosition(this._viewportEl,c)}}else(!this._zooming&&Math.abs(this._scrollPosition-a)>1||this._zooming&&Math.abs(this._zoomPosition-a)>1)&&(this._zoomPosition=a,this._zooming=!0,this.layout===t.Orientation.horizontal?(this._viewportEl.style.msScrollSnapType="none",r._zoomTo(this._viewportEl,{contentX:a,contentY:0,viewportX:0,viewportY:0})):r._zoomTo(this._viewportEl,{contentX:0,contentY:a,viewportX:0,viewportY:0}),this._closeSplitIfOpen())},_MSManipulationStateChangedHandler:function(a){this._currentManipulationState=a.currentState,a.currentState===a.MS_MANIPULATION_STATE_ACTIVE&&(this._viewportEl.style.msScrollSnapType="",this._zooming=!1),b.clearTimeout(this._manipulationStateTimeoutId),a.currentState===a.MS_MANIPULATION_STATE_STOPPED&&(this._manipulationStateTimeoutId=b.setTimeout(function(){this._viewportEl.style.msScrollSnapType="",this._zooming=!1,this._updateCurrentIndexIfPageChanged()}.bind(this),100))},_scrollHandler:function(){if(!this._disposed&&(this._measured=!1,!this._checkingScroll)){var a=this;this._checkingScroll=d._requestAnimationFrame(function(){if(!a._disposed){a._checkingScroll=null;var b=r.getScrollPosition(a._viewportEl)[a.layout===t.Orientation.horizontal?"scrollLeft":"scrollTop"];b!==a._scrollPosition&&(a._scrollPosition=b,a._closeSplitIfOpen()),a._updatePageUI(),a._zooming||a._currentManipulationState!==A||a._updateCurrentIndexIfPageChanged()}})}},_updateCurrentIndexIfPageChanged:function(){if(this.layout===t.Orientation.horizontal){this._measure();var a=this._currentPage,c=a*this._sizes.rowsPerPage*this._sizes.columnsPerPage,d=(a+1)*this._sizes.rowsPerPage*this._sizes.columnsPerPage-1;(this._keyboardBehavior.currentIndex<c||this._keyboardBehavior.currentIndex>d)&&(this._keyboardBehavior.currentIndex=c,this.element.contains(b.document.activeElement)&&this._keyboardBehavior._focus(this._keyboardBehavior.currentIndex))}},_measure:function(){if(!this._measured){this._resizeImpl(),this._writeProfilerMark("measure,StartTM");var a=this._sizes;a.rtl="rtl"===r._getComputedStyle(this._element).direction;var b=this._surfaceEl.children.length;if(b>0){if(!this._sizes.itemMeasured){this._writeProfilerMark("measureItem,StartTM");var c=this._surfaceEl.firstElementChild;c.style.margin="",c.style.width="";var d=r._getComputedStyle(c);a.itemOffsetWidth=parseFloat(r._getComputedStyle(c).width),0===c.offsetWidth&&(a.itemOffsetWidth=0),a.itemMarginLeft=parseFloat(d.marginLeft),a.itemMarginRight=parseFloat(d.marginRight),a.itemWidth=a.itemOffsetWidth+a.itemMarginLeft+a.itemMarginRight,a.itemOffsetHeight=parseFloat(r._getComputedStyle(c).height),0===c.offsetHeight&&(a.itemOffsetHeight=0),a.itemMarginTop=parseFloat(d.marginTop),a.itemMarginBottom=parseFloat(d.marginBottom),a.itemHeight=a.itemOffsetHeight+a.itemMarginTop+a.itemMarginBottom,a.itemOffsetWidth>0&&a.itemOffsetHeight>0&&(a.itemMeasured=!0),this._writeProfilerMark("measureItem,StopTM")}if(a.viewportOffsetWidth=parseFloat(r._getComputedStyle(this._viewportEl).width),0===this._viewportEl.offsetWidth&&(a.viewportOffsetWidth=0),a.viewportOffsetHeight=parseFloat(r._getComputedStyle(this._viewportEl).height),0===this._viewportEl.offsetHeight&&(a.viewportOffsetHeight=0),this._measured=0===a.viewportOffsetWidth||0===a.itemOffsetHeight?!1:!0,this.layout===t.Orientation.horizontal){this._scrollPosition=r.getScrollPosition(this._viewportEl).scrollLeft,a.leadingEdge=this._leftArrowEl.offsetWidth+parseInt(r._getComputedStyle(this._leftArrowEl).marginLeft)+parseInt(r._getComputedStyle(this._leftArrowEl).marginRight);var e=a.viewportOffsetWidth-2*a.leadingEdge;a.maxColumns=a.itemWidth?Math.max(1,Math.floor(e/a.itemWidth)):1,a.rowsPerPage=Math.min(this.maxRows,Math.ceil(b/a.maxColumns)),a.columnsPerPage=Math.min(a.maxColumns,b),a.pages=Math.ceil(b/(a.columnsPerPage*a.rowsPerPage)),a.trailingEdge=a.leadingEdge,a.extraSpace=e-a.columnsPerPage*a.itemWidth,this._scrollLength=a.viewportOffsetWidth*a.pages,this._keyboardBehavior.fixedSize=a.rowsPerPage,this._keyboardBehavior.fixedDirection=s._KeyboardBehavior.FixedDirection.height,this._surfaceEl.style.height=a.itemHeight*a.rowsPerPage+"px",this._surfaceEl.style.width=this._scrollLength+"px"}else this._scrollPosition=this._viewportEl.scrollTop,a.leadingEdge=0,a.rowsPerPage=b,a.columnsPerPage=1,a.pages=1,a.trailingEdge=0,this._scrollLength=this._viewportEl.scrollHeight,this._keyboardBehavior.fixedSize=a.columnsPerPage,this._keyboardBehavior.fixedDirection=s._KeyboardBehavior.FixedDirection.width,this._surfaceEl.style.height="",this._surfaceEl.style.width="";this._updateGridStyles()}else a.pages=1,this._hasPreviousContent=!1,this._hasNextContent=!1,this._surfaceEl.style.height="",this._surfaceEl.style.width="";this._writeProfilerMark("measure,StopTM")}},_updateGridStyles:function(){for(var a=this._sizes,b=this._surfaceEl.children.length,c=0;b>c;c++){var d,e,f=this._surfaceEl.children[c],g="";if(this.layout===t.Orientation.horizontal){var h=Math.floor(c/a.rowsPerPage),i=h%a.columnsPerPage===0,j=h%a.columnsPerPage===a.columnsPerPage-1,k=a.trailingEdge;if(this.fixedSize)k+=a.extraSpace;else{var l=a.extraSpace-(a.maxColumns-a.columnsPerPage)*a.itemWidth;g=a.itemOffsetWidth+l/a.maxColumns+"px"}var m,n;a.rtl?(m=i?a.leadingEdge:0,n=j?k:0):(m=j?k:0,n=i?a.leadingEdge:0),d=m+a.itemMarginRight+"px",e=n+a.itemMarginLeft+"px"}else d="",e="";f.style.marginRight!==d&&(f.style.marginRight=d),f.style.marginLeft!==e&&(f.style.marginLeft=e),f.style.width!==g&&(f.style.width=g)}},_updatePageUI:function(){this._measure();var a=this._currentPage;this._hasPreviousContent=0!==a,this._hasNextContent=a<this._sizes.pages-1,this._updateArrows(),this._indicatorCount!==this._sizes.pages&&(this._indicatorCount=this._sizes.pages,this._pageindicatorsEl.innerHTML=new Array(this._sizes.pages+1).join('<span class="'+E._ClassName.indicator+'"></span>'));for(var b=0;b<this._pageindicatorsEl.children.length;b++)b===a?r.addClass(this._pageindicatorsEl.children[b],E._ClassName.currentindicator):r.removeClass(this._pageindicatorsEl.children[b],E._ClassName.currentindicator);if(this._sizes.pages>1?(this._viewportEl.style.overflowX=this._panningDisabled?"hidden":"",this._pageindicatorsEl.style.visibility=""):(this._viewportEl.style.overflowX="hidden",this._pageindicatorsEl.style.visibility="hidden"),this._sizes.pages<=1||this._layout!==t.Orientation.horizontal)this._ariaStartMarker.removeAttribute("aria-flowto"),this._ariaEndMarker.removeAttribute("x-ms-aria-flowfrom");else{var c=a*this._sizes.rowsPerPage*this._sizes.columnsPerPage,d=this._surfaceEl.children[c].winControl._buttonEl;r._ensureId(d),this._ariaStartMarker.setAttribute("aria-flowto",d.id);var e=Math.min(this._surfaceEl.children.length-1,(a+1)*this._sizes.rowsPerPage*this._sizes.columnsPerPage-1),f=this._surfaceEl.children[e].winControl._buttonEl;r._ensureId(f),this._ariaEndMarker.setAttribute("x-ms-aria-flowfrom",f.id)}},_closeSplitIfOpen:function(){this._currentSplitNavItem&&(this._currentSplitNavItem.splitOpened&&this._currentSplitNavItem._toggleSplit(),this._currentSplitNavItem=null)},_updateArrows:function(){var a=this._sizes.rtl?this._hasNextContent:this._hasPreviousContent,b=this._sizes.rtl?this._hasPreviousContent:this._hasNextContent,c=this;(this._mouseInViewport||this._panningDisabled)&&a?(this._leftArrowWaitingToFadeOut&&this._leftArrowWaitingToFadeOut.cancel(),this._leftArrowWaitingToFadeOut=null,this._leftArrowFadeOut&&this._leftArrowFadeOut.cancel(),this._leftArrowFadeOut=null,this._leftArrowEl.style.visibility="",this._leftArrowFadeIn=this._leftArrowFadeIn||j.fadeIn(this._leftArrowEl)):(a?this._leftArrowWaitingToFadeOut=this._leftArrowWaitingToFadeOut||o.timeout(k._animationTimeAdjustment(y)):(this._leftArrowWaitingToFadeOut&&this._leftArrowWaitingToFadeOut.cancel(),this._leftArrowWaitingToFadeOut=o.wrap()),this._leftArrowWaitingToFadeOut.then(function(){this._leftArrowFadeIn&&this._leftArrowFadeIn.cancel(),this._leftArrowFadeIn=null,this._leftArrowFadeOut=this._leftArrowFadeOut||j.fadeOut(this._leftArrowEl).then(function(){c._leftArrowEl.style.visibility="hidden"})}.bind(this))),(this._mouseInViewport||this._panningDisabled)&&b?(this._rightArrowWaitingToFadeOut&&this._rightArrowWaitingToFadeOut.cancel(),this._rightArrowWaitingToFadeOut=null,this._rightArrowFadeOut&&this._rightArrowFadeOut.cancel(),this._rightArrowFadeOut=null,this._rightArrowEl.style.visibility="",this._rightArrowFadeIn=this._rightArrowFadeIn||j.fadeIn(this._rightArrowEl)):(b?this._rightArrowWaitingToFadeOut=this._rightArrowWaitingToFadeOut||o.timeout(k._animationTimeAdjustment(y)):(this._rightArrowWaitingToFadeOut&&this._rightArrowWaitingToFadeOut.cancel(),this._rightArrowWaitingToFadeOut=o.wrap()),this._rightArrowWaitingToFadeOut.then(function(){this._rightArrowFadeIn&&this._rightArrowFadeIn.cancel(),this._rightArrowFadeIn=null,this._rightArrowFadeOut=this._rightArrowFadeOut||j.fadeOut(this._rightArrowEl).then(function(){c._rightArrowEl.style.visibility="hidden"})}.bind(this)))},_navbarCommandInvokedHandler:function(a){for(var b=a.target,c=-1;b;)c++,b=b.previousSibling;this._fireEvent(E._EventName.invoked,{index:c,navbarCommand:a.target.winControl,data:this._repeater?this._repeater.data.getAt(c):null})},_navbarCommandSplitToggleHandler:function(a){for(var b=a.target,c=-1;b;)c++,b=b.previousSibling;var d=a.target.winControl;this._closeSplitIfOpen(),d.splitOpened&&(this._currentSplitNavItem=d),this._fireEvent(E._EventName.splitToggle,{opened:d.splitOpened,index:c,navbarCommand:d,data:this._repeater?this._repeater.data.getAt(c):null})},_fireEvent:function(a,c){var d=b.document.createEvent("CustomEvent");d.initCustomEvent(a,!0,!1,c),this.element.dispatchEvent(d)},_writeProfilerMark:function(a){var b="WinJS.UI.NavBarContainer:"+this._id+":"+a;i(b),g.log&&g.log(b,null,"navbarcontainerprofiler")},dispose:function(){this._disposed||(this._disposed=!0,this._appBarEl&&(this._appBarEl.removeEventListener("beforeopen",this._closeSplitAndResetBound),this._appBarEl.removeEventListener("beforeopen",this._resizeImplBound)),n.removeEventListener("navigated",this._closeSplitAndResetBound),this._leftArrowWaitingToFadeOut&&this._leftArrowWaitingToFadeOut.cancel(),this._leftArrowFadeOut&&this._leftArrowFadeOut.cancel(),this._leftArrowFadeIn&&this._leftArrowFadeIn.cancel(),this._rightArrowWaitingToFadeOut&&this._rightArrowWaitingToFadeOut.cancel(),this._rightArrowFadeOut&&this._rightArrowFadeOut.cancel(),this._rightArrowFadeIn&&this._rightArrowFadeIn.cancel(),r._resizeNotifier.unsubscribe(this._element,this._boundResizeHandler),this._removeDataChangingEvents(),this._removeDataChangedEvents())}},{_ClassName:{navbarcontainer:"win-navbarcontainer",pageindicators:"win-navbarcontainer-pageindicator-box",indicator:"win-navbarcontainer-pageindicator",currentindicator:"win-navbarcontainer-pageindicator-current",vertical:"win-navbarcontainer-vertical",horizontal:"win-navbarcontainer-horizontal",viewport:"win-navbarcontainer-viewport",surface:"win-navbarcontainer-surface",navarrow:"win-navbarcontainer-navarrow",navleftarrow:"win-navbarcontainer-navleft",navrightarrow:"win-navbarcontainer-navright"},_EventName:{invoked:C.invoked,splitToggle:C.splittoggle}});return c.Class.mix(E,q.DOMEventMixin),E})})}),d("require-style!less/styles-navbar",[],function(){}),d("require-style!less/colors-navbar",[],function(){}),d("WinJS/Controls/NavBar",["../Core/_Global","../Core/_WinRT","../Core/_Base","../Core/_BaseUtils","../Core/_Events","../Core/_WriteProfilerMark","../Promise","../Scheduler","../Utilities/_ElementUtilities","../Utilities/_Hoverable","../_Accents","./_LegacyAppBar","./NavBar/_Command","./NavBar/_Container","require-style!less/styles-navbar","require-style!less/colors-navbar"],function(a,b,c,d,e,f,g,h,i,j,k,l){"use strict";k.createAccentRule("html.win-hoverable .win-navbarcommand-splitbutton.win-navbarcommand-splitbutton-opened:hover",[{name:"background-color",value:k.ColorTypes.listSelectHover}]),k.createAccentRule("html.win-hoverable .win-navbarcommand-splitbutton.win-navbarcommand-splitbutton-opened:hover.win-pressed",[{name:"background-color",value:k.ColorTypes.listSelectPress}]),k.createAccentRule(".win-navbarcommand-splitbutton.win-navbarcommand-splitbutton-opened",[{name:"background-color",value:k.ColorTypes.listSelectRest}]),k.createAccentRule(".win-navbarcommand-splitbutton.win-navbarcommand-splitbutton-opened.win-pressed",[{name:"background-color",value:k.ColorTypes.listSelectPress}]);var m="custom";c.Namespace.define("WinJS.UI",{NavBar:c.Namespace._lazy(function(){var j="childrenprocessed",k=e._createEventProperty,n=c.Class.derive(l._LegacyAppBar,function(a,c){i._deprecated(o.navBarIsDeprecated),c=c||{},c=d._shallowCopy(c),c.placement=c.placement||"top",c.layout=m,c.closedDisplayMode=c.closedDisplayMode||"minimal",l._LegacyAppBar.call(this,a,c),this._element.addEventListener("beforeopen",this._handleBeforeShow.bind(this)),i.addClass(this.element,n._ClassName.navbar),b.Windows.ApplicationModel.DesignMode.designModeEnabled?this._processChildren():h.schedule(this._processChildren.bind(this),h.Priority.idle,null,"WinJS.UI.NavBar.processChildren")},{closedDisplayMode:{get:function(){return this._closedDisplayMode},set:function(a){var b="none"===a?"none":"minimal";Object.getOwnPropertyDescriptor(l._LegacyAppBar.prototype,"closedDisplayMode").set.call(this,b),this._closedDisplayMode=b}},onchildrenprocessed:k(j),_processChildren:function(){if(!this._processed){this._processed=!0,this._writeProfilerMark("processChildren,StartTM");var a=this,b=g.as();return this._processors&&this._processors.forEach(function(c){for(var d=0,e=a.element.children.length;e>d;d++)!function(a){b=b.then(function(){c(a)})}(a.element.children[d])}),b.then(function(){a._writeProfilerMark("processChildren,StopTM"),a._fireEvent(n._EventName.childrenProcessed)},function(){a._writeProfilerMark("processChildren,StopTM"),a._fireEvent(n._EventName.childrenProcessed)})}return g.wrap()},_show:function(){if(!this.disabled){var a=this;this._processChildren().then(function(){l._LegacyAppBar.prototype._show.call(a)})}},_handleBeforeShow:function(){if(!this._disposed)for(var a=this.element.querySelectorAll(".win-navbarcontainer"),b=0;b<a.length;b++)a[b].winControl.forceLayout()},_fireEvent:function(b,c){var d=a.document.createEvent("CustomEvent");d.initCustomEvent(b,!0,!1,c||{}),this.element.dispatchEvent(d)},_writeProfilerMark:function(a){f("WinJS.UI.NavBar:"+this._id+":"+a)}},{_ClassName:{navbar:"win-navbar"},_EventName:{childrenProcessed:j},isDeclarativeControlContainer:d.markSupportedForProcessing(function(a,b){if(a._processed)for(var c=0,d=a.element.children.length;d>c;c++)b(a.element.children[c]);else a._processors=a._processors||[],a._processors.push(b)})}),o={get navBarIsDeprecated(){return"NavBar is deprecated and may not be available in future releases. Instead, use a WinJS SplitView to display navigation targets within the app."}};return n})})}),d("require-style!less/styles-viewbox",[],function(){}),d("WinJS/Controls/ViewBox",["../Core/_Global","../Core/_Base","../Core/_BaseUtils","../Core/_ErrorFromName","../Core/_Resources","../Scheduler","../Utilities/_Control","../Utilities/_Dispose","../Utilities/_ElementUtilities","../Utilities/_Hoverable","require-style!less/styles-viewbox"],function(a,b,c,d,e,f,g,h,i){"use strict";b.Namespace.define("WinJS.UI",{ViewBox:b.Namespace._lazy(function(){function e(a){if(a&&!a._resizing){a._resizing=a._resizing||0,a._resizing++;try{a._updateLayout()}finally{a._resizing--}}}function j(a){a.target&&e(a.target.winControl)}function k(a){a.target&&e(a.target.parentElement.winControl)}var l={get invalidViewBoxChildren(){return"ViewBox expects to only have one child element"}},m=b.Class.define(function(b){this._disposed=!1,this._element=b||a.document.createElement("div");var c=this.element;c.winControl=this,i.addClass(c,"win-disposable"),i.addClass(c,"win-viewbox"),this.forceLayout()},{_sizer:null,_element:null,element:{get:function(){return this._element}},_rtl:{get:function(){return"rtl"===i._getComputedStyle(this.element).direction}},_initialize:function(){var a=this.element;if(a.firstElementChild!==this._sizer){if(c.validation&&1!==a.childElementCount)throw new d("WinJS.UI.ViewBox.InvalidChildren",l.invalidViewBoxChildren);this._sizer&&(this._sizer.onresize=null);var b=a.firstElementChild;if(this._sizer=b,b&&(i._resizeNotifier.subscribe(a,j),a.addEventListener("mselementresize",j),i._resizeNotifier.subscribe(b,k),b.addEventListener("mselementresize",k)),0===a.clientWidth&&0===a.clientHeight){var e=this;f.schedule(function(){e._updateLayout()},f.Priority.normal,null,"WinJS.UI.ViewBox._updateLayout")}}},_updateLayout:function(){var a=this._sizer;if(a){var b=this.element,d=a.clientWidth,e=a.clientHeight,f=b.clientWidth,g=b.clientHeight,h=f/d,i=g/e,j=Math.min(h,i),k=Math.abs(f-d*j)/2,l=Math.abs(g-e*j)/2,m=this._rtl;this._sizer.style[c._browserStyleEquivalents.transform.scriptName]="translate("+(m?"-":"")+k+"px,"+l+"px) scale("+j+")",this._sizer.style[c._browserStyleEquivalents["transform-origin"].scriptName]=m?"top right":"top left"}},dispose:function(){this._disposed||(this.element&&i._resizeNotifier.unsubscribe(this.element,j),this._sizer&&i._resizeNotifier.unsubscribe(this._sizer,k),this._disposed=!0,h.disposeSubTree(this._element))},forceLayout:function(){this._initialize(),this._updateLayout()}});return b.Class.mix(m,g.DOMEventMixin),m})})}),d("require-style!less/styles-contentdialog",[],function(){}),d("require-style!less/colors-contentdialog",[],function(){}),d("WinJS/Controls/ContentDialog",["../Application","../Utilities/_Dispose","../_Accents","../Promise","../_Signal","../_LightDismissService","../Core/_BaseUtils","../Core/_Global","../Core/_WinRT","../Core/_Base","../Core/_Events","../Core/_ErrorFromName","../Core/_Resources","../Utilities/_Control","../Utilities/_ElementUtilities","../Utilities/_KeyboardInfo","../Utilities/_Hoverable","../Animations","require-style!less/styles-contentdialog","require-style!less/colors-contentdialog"],function(a,b,c,d,e,f,g,h,i,j,k,l,m,n,o,p,q,r){"use strict";c.createAccentRule(".win-contentdialog-dialog",[{name:"outline-color",value:c.ColorTypes.accent}]),j.Namespace.define("WinJS.UI",{ContentDialog:j.Namespace._lazy(function(){function a(){if("undefined"==typeof u){var a=h.document.createElement("div");a.style.position="-ms-device-fixed",u="-ms-device-fixed"===o._getComputedStyle(a).position}return u}function c(a){return d._cancelBlocker(a,function(){a.cancel()})}function i(a){a.ensuredFocusedElementInView=!0,this.dialog._renderForInputPane(a.occludedRect.height)}function m(){this.dialog._clearInputPaneRendering()}function q(){}function s(a,b){a._interruptibleWorkPromises=a._interruptibleWorkPromises||[];var c=new e;a._interruptibleWorkPromises.push(b(a,c.promise)),c.complete()}function t(){(this._interruptibleWorkPromises||[]).forEach(function(a){a.cancel()})}var u,v={get duplicateConstruction(){return"Invalid argument: Controls may only be instantiated one time for each DOM element"},get controlDisposed(){return"Cannot interact with the control after it has been disposed"},get contentDialogAlreadyShowing(){return"Cannot show a ContentDialog if there is already a ContentDialog that is showing"}},w={none:"none",primary:"primary",secondary:"secondary"},x={contentDialog:"win-contentdialog",backgroundOverlay:"win-contentdialog-backgroundoverlay",dialog:"win-contentdialog-dialog",title:"win-contentdialog-title",content:"win-contentdialog-content",commands:"win-contentdialog-commands",primaryCommand:"win-contentdialog-primarycommand",secondaryCommand:"win-contentdialog-secondarycommand",_verticalAlignment:"win-contentdialog-verticalalignment",_scroller:"win-contentdialog-scroller",_column0or1:"win-contentdialog-column0or1",_visible:"win-contentdialog-visible",_tabStop:"win-contentdialog-tabstop",_commandSpacer:"win-contentdialog-commandspacer",_deviceFixedSupported:"win-contentdialog-devicefixedsupported"},y={beforeShow:"beforeshow",afterShow:"aftershow",beforeHide:"beforehide",afterHide:"afterhide"},z={Init:j.Class.define(null,{name:"Init",hidden:!0,enter:function(){var a=this.dialog;a._dismissable=new f.ModalElement({element:a._dom.root,tabIndex:a._dom.root.hasAttribute("tabIndex")?a._dom.root.tabIndex:-1,onLightDismiss:function(){a.hide(w.none)},onTakeFocus:function(b){a._dismissable.restoreFocus()||o._tryFocusOnAnyElement(a._dom.dialog,b)}}),this.dialog._dismissedSignal=null,this.dialog._setState(z.Hidden,!1)},exit:q,show:function(){throw"It's illegal to call show on the Init state"},hide:q,onCommandClicked:q,onInputPaneShown:q,onInputPaneHidden:q}),Hidden:j.Class.define(null,{name:"Hidden",hidden:!0,enter:function(a){a&&this.show()},exit:q,show:function(){var a=this.dialog._dismissedSignal=new e;return this.dialog._setState(z.BeforeShow),a.promise},hide:q,onCommandClicked:q,onInputPaneShown:q,onInputPaneHidden:q}),BeforeShow:j.Class.define(null,{name:"BeforeShow",hidden:!0,enter:function(){s(this,function(a,b){return b.then(function(){return a.dialog._fireBeforeShow()}).then(function(b){return b||a.dialog._cancelDismissalPromise(null),b}).then(function(b){b?a.dialog._setState(z.Showing):a.dialog._setState(z.Hidden,!1)})})},exit:t,show:function(){return d.wrapError(new l("WinJS.UI.ContentDialog.ContentDialogAlreadyShowing",v.contentDialogAlreadyShowing))},hide:q,onCommandClicked:q,onInputPaneShown:q,onInputPaneHidden:q}),Showing:j.Class.define(null,{name:"Showing",hidden:{get:function(){return!!this._pendingHide}},enter:function(){s(this,function(a,b){return b.then(function(){return a._pendingHide=null,o.addClass(a.dialog._dom.root,x._visible),a.dialog._addExternalListeners(),p._KeyboardInfo._visible&&a.dialog._renderForInputPane(),f.shown(a.dialog._dismissable),a.dialog._playEntranceAnimation()}).then(function(){a.dialog._fireEvent(y.afterShow)}).then(function(){a.dialog._setState(z.Shown,a._pendingHide)})})},exit:t,show:function(){if(this._pendingHide){var a=this._pendingHide.dismissalResult;return this._pendingHide=null,this.dialog._resetDismissalPromise(a,new e).promise}return d.wrapError(new l("WinJS.UI.ContentDialog.ContentDialogAlreadyShowing",v.contentDialogAlreadyShowing))},hide:function(a){this._pendingHide={dismissalResult:a}},onCommandClicked:q,onInputPaneShown:i,onInputPaneHidden:m}),Shown:j.Class.define(null,{name:"Shown",hidden:!1,enter:function(a){a&&this.hide(a.dismissalResult)},exit:q,show:function(){return d.wrapError(new l("WinJS.UI.ContentDialog.ContentDialogAlreadyShowing",v.contentDialogAlreadyShowing))},hide:function(a){this.dialog._setState(z.BeforeHide,a)},onCommandClicked:function(a){this.hide(a)},onInputPaneShown:i,onInputPaneHidden:m}),BeforeHide:j.Class.define(null,{name:"BeforeHide",hidden:!1,enter:function(a){s(this,function(b,c){return c.then(function(){return b.dialog._fireBeforeHide(a)}).then(function(c){c?b.dialog._setState(z.Hiding,a):b.dialog._setState(z.Shown,null)})})},exit:t,show:function(){return d.wrapError(new l("WinJS.UI.ContentDialog.ContentDialogAlreadyShowing",v.contentDialogAlreadyShowing))},hide:q,onCommandClicked:q,onInputPaneShown:i,onInputPaneHidden:m}),Hiding:j.Class.define(null,{name:"Hiding",hidden:{get:function(){return!this._showIsPending}},enter:function(a){s(this,function(b,c){return c.then(function(){b._showIsPending=!1,b.dialog._resetDismissalPromise(a,null)}).then(function(){return b.dialog._playExitAnimation()}).then(function(){b.dialog._removeExternalListeners(),f.hidden(b.dialog._dismissable),o.removeClass(b.dialog._dom.root,x._visible),b.dialog._clearInputPaneRendering(),b.dialog._fireAfterHide(a)}).then(function(){b.dialog._setState(z.Hidden,b._showIsPending)})})},exit:t,show:function(){return this._showIsPending?d.wrapError(new l("WinJS.UI.ContentDialog.ContentDialogAlreadyShowing",v.contentDialogAlreadyShowing)):(this._showIsPending=!0,this.dialog._dismissedSignal=new e,this.dialog._dismissedSignal.promise)},hide:function(a){this._showIsPending&&(this._showIsPending=!1,this.dialog._resetDismissalPromise(a,null))},onCommandClicked:q,onInputPaneShown:q,onInputPaneHidden:q}),Disposed:j.Class.define(null,{name:"Disposed",hidden:!0,enter:function(){f.hidden(this.dialog._dismissable),this.dialog._removeExternalListeners(),this.dialog._dismissedSignal&&this.dialog._dismissedSignal.error(new l("WinJS.UI.ContentDialog.ControlDisposed",v.controlDisposed))},exit:q,show:function(){return d.wrapError(new l("WinJS.UI.ContentDialog.ControlDisposed",v.controlDisposed))},hide:q,onCommandClicked:q,onInputPaneShown:q,onInputPaneHidden:q})},A=j.Class.define(function(a,b){if(a&&a.winControl)throw new l("WinJS.UI.ContentDialog.DuplicateConstruction",v.duplicateConstruction);b=b||{},this._onInputPaneShownBound=this._onInputPaneShown.bind(this),this._onInputPaneHiddenBound=this._onInputPaneHidden.bind(this),this._onUpdateInputPaneRenderingBound=this._onUpdateInputPaneRendering.bind(this),this._disposed=!1,this._currentFocus=null,this._rendered={registeredForResize:!1,resizedForInputPane:!1,top:"",bottom:""},this._initializeDom(a||h.document.createElement("div")),this._setState(z.Init),this.title="",this.primaryCommandText="",this.primaryCommandDisabled=!1,this.secondaryCommandText="",this.secondaryCommandDisabled=!1,n.setOptions(this,b)},{element:{get:function(){return this._dom.root}},title:{get:function(){return this._title},set:function(a){a=a||"",this._title!==a&&(this._title=a,this._dom.title.textContent=a,this._dom.title.style.display=a?"":"none")}},primaryCommandText:{get:function(){return this._primaryCommandText},set:function(a){a=a||"",this._primaryCommandText!==a&&(this._primaryCommandText=a,this._dom.commands[0].textContent=a,this._updateCommandsUI())}},secondaryCommandText:{get:function(){return this._secondaryCommandText},set:function(a){a=a||"",this._secondaryCommandText!==a&&(this._secondaryCommandText=a,this._dom.commands[1].textContent=a,this._updateCommandsUI())}},primaryCommandDisabled:{get:function(){return this._primaryCommandDisabled},set:function(a){a=!!a,this._primaryCommandDisabled!==a&&(this._primaryCommandDisabled=a,this._dom.commands[0].disabled=a)}},secondaryCommandDisabled:{get:function(){return this._secondaryCommandDisabled},set:function(a){a=!!a,this._secondaryCommandDisabled!==a&&(this._secondaryCommandDisabled=a,this._dom.commands[1].disabled=a)}},hidden:{get:function(){return this._state.hidden},set:function(a){if(!a&&this._state.hidden){var b=function(){};this.show().done(b,b)}else a&&!this._state.hidden&&this.hide(w.none)}},dispose:function(){this._disposed||(this._setState(z.Disposed),this._disposed=!0,o._resizeNotifier.unsubscribe(this._dom.root,this._onUpdateInputPaneRenderingBound),b._disposeElement(this._dom.content))},show:function(){return this._state.show()},hide:function(a){this._state.hide(void 0===a?w.none:a)},_initializeDom:function(b){var c=h.document.createElement("div");c.className=x.content,o._reparentChildren(b,c),b.winControl=this,o.addClass(b,x.contentDialog),o.addClass(b,x._verticalAlignment),o.addClass(b,"win-disposable"),b.innerHTML='<div class="'+x.backgroundOverlay+'"></div><div class="'+x._tabStop+'"></div><div tabindex="-1" role="dialog" class="'+x.dialog+'"><h2 class="'+x.title+'" role="heading"></h2><div class="'+x._scroller+'"></div><div class="'+x.commands+'"><button type="button" class="'+x._commandSpacer+' win-button"></button><button type="button" class="'+x.primaryCommand+' win-button"></button><button type="button" class="'+x.secondaryCommand+' win-button"></button></div></div><div class="'+x._tabStop+'"></div><div class="'+x._column0or1+'"></div>';var d={};d.root=b,d.backgroundOverlay=d.root.firstElementChild,d.startBodyTab=d.backgroundOverlay.nextElementSibling,d.dialog=d.startBodyTab.nextElementSibling,d.title=d.dialog.firstElementChild,d.scroller=d.title.nextElementSibling,d.commandContainer=d.scroller.nextElementSibling,d.commandSpacer=d.commandContainer.firstElementChild,d.commands=[],d.commands.push(d.commandSpacer.nextElementSibling),d.commands.push(d.commands[0].nextElementSibling),d.endBodyTab=d.dialog.nextElementSibling,d.content=c,this._dom=d,d.scroller.appendChild(d.content),o._ensureId(d.title),o._ensureId(d.startBodyTab),o._ensureId(d.endBodyTab),d.dialog.setAttribute("aria-labelledby",d.title.id),d.startBodyTab.setAttribute("x-ms-aria-flowfrom",d.endBodyTab.id),d.endBodyTab.setAttribute("aria-flowto",d.startBodyTab.id),this._updateTabIndices(),d.root.addEventListener("keydown",this._onKeyDownEnteringElement.bind(this),!0),o._addEventListener(d.root,"pointerdown",this._onPointerDown.bind(this)),o._addEventListener(d.root,"pointerup",this._onPointerUp.bind(this)),d.root.addEventListener("click",this._onClick.bind(this)),o._addEventListener(d.startBodyTab,"focusin",this._onStartBodyTabFocusIn.bind(this)),o._addEventListener(d.endBodyTab,"focusin",this._onEndBodyTabFocusIn.bind(this)),d.commands[0].addEventListener("click",this._onCommandClicked.bind(this,w.primary)),d.commands[1].addEventListener("click",this._onCommandClicked.bind(this,w.secondary)),a()&&o.addClass(d.root,x._deviceFixedSupported)},_updateCommandsUI:function(){this._dom.commands[0].style.display=this.primaryCommandText?"":"none",this._dom.commands[1].style.display=this.secondaryCommandText?"":"none",this._dom.commandSpacer.style.display=this.primaryCommandText&&!this.secondaryCommandText||!this.primaryCommandText&&this.secondaryCommandText?"":"none"},_updateTabIndices:function(){this._updateTabIndicesThrottled||(this._updateTabIndicesThrottled=g._throttledFunction(100,this._updateTabIndicesImpl.bind(this))),this._updateTabIndicesThrottled()},_updateTabIndicesImpl:function(){var a=o._getHighAndLowTabIndices(this._dom.content);this._dom.startBodyTab.tabIndex=a.lowest,this._dom.commands[0].tabIndex=a.highest,this._dom.commands[1].tabIndex=a.highest,this._dom.endBodyTab.tabIndex=a.highest},_elementInDialog:function(a){return this._dom.dialog.contains(a)||a===this._dom.startBodyTab||a===this._dom.endBodyTab},_onCommandClicked:function(a){this._state.onCommandClicked(a)},_onPointerDown:function(a){a.stopPropagation(),this._elementInDialog(a.target)||a.preventDefault()},_onPointerUp:function(a){a.stopPropagation(),this._elementInDialog(a.target)||a.preventDefault()},_onClick:function(a){a.stopPropagation(),this._elementInDialog(a.target)||a.preventDefault()},_onKeyDownEnteringElement:function(a){a.keyCode===o.Key.tab&&this._updateTabIndices()},_onStartBodyTabFocusIn:function(){o._focusLastFocusableElement(this._dom.dialog)},_onEndBodyTabFocusIn:function(){o._focusFirstFocusableElement(this._dom.dialog)},_onInputPaneShown:function(a){this._state.onInputPaneShown(a.detail.originalEvent) },_onInputPaneHidden:function(){this._state.onInputPaneHidden()},_onUpdateInputPaneRendering:function(){this._renderForInputPane()},_setState:function(a,b){this._disposed||(this._state&&this._state.exit(),this._state=new a,this._state.dialog=this,this._state.enter(b))},_resetDismissalPromise:function(a,b){var c=this._dismissedSignal,d=this._dismissedSignal=b;return c.complete({result:a}),d},_cancelDismissalPromise:function(a){var b=this._dismissedSignal,c=this._dismissedSignal=a;return b.cancel(),c},_fireEvent:function(a,b){b=b||{};var c=b.detail||null,d=!!b.cancelable,e=h.document.createEvent("CustomEvent");return e.initCustomEvent(a,!0,d,c),this._dom.root.dispatchEvent(e)},_fireBeforeShow:function(){return this._fireEvent(y.beforeShow,{cancelable:!0})},_fireBeforeHide:function(a){return this._fireEvent(y.beforeHide,{detail:{result:a},cancelable:!0})},_fireAfterHide:function(a){this._fireEvent(y.afterHide,{detail:{result:a}})},_playEntranceAnimation:function(){return c(r.fadeIn(this._dom.root))},_playExitAnimation:function(){return c(r.fadeOut(this._dom.root))},_addExternalListeners:function(){o._inputPaneListener.addEventListener(this._dom.root,"showing",this._onInputPaneShownBound),o._inputPaneListener.addEventListener(this._dom.root,"hiding",this._onInputPaneHiddenBound)},_removeExternalListeners:function(){o._inputPaneListener.removeEventListener(this._dom.root,"showing",this._onInputPaneShownBound),o._inputPaneListener.removeEventListener(this._dom.root,"hiding",this._onInputPaneHiddenBound)},_shouldResizeForInputPane:function(){if(this._rendered.resizedForInputPane)return!0;var a=this._dom.dialog.getBoundingClientRect(),b=p._KeyboardInfo._visibleDocTop>a.top||p._KeyboardInfo._visibleDocBottom<a.bottom;return b},_renderForInputPane:function(){var a=this._rendered;if(a.registeredForResize||(o._resizeNotifier.subscribe(this._dom.root,this._onUpdateInputPaneRenderingBound),a.registeredForResize=!0),this._shouldResizeForInputPane()){var b=p._KeyboardInfo._visibleDocTop+"px",c=p._KeyboardInfo._visibleDocBottomOffset+"px";if(a.top!==b&&(this._dom.root.style.top=b,a.top=b),a.bottom!==c&&(this._dom.root.style.bottom=c,a.bottom=c),!a.resizedForInputPane){this._dom.scroller.insertBefore(this._dom.title,this._dom.content),this._dom.root.style.height="auto";var d=h.document.activeElement;d&&this._dom.scroller.contains(d)&&d.scrollIntoView(),a.resizedForInputPane=!0}}},_clearInputPaneRendering:function(){var a=this._rendered;a.registeredForResize&&(o._resizeNotifier.unsubscribe(this._dom.root,this._onUpdateInputPaneRenderingBound),a.registeredForResize=!1),""!==a.top&&(this._dom.root.style.top="",a.top=""),""!==a.bottom&&(this._dom.root.style.bottom="",a.bottom=""),a.resizedForInputPane&&(this._dom.dialog.insertBefore(this._dom.title,this._dom.scroller),this._dom.root.style.height="",a.resizedForInputPane=!1)}},{DismissalResult:w,_ClassNames:x});return j.Class.mix(A,k.createEventProperties("beforeshow","aftershow","beforehide","afterhide")),j.Class.mix(A,n.DOMEventMixin),A})})}),d("require-style!less/styles-splitview",[],function(){}),d("require-style!less/colors-splitview",[],function(){}),d("WinJS/Controls/SplitView/_SplitView",["require","exports","../../Animations","../../Core/_Base","../../Core/_BaseUtils","../../Utilities/_Control","../../Utilities/_Dispose","../../Utilities/_ElementUtilities","../../Core/_ErrorFromName","../../Core/_Events","../../Core/_Global","../../_LightDismissService","../../Utilities/_OpenCloseMachine"],function(a,b,c,d,e,f,g,h,i,j,k,l,m){function n(a,b){b&&h.addClass(a,b)}function o(a,b){b&&h.removeClass(a,b)}function p(a,b){return b===u.width?{content:a.contentWidth,total:a.totalWidth}:{content:a.contentHeight,total:a.totalHeight}}a(["require-style!less/styles-splitview"]),a(["require-style!less/colors-splitview"]);var q=e._browserStyleEquivalents.transform,r={get duplicateConstruction(){return"Invalid argument: Controls may only be instantiated one time for each DOM element"}},s={splitView:"win-splitview",pane:"win-splitview-pane",content:"win-splitview-content",paneClosed:"win-splitview-pane-closed",paneOpened:"win-splitview-pane-opened",_panePlaceholder:"win-splitview-paneplaceholder",_paneOutline:"win-splitview-paneoutline",_paneWrapper:"win-splitview-panewrapper",_contentWrapper:"win-splitview-contentwrapper",_animating:"win-splitview-animating",_placementLeft:"win-splitview-placementleft",_placementRight:"win-splitview-placementright",_placementTop:"win-splitview-placementtop",_placementBottom:"win-splitview-placementbottom",_closedDisplayNone:"win-splitview-closeddisplaynone",_closedDisplayInline:"win-splitview-closeddisplayinline",_openedDisplayInline:"win-splitview-openeddisplayinline",_openedDisplayOverlay:"win-splitview-openeddisplayoverlay"},t={beforeOpen:"beforeopen",afterOpen:"afteropen",beforeClose:"beforeclose",afterClose:"afterclose"},u={width:"width",height:"height"},v={none:"none",inline:"inline"},w={inline:"inline",overlay:"overlay"},x={left:"left",right:"right",top:"top",bottom:"bottom"},y={};y[v.none]=s._closedDisplayNone,y[v.inline]=s._closedDisplayInline;var z={};z[w.overlay]=s._openedDisplayOverlay,z[w.inline]=s._openedDisplayInline;var A={};A[x.left]=s._placementLeft,A[x.right]=s._placementRight,A[x.top]=s._placementTop,A[x.bottom]=s._placementBottom;var B=function(){function a(a,b){var c=this;if(void 0===b&&(b={}),this._updateDomImpl_rendered={paneIsFirst:void 0,isOpenedMode:void 0,closedDisplayMode:void 0,openedDisplayMode:void 0,panePlacement:void 0,panePlaceholderWidth:void 0,panePlaceholderHeight:void 0,isOverlayShown:void 0},a&&a.winControl)throw new i("WinJS.UI.SplitView.DuplicateConstruction",r.duplicateConstruction);this._initializeDom(a||k.document.createElement("div")),this._machine=new m.OpenCloseMachine({eventElement:this._dom.root,onOpen:function(){c._cachedHiddenPaneThickness=null;var a=c._getHiddenPaneThickness();return c._isOpenedMode=!0,c._updateDomImpl(),h.addClass(c._dom.root,s._animating),c._playShowAnimation(a).then(function(){h.removeClass(c._dom.root,s._animating)})},onClose:function(){return h.addClass(c._dom.root,s._animating),c._playHideAnimation(c._getHiddenPaneThickness()).then(function(){h.removeClass(c._dom.root,s._animating),c._isOpenedMode=!1,c._updateDomImpl()})},onUpdateDom:function(){c._updateDomImpl()},onUpdateDomWithIsOpened:function(a){c._isOpenedMode=a,c._updateDomImpl()}}),this._disposed=!1,this._dismissable=new l.LightDismissableElement({element:this._dom.paneWrapper,tabIndex:-1,onLightDismiss:function(){c.closePane()},onTakeFocus:function(a){c._dismissable.restoreFocus()||h._tryFocusOnAnyElement(c._dom.pane,a)}}),this._cachedHiddenPaneThickness=null,this.paneOpened=!1,this.closedDisplayMode=v.inline,this.openedDisplayMode=w.overlay,this.panePlacement=x.left,f.setOptions(this,b),h._inDom(this._dom.root).then(function(){c._rtl="rtl"===h._getComputedStyle(c._dom.root).direction,c._machine.exitInit()})}return Object.defineProperty(a.prototype,"element",{get:function(){return this._dom.root},enumerable:!0,configurable:!0}),Object.defineProperty(a.prototype,"paneElement",{get:function(){return this._dom.pane},enumerable:!0,configurable:!0}),Object.defineProperty(a.prototype,"contentElement",{get:function(){return this._dom.content},enumerable:!0,configurable:!0}),Object.defineProperty(a.prototype,"closedDisplayMode",{get:function(){return this._closedDisplayMode},set:function(a){v[a]&&this._closedDisplayMode!==a&&(this._closedDisplayMode=a,this._cachedHiddenPaneThickness=null,this._machine.updateDom())},enumerable:!0,configurable:!0}),Object.defineProperty(a.prototype,"openedDisplayMode",{get:function(){return this._openedDisplayMode},set:function(a){w[a]&&this._openedDisplayMode!==a&&(this._openedDisplayMode=a,this._cachedHiddenPaneThickness=null,this._machine.updateDom())},enumerable:!0,configurable:!0}),Object.defineProperty(a.prototype,"panePlacement",{get:function(){return this._panePlacement},set:function(a){x[a]&&this._panePlacement!==a&&(this._panePlacement=a,this._cachedHiddenPaneThickness=null,this._machine.updateDom())},enumerable:!0,configurable:!0}),Object.defineProperty(a.prototype,"paneOpened",{get:function(){return this._machine.opened},set:function(a){this._machine.opened=a},enumerable:!0,configurable:!0}),a.prototype.dispose=function(){this._disposed||(this._disposed=!0,this._machine.dispose(),l.hidden(this._dismissable),g._disposeElement(this._dom.pane),g._disposeElement(this._dom.content))},a.prototype.openPane=function(){this._machine.open()},a.prototype.closePane=function(){this._machine.close()},a.prototype._initializeDom=function(a){var b=a.firstElementChild||k.document.createElement("div");h.addClass(b,s.pane),b.hasAttribute("tabIndex")||(b.tabIndex=-1);var c=k.document.createElement("div");h.addClass(c,s.content);for(var d=b.nextSibling;d;){var e=d.nextSibling;c.appendChild(d),d=e}var f=k.document.createElement("div");f.className=s._paneOutline;var g=k.document.createElement("div");g.className=s._paneWrapper,g.appendChild(b),g.appendChild(f);var i=k.document.createElement("div");i.className=s._panePlaceholder;var j=k.document.createElement("div");j.className=s._contentWrapper,j.appendChild(c),a.winControl=this,h.addClass(a,s.splitView),h.addClass(a,"win-disposable"),this._dom={root:a,pane:b,paneOutline:f,paneWrapper:g,panePlaceholder:i,content:c,contentWrapper:j}},a.prototype._measureElement=function(a){var b=h._getComputedStyle(a),c=h._getPositionRelativeTo(a,this._dom.root),d=parseInt(b.marginLeft,10),e=parseInt(b.marginTop,10);return{left:c.left-d,top:c.top-e,contentWidth:h.getContentWidth(a),contentHeight:h.getContentHeight(a),totalWidth:h.getTotalWidth(a),totalHeight:h.getTotalHeight(a)}},a.prototype._setContentRect=function(a){var b=this._dom.contentWrapper.style;b.left=a.left+"px",b.top=a.top+"px",b.height=a.contentHeight+"px",b.width=a.contentWidth+"px"},a.prototype._prepareAnimation=function(a,b){var c=this._dom.paneWrapper.style;c.position="absolute",c.left=a.left+"px",c.top=a.top+"px",c.height=a.totalHeight+"px",c.width=a.totalWidth+"px";var d=this._dom.contentWrapper.style;d.position="absolute",this._setContentRect(b)},a.prototype._clearAnimation=function(){var a=this._dom.paneWrapper.style;a.position="",a.left="",a.top="",a.height="",a.width="",a[q.scriptName]="";var b=this._dom.contentWrapper.style;b.position="",b.left="",b.top="",b.height="",b.width="",b[q.scriptName]="";var c=this._dom.pane.style;c.height="",c.width="",c[q.scriptName]=""},a.prototype._getHiddenContentRect=function(a,b,c){if(this.openedDisplayMode===w.overlay)return a;var d=this._rtl?x.left:x.right,e=this.panePlacement===d||this.panePlacement===x.bottom?0:1,f={content:c.content-b.content,total:c.total-b.total};return this._horizontal?{left:a.left-e*f.total,top:a.top,contentWidth:a.contentWidth+f.content,contentHeight:a.contentHeight,totalWidth:a.totalWidth+f.total,totalHeight:a.totalHeight}:{left:a.left,top:a.top-e*f.total,contentWidth:a.contentWidth,contentHeight:a.contentHeight+f.content,totalWidth:a.totalWidth,totalHeight:a.totalHeight+f.total}},Object.defineProperty(a.prototype,"_horizontal",{get:function(){return this.panePlacement===x.left||this.panePlacement===x.right},enumerable:!0,configurable:!0}),a.prototype._getHiddenPaneThickness=function(){if(null===this._cachedHiddenPaneThickness)if(this._closedDisplayMode===v.none)this._cachedHiddenPaneThickness={content:0,total:0};else{this._isOpenedMode&&(h.removeClass(this._dom.root,s.paneOpened),h.addClass(this._dom.root,s.paneClosed));var a=this._measureElement(this._dom.pane);this._cachedHiddenPaneThickness=p(a,this._horizontal?u.width:u.height),this._isOpenedMode&&(h.removeClass(this._dom.root,s.paneClosed),h.addClass(this._dom.root,s.paneOpened))}return this._cachedHiddenPaneThickness},a.prototype._playShowAnimation=function(a){var b=this,d=this._horizontal?u.width:u.height,e=this._measureElement(this._dom.pane),f=this._measureElement(this._dom.content),g=p(e,d),h=this._getHiddenContentRect(f,a,g);this._prepareAnimation(e,h);var i=function(){var e=b._rtl?x.left:x.right,f=.3,h=a.total+f*(g.total-a.total);return c._resizeTransition(b._dom.paneWrapper,b._dom.pane,{from:h,to:g.total,actualSize:g.total,dimension:d,anchorTrailingEdge:b.panePlacement===e||b.panePlacement===x.bottom})},j=function(){return b.openedDisplayMode===w.inline&&b._setContentRect(f),i()};return j().then(function(){b._clearAnimation()})},a.prototype._playHideAnimation=function(a){var b=this,d=this._horizontal?u.width:u.height,e=this._measureElement(this._dom.pane),f=this._measureElement(this._dom.content),g=p(e,d),h=this._getHiddenContentRect(f,a,g);this._prepareAnimation(e,f);var i=function(){var e=b._rtl?x.left:x.right,f=.3,h=g.total-f*(g.total-a.total);return c._resizeTransition(b._dom.paneWrapper,b._dom.pane,{from:h,to:a.total,actualSize:g.total,dimension:d,anchorTrailingEdge:b.panePlacement===e||b.panePlacement===x.bottom})},j=function(){return b.openedDisplayMode===w.inline&&b._setContentRect(h),i()};return j().then(function(){b._clearAnimation()})},a.prototype._updateDomImpl=function(){var a=this._updateDomImpl_rendered,b=this.panePlacement===x.left||this.panePlacement===x.top;b!==a.paneIsFirst&&(b?(this._dom.root.appendChild(this._dom.panePlaceholder),this._dom.root.appendChild(this._dom.paneWrapper),this._dom.root.appendChild(this._dom.contentWrapper)):(this._dom.root.appendChild(this._dom.contentWrapper),this._dom.root.appendChild(this._dom.paneWrapper),this._dom.root.appendChild(this._dom.panePlaceholder))),a.paneIsFirst=b,a.isOpenedMode!==this._isOpenedMode&&(this._isOpenedMode?(h.removeClass(this._dom.root,s.paneClosed),h.addClass(this._dom.root,s.paneOpened)):(h.removeClass(this._dom.root,s.paneOpened),h.addClass(this._dom.root,s.paneClosed))),a.isOpenedMode=this._isOpenedMode,a.panePlacement!==this.panePlacement&&(o(this._dom.root,A[a.panePlacement]),n(this._dom.root,A[this.panePlacement]),a.panePlacement=this.panePlacement),a.closedDisplayMode!==this.closedDisplayMode&&(o(this._dom.root,y[a.closedDisplayMode]),n(this._dom.root,y[this.closedDisplayMode]),a.closedDisplayMode=this.closedDisplayMode),a.openedDisplayMode!==this.openedDisplayMode&&(o(this._dom.root,z[a.openedDisplayMode]),n(this._dom.root,z[this.openedDisplayMode]),a.openedDisplayMode=this.openedDisplayMode);var c,d,e=this._isOpenedMode&&this.openedDisplayMode===w.overlay;if(e){var f=this._getHiddenPaneThickness();this._horizontal?(c=f.total+"px",d=""):(c="",d=f.total+"px")}else c="",d="";if(a.panePlaceholderWidth!==c||a.panePlaceholderHeight!==d){var g=this._dom.panePlaceholder.style;g.width=c,g.height=d,a.panePlaceholderWidth=c,a.panePlaceholderHeight=d}a.isOverlayShown!==e&&(e?l.shown(this._dismissable):l.hidden(this._dismissable),a.isOverlayShown=e)},a.ClosedDisplayMode=v,a.OpenedDisplayMode=w,a.PanePlacement=x,a.supportedForProcessing=!0,a._ClassNames=s,a}();b.SplitView=B,d.Class.mix(B,j.createEventProperties(t.beforeOpen,t.afterOpen,t.beforeClose,t.afterClose)),d.Class.mix(B,f.DOMEventMixin)}),d("WinJS/Controls/SplitView",["require","exports","../Core/_Base"],function(a,b,c){var d=null;c.Namespace.define("WinJS.UI",{SplitView:{get:function(){return d||a(["./SplitView/_SplitView"],function(a){d=a}),d.SplitView}}})}),d("require-style!less/styles-splitviewpanetoggle",[],function(){}),d("require-style!less/colors-splitviewpanetoggle",[],function(){}),d("WinJS/Controls/SplitViewPaneToggle/_SplitViewPaneToggle",["require","exports","../../Core/_Base","../../Utilities/_Control","../../Utilities/_ElementUtilities","../../Core/_ErrorFromName","../../Core/_Events","../../Core/_Global","../../Utilities/_KeyboardBehavior","../../Utilities/_Hoverable"],function(a,b,c,d,e,f,g,h,i,j){function k(a){return a&&a.winControl}function l(a){var b=k(a);return b?b.paneOpened:!1}j.isHoverable,a(["require-style!less/styles-splitviewpanetoggle"]),a(["require-style!less/colors-splitviewpanetoggle"]);var m={splitViewPaneToggle:"win-splitviewpanetoggle"},n={invoked:"invoked"},o={get duplicateConstruction(){return"Invalid argument: Controls may only be instantiated one time for each DOM element"},get badButtonElement(){return"Invalid argument: The SplitViewPaneToggle's element must be a button element"}},p=function(){function a(a,b){if(void 0===b&&(b={}),this._updateDom_rendered={splitView:void 0},a&&a.winControl)throw new f("WinJS.UI.SplitViewPaneToggle.DuplicateConstruction",o.duplicateConstruction);this._onPaneStateSettledBound=this._onPaneStateSettled.bind(this),this._ariaExpandedMutationObserver=new e._MutationObserver(this._onAriaExpandedPropertyChanged.bind(this)),this._initializeDom(a||h.document.createElement("button")),this._disposed=!1,this.splitView=null,d.setOptions(this,b),this._initialized=!0,this._updateDom()}return Object.defineProperty(a.prototype,"element",{get:function(){return this._dom.root},enumerable:!0,configurable:!0}),Object.defineProperty(a.prototype,"splitView",{get:function(){return this._splitView},set:function(a){this._splitView=a,a&&(this._opened=l(a)),this._updateDom()},enumerable:!0,configurable:!0}),a.prototype.dispose=function(){this._disposed||(this._disposed=!0,this._splitView&&this._removeListeners(this._splitView))},a.prototype._initializeDom=function(a){if("BUTTON"!==a.tagName)throw new f("WinJS.UI.SplitViewPaneToggle.BadButtonElement",o.badButtonElement);a.winControl=this,e.addClass(a,m.splitViewPaneToggle),e.addClass(a,"win-disposable"),a.hasAttribute("type")||(a.type="button"),new i._WinKeyboard(a),a.addEventListener("click",this._onClick.bind(this)),this._dom={root:a}},a.prototype._updateDom=function(){if(this._initialized&&!this._disposed){var a=this._updateDom_rendered;if(this._splitView!==a.splitView&&(a.splitView&&(this._dom.root.removeAttribute("aria-controls"),this._removeListeners(a.splitView)),this._splitView&&(e._ensureId(this._splitView),this._dom.root.setAttribute("aria-controls",this._splitView.id),this._addListeners(this._splitView)),a.splitView=this._splitView),this._splitView){var b=this._opened?"true":"false";e._setAttribute(this._dom.root,"aria-expanded",b);var c=k(this._splitView);c&&(c.paneOpened=this._opened)}}},a.prototype._addListeners=function(a){a.addEventListener("_openCloseStateSettled",this._onPaneStateSettledBound),this._ariaExpandedMutationObserver.observe(this._dom.root,{attributes:!0,attributeFilter:["aria-expanded"]})},a.prototype._removeListeners=function(a){a.removeEventListener("_openCloseStateSettled",this._onPaneStateSettledBound),this._ariaExpandedMutationObserver.disconnect()},a.prototype._fireEvent=function(a){var b=h.document.createEvent("CustomEvent");return b.initCustomEvent(a,!0,!1,null),this._dom.root.dispatchEvent(b)},a.prototype._onPaneStateSettled=function(a){a.target===this._splitView&&(this._opened=l(this._splitView),this._updateDom())},a.prototype._onAriaExpandedPropertyChanged=function(){var a="true"===this._dom.root.getAttribute("aria-expanded");this._opened=a,this._updateDom()},a.prototype._onClick=function(){this._invoked()},a.prototype._invoked=function(){this._disposed||(this._splitView&&(this._opened=!this._opened,this._updateDom()),this._fireEvent(n.invoked))},a._ClassNames=m,a.supportedForProcessing=!0,a}();b.SplitViewPaneToggle=p,c.Class.mix(p,g.createEventProperties(n.invoked)),c.Class.mix(p,d.DOMEventMixin)}),d("WinJS/Controls/SplitViewPaneToggle",["require","exports","../Core/_Base"],function(a,b,c){var d=null;c.Namespace.define("WinJS.UI",{SplitViewPaneToggle:{get:function(){return d||a(["./SplitViewPaneToggle/_SplitViewPaneToggle"],function(a){d=a}),d.SplitViewPaneToggle}}})}),d("WinJS/Controls/AppBar/_Constants",["require","exports","../CommandingSurface/_Constants"],function(a,b,c){b.ClassNames={controlCssClass:"win-appbar",disposableCssClass:"win-disposable",actionAreaCssClass:"win-appbar-actionarea",overflowButtonCssClass:"win-appbar-overflowbutton",spacerCssClass:"win-appbar-spacer",ellipsisCssClass:"win-appbar-ellipsis",overflowAreaCssClass:"win-appbar-overflowarea",contentFlyoutCssClass:"win-appbar-contentflyout",emptyappbarCssClass:"win-appbar-empty",menuCssClass:"win-menu",menuContainsToggleCommandClass:"win-menu-containstogglecommand",openedClass:"win-appbar-opened",closedClass:"win-appbar-closed",noneClass:"win-appbar-closeddisplaynone",minimalClass:"win-appbar-closeddisplayminimal",compactClass:"win-appbar-closeddisplaycompact",fullClass:"win-appbar-closeddisplayfull",placementTopClass:"win-appbar-top",placementBottomClass:"win-appbar-bottom"},b.EventNames={beforeOpen:"beforeopen",afterOpen:"afteropen",beforeClose:"beforeclose",afterClose:"afterclose",commandPropertyMutated:"_commandpropertymutated"},b.controlMinWidth=c.controlMinWidth,b.defaultClosedDisplayMode="compact",b.defaultOpened=!1,b.defaultPlacement="bottom",b.typeSeparator="separator",b.typeContent="content",b.typeButton="button",b.typeToggle="toggle",b.typeFlyout="flyout",b.commandSelector=".win-command",b.primaryCommandSection="primary",b.secondaryCommandSection="secondary"}),d("require-style!less/styles-appbar",[],function(){}),d("WinJS/Controls/AppBar/_AppBar",["require","exports","../../Core/_Base","../AppBar/_Constants","../CommandingSurface","../../Utilities/_Control","../../Utilities/_Dispose","../../Utilities/_ElementUtilities","../../Core/_ErrorFromName","../../Core/_Events","../../Core/_Global","../../Utilities/_KeyboardInfo","../../_LightDismissService","../../Promise","../../Core/_Resources","../../Utilities/_OpenCloseMachine","../../Core/_WriteProfilerMark"],function(a,b,c,d,e,f,g,h,i,j,k,l,m,n,o,p,q){function r(a,b){b&&h.addClass(a,b)}function s(a,b){b&&h.removeClass(a,b)}a(["require-style!less/styles-appbar"]);var t=l._KeyboardInfo,u={get ariaLabel(){return o._getWinJSString("ui/appBarAriaLabel").value},get overflowButtonAriaLabel(){return o._getWinJSString("ui/appBarOverflowButtonAriaLabel").value},get mustContainCommands(){return"The AppBar can only contain WinJS.UI.Command or WinJS.UI.AppBarCommand controls"},get duplicateConstruction(){return"Invalid argument: Controls may only be instantiated one time for each DOM element"}},v={none:"none",minimal:"minimal",compact:"compact",full:"full"},w={};w[v.none]=d.ClassNames.noneClass,w[v.minimal]=d.ClassNames.minimalClass,w[v.compact]=d.ClassNames.compactClass,w[v.full]=d.ClassNames.fullClass;var x={top:"top",bottom:"bottom"},y={};y[x.top]=d.ClassNames.placementTopClass,y[x.bottom]=d.ClassNames.placementBottomClass;var z=function(){function a(b,c){var g=this;if(void 0===c&&(c={}),this._updateDomImpl_renderedState={isOpenedMode:void 0,placement:void 0,closedDisplayMode:void 0,adjustedOffsets:{top:void 0,bottom:void 0}},this._writeProfilerMark("constructor,StartTM"),b&&b.winControl)throw new i("WinJS.UI.AppBar.DuplicateConstruction",u.duplicateConstruction);this._initializeDom(b||k.document.createElement("div"));var j=new p.OpenCloseMachine({eventElement:this.element,onOpen:function(){var b=g._commandingSurface.createOpenAnimation(g._getClosedHeight());return g.element.style.position="fixed",g._placement===a.Placement.top?g.element.style.top=l._KeyboardInfo._layoutViewportCoords.visibleDocTop+"px":g.element.style.bottom=l._KeyboardInfo._layoutViewportCoords.visibleDocBottom+"px",g._synchronousOpen(),b.execute().then(function(){g.element.style.position="",g.element.style.top=g._adjustedOffsets.top,g.element.style.bottom=g._adjustedOffsets.bottom})},onClose:function(){var b=g._commandingSurface.createCloseAnimation(g._getClosedHeight());return g.element.style.position="fixed",g._placement===a.Placement.top?g.element.style.top=l._KeyboardInfo._layoutViewportCoords.visibleDocTop+"px":g.element.style.bottom=l._KeyboardInfo._layoutViewportCoords.visibleDocBottom+"px",b.execute().then(function(){g._synchronousClose(),g.element.style.position="",g.element.style.top=g._adjustedOffsets.top,g.element.style.bottom=g._adjustedOffsets.bottom})},onUpdateDom:function(){g._updateDomImpl()},onUpdateDomWithIsOpened:function(a){g._isOpenedMode=a,g._updateDomImpl()}});this._handleShowingKeyboardBound=this._handleShowingKeyboard.bind(this),this._handleHidingKeyboardBound=this._handleHidingKeyboard.bind(this),h._inputPaneListener.addEventListener(this._dom.root,"showing",this._handleShowingKeyboardBound),h._inputPaneListener.addEventListener(this._dom.root,"hiding",this._handleHidingKeyboardBound),this._disposed=!1,this._cachedClosedHeight=null,this._commandingSurface=new e._CommandingSurface(this._dom.commandingSurfaceEl,{openCloseMachine:j}),r(this._dom.commandingSurfaceEl.querySelector(".win-commandingsurface-actionarea"),d.ClassNames.actionAreaCssClass),r(this._dom.commandingSurfaceEl.querySelector(".win-commandingsurface-overflowarea"),d.ClassNames.overflowAreaCssClass),r(this._dom.commandingSurfaceEl.querySelector(".win-commandingsurface-overflowbutton"),d.ClassNames.overflowButtonCssClass),r(this._dom.commandingSurfaceEl.querySelector(".win-commandingsurface-ellipsis"),d.ClassNames.ellipsisCssClass),this._isOpenedMode=d.defaultOpened,this._dismissable=new m.LightDismissableElement({element:this._dom.root,tabIndex:this._dom.root.hasAttribute("tabIndex")?this._dom.root.tabIndex:-1,onLightDismiss:function(){g.close()},onTakeFocus:function(a){g._dismissable.restoreFocus()||g._commandingSurface.takeFocus(a)}}),this.closedDisplayMode=d.defaultClosedDisplayMode,this.placement=d.defaultPlacement,this.opened=this._isOpenedMode,f.setOptions(this,c),h._inDom(this.element).then(function(){return g._commandingSurface.initialized}).then(function(){j.exitInit(),g._writeProfilerMark("constructor,StopTM")})}return Object.defineProperty(a.prototype,"element",{get:function(){return this._dom.root},enumerable:!0,configurable:!0}),Object.defineProperty(a.prototype,"data",{get:function(){return this._commandingSurface.data},set:function(a){this._commandingSurface.data=a},enumerable:!0,configurable:!0}),Object.defineProperty(a.prototype,"closedDisplayMode",{get:function(){return this._commandingSurface.closedDisplayMode},set:function(a){v[a]&&(this._commandingSurface.closedDisplayMode=a,this._cachedClosedHeight=null)},enumerable:!0,configurable:!0}),Object.defineProperty(a.prototype,"placement",{get:function(){return this._placement},set:function(a){if(x[a]&&this._placement!==a){switch(this._placement=a,a){case x.top:this._commandingSurface.overflowDirection="bottom";break;case x.bottom:this._commandingSurface.overflowDirection="top"}this._adjustedOffsets=this._computeAdjustedOffsets(),this._commandingSurface.deferredDomUpate()}},enumerable:!0,configurable:!0}),Object.defineProperty(a.prototype,"opened",{get:function(){return this._commandingSurface.opened},set:function(a){this._commandingSurface.opened=a},enumerable:!0,configurable:!0}),a.prototype.open=function(){this._commandingSurface.open()},a.prototype.close=function(){this._commandingSurface.close()},a.prototype.dispose=function(){this._disposed||(this._disposed=!0,m.hidden(this._dismissable),this._commandingSurface.dispose(),h._inputPaneListener.removeEventListener(this._dom.root,"showing",this._handleShowingKeyboardBound),h._inputPaneListener.removeEventListener(this._dom.root,"hiding",this._handleHidingKeyboardBound),g.disposeSubTree(this.element))},a.prototype.forceLayout=function(){this._commandingSurface.forceLayout()},a.prototype.getCommandById=function(a){return this._commandingSurface.getCommandById(a)},a.prototype.showOnlyCommands=function(a){return this._commandingSurface.showOnlyCommands(a)},a.prototype._writeProfilerMark=function(a){q("WinJS.UI.AppBar:"+this._id+":"+a)},a.prototype._initializeDom=function(a){this._writeProfilerMark("_intializeDom,info"),a.winControl=this,this._id=a.id||h._uniqueID(a),h.addClass(a,d.ClassNames.controlCssClass),h.addClass(a,d.ClassNames.disposableCssClass);var b=a.getAttribute("role");b||a.setAttribute("role","menubar");var c=a.getAttribute("aria-label");c||a.setAttribute("aria-label",u.ariaLabel);var e=document.createElement("DIV");h._reparentChildren(a,e),a.appendChild(e),this._dom={root:a,commandingSurfaceEl:e}},a.prototype._handleShowingKeyboard=function(a){var b=this;if(this._dom.root.contains(k.document.activeElement)){var c=a.detail.originalEvent;c.ensuredFocusedElementInView=!0}var d=t._animationShowLength+t._scrollTimeout;return n.timeout(d).then(function(){b._shouldAdjustForShowingKeyboard()&&!b._disposed&&(b._adjustedOffsets=b._computeAdjustedOffsets(),b._commandingSurface.deferredDomUpate())})},a.prototype._shouldAdjustForShowingKeyboard=function(){return t._visible&&!t._isResized},a.prototype._handleHidingKeyboard=function(){this._adjustedOffsets=this._computeAdjustedOffsets(),this._commandingSurface.deferredDomUpate()},a.prototype._computeAdjustedOffsets=function(){var a={top:"",bottom:""};return this._placement===x.bottom?a.bottom=t._visibleDocBottomOffset+"px":this._placement===x.top&&(a.top=t._visibleDocTop+"px"),a},a.prototype._synchronousOpen=function(){this._isOpenedMode=!0,this._updateDomImpl()},a.prototype._synchronousClose=function(){this._isOpenedMode=!1,this._updateDomImpl()},a.prototype._updateDomImpl=function(){var a=this._updateDomImpl_renderedState;a.isOpenedMode!==this._isOpenedMode&&(this._isOpenedMode?this._updateDomImpl_renderOpened():this._updateDomImpl_renderClosed(),a.isOpenedMode=this._isOpenedMode),a.placement!==this.placement&&(s(this._dom.root,y[a.placement]),r(this._dom.root,y[this.placement]),a.placement=this.placement),a.closedDisplayMode!==this.closedDisplayMode&&(s(this._dom.root,w[a.closedDisplayMode]),r(this._dom.root,w[this.closedDisplayMode]),a.closedDisplayMode=this.closedDisplayMode),a.adjustedOffsets.top!==this._adjustedOffsets.top&&(this._dom.root.style.top=this._adjustedOffsets.top,a.adjustedOffsets.top=this._adjustedOffsets.top),a.adjustedOffsets.bottom!==this._adjustedOffsets.bottom&&(this._dom.root.style.bottom=this._adjustedOffsets.bottom,a.adjustedOffsets.bottom=this._adjustedOffsets.bottom),this._commandingSurface.updateDom()},a.prototype._getClosedHeight=function(){if(null===this._cachedClosedHeight){var a=this._isOpenedMode;this._isOpenedMode&&this._synchronousClose(),this._cachedClosedHeight=this._commandingSurface.getBoundingRects().commandingSurface.height,a&&this._synchronousOpen()}return this._cachedClosedHeight},a.prototype._updateDomImpl_renderOpened=function(){r(this._dom.root,d.ClassNames.openedClass),s(this._dom.root,d.ClassNames.closedClass),this._commandingSurface.synchronousOpen(),m.shown(this._dismissable)},a.prototype._updateDomImpl_renderClosed=function(){r(this._dom.root,d.ClassNames.closedClass),s(this._dom.root,d.ClassNames.openedClass),this._commandingSurface.synchronousClose(),m.hidden(this._dismissable)},a.ClosedDisplayMode=v,a.Placement=x,a.supportedForProcessing=!0,a}();b.AppBar=z,c.Class.mix(z,j.createEventProperties(d.EventNames.beforeOpen,d.EventNames.afterOpen,d.EventNames.beforeClose,d.EventNames.afterClose)),c.Class.mix(z,f.DOMEventMixin)}),d("WinJS/Controls/AppBar",["require","exports","../Core/_Base"],function(a,b,c){var d=null;c.Namespace.define("WinJS.UI",{AppBar:{get:function(){return d||a(["./AppBar/_AppBar"],function(a){d=a}),d.AppBar}}})}),d("ui",["WinJS/Core/_WinJS","WinJS/VirtualizedDataSource","WinJS/Vui","WinJS/Controls/IntrinsicControls","WinJS/Controls/ListView","WinJS/Controls/FlipView","WinJS/Controls/ItemContainer","WinJS/Controls/Repeater","WinJS/Controls/DatePicker","WinJS/Controls/TimePicker","WinJS/Controls/BackButton","WinJS/Controls/Rating","WinJS/Controls/ToggleSwitch","WinJS/Controls/SemanticZoom","WinJS/Controls/Pivot","WinJS/Controls/Hub","WinJS/Controls/Flyout","WinJS/Controls/_LegacyAppBar","WinJS/Controls/Menu","WinJS/Controls/SearchBox","WinJS/Controls/SettingsFlyout","WinJS/Controls/NavBar","WinJS/Controls/Tooltip","WinJS/Controls/ViewBox","WinJS/Controls/ContentDialog","WinJS/Controls/SplitView","WinJS/Controls/SplitViewPaneToggle","WinJS/Controls/SplitView/Command","WinJS/Controls/ToolBar","WinJS/Controls/AppBar"],function(a){"use strict";return a}),c(["WinJS/Core/_WinJS","ui"],function(b){a.WinJS=b,"undefined"!=typeof module&&(module.exports=b)}),a.WinJS})}(); //# sourceMappingURL=ui.min.js.map
PatientManagement/PatientManagement.Web/wwwroot/Scripts/vue.js
Magik3a/PatientManagement_Admin
/*! * Vue.js v2.1.10 * (c) 2014-2017 Evan You * Released under the MIT License. */ (function (global, factory) { typeof exports === 'object' && typeof module !== 'undefined' ? module.exports = factory() : typeof define === 'function' && define.amd ? define(factory) : (global.Vue = factory()); }(this, (function () { 'use strict'; /* */ /** * Convert a value to a string that is actually rendered. */ function _toString (val) { return val == null ? '' : typeof val === 'object' ? JSON.stringify(val, null, 2) : String(val) } /** * Convert a input value to a number for persistence. * If the conversion fails, return original string. */ function toNumber (val) { var n = parseFloat(val); return isNaN(n) ? val : n } /** * Make a map and return a function for checking if a key * is in that map. */ function makeMap ( str, expectsLowerCase ) { var map = Object.create(null); var list = str.split(','); for (var i = 0; i < list.length; i++) { map[list[i]] = true; } return expectsLowerCase ? function (val) { return map[val.toLowerCase()]; } : function (val) { return map[val]; } } /** * Check if a tag is a built-in tag. */ var isBuiltInTag = makeMap('slot,component', true); /** * Remove an item from an array */ function remove$1 (arr, item) { if (arr.length) { var index = arr.indexOf(item); if (index > -1) { return arr.splice(index, 1) } } } /** * Check whether the object has the property. */ var hasOwnProperty = Object.prototype.hasOwnProperty; function hasOwn (obj, key) { return hasOwnProperty.call(obj, key) } /** * Check if value is primitive */ function isPrimitive (value) { return typeof value === 'string' || typeof value === 'number' } /** * Create a cached version of a pure function. */ function cached (fn) { var cache = Object.create(null); return (function cachedFn (str) { var hit = cache[str]; return hit || (cache[str] = fn(str)) }) } /** * Camelize a hyphen-delimited string. */ var camelizeRE = /-(\w)/g; var camelize = cached(function (str) { return str.replace(camelizeRE, function (_, c) { return c ? c.toUpperCase() : ''; }) }); /** * Capitalize a string. */ var capitalize = cached(function (str) { return str.charAt(0).toUpperCase() + str.slice(1) }); /** * Hyphenate a camelCase string. */ var hyphenateRE = /([^-])([A-Z])/g; var hyphenate = cached(function (str) { return str .replace(hyphenateRE, '$1-$2') .replace(hyphenateRE, '$1-$2') .toLowerCase() }); /** * Simple bind, faster than native */ function bind$1 (fn, ctx) { function boundFn (a) { var l = arguments.length; return l ? l > 1 ? fn.apply(ctx, arguments) : fn.call(ctx, a) : fn.call(ctx) } // record original fn length boundFn._length = fn.length; return boundFn } /** * Convert an Array-like object to a real Array. */ function toArray (list, start) { start = start || 0; var i = list.length - start; var ret = new Array(i); while (i--) { ret[i] = list[i + start]; } return ret } /** * Mix properties into target object. */ function extend (to, _from) { for (var key in _from) { to[key] = _from[key]; } return to } /** * Quick object check - this is primarily used to tell * Objects from primitive values when we know the value * is a JSON-compliant type. */ function isObject (obj) { return obj !== null && typeof obj === 'object' } /** * Strict object type check. Only returns true * for plain JavaScript objects. */ var toString = Object.prototype.toString; var OBJECT_STRING = '[object Object]'; function isPlainObject (obj) { return toString.call(obj) === OBJECT_STRING } /** * Merge an Array of Objects into a single Object. */ function toObject (arr) { var res = {}; for (var i = 0; i < arr.length; i++) { if (arr[i]) { extend(res, arr[i]); } } return res } /** * Perform no operation. */ function noop () {} /** * Always return false. */ var no = function () { return false; }; /** * Return same value */ var identity = function (_) { return _; }; /** * Generate a static keys string from compiler modules. */ function genStaticKeys (modules) { return modules.reduce(function (keys, m) { return keys.concat(m.staticKeys || []) }, []).join(',') } /** * Check if two values are loosely equal - that is, * if they are plain objects, do they have the same shape? */ function looseEqual (a, b) { var isObjectA = isObject(a); var isObjectB = isObject(b); if (isObjectA && isObjectB) { return JSON.stringify(a) === JSON.stringify(b) } else if (!isObjectA && !isObjectB) { return String(a) === String(b) } else { return false } } function looseIndexOf (arr, val) { for (var i = 0; i < arr.length; i++) { if (looseEqual(arr[i], val)) { return i } } return -1 } /* */ var config = { /** * Option merge strategies (used in core/util/options) */ optionMergeStrategies: Object.create(null), /** * Whether to suppress warnings. */ silent: false, /** * Whether to enable devtools */ devtools: "development" !== 'production', /** * Error handler for watcher errors */ errorHandler: null, /** * Ignore certain custom elements */ ignoredElements: [], /** * Custom user key aliases for v-on */ keyCodes: Object.create(null), /** * Check if a tag is reserved so that it cannot be registered as a * component. This is platform-dependent and may be overwritten. */ isReservedTag: no, /** * Check if a tag is an unknown element. * Platform-dependent. */ isUnknownElement: no, /** * Get the namespace of an element */ getTagNamespace: noop, /** * Parse the real tag name for the specific platform. */ parsePlatformTagName: identity, /** * Check if an attribute must be bound using property, e.g. value * Platform-dependent. */ mustUseProp: no, /** * List of asset types that a component can own. */ _assetTypes: [ 'component', 'directive', 'filter' ], /** * List of lifecycle hooks. */ _lifecycleHooks: [ 'beforeCreate', 'created', 'beforeMount', 'mounted', 'beforeUpdate', 'updated', 'beforeDestroy', 'destroyed', 'activated', 'deactivated' ], /** * Max circular updates allowed in a scheduler flush cycle. */ _maxUpdateCount: 100 }; /* */ /** * Check if a string starts with $ or _ */ function isReserved (str) { var c = (str + '').charCodeAt(0); return c === 0x24 || c === 0x5F } /** * Define a property. */ function def (obj, key, val, enumerable) { Object.defineProperty(obj, key, { value: val, enumerable: !!enumerable, writable: true, configurable: true }); } /** * Parse simple path. */ var bailRE = /[^\w.$]/; function parsePath (path) { if (bailRE.test(path)) { return } else { var segments = path.split('.'); return function (obj) { for (var i = 0; i < segments.length; i++) { if (!obj) { return } obj = obj[segments[i]]; } return obj } } } /* */ /* globals MutationObserver */ // can we use __proto__? var hasProto = '__proto__' in {}; // Browser environment sniffing var inBrowser = typeof window !== 'undefined'; var UA = inBrowser && window.navigator.userAgent.toLowerCase(); var isIE = UA && /msie|trident/.test(UA); var isIE9 = UA && UA.indexOf('msie 9.0') > 0; var isEdge = UA && UA.indexOf('edge/') > 0; var isAndroid = UA && UA.indexOf('android') > 0; var isIOS = UA && /iphone|ipad|ipod|ios/.test(UA); // this needs to be lazy-evaled because vue may be required before // vue-server-renderer can set VUE_ENV var _isServer; var isServerRendering = function () { if (_isServer === undefined) { /* istanbul ignore if */ if (!inBrowser && typeof global !== 'undefined') { // detect presence of vue-server-renderer and avoid // Webpack shimming the process _isServer = global['process'].env.VUE_ENV === 'server'; } else { _isServer = false; } } return _isServer }; // detect devtools var devtools = inBrowser && window.__VUE_DEVTOOLS_GLOBAL_HOOK__; /* istanbul ignore next */ function isNative (Ctor) { return /native code/.test(Ctor.toString()) } /** * Defer a task to execute it asynchronously. */ var nextTick = (function () { var callbacks = []; var pending = false; var timerFunc; function nextTickHandler () { pending = false; var copies = callbacks.slice(0); callbacks.length = 0; for (var i = 0; i < copies.length; i++) { copies[i](); } } // the nextTick behavior leverages the microtask queue, which can be accessed // via either native Promise.then or MutationObserver. // MutationObserver has wider support, however it is seriously bugged in // UIWebView in iOS >= 9.3.3 when triggered in touch event handlers. It // completely stops working after triggering a few times... so, if native // Promise is available, we will use it: /* istanbul ignore if */ if (typeof Promise !== 'undefined' && isNative(Promise)) { var p = Promise.resolve(); var logError = function (err) { console.error(err); }; timerFunc = function () { p.then(nextTickHandler).catch(logError); // in problematic UIWebViews, Promise.then doesn't completely break, but // it can get stuck in a weird state where callbacks are pushed into the // microtask queue but the queue isn't being flushed, until the browser // needs to do some other work, e.g. handle a timer. Therefore we can // "force" the microtask queue to be flushed by adding an empty timer. if (isIOS) { setTimeout(noop); } }; } else if (typeof MutationObserver !== 'undefined' && ( isNative(MutationObserver) || // PhantomJS and iOS 7.x MutationObserver.toString() === '[object MutationObserverConstructor]' )) { // use MutationObserver where native Promise is not available, // e.g. PhantomJS IE11, iOS7, Android 4.4 var counter = 1; var observer = new MutationObserver(nextTickHandler); var textNode = document.createTextNode(String(counter)); observer.observe(textNode, { characterData: true }); timerFunc = function () { counter = (counter + 1) % 2; textNode.data = String(counter); }; } else { // fallback to setTimeout /* istanbul ignore next */ timerFunc = function () { setTimeout(nextTickHandler, 0); }; } return function queueNextTick (cb, ctx) { var _resolve; callbacks.push(function () { if (cb) { cb.call(ctx); } if (_resolve) { _resolve(ctx); } }); if (!pending) { pending = true; timerFunc(); } if (!cb && typeof Promise !== 'undefined') { return new Promise(function (resolve) { _resolve = resolve; }) } } })(); var _Set; /* istanbul ignore if */ if (typeof Set !== 'undefined' && isNative(Set)) { // use native Set when available. _Set = Set; } else { // a non-standard Set polyfill that only works with primitive keys. _Set = (function () { function Set () { this.set = Object.create(null); } Set.prototype.has = function has (key) { return this.set[key] === true }; Set.prototype.add = function add (key) { this.set[key] = true; }; Set.prototype.clear = function clear () { this.set = Object.create(null); }; return Set; }()); } var warn = noop; var formatComponentName; { var hasConsole = typeof console !== 'undefined'; warn = function (msg, vm) { if (hasConsole && (!config.silent)) { console.error("[Vue warn]: " + msg + " " + ( vm ? formatLocation(formatComponentName(vm)) : '' )); } }; formatComponentName = function (vm) { if (vm.$root === vm) { return 'root instance' } var name = vm._isVue ? vm.$options.name || vm.$options._componentTag : vm.name; return ( (name ? ("component <" + name + ">") : "anonymous component") + (vm._isVue && vm.$options.__file ? (" at " + (vm.$options.__file)) : '') ) }; var formatLocation = function (str) { if (str === 'anonymous component') { str += " - use the \"name\" option for better debugging messages."; } return ("\n(found in " + str + ")") }; } /* */ var uid$1 = 0; /** * A dep is an observable that can have multiple * directives subscribing to it. */ var Dep = function Dep () { this.id = uid$1++; this.subs = []; }; Dep.prototype.addSub = function addSub (sub) { this.subs.push(sub); }; Dep.prototype.removeSub = function removeSub (sub) { remove$1(this.subs, sub); }; Dep.prototype.depend = function depend () { if (Dep.target) { Dep.target.addDep(this); } }; Dep.prototype.notify = function notify () { // stablize the subscriber list first var subs = this.subs.slice(); for (var i = 0, l = subs.length; i < l; i++) { subs[i].update(); } }; // the current target watcher being evaluated. // this is globally unique because there could be only one // watcher being evaluated at any time. Dep.target = null; var targetStack = []; function pushTarget (_target) { if (Dep.target) { targetStack.push(Dep.target); } Dep.target = _target; } function popTarget () { Dep.target = targetStack.pop(); } /* * not type checking this file because flow doesn't play well with * dynamically accessing methods on Array prototype */ var arrayProto = Array.prototype; var arrayMethods = Object.create(arrayProto);[ 'push', 'pop', 'shift', 'unshift', 'splice', 'sort', 'reverse' ] .forEach(function (method) { // cache original method var original = arrayProto[method]; def(arrayMethods, method, function mutator () { var arguments$1 = arguments; // avoid leaking arguments: // http://jsperf.com/closure-with-arguments var i = arguments.length; var args = new Array(i); while (i--) { args[i] = arguments$1[i]; } var result = original.apply(this, args); var ob = this.__ob__; var inserted; switch (method) { case 'push': inserted = args; break case 'unshift': inserted = args; break case 'splice': inserted = args.slice(2); break } if (inserted) { ob.observeArray(inserted); } // notify change ob.dep.notify(); return result }); }); /* */ var arrayKeys = Object.getOwnPropertyNames(arrayMethods); /** * By default, when a reactive property is set, the new value is * also converted to become reactive. However when passing down props, * we don't want to force conversion because the value may be a nested value * under a frozen data structure. Converting it would defeat the optimization. */ var observerState = { shouldConvert: true, isSettingProps: false }; /** * Observer class that are attached to each observed * object. Once attached, the observer converts target * object's property keys into getter/setters that * collect dependencies and dispatches updates. */ var Observer = function Observer (value) { this.value = value; this.dep = new Dep(); this.vmCount = 0; def(value, '__ob__', this); if (Array.isArray(value)) { var augment = hasProto ? protoAugment : copyAugment; augment(value, arrayMethods, arrayKeys); this.observeArray(value); } else { this.walk(value); } }; /** * Walk through each property and convert them into * getter/setters. This method should only be called when * value type is Object. */ Observer.prototype.walk = function walk (obj) { var keys = Object.keys(obj); for (var i = 0; i < keys.length; i++) { defineReactive$$1(obj, keys[i], obj[keys[i]]); } }; /** * Observe a list of Array items. */ Observer.prototype.observeArray = function observeArray (items) { for (var i = 0, l = items.length; i < l; i++) { observe(items[i]); } }; // helpers /** * Augment an target Object or Array by intercepting * the prototype chain using __proto__ */ function protoAugment (target, src) { /* eslint-disable no-proto */ target.__proto__ = src; /* eslint-enable no-proto */ } /** * Augment an target Object or Array by defining * hidden properties. */ /* istanbul ignore next */ function copyAugment (target, src, keys) { for (var i = 0, l = keys.length; i < l; i++) { var key = keys[i]; def(target, key, src[key]); } } /** * Attempt to create an observer instance for a value, * returns the new observer if successfully observed, * or the existing observer if the value already has one. */ function observe (value, asRootData) { if (!isObject(value)) { return } var ob; if (hasOwn(value, '__ob__') && value.__ob__ instanceof Observer) { ob = value.__ob__; } else if ( observerState.shouldConvert && !isServerRendering() && (Array.isArray(value) || isPlainObject(value)) && Object.isExtensible(value) && !value._isVue ) { ob = new Observer(value); } if (asRootData && ob) { ob.vmCount++; } return ob } /** * Define a reactive property on an Object. */ function defineReactive$$1 ( obj, key, val, customSetter ) { var dep = new Dep(); var property = Object.getOwnPropertyDescriptor(obj, key); if (property && property.configurable === false) { return } // cater for pre-defined getter/setters var getter = property && property.get; var setter = property && property.set; var childOb = observe(val); Object.defineProperty(obj, key, { enumerable: true, configurable: true, get: function reactiveGetter () { var value = getter ? getter.call(obj) : val; if (Dep.target) { dep.depend(); if (childOb) { childOb.dep.depend(); } if (Array.isArray(value)) { dependArray(value); } } return value }, set: function reactiveSetter (newVal) { var value = getter ? getter.call(obj) : val; /* eslint-disable no-self-compare */ if (newVal === value || (newVal !== newVal && value !== value)) { return } /* eslint-enable no-self-compare */ if ("development" !== 'production' && customSetter) { customSetter(); } if (setter) { setter.call(obj, newVal); } else { val = newVal; } childOb = observe(newVal); dep.notify(); } }); } /** * Set a property on an object. Adds the new property and * triggers change notification if the property doesn't * already exist. */ function set$1 (obj, key, val) { if (Array.isArray(obj)) { obj.length = Math.max(obj.length, key); obj.splice(key, 1, val); return val } if (hasOwn(obj, key)) { obj[key] = val; return } var ob = obj.__ob__; if (obj._isVue || (ob && ob.vmCount)) { "development" !== 'production' && warn( 'Avoid adding reactive properties to a Vue instance or its root $data ' + 'at runtime - declare it upfront in the data option.' ); return } if (!ob) { obj[key] = val; return } defineReactive$$1(ob.value, key, val); ob.dep.notify(); return val } /** * Delete a property and trigger change if necessary. */ function del (obj, key) { var ob = obj.__ob__; if (obj._isVue || (ob && ob.vmCount)) { "development" !== 'production' && warn( 'Avoid deleting properties on a Vue instance or its root $data ' + '- just set it to null.' ); return } if (!hasOwn(obj, key)) { return } delete obj[key]; if (!ob) { return } ob.dep.notify(); } /** * Collect dependencies on array elements when the array is touched, since * we cannot intercept array element access like property getters. */ function dependArray (value) { for (var e = (void 0), i = 0, l = value.length; i < l; i++) { e = value[i]; e && e.__ob__ && e.__ob__.dep.depend(); if (Array.isArray(e)) { dependArray(e); } } } /* */ /** * Option overwriting strategies are functions that handle * how to merge a parent option value and a child option * value into the final value. */ var strats = config.optionMergeStrategies; /** * Options with restrictions */ { strats.el = strats.propsData = function (parent, child, vm, key) { if (!vm) { warn( "option \"" + key + "\" can only be used during instance " + 'creation with the `new` keyword.' ); } return defaultStrat(parent, child) }; } /** * Helper that recursively merges two data objects together. */ function mergeData (to, from) { if (!from) { return to } var key, toVal, fromVal; var keys = Object.keys(from); for (var i = 0; i < keys.length; i++) { key = keys[i]; toVal = to[key]; fromVal = from[key]; if (!hasOwn(to, key)) { set$1(to, key, fromVal); } else if (isPlainObject(toVal) && isPlainObject(fromVal)) { mergeData(toVal, fromVal); } } return to } /** * Data */ strats.data = function ( parentVal, childVal, vm ) { if (!vm) { // in a Vue.extend merge, both should be functions if (!childVal) { return parentVal } if (typeof childVal !== 'function') { "development" !== 'production' && warn( 'The "data" option should be a function ' + 'that returns a per-instance value in component ' + 'definitions.', vm ); return parentVal } if (!parentVal) { return childVal } // when parentVal & childVal are both present, // we need to return a function that returns the // merged result of both functions... no need to // check if parentVal is a function here because // it has to be a function to pass previous merges. return function mergedDataFn () { return mergeData( childVal.call(this), parentVal.call(this) ) } } else if (parentVal || childVal) { return function mergedInstanceDataFn () { // instance merge var instanceData = typeof childVal === 'function' ? childVal.call(vm) : childVal; var defaultData = typeof parentVal === 'function' ? parentVal.call(vm) : undefined; if (instanceData) { return mergeData(instanceData, defaultData) } else { return defaultData } } } }; /** * Hooks and param attributes are merged as arrays. */ function mergeHook ( parentVal, childVal ) { return childVal ? parentVal ? parentVal.concat(childVal) : Array.isArray(childVal) ? childVal : [childVal] : parentVal } config._lifecycleHooks.forEach(function (hook) { strats[hook] = mergeHook; }); /** * Assets * * When a vm is present (instance creation), we need to do * a three-way merge between constructor options, instance * options and parent options. */ function mergeAssets (parentVal, childVal) { var res = Object.create(parentVal || null); return childVal ? extend(res, childVal) : res } config._assetTypes.forEach(function (type) { strats[type + 's'] = mergeAssets; }); /** * Watchers. * * Watchers hashes should not overwrite one * another, so we merge them as arrays. */ strats.watch = function (parentVal, childVal) { /* istanbul ignore if */ if (!childVal) { return parentVal } if (!parentVal) { return childVal } var ret = {}; extend(ret, parentVal); for (var key in childVal) { var parent = ret[key]; var child = childVal[key]; if (parent && !Array.isArray(parent)) { parent = [parent]; } ret[key] = parent ? parent.concat(child) : [child]; } return ret }; /** * Other object hashes. */ strats.props = strats.methods = strats.computed = function (parentVal, childVal) { if (!childVal) { return parentVal } if (!parentVal) { return childVal } var ret = Object.create(null); extend(ret, parentVal); extend(ret, childVal); return ret }; /** * Default strategy. */ var defaultStrat = function (parentVal, childVal) { return childVal === undefined ? parentVal : childVal }; /** * Validate component names */ function checkComponents (options) { for (var key in options.components) { var lower = key.toLowerCase(); if (isBuiltInTag(lower) || config.isReservedTag(lower)) { warn( 'Do not use built-in or reserved HTML elements as component ' + 'id: ' + key ); } } } /** * Ensure all props option syntax are normalized into the * Object-based format. */ function normalizeProps (options) { var props = options.props; if (!props) { return } var res = {}; var i, val, name; if (Array.isArray(props)) { i = props.length; while (i--) { val = props[i]; if (typeof val === 'string') { name = camelize(val); res[name] = { type: null }; } else { warn('props must be strings when using array syntax.'); } } } else if (isPlainObject(props)) { for (var key in props) { val = props[key]; name = camelize(key); res[name] = isPlainObject(val) ? val : { type: val }; } } options.props = res; } /** * Normalize raw function directives into object format. */ function normalizeDirectives (options) { var dirs = options.directives; if (dirs) { for (var key in dirs) { var def = dirs[key]; if (typeof def === 'function') { dirs[key] = { bind: def, update: def }; } } } } /** * Merge two option objects into a new one. * Core utility used in both instantiation and inheritance. */ function mergeOptions ( parent, child, vm ) { { checkComponents(child); } normalizeProps(child); normalizeDirectives(child); var extendsFrom = child.extends; if (extendsFrom) { parent = typeof extendsFrom === 'function' ? mergeOptions(parent, extendsFrom.options, vm) : mergeOptions(parent, extendsFrom, vm); } if (child.mixins) { for (var i = 0, l = child.mixins.length; i < l; i++) { var mixin = child.mixins[i]; if (mixin.prototype instanceof Vue$3) { mixin = mixin.options; } parent = mergeOptions(parent, mixin, vm); } } var options = {}; var key; for (key in parent) { mergeField(key); } for (key in child) { if (!hasOwn(parent, key)) { mergeField(key); } } function mergeField (key) { var strat = strats[key] || defaultStrat; options[key] = strat(parent[key], child[key], vm, key); } return options } /** * Resolve an asset. * This function is used because child instances need access * to assets defined in its ancestor chain. */ function resolveAsset ( options, type, id, warnMissing ) { /* istanbul ignore if */ if (typeof id !== 'string') { return } var assets = options[type]; // check local registration variations first if (hasOwn(assets, id)) { return assets[id] } var camelizedId = camelize(id); if (hasOwn(assets, camelizedId)) { return assets[camelizedId] } var PascalCaseId = capitalize(camelizedId); if (hasOwn(assets, PascalCaseId)) { return assets[PascalCaseId] } // fallback to prototype chain var res = assets[id] || assets[camelizedId] || assets[PascalCaseId]; if ("development" !== 'production' && warnMissing && !res) { warn( 'Failed to resolve ' + type.slice(0, -1) + ': ' + id, options ); } return res } /* */ function validateProp ( key, propOptions, propsData, vm ) { var prop = propOptions[key]; var absent = !hasOwn(propsData, key); var value = propsData[key]; // handle boolean props if (isType(Boolean, prop.type)) { if (absent && !hasOwn(prop, 'default')) { value = false; } else if (!isType(String, prop.type) && (value === '' || value === hyphenate(key))) { value = true; } } // check default value if (value === undefined) { value = getPropDefaultValue(vm, prop, key); // since the default value is a fresh copy, // make sure to observe it. var prevShouldConvert = observerState.shouldConvert; observerState.shouldConvert = true; observe(value); observerState.shouldConvert = prevShouldConvert; } { assertProp(prop, key, value, vm, absent); } return value } /** * Get the default value of a prop. */ function getPropDefaultValue (vm, prop, key) { // no default, return undefined if (!hasOwn(prop, 'default')) { return undefined } var def = prop.default; // warn against non-factory defaults for Object & Array if (isObject(def)) { "development" !== 'production' && warn( 'Invalid default value for prop "' + key + '": ' + 'Props with type Object/Array must use a factory function ' + 'to return the default value.', vm ); } // the raw prop value was also undefined from previous render, // return previous default value to avoid unnecessary watcher trigger if (vm && vm.$options.propsData && vm.$options.propsData[key] === undefined && vm[key] !== undefined) { return vm[key] } // call factory function for non-Function types return typeof def === 'function' && prop.type !== Function ? def.call(vm) : def } /** * Assert whether a prop is valid. */ function assertProp ( prop, name, value, vm, absent ) { if (prop.required && absent) { warn( 'Missing required prop: "' + name + '"', vm ); return } if (value == null && !prop.required) { return } var type = prop.type; var valid = !type || type === true; var expectedTypes = []; if (type) { if (!Array.isArray(type)) { type = [type]; } for (var i = 0; i < type.length && !valid; i++) { var assertedType = assertType(value, type[i]); expectedTypes.push(assertedType.expectedType || ''); valid = assertedType.valid; } } if (!valid) { warn( 'Invalid prop: type check failed for prop "' + name + '".' + ' Expected ' + expectedTypes.map(capitalize).join(', ') + ', got ' + Object.prototype.toString.call(value).slice(8, -1) + '.', vm ); return } var validator = prop.validator; if (validator) { if (!validator(value)) { warn( 'Invalid prop: custom validator check failed for prop "' + name + '".', vm ); } } } /** * Assert the type of a value */ function assertType (value, type) { var valid; var expectedType = getType(type); if (expectedType === 'String') { valid = typeof value === (expectedType = 'string'); } else if (expectedType === 'Number') { valid = typeof value === (expectedType = 'number'); } else if (expectedType === 'Boolean') { valid = typeof value === (expectedType = 'boolean'); } else if (expectedType === 'Function') { valid = typeof value === (expectedType = 'function'); } else if (expectedType === 'Object') { valid = isPlainObject(value); } else if (expectedType === 'Array') { valid = Array.isArray(value); } else { valid = value instanceof type; } return { valid: valid, expectedType: expectedType } } /** * Use function string name to check built-in types, * because a simple equality check will fail when running * across different vms / iframes. */ function getType (fn) { var match = fn && fn.toString().match(/^\s*function (\w+)/); return match && match[1] } function isType (type, fn) { if (!Array.isArray(fn)) { return getType(fn) === getType(type) } for (var i = 0, len = fn.length; i < len; i++) { if (getType(fn[i]) === getType(type)) { return true } } /* istanbul ignore next */ return false } var util = Object.freeze({ defineReactive: defineReactive$$1, _toString: _toString, toNumber: toNumber, makeMap: makeMap, isBuiltInTag: isBuiltInTag, remove: remove$1, hasOwn: hasOwn, isPrimitive: isPrimitive, cached: cached, camelize: camelize, capitalize: capitalize, hyphenate: hyphenate, bind: bind$1, toArray: toArray, extend: extend, isObject: isObject, isPlainObject: isPlainObject, toObject: toObject, noop: noop, no: no, identity: identity, genStaticKeys: genStaticKeys, looseEqual: looseEqual, looseIndexOf: looseIndexOf, isReserved: isReserved, def: def, parsePath: parsePath, hasProto: hasProto, inBrowser: inBrowser, UA: UA, isIE: isIE, isIE9: isIE9, isEdge: isEdge, isAndroid: isAndroid, isIOS: isIOS, isServerRendering: isServerRendering, devtools: devtools, nextTick: nextTick, get _Set () { return _Set; }, mergeOptions: mergeOptions, resolveAsset: resolveAsset, get warn () { return warn; }, get formatComponentName () { return formatComponentName; }, validateProp: validateProp }); /* not type checking this file because flow doesn't play well with Proxy */ var initProxy; { var allowedGlobals = makeMap( 'Infinity,undefined,NaN,isFinite,isNaN,' + 'parseFloat,parseInt,decodeURI,decodeURIComponent,encodeURI,encodeURIComponent,' + 'Math,Number,Date,Array,Object,Boolean,String,RegExp,Map,Set,JSON,Intl,' + 'require' // for Webpack/Browserify ); var warnNonPresent = function (target, key) { warn( "Property or method \"" + key + "\" is not defined on the instance but " + "referenced during render. Make sure to declare reactive data " + "properties in the data option.", target ); }; var hasProxy = typeof Proxy !== 'undefined' && Proxy.toString().match(/native code/); if (hasProxy) { var isBuiltInModifier = makeMap('stop,prevent,self,ctrl,shift,alt,meta'); config.keyCodes = new Proxy(config.keyCodes, { set: function set (target, key, value) { if (isBuiltInModifier(key)) { warn(("Avoid overwriting built-in modifier in config.keyCodes: ." + key)); return false } else { target[key] = value; return true } } }); } var hasHandler = { has: function has (target, key) { var has = key in target; var isAllowed = allowedGlobals(key) || key.charAt(0) === '_'; if (!has && !isAllowed) { warnNonPresent(target, key); } return has || !isAllowed } }; var getHandler = { get: function get (target, key) { if (typeof key === 'string' && !(key in target)) { warnNonPresent(target, key); } return target[key] } }; initProxy = function initProxy (vm) { if (hasProxy) { // determine which proxy handler to use var options = vm.$options; var handlers = options.render && options.render._withStripped ? getHandler : hasHandler; vm._renderProxy = new Proxy(vm, handlers); } else { vm._renderProxy = vm; } }; } /* */ var VNode = function VNode ( tag, data, children, text, elm, context, componentOptions ) { this.tag = tag; this.data = data; this.children = children; this.text = text; this.elm = elm; this.ns = undefined; this.context = context; this.functionalContext = undefined; this.key = data && data.key; this.componentOptions = componentOptions; this.componentInstance = undefined; this.parent = undefined; this.raw = false; this.isStatic = false; this.isRootInsert = true; this.isComment = false; this.isCloned = false; this.isOnce = false; }; var prototypeAccessors = { child: {} }; // DEPRECATED: alias for componentInstance for backwards compat. /* istanbul ignore next */ prototypeAccessors.child.get = function () { return this.componentInstance }; Object.defineProperties( VNode.prototype, prototypeAccessors ); var createEmptyVNode = function () { var node = new VNode(); node.text = ''; node.isComment = true; return node }; function createTextVNode (val) { return new VNode(undefined, undefined, undefined, String(val)) } // optimized shallow clone // used for static nodes and slot nodes because they may be reused across // multiple renders, cloning them avoids errors when DOM manipulations rely // on their elm reference. function cloneVNode (vnode) { var cloned = new VNode( vnode.tag, vnode.data, vnode.children, vnode.text, vnode.elm, vnode.context, vnode.componentOptions ); cloned.ns = vnode.ns; cloned.isStatic = vnode.isStatic; cloned.key = vnode.key; cloned.isCloned = true; return cloned } function cloneVNodes (vnodes) { var res = new Array(vnodes.length); for (var i = 0; i < vnodes.length; i++) { res[i] = cloneVNode(vnodes[i]); } return res } /* */ var hooks = { init: init, prepatch: prepatch, insert: insert, destroy: destroy$1 }; var hooksToMerge = Object.keys(hooks); function createComponent ( Ctor, data, context, children, tag ) { if (!Ctor) { return } var baseCtor = context.$options._base; if (isObject(Ctor)) { Ctor = baseCtor.extend(Ctor); } if (typeof Ctor !== 'function') { { warn(("Invalid Component definition: " + (String(Ctor))), context); } return } // async component if (!Ctor.cid) { if (Ctor.resolved) { Ctor = Ctor.resolved; } else { Ctor = resolveAsyncComponent(Ctor, baseCtor, function () { // it's ok to queue this on every render because // $forceUpdate is buffered by the scheduler. context.$forceUpdate(); }); if (!Ctor) { // return nothing if this is indeed an async component // wait for the callback to trigger parent update. return } } } // resolve constructor options in case global mixins are applied after // component constructor creation resolveConstructorOptions(Ctor); data = data || {}; // extract props var propsData = extractProps(data, Ctor); // functional component if (Ctor.options.functional) { return createFunctionalComponent(Ctor, propsData, data, context, children) } // extract listeners, since these needs to be treated as // child component listeners instead of DOM listeners var listeners = data.on; // replace with listeners with .native modifier data.on = data.nativeOn; if (Ctor.options.abstract) { // abstract components do not keep anything // other than props & listeners data = {}; } // merge component management hooks onto the placeholder node mergeHooks(data); // return a placeholder vnode var name = Ctor.options.name || tag; var vnode = new VNode( ("vue-component-" + (Ctor.cid) + (name ? ("-" + name) : '')), data, undefined, undefined, undefined, context, { Ctor: Ctor, propsData: propsData, listeners: listeners, tag: tag, children: children } ); return vnode } function createFunctionalComponent ( Ctor, propsData, data, context, children ) { var props = {}; var propOptions = Ctor.options.props; if (propOptions) { for (var key in propOptions) { props[key] = validateProp(key, propOptions, propsData); } } // ensure the createElement function in functional components // gets a unique context - this is necessary for correct named slot check var _context = Object.create(context); var h = function (a, b, c, d) { return createElement(_context, a, b, c, d, true); }; var vnode = Ctor.options.render.call(null, h, { props: props, data: data, parent: context, children: children, slots: function () { return resolveSlots(children, context); } }); if (vnode instanceof VNode) { vnode.functionalContext = context; if (data.slot) { (vnode.data || (vnode.data = {})).slot = data.slot; } } return vnode } function createComponentInstanceForVnode ( vnode, // we know it's MountedComponentVNode but flow doesn't parent, // activeInstance in lifecycle state parentElm, refElm ) { var vnodeComponentOptions = vnode.componentOptions; var options = { _isComponent: true, parent: parent, propsData: vnodeComponentOptions.propsData, _componentTag: vnodeComponentOptions.tag, _parentVnode: vnode, _parentListeners: vnodeComponentOptions.listeners, _renderChildren: vnodeComponentOptions.children, _parentElm: parentElm || null, _refElm: refElm || null }; // check inline-template render functions var inlineTemplate = vnode.data.inlineTemplate; if (inlineTemplate) { options.render = inlineTemplate.render; options.staticRenderFns = inlineTemplate.staticRenderFns; } return new vnodeComponentOptions.Ctor(options) } function init ( vnode, hydrating, parentElm, refElm ) { if (!vnode.componentInstance || vnode.componentInstance._isDestroyed) { var child = vnode.componentInstance = createComponentInstanceForVnode( vnode, activeInstance, parentElm, refElm ); child.$mount(hydrating ? vnode.elm : undefined, hydrating); } else if (vnode.data.keepAlive) { // kept-alive components, treat as a patch var mountedNode = vnode; // work around flow prepatch(mountedNode, mountedNode); } } function prepatch ( oldVnode, vnode ) { var options = vnode.componentOptions; var child = vnode.componentInstance = oldVnode.componentInstance; child._updateFromParent( options.propsData, // updated props options.listeners, // updated listeners vnode, // new parent vnode options.children // new children ); } function insert (vnode) { if (!vnode.componentInstance._isMounted) { vnode.componentInstance._isMounted = true; callHook(vnode.componentInstance, 'mounted'); } if (vnode.data.keepAlive) { vnode.componentInstance._inactive = false; callHook(vnode.componentInstance, 'activated'); } } function destroy$1 (vnode) { if (!vnode.componentInstance._isDestroyed) { if (!vnode.data.keepAlive) { vnode.componentInstance.$destroy(); } else { vnode.componentInstance._inactive = true; callHook(vnode.componentInstance, 'deactivated'); } } } function resolveAsyncComponent ( factory, baseCtor, cb ) { if (factory.requested) { // pool callbacks factory.pendingCallbacks.push(cb); } else { factory.requested = true; var cbs = factory.pendingCallbacks = [cb]; var sync = true; var resolve = function (res) { if (isObject(res)) { res = baseCtor.extend(res); } // cache resolved factory.resolved = res; // invoke callbacks only if this is not a synchronous resolve // (async resolves are shimmed as synchronous during SSR) if (!sync) { for (var i = 0, l = cbs.length; i < l; i++) { cbs[i](res); } } }; var reject = function (reason) { "development" !== 'production' && warn( "Failed to resolve async component: " + (String(factory)) + (reason ? ("\nReason: " + reason) : '') ); }; var res = factory(resolve, reject); // handle promise if (res && typeof res.then === 'function' && !factory.resolved) { res.then(resolve, reject); } sync = false; // return in case resolved synchronously return factory.resolved } } function extractProps (data, Ctor) { // we are only extracting raw values here. // validation and default values are handled in the child // component itself. var propOptions = Ctor.options.props; if (!propOptions) { return } var res = {}; var attrs = data.attrs; var props = data.props; var domProps = data.domProps; if (attrs || props || domProps) { for (var key in propOptions) { var altKey = hyphenate(key); checkProp(res, props, key, altKey, true) || checkProp(res, attrs, key, altKey) || checkProp(res, domProps, key, altKey); } } return res } function checkProp ( res, hash, key, altKey, preserve ) { if (hash) { if (hasOwn(hash, key)) { res[key] = hash[key]; if (!preserve) { delete hash[key]; } return true } else if (hasOwn(hash, altKey)) { res[key] = hash[altKey]; if (!preserve) { delete hash[altKey]; } return true } } return false } function mergeHooks (data) { if (!data.hook) { data.hook = {}; } for (var i = 0; i < hooksToMerge.length; i++) { var key = hooksToMerge[i]; var fromParent = data.hook[key]; var ours = hooks[key]; data.hook[key] = fromParent ? mergeHook$1(ours, fromParent) : ours; } } function mergeHook$1 (one, two) { return function (a, b, c, d) { one(a, b, c, d); two(a, b, c, d); } } /* */ function mergeVNodeHook (def, hookKey, hook, key) { key = key + hookKey; var injectedHash = def.__injected || (def.__injected = {}); if (!injectedHash[key]) { injectedHash[key] = true; var oldHook = def[hookKey]; if (oldHook) { def[hookKey] = function () { oldHook.apply(this, arguments); hook.apply(this, arguments); }; } else { def[hookKey] = hook; } } } /* */ var normalizeEvent = cached(function (name) { var once = name.charAt(0) === '~'; // Prefixed last, checked first name = once ? name.slice(1) : name; var capture = name.charAt(0) === '!'; name = capture ? name.slice(1) : name; return { name: name, once: once, capture: capture } }); function createEventHandle (fn) { var handle = { fn: fn, invoker: function () { var arguments$1 = arguments; var fn = handle.fn; if (Array.isArray(fn)) { for (var i = 0; i < fn.length; i++) { fn[i].apply(null, arguments$1); } } else { fn.apply(null, arguments); } } }; return handle } function updateListeners ( on, oldOn, add, remove$$1, vm ) { var name, cur, old, event; for (name in on) { cur = on[name]; old = oldOn[name]; event = normalizeEvent(name); if (!cur) { "development" !== 'production' && warn( "Invalid handler for event \"" + (event.name) + "\": got " + String(cur), vm ); } else if (!old) { if (!cur.invoker) { cur = on[name] = createEventHandle(cur); } add(event.name, cur.invoker, event.once, event.capture); } else if (cur !== old) { old.fn = cur; on[name] = old; } } for (name in oldOn) { if (!on[name]) { event = normalizeEvent(name); remove$$1(event.name, oldOn[name].invoker, event.capture); } } } /* */ // The template compiler attempts to minimize the need for normalization by // statically analyzing the template at compile time. // // For plain HTML markup, normalization can be completely skipped because the // generated render function is guaranteed to return Array<VNode>. There are // two cases where extra normalization is needed: // 1. When the children contains components - because a functional component // may return an Array instead of a single root. In this case, just a simple // nomralization is needed - if any child is an Array, we flatten the whole // thing with Array.prototype.concat. It is guaranteed to be only 1-level deep // because functional components already normalize their own children. function simpleNormalizeChildren (children) { for (var i = 0; i < children.length; i++) { if (Array.isArray(children[i])) { return Array.prototype.concat.apply([], children) } } return children } // 2. When the children contains constrcuts that always generated nested Arrays, // e.g. <template>, <slot>, v-for, or when the children is provided by user // with hand-written render functions / JSX. In such cases a full normalization // is needed to cater to all possible types of children values. function normalizeChildren (children) { return isPrimitive(children) ? [createTextVNode(children)] : Array.isArray(children) ? normalizeArrayChildren(children) : undefined } function normalizeArrayChildren (children, nestedIndex) { var res = []; var i, c, last; for (i = 0; i < children.length; i++) { c = children[i]; if (c == null || typeof c === 'boolean') { continue } last = res[res.length - 1]; // nested if (Array.isArray(c)) { res.push.apply(res, normalizeArrayChildren(c, ((nestedIndex || '') + "_" + i))); } else if (isPrimitive(c)) { if (last && last.text) { last.text += String(c); } else if (c !== '') { // convert primitive to vnode res.push(createTextVNode(c)); } } else { if (c.text && last && last.text) { res[res.length - 1] = createTextVNode(last.text + c.text); } else { // default key for nested array children (likely generated by v-for) if (c.tag && c.key == null && nestedIndex != null) { c.key = "__vlist" + nestedIndex + "_" + i + "__"; } res.push(c); } } } return res } /* */ function getFirstComponentChild (children) { return children && children.filter(function (c) { return c && c.componentOptions; })[0] } /* */ var SIMPLE_NORMALIZE = 1; var ALWAYS_NORMALIZE = 2; // wrapper function for providing a more flexible interface // without getting yelled at by flow function createElement ( context, tag, data, children, normalizationType, alwaysNormalize ) { if (Array.isArray(data) || isPrimitive(data)) { normalizationType = children; children = data; data = undefined; } if (alwaysNormalize) { normalizationType = ALWAYS_NORMALIZE; } return _createElement(context, tag, data, children, normalizationType) } function _createElement ( context, tag, data, children, normalizationType ) { if (data && data.__ob__) { "development" !== 'production' && warn( "Avoid using observed data object as vnode data: " + (JSON.stringify(data)) + "\n" + 'Always create fresh vnode data objects in each render!', context ); return createEmptyVNode() } if (!tag) { // in case of component :is set to falsy value return createEmptyVNode() } // support single function children as default scoped slot if (Array.isArray(children) && typeof children[0] === 'function') { data = data || {}; data.scopedSlots = { default: children[0] }; children.length = 0; } if (normalizationType === ALWAYS_NORMALIZE) { children = normalizeChildren(children); } else if (normalizationType === SIMPLE_NORMALIZE) { children = simpleNormalizeChildren(children); } var vnode, ns; if (typeof tag === 'string') { var Ctor; ns = config.getTagNamespace(tag); if (config.isReservedTag(tag)) { // platform built-in elements vnode = new VNode( config.parsePlatformTagName(tag), data, children, undefined, undefined, context ); } else if ((Ctor = resolveAsset(context.$options, 'components', tag))) { // component vnode = createComponent(Ctor, data, context, children, tag); } else { // unknown or unlisted namespaced elements // check at runtime because it may get assigned a namespace when its // parent normalizes children vnode = new VNode( tag, data, children, undefined, undefined, context ); } } else { // direct component options / constructor vnode = createComponent(tag, data, context, children); } if (vnode) { if (ns) { applyNS(vnode, ns); } return vnode } else { return createEmptyVNode() } } function applyNS (vnode, ns) { vnode.ns = ns; if (vnode.tag === 'foreignObject') { // use default namespace inside foreignObject return } if (vnode.children) { for (var i = 0, l = vnode.children.length; i < l; i++) { var child = vnode.children[i]; if (child.tag && !child.ns) { applyNS(child, ns); } } } } /* */ function initRender (vm) { vm.$vnode = null; // the placeholder node in parent tree vm._vnode = null; // the root of the child tree vm._staticTrees = null; var parentVnode = vm.$options._parentVnode; var renderContext = parentVnode && parentVnode.context; vm.$slots = resolveSlots(vm.$options._renderChildren, renderContext); vm.$scopedSlots = {}; // bind the createElement fn to this instance // so that we get proper render context inside it. // args order: tag, data, children, normalizationType, alwaysNormalize // internal version is used by render functions compiled from templates vm._c = function (a, b, c, d) { return createElement(vm, a, b, c, d, false); }; // normalization is always applied for the public version, used in // user-written render functions. vm.$createElement = function (a, b, c, d) { return createElement(vm, a, b, c, d, true); }; } function renderMixin (Vue) { Vue.prototype.$nextTick = function (fn) { return nextTick(fn, this) }; Vue.prototype._render = function () { var vm = this; var ref = vm.$options; var render = ref.render; var staticRenderFns = ref.staticRenderFns; var _parentVnode = ref._parentVnode; if (vm._isMounted) { // clone slot nodes on re-renders for (var key in vm.$slots) { vm.$slots[key] = cloneVNodes(vm.$slots[key]); } } if (_parentVnode && _parentVnode.data.scopedSlots) { vm.$scopedSlots = _parentVnode.data.scopedSlots; } if (staticRenderFns && !vm._staticTrees) { vm._staticTrees = []; } // set parent vnode. this allows render functions to have access // to the data on the placeholder node. vm.$vnode = _parentVnode; // render self var vnode; try { vnode = render.call(vm._renderProxy, vm.$createElement); } catch (e) { /* istanbul ignore else */ if (config.errorHandler) { config.errorHandler.call(null, e, vm); } else { { warn(("Error when rendering " + (formatComponentName(vm)) + ":")); } throw e } // return previous vnode to prevent render error causing blank component vnode = vm._vnode; } // return empty vnode in case the render function errored out if (!(vnode instanceof VNode)) { if ("development" !== 'production' && Array.isArray(vnode)) { warn( 'Multiple root nodes returned from render function. Render function ' + 'should return a single root node.', vm ); } vnode = createEmptyVNode(); } // set parent vnode.parent = _parentVnode; return vnode }; // toString for mustaches Vue.prototype._s = _toString; // convert text to vnode Vue.prototype._v = createTextVNode; // number conversion Vue.prototype._n = toNumber; // empty vnode Vue.prototype._e = createEmptyVNode; // loose equal Vue.prototype._q = looseEqual; // loose indexOf Vue.prototype._i = looseIndexOf; // render static tree by index Vue.prototype._m = function renderStatic ( index, isInFor ) { var tree = this._staticTrees[index]; // if has already-rendered static tree and not inside v-for, // we can reuse the same tree by doing a shallow clone. if (tree && !isInFor) { return Array.isArray(tree) ? cloneVNodes(tree) : cloneVNode(tree) } // otherwise, render a fresh tree. tree = this._staticTrees[index] = this.$options.staticRenderFns[index].call(this._renderProxy); markStatic(tree, ("__static__" + index), false); return tree }; // mark node as static (v-once) Vue.prototype._o = function markOnce ( tree, index, key ) { markStatic(tree, ("__once__" + index + (key ? ("_" + key) : "")), true); return tree }; function markStatic (tree, key, isOnce) { if (Array.isArray(tree)) { for (var i = 0; i < tree.length; i++) { if (tree[i] && typeof tree[i] !== 'string') { markStaticNode(tree[i], (key + "_" + i), isOnce); } } } else { markStaticNode(tree, key, isOnce); } } function markStaticNode (node, key, isOnce) { node.isStatic = true; node.key = key; node.isOnce = isOnce; } // filter resolution helper Vue.prototype._f = function resolveFilter (id) { return resolveAsset(this.$options, 'filters', id, true) || identity }; // render v-for Vue.prototype._l = function renderList ( val, render ) { var ret, i, l, keys, key; if (Array.isArray(val) || typeof val === 'string') { ret = new Array(val.length); for (i = 0, l = val.length; i < l; i++) { ret[i] = render(val[i], i); } } else if (typeof val === 'number') { ret = new Array(val); for (i = 0; i < val; i++) { ret[i] = render(i + 1, i); } } else if (isObject(val)) { keys = Object.keys(val); ret = new Array(keys.length); for (i = 0, l = keys.length; i < l; i++) { key = keys[i]; ret[i] = render(val[key], key, i); } } return ret }; // renderSlot Vue.prototype._t = function ( name, fallback, props, bindObject ) { var scopedSlotFn = this.$scopedSlots[name]; if (scopedSlotFn) { // scoped slot props = props || {}; if (bindObject) { extend(props, bindObject); } return scopedSlotFn(props) || fallback } else { var slotNodes = this.$slots[name]; // warn duplicate slot usage if (slotNodes && "development" !== 'production') { slotNodes._rendered && warn( "Duplicate presence of slot \"" + name + "\" found in the same render tree " + "- this will likely cause render errors.", this ); slotNodes._rendered = true; } return slotNodes || fallback } }; // apply v-bind object Vue.prototype._b = function bindProps ( data, tag, value, asProp ) { if (value) { if (!isObject(value)) { "development" !== 'production' && warn( 'v-bind without argument expects an Object or Array value', this ); } else { if (Array.isArray(value)) { value = toObject(value); } for (var key in value) { if (key === 'class' || key === 'style') { data[key] = value[key]; } else { var type = data.attrs && data.attrs.type; var hash = asProp || config.mustUseProp(tag, type, key) ? data.domProps || (data.domProps = {}) : data.attrs || (data.attrs = {}); hash[key] = value[key]; } } } } return data }; // check v-on keyCodes Vue.prototype._k = function checkKeyCodes ( eventKeyCode, key, builtInAlias ) { var keyCodes = config.keyCodes[key] || builtInAlias; if (Array.isArray(keyCodes)) { return keyCodes.indexOf(eventKeyCode) === -1 } else { return keyCodes !== eventKeyCode } }; } function resolveSlots ( children, context ) { var slots = {}; if (!children) { return slots } var defaultSlot = []; var name, child; for (var i = 0, l = children.length; i < l; i++) { child = children[i]; // named slots should only be respected if the vnode was rendered in the // same context. if ((child.context === context || child.functionalContext === context) && child.data && (name = child.data.slot)) { var slot = (slots[name] || (slots[name] = [])); if (child.tag === 'template') { slot.push.apply(slot, child.children); } else { slot.push(child); } } else { defaultSlot.push(child); } } // ignore single whitespace if (defaultSlot.length && !( defaultSlot.length === 1 && (defaultSlot[0].text === ' ' || defaultSlot[0].isComment) )) { slots.default = defaultSlot; } return slots } /* */ function initEvents (vm) { vm._events = Object.create(null); vm._hasHookEvent = false; // init parent attached events var listeners = vm.$options._parentListeners; if (listeners) { updateComponentListeners(vm, listeners); } } var target; function add$1 (event, fn, once) { if (once) { target.$once(event, fn); } else { target.$on(event, fn); } } function remove$2 (event, fn) { target.$off(event, fn); } function updateComponentListeners ( vm, listeners, oldListeners ) { target = vm; updateListeners(listeners, oldListeners || {}, add$1, remove$2, vm); } function eventsMixin (Vue) { var hookRE = /^hook:/; Vue.prototype.$on = function (event, fn) { var vm = this;(vm._events[event] || (vm._events[event] = [])).push(fn); // optimize hook:event cost by using a boolean flag marked at registration // instead of a hash lookup if (hookRE.test(event)) { vm._hasHookEvent = true; } return vm }; Vue.prototype.$once = function (event, fn) { var vm = this; function on () { vm.$off(event, on); fn.apply(vm, arguments); } on.fn = fn; vm.$on(event, on); return vm }; Vue.prototype.$off = function (event, fn) { var vm = this; // all if (!arguments.length) { vm._events = Object.create(null); return vm } // specific event var cbs = vm._events[event]; if (!cbs) { return vm } if (arguments.length === 1) { vm._events[event] = null; return vm } // specific handler var cb; var i = cbs.length; while (i--) { cb = cbs[i]; if (cb === fn || cb.fn === fn) { cbs.splice(i, 1); break } } return vm }; Vue.prototype.$emit = function (event) { var vm = this; var cbs = vm._events[event]; if (cbs) { cbs = cbs.length > 1 ? toArray(cbs) : cbs; var args = toArray(arguments, 1); for (var i = 0, l = cbs.length; i < l; i++) { cbs[i].apply(vm, args); } } return vm }; } /* */ var activeInstance = null; function initLifecycle (vm) { var options = vm.$options; // locate first non-abstract parent var parent = options.parent; if (parent && !options.abstract) { while (parent.$options.abstract && parent.$parent) { parent = parent.$parent; } parent.$children.push(vm); } vm.$parent = parent; vm.$root = parent ? parent.$root : vm; vm.$children = []; vm.$refs = {}; vm._watcher = null; vm._inactive = false; vm._isMounted = false; vm._isDestroyed = false; vm._isBeingDestroyed = false; } function lifecycleMixin (Vue) { Vue.prototype._mount = function ( el, hydrating ) { var vm = this; vm.$el = el; if (!vm.$options.render) { vm.$options.render = createEmptyVNode; { /* istanbul ignore if */ if (vm.$options.template && vm.$options.template.charAt(0) !== '#') { warn( 'You are using the runtime-only build of Vue where the template ' + 'option is not available. Either pre-compile the templates into ' + 'render functions, or use the compiler-included build.', vm ); } else { warn( 'Failed to mount component: template or render function not defined.', vm ); } } } callHook(vm, 'beforeMount'); vm._watcher = new Watcher(vm, function updateComponent () { vm._update(vm._render(), hydrating); }, noop); hydrating = false; // manually mounted instance, call mounted on self // mounted is called for render-created child components in its inserted hook if (vm.$vnode == null) { vm._isMounted = true; callHook(vm, 'mounted'); } return vm }; Vue.prototype._update = function (vnode, hydrating) { var vm = this; if (vm._isMounted) { callHook(vm, 'beforeUpdate'); } var prevEl = vm.$el; var prevVnode = vm._vnode; var prevActiveInstance = activeInstance; activeInstance = vm; vm._vnode = vnode; // Vue.prototype.__patch__ is injected in entry points // based on the rendering backend used. if (!prevVnode) { // initial render vm.$el = vm.__patch__( vm.$el, vnode, hydrating, false /* removeOnly */, vm.$options._parentElm, vm.$options._refElm ); } else { // updates vm.$el = vm.__patch__(prevVnode, vnode); } activeInstance = prevActiveInstance; // update __vue__ reference if (prevEl) { prevEl.__vue__ = null; } if (vm.$el) { vm.$el.__vue__ = vm; } // if parent is an HOC, update its $el as well if (vm.$vnode && vm.$parent && vm.$vnode === vm.$parent._vnode) { vm.$parent.$el = vm.$el; } // updated hook is called by the scheduler to ensure that children are // updated in a parent's updated hook. }; Vue.prototype._updateFromParent = function ( propsData, listeners, parentVnode, renderChildren ) { var vm = this; var hasChildren = !!(vm.$options._renderChildren || renderChildren); vm.$options._parentVnode = parentVnode; vm.$vnode = parentVnode; // update vm's placeholder node without re-render if (vm._vnode) { // update child tree's parent vm._vnode.parent = parentVnode; } vm.$options._renderChildren = renderChildren; // update props if (propsData && vm.$options.props) { observerState.shouldConvert = false; { observerState.isSettingProps = true; } var propKeys = vm.$options._propKeys || []; for (var i = 0; i < propKeys.length; i++) { var key = propKeys[i]; vm[key] = validateProp(key, vm.$options.props, propsData, vm); } observerState.shouldConvert = true; { observerState.isSettingProps = false; } vm.$options.propsData = propsData; } // update listeners if (listeners) { var oldListeners = vm.$options._parentListeners; vm.$options._parentListeners = listeners; updateComponentListeners(vm, listeners, oldListeners); } // resolve slots + force update if has children if (hasChildren) { vm.$slots = resolveSlots(renderChildren, parentVnode.context); vm.$forceUpdate(); } }; Vue.prototype.$forceUpdate = function () { var vm = this; if (vm._watcher) { vm._watcher.update(); } }; Vue.prototype.$destroy = function () { var vm = this; if (vm._isBeingDestroyed) { return } callHook(vm, 'beforeDestroy'); vm._isBeingDestroyed = true; // remove self from parent var parent = vm.$parent; if (parent && !parent._isBeingDestroyed && !vm.$options.abstract) { remove$1(parent.$children, vm); } // teardown watchers if (vm._watcher) { vm._watcher.teardown(); } var i = vm._watchers.length; while (i--) { vm._watchers[i].teardown(); } // remove reference from data ob // frozen object may not have observer. if (vm._data.__ob__) { vm._data.__ob__.vmCount--; } // call the last hook... vm._isDestroyed = true; callHook(vm, 'destroyed'); // turn off all instance listeners. vm.$off(); // remove __vue__ reference if (vm.$el) { vm.$el.__vue__ = null; } // invoke destroy hooks on current rendered tree vm.__patch__(vm._vnode, null); }; } function callHook (vm, hook) { var handlers = vm.$options[hook]; if (handlers) { for (var i = 0, j = handlers.length; i < j; i++) { handlers[i].call(vm); } } if (vm._hasHookEvent) { vm.$emit('hook:' + hook); } } /* */ var queue = []; var has$1 = {}; var circular = {}; var waiting = false; var flushing = false; var index = 0; /** * Reset the scheduler's state. */ function resetSchedulerState () { queue.length = 0; has$1 = {}; { circular = {}; } waiting = flushing = false; } /** * Flush both queues and run the watchers. */ function flushSchedulerQueue () { flushing = true; var watcher, id, vm; // Sort queue before flush. // This ensures that: // 1. Components are updated from parent to child. (because parent is always // created before the child) // 2. A component's user watchers are run before its render watcher (because // user watchers are created before the render watcher) // 3. If a component is destroyed during a parent component's watcher run, // its watchers can be skipped. queue.sort(function (a, b) { return a.id - b.id; }); // do not cache length because more watchers might be pushed // as we run existing watchers for (index = 0; index < queue.length; index++) { watcher = queue[index]; id = watcher.id; has$1[id] = null; watcher.run(); // in dev build, check and stop circular updates. if ("development" !== 'production' && has$1[id] != null) { circular[id] = (circular[id] || 0) + 1; if (circular[id] > config._maxUpdateCount) { warn( 'You may have an infinite update loop ' + ( watcher.user ? ("in watcher with expression \"" + (watcher.expression) + "\"") : "in a component render function." ), watcher.vm ); break } } } // call updated hooks index = queue.length; while (index--) { watcher = queue[index]; vm = watcher.vm; if (vm._watcher === watcher && vm._isMounted) { callHook(vm, 'updated'); } } // devtool hook /* istanbul ignore if */ if (devtools && config.devtools) { devtools.emit('flush'); } resetSchedulerState(); } /** * Push a watcher into the watcher queue. * Jobs with duplicate IDs will be skipped unless it's * pushed when the queue is being flushed. */ function queueWatcher (watcher) { var id = watcher.id; if (has$1[id] == null) { has$1[id] = true; if (!flushing) { queue.push(watcher); } else { // if already flushing, splice the watcher based on its id // if already past its id, it will be run next immediately. var i = queue.length - 1; while (i >= 0 && queue[i].id > watcher.id) { i--; } queue.splice(Math.max(i, index) + 1, 0, watcher); } // queue the flush if (!waiting) { waiting = true; nextTick(flushSchedulerQueue); } } } /* */ var uid$2 = 0; /** * A watcher parses an expression, collects dependencies, * and fires callback when the expression value changes. * This is used for both the $watch() api and directives. */ var Watcher = function Watcher ( vm, expOrFn, cb, options ) { this.vm = vm; vm._watchers.push(this); // options if (options) { this.deep = !!options.deep; this.user = !!options.user; this.lazy = !!options.lazy; this.sync = !!options.sync; } else { this.deep = this.user = this.lazy = this.sync = false; } this.cb = cb; this.id = ++uid$2; // uid for batching this.active = true; this.dirty = this.lazy; // for lazy watchers this.deps = []; this.newDeps = []; this.depIds = new _Set(); this.newDepIds = new _Set(); this.expression = expOrFn.toString(); // parse expression for getter if (typeof expOrFn === 'function') { this.getter = expOrFn; } else { this.getter = parsePath(expOrFn); if (!this.getter) { this.getter = function () {}; "development" !== 'production' && warn( "Failed watching path: \"" + expOrFn + "\" " + 'Watcher only accepts simple dot-delimited paths. ' + 'For full control, use a function instead.', vm ); } } this.value = this.lazy ? undefined : this.get(); }; /** * Evaluate the getter, and re-collect dependencies. */ Watcher.prototype.get = function get () { pushTarget(this); var value = this.getter.call(this.vm, this.vm); // "touch" every property so they are all tracked as // dependencies for deep watching if (this.deep) { traverse(value); } popTarget(); this.cleanupDeps(); return value }; /** * Add a dependency to this directive. */ Watcher.prototype.addDep = function addDep (dep) { var id = dep.id; if (!this.newDepIds.has(id)) { this.newDepIds.add(id); this.newDeps.push(dep); if (!this.depIds.has(id)) { dep.addSub(this); } } }; /** * Clean up for dependency collection. */ Watcher.prototype.cleanupDeps = function cleanupDeps () { var this$1 = this; var i = this.deps.length; while (i--) { var dep = this$1.deps[i]; if (!this$1.newDepIds.has(dep.id)) { dep.removeSub(this$1); } } var tmp = this.depIds; this.depIds = this.newDepIds; this.newDepIds = tmp; this.newDepIds.clear(); tmp = this.deps; this.deps = this.newDeps; this.newDeps = tmp; this.newDeps.length = 0; }; /** * Subscriber interface. * Will be called when a dependency changes. */ Watcher.prototype.update = function update () { /* istanbul ignore else */ if (this.lazy) { this.dirty = true; } else if (this.sync) { this.run(); } else { queueWatcher(this); } }; /** * Scheduler job interface. * Will be called by the scheduler. */ Watcher.prototype.run = function run () { if (this.active) { var value = this.get(); if ( value !== this.value || // Deep watchers and watchers on Object/Arrays should fire even // when the value is the same, because the value may // have mutated. isObject(value) || this.deep ) { // set new value var oldValue = this.value; this.value = value; if (this.user) { try { this.cb.call(this.vm, value, oldValue); } catch (e) { /* istanbul ignore else */ if (config.errorHandler) { config.errorHandler.call(null, e, this.vm); } else { "development" !== 'production' && warn( ("Error in watcher \"" + (this.expression) + "\""), this.vm ); throw e } } } else { this.cb.call(this.vm, value, oldValue); } } } }; /** * Evaluate the value of the watcher. * This only gets called for lazy watchers. */ Watcher.prototype.evaluate = function evaluate () { this.value = this.get(); this.dirty = false; }; /** * Depend on all deps collected by this watcher. */ Watcher.prototype.depend = function depend () { var this$1 = this; var i = this.deps.length; while (i--) { this$1.deps[i].depend(); } }; /** * Remove self from all dependencies' subscriber list. */ Watcher.prototype.teardown = function teardown () { var this$1 = this; if (this.active) { // remove self from vm's watcher list // this is a somewhat expensive operation so we skip it // if the vm is being destroyed. if (!this.vm._isBeingDestroyed) { remove$1(this.vm._watchers, this); } var i = this.deps.length; while (i--) { this$1.deps[i].removeSub(this$1); } this.active = false; } }; /** * Recursively traverse an object to evoke all converted * getters, so that every nested property inside the object * is collected as a "deep" dependency. */ var seenObjects = new _Set(); function traverse (val) { seenObjects.clear(); _traverse(val, seenObjects); } function _traverse (val, seen) { var i, keys; var isA = Array.isArray(val); if ((!isA && !isObject(val)) || !Object.isExtensible(val)) { return } if (val.__ob__) { var depId = val.__ob__.dep.id; if (seen.has(depId)) { return } seen.add(depId); } if (isA) { i = val.length; while (i--) { _traverse(val[i], seen); } } else { keys = Object.keys(val); i = keys.length; while (i--) { _traverse(val[keys[i]], seen); } } } /* */ function initState (vm) { vm._watchers = []; var opts = vm.$options; if (opts.props) { initProps(vm, opts.props); } if (opts.methods) { initMethods(vm, opts.methods); } if (opts.data) { initData(vm); } else { observe(vm._data = {}, true /* asRootData */); } if (opts.computed) { initComputed(vm, opts.computed); } if (opts.watch) { initWatch(vm, opts.watch); } } var isReservedProp = { key: 1, ref: 1, slot: 1 }; function initProps (vm, props) { var propsData = vm.$options.propsData || {}; var keys = vm.$options._propKeys = Object.keys(props); var isRoot = !vm.$parent; // root instance props should be converted observerState.shouldConvert = isRoot; var loop = function ( i ) { var key = keys[i]; /* istanbul ignore else */ { if (isReservedProp[key]) { warn( ("\"" + key + "\" is a reserved attribute and cannot be used as component prop."), vm ); } defineReactive$$1(vm, key, validateProp(key, props, propsData, vm), function () { if (vm.$parent && !observerState.isSettingProps) { warn( "Avoid mutating a prop directly since the value will be " + "overwritten whenever the parent component re-renders. " + "Instead, use a data or computed property based on the prop's " + "value. Prop being mutated: \"" + key + "\"", vm ); } }); } }; for (var i = 0; i < keys.length; i++) loop( i ); observerState.shouldConvert = true; } function initData (vm) { var data = vm.$options.data; data = vm._data = typeof data === 'function' ? data.call(vm) : data || {}; if (!isPlainObject(data)) { data = {}; "development" !== 'production' && warn( 'data functions should return an object:\n' + 'https://vuejs.org/v2/guide/components.html#data-Must-Be-a-Function', vm ); } // proxy data on instance var keys = Object.keys(data); var props = vm.$options.props; var i = keys.length; while (i--) { if (props && hasOwn(props, keys[i])) { "development" !== 'production' && warn( "The data property \"" + (keys[i]) + "\" is already declared as a prop. " + "Use prop default value instead.", vm ); } else { proxy(vm, keys[i]); } } // observe data observe(data, true /* asRootData */); } var computedSharedDefinition = { enumerable: true, configurable: true, get: noop, set: noop }; function initComputed (vm, computed) { for (var key in computed) { /* istanbul ignore if */ if ("development" !== 'production' && key in vm) { warn( "existing instance property \"" + key + "\" will be " + "overwritten by a computed property with the same name.", vm ); } var userDef = computed[key]; if (typeof userDef === 'function') { computedSharedDefinition.get = makeComputedGetter(userDef, vm); computedSharedDefinition.set = noop; } else { computedSharedDefinition.get = userDef.get ? userDef.cache !== false ? makeComputedGetter(userDef.get, vm) : bind$1(userDef.get, vm) : noop; computedSharedDefinition.set = userDef.set ? bind$1(userDef.set, vm) : noop; } Object.defineProperty(vm, key, computedSharedDefinition); } } function makeComputedGetter (getter, owner) { var watcher = new Watcher(owner, getter, noop, { lazy: true }); return function computedGetter () { if (watcher.dirty) { watcher.evaluate(); } if (Dep.target) { watcher.depend(); } return watcher.value } } function initMethods (vm, methods) { for (var key in methods) { vm[key] = methods[key] == null ? noop : bind$1(methods[key], vm); if ("development" !== 'production' && methods[key] == null) { warn( "method \"" + key + "\" has an undefined value in the component definition. " + "Did you reference the function correctly?", vm ); } } } function initWatch (vm, watch) { for (var key in watch) { var handler = watch[key]; if (Array.isArray(handler)) { for (var i = 0; i < handler.length; i++) { createWatcher(vm, key, handler[i]); } } else { createWatcher(vm, key, handler); } } } function createWatcher (vm, key, handler) { var options; if (isPlainObject(handler)) { options = handler; handler = handler.handler; } if (typeof handler === 'string') { handler = vm[handler]; } vm.$watch(key, handler, options); } function stateMixin (Vue) { // flow somehow has problems with directly declared definition object // when using Object.defineProperty, so we have to procedurally build up // the object here. var dataDef = {}; dataDef.get = function () { return this._data }; { dataDef.set = function (newData) { warn( 'Avoid replacing instance root $data. ' + 'Use nested data properties instead.', this ); }; } Object.defineProperty(Vue.prototype, '$data', dataDef); Vue.prototype.$set = set$1; Vue.prototype.$delete = del; Vue.prototype.$watch = function ( expOrFn, cb, options ) { var vm = this; options = options || {}; options.user = true; var watcher = new Watcher(vm, expOrFn, cb, options); if (options.immediate) { cb.call(vm, watcher.value); } return function unwatchFn () { watcher.teardown(); } }; } function proxy (vm, key) { if (!isReserved(key)) { Object.defineProperty(vm, key, { configurable: true, enumerable: true, get: function proxyGetter () { return vm._data[key] }, set: function proxySetter (val) { vm._data[key] = val; } }); } } /* */ var uid = 0; function initMixin (Vue) { Vue.prototype._init = function (options) { var vm = this; // a uid vm._uid = uid++; // a flag to avoid this being observed vm._isVue = true; // merge options if (options && options._isComponent) { // optimize internal component instantiation // since dynamic options merging is pretty slow, and none of the // internal component options needs special treatment. initInternalComponent(vm, options); } else { vm.$options = mergeOptions( resolveConstructorOptions(vm.constructor), options || {}, vm ); } /* istanbul ignore else */ { initProxy(vm); } // expose real self vm._self = vm; initLifecycle(vm); initEvents(vm); initRender(vm); callHook(vm, 'beforeCreate'); initState(vm); callHook(vm, 'created'); if (vm.$options.el) { vm.$mount(vm.$options.el); } }; } function initInternalComponent (vm, options) { var opts = vm.$options = Object.create(vm.constructor.options); // doing this because it's faster than dynamic enumeration. opts.parent = options.parent; opts.propsData = options.propsData; opts._parentVnode = options._parentVnode; opts._parentListeners = options._parentListeners; opts._renderChildren = options._renderChildren; opts._componentTag = options._componentTag; opts._parentElm = options._parentElm; opts._refElm = options._refElm; if (options.render) { opts.render = options.render; opts.staticRenderFns = options.staticRenderFns; } } function resolveConstructorOptions (Ctor) { var options = Ctor.options; if (Ctor.super) { var superOptions = Ctor.super.options; var cachedSuperOptions = Ctor.superOptions; var extendOptions = Ctor.extendOptions; if (superOptions !== cachedSuperOptions) { // super option changed Ctor.superOptions = superOptions; extendOptions.render = options.render; extendOptions.staticRenderFns = options.staticRenderFns; extendOptions._scopeId = options._scopeId; options = Ctor.options = mergeOptions(superOptions, extendOptions); if (options.name) { options.components[options.name] = Ctor; } } } return options } function Vue$3 (options) { if ("development" !== 'production' && !(this instanceof Vue$3)) { warn('Vue is a constructor and should be called with the `new` keyword'); } this._init(options); } initMixin(Vue$3); stateMixin(Vue$3); eventsMixin(Vue$3); lifecycleMixin(Vue$3); renderMixin(Vue$3); /* */ function initUse (Vue) { Vue.use = function (plugin) { /* istanbul ignore if */ if (plugin.installed) { return } // additional parameters var args = toArray(arguments, 1); args.unshift(this); if (typeof plugin.install === 'function') { plugin.install.apply(plugin, args); } else { plugin.apply(null, args); } plugin.installed = true; return this }; } /* */ function initMixin$1 (Vue) { Vue.mixin = function (mixin) { this.options = mergeOptions(this.options, mixin); }; } /* */ function initExtend (Vue) { /** * Each instance constructor, including Vue, has a unique * cid. This enables us to create wrapped "child * constructors" for prototypal inheritance and cache them. */ Vue.cid = 0; var cid = 1; /** * Class inheritance */ Vue.extend = function (extendOptions) { extendOptions = extendOptions || {}; var Super = this; var SuperId = Super.cid; var cachedCtors = extendOptions._Ctor || (extendOptions._Ctor = {}); if (cachedCtors[SuperId]) { return cachedCtors[SuperId] } var name = extendOptions.name || Super.options.name; { if (!/^[a-zA-Z][\w-]*$/.test(name)) { warn( 'Invalid component name: "' + name + '". Component names ' + 'can only contain alphanumeric characters and the hyphen, ' + 'and must start with a letter.' ); } } var Sub = function VueComponent (options) { this._init(options); }; Sub.prototype = Object.create(Super.prototype); Sub.prototype.constructor = Sub; Sub.cid = cid++; Sub.options = mergeOptions( Super.options, extendOptions ); Sub['super'] = Super; // allow further extension/mixin/plugin usage Sub.extend = Super.extend; Sub.mixin = Super.mixin; Sub.use = Super.use; // create asset registers, so extended classes // can have their private assets too. config._assetTypes.forEach(function (type) { Sub[type] = Super[type]; }); // enable recursive self-lookup if (name) { Sub.options.components[name] = Sub; } // keep a reference to the super options at extension time. // later at instantiation we can check if Super's options have // been updated. Sub.superOptions = Super.options; Sub.extendOptions = extendOptions; // cache constructor cachedCtors[SuperId] = Sub; return Sub }; } /* */ function initAssetRegisters (Vue) { /** * Create asset registration methods. */ config._assetTypes.forEach(function (type) { Vue[type] = function ( id, definition ) { if (!definition) { return this.options[type + 's'][id] } else { /* istanbul ignore if */ { if (type === 'component' && config.isReservedTag(id)) { warn( 'Do not use built-in or reserved HTML elements as component ' + 'id: ' + id ); } } if (type === 'component' && isPlainObject(definition)) { definition.name = definition.name || id; definition = this.options._base.extend(definition); } if (type === 'directive' && typeof definition === 'function') { definition = { bind: definition, update: definition }; } this.options[type + 's'][id] = definition; return definition } }; }); } /* */ var patternTypes = [String, RegExp]; function getComponentName (opts) { return opts && (opts.Ctor.options.name || opts.tag) } function matches (pattern, name) { if (typeof pattern === 'string') { return pattern.split(',').indexOf(name) > -1 } else { return pattern.test(name) } } function pruneCache (cache, filter) { for (var key in cache) { var cachedNode = cache[key]; if (cachedNode) { var name = getComponentName(cachedNode.componentOptions); if (name && !filter(name)) { pruneCacheEntry(cachedNode); cache[key] = null; } } } } function pruneCacheEntry (vnode) { if (vnode) { if (!vnode.componentInstance._inactive) { callHook(vnode.componentInstance, 'deactivated'); } vnode.componentInstance.$destroy(); } } var KeepAlive = { name: 'keep-alive', abstract: true, props: { include: patternTypes, exclude: patternTypes }, created: function created () { this.cache = Object.create(null); }, destroyed: function destroyed () { var this$1 = this; for (var key in this.cache) { pruneCacheEntry(this$1.cache[key]); } }, watch: { include: function include (val) { pruneCache(this.cache, function (name) { return matches(val, name); }); }, exclude: function exclude (val) { pruneCache(this.cache, function (name) { return !matches(val, name); }); } }, render: function render () { var vnode = getFirstComponentChild(this.$slots.default); var componentOptions = vnode && vnode.componentOptions; if (componentOptions) { // check pattern var name = getComponentName(componentOptions); if (name && ( (this.include && !matches(this.include, name)) || (this.exclude && matches(this.exclude, name)) )) { return vnode } var key = vnode.key == null // same constructor may get registered as different local components // so cid alone is not enough (#3269) ? componentOptions.Ctor.cid + (componentOptions.tag ? ("::" + (componentOptions.tag)) : '') : vnode.key; if (this.cache[key]) { vnode.componentInstance = this.cache[key].componentInstance; } else { this.cache[key] = vnode; } vnode.data.keepAlive = true; } return vnode } }; var builtInComponents = { KeepAlive: KeepAlive }; /* */ function initGlobalAPI (Vue) { // config var configDef = {}; configDef.get = function () { return config; }; { configDef.set = function () { warn( 'Do not replace the Vue.config object, set individual fields instead.' ); }; } Object.defineProperty(Vue, 'config', configDef); Vue.util = util; Vue.set = set$1; Vue.delete = del; Vue.nextTick = nextTick; Vue.options = Object.create(null); config._assetTypes.forEach(function (type) { Vue.options[type + 's'] = Object.create(null); }); // this is used to identify the "base" constructor to extend all plain-object // components with in Weex's multi-instance scenarios. Vue.options._base = Vue; extend(Vue.options.components, builtInComponents); initUse(Vue); initMixin$1(Vue); initExtend(Vue); initAssetRegisters(Vue); } initGlobalAPI(Vue$3); Object.defineProperty(Vue$3.prototype, '$isServer', { get: isServerRendering }); Vue$3.version = '2.1.10'; /* */ // attributes that should be using props for binding var acceptValue = makeMap('input,textarea,option,select'); var mustUseProp = function (tag, type, attr) { return ( (attr === 'value' && acceptValue(tag)) && type !== 'button' || (attr === 'selected' && tag === 'option') || (attr === 'checked' && tag === 'input') || (attr === 'muted' && tag === 'video') ) }; var isEnumeratedAttr = makeMap('contenteditable,draggable,spellcheck'); var isBooleanAttr = makeMap( 'allowfullscreen,async,autofocus,autoplay,checked,compact,controls,declare,' + 'default,defaultchecked,defaultmuted,defaultselected,defer,disabled,' + 'enabled,formnovalidate,hidden,indeterminate,inert,ismap,itemscope,loop,multiple,' + 'muted,nohref,noresize,noshade,novalidate,nowrap,open,pauseonexit,readonly,' + 'required,reversed,scoped,seamless,selected,sortable,translate,' + 'truespeed,typemustmatch,visible' ); var xlinkNS = 'http://www.w3.org/1999/xlink'; var isXlink = function (name) { return name.charAt(5) === ':' && name.slice(0, 5) === 'xlink' }; var getXlinkProp = function (name) { return isXlink(name) ? name.slice(6, name.length) : '' }; var isFalsyAttrValue = function (val) { return val == null || val === false }; /* */ function genClassForVnode (vnode) { var data = vnode.data; var parentNode = vnode; var childNode = vnode; while (childNode.componentInstance) { childNode = childNode.componentInstance._vnode; if (childNode.data) { data = mergeClassData(childNode.data, data); } } while ((parentNode = parentNode.parent)) { if (parentNode.data) { data = mergeClassData(data, parentNode.data); } } return genClassFromData(data) } function mergeClassData (child, parent) { return { staticClass: concat(child.staticClass, parent.staticClass), class: child.class ? [child.class, parent.class] : parent.class } } function genClassFromData (data) { var dynamicClass = data.class; var staticClass = data.staticClass; if (staticClass || dynamicClass) { return concat(staticClass, stringifyClass(dynamicClass)) } /* istanbul ignore next */ return '' } function concat (a, b) { return a ? b ? (a + ' ' + b) : a : (b || '') } function stringifyClass (value) { var res = ''; if (!value) { return res } if (typeof value === 'string') { return value } if (Array.isArray(value)) { var stringified; for (var i = 0, l = value.length; i < l; i++) { if (value[i]) { if ((stringified = stringifyClass(value[i]))) { res += stringified + ' '; } } } return res.slice(0, -1) } if (isObject(value)) { for (var key in value) { if (value[key]) { res += key + ' '; } } return res.slice(0, -1) } /* istanbul ignore next */ return res } /* */ var namespaceMap = { svg: 'http://www.w3.org/2000/svg', math: 'http://www.w3.org/1998/Math/MathML' }; var isHTMLTag = makeMap( 'html,body,base,head,link,meta,style,title,' + 'address,article,aside,footer,header,h1,h2,h3,h4,h5,h6,hgroup,nav,section,' + 'div,dd,dl,dt,figcaption,figure,hr,img,li,main,ol,p,pre,ul,' + 'a,b,abbr,bdi,bdo,br,cite,code,data,dfn,em,i,kbd,mark,q,rp,rt,rtc,ruby,' + 's,samp,small,span,strong,sub,sup,time,u,var,wbr,area,audio,map,track,video,' + 'embed,object,param,source,canvas,script,noscript,del,ins,' + 'caption,col,colgroup,table,thead,tbody,td,th,tr,' + 'button,datalist,fieldset,form,input,label,legend,meter,optgroup,option,' + 'output,progress,select,textarea,' + 'details,dialog,menu,menuitem,summary,' + 'content,element,shadow,template' ); // this map is intentionally selective, only covering SVG elements that may // contain child elements. var isSVG = makeMap( 'svg,animate,circle,clippath,cursor,defs,desc,ellipse,filter,' + 'font-face,g,glyph,image,line,marker,mask,missing-glyph,path,pattern,' + 'polygon,polyline,rect,switch,symbol,text,textpath,tspan,use,view', true ); var isPreTag = function (tag) { return tag === 'pre'; }; var isReservedTag = function (tag) { return isHTMLTag(tag) || isSVG(tag) }; function getTagNamespace (tag) { if (isSVG(tag)) { return 'svg' } // basic support for MathML // note it doesn't support other MathML elements being component roots if (tag === 'math') { return 'math' } } var unknownElementCache = Object.create(null); function isUnknownElement (tag) { /* istanbul ignore if */ if (!inBrowser) { return true } if (isReservedTag(tag)) { return false } tag = tag.toLowerCase(); /* istanbul ignore if */ if (unknownElementCache[tag] != null) { return unknownElementCache[tag] } var el = document.createElement(tag); if (tag.indexOf('-') > -1) { // http://stackoverflow.com/a/28210364/1070244 return (unknownElementCache[tag] = ( el.constructor === window.HTMLUnknownElement || el.constructor === window.HTMLElement )) } else { return (unknownElementCache[tag] = /HTMLUnknownElement/.test(el.toString())) } } /* */ /** * Query an element selector if it's not an element already. */ function query (el) { if (typeof el === 'string') { var selector = el; el = document.querySelector(el); if (!el) { "development" !== 'production' && warn( 'Cannot find element: ' + selector ); return document.createElement('div') } } return el } /* */ function createElement$1 (tagName, vnode) { var elm = document.createElement(tagName); if (tagName !== 'select') { return elm } if (vnode.data && vnode.data.attrs && 'multiple' in vnode.data.attrs) { elm.setAttribute('multiple', 'multiple'); } return elm } function createElementNS (namespace, tagName) { return document.createElementNS(namespaceMap[namespace], tagName) } function createTextNode (text) { return document.createTextNode(text) } function createComment (text) { return document.createComment(text) } function insertBefore (parentNode, newNode, referenceNode) { parentNode.insertBefore(newNode, referenceNode); } function removeChild (node, child) { node.removeChild(child); } function appendChild (node, child) { node.appendChild(child); } function parentNode (node) { return node.parentNode } function nextSibling (node) { return node.nextSibling } function tagName (node) { return node.tagName } function setTextContent (node, text) { node.textContent = text; } function setAttribute (node, key, val) { node.setAttribute(key, val); } var nodeOps = Object.freeze({ createElement: createElement$1, createElementNS: createElementNS, createTextNode: createTextNode, createComment: createComment, insertBefore: insertBefore, removeChild: removeChild, appendChild: appendChild, parentNode: parentNode, nextSibling: nextSibling, tagName: tagName, setTextContent: setTextContent, setAttribute: setAttribute }); /* */ var ref = { create: function create (_, vnode) { registerRef(vnode); }, update: function update (oldVnode, vnode) { if (oldVnode.data.ref !== vnode.data.ref) { registerRef(oldVnode, true); registerRef(vnode); } }, destroy: function destroy (vnode) { registerRef(vnode, true); } }; function registerRef (vnode, isRemoval) { var key = vnode.data.ref; if (!key) { return } var vm = vnode.context; var ref = vnode.componentInstance || vnode.elm; var refs = vm.$refs; if (isRemoval) { if (Array.isArray(refs[key])) { remove$1(refs[key], ref); } else if (refs[key] === ref) { refs[key] = undefined; } } else { if (vnode.data.refInFor) { if (Array.isArray(refs[key]) && refs[key].indexOf(ref) < 0) { refs[key].push(ref); } else { refs[key] = [ref]; } } else { refs[key] = ref; } } } /** * Virtual DOM patching algorithm based on Snabbdom by * Simon Friis Vindum (@paldepind) * Licensed under the MIT License * https://github.com/paldepind/snabbdom/blob/master/LICENSE * * modified by Evan You (@yyx990803) * /* * Not type-checking this because this file is perf-critical and the cost * of making flow understand it is not worth it. */ var emptyNode = new VNode('', {}, []); var hooks$1 = ['create', 'activate', 'update', 'remove', 'destroy']; function isUndef (s) { return s == null } function isDef (s) { return s != null } function sameVnode (vnode1, vnode2) { return ( vnode1.key === vnode2.key && vnode1.tag === vnode2.tag && vnode1.isComment === vnode2.isComment && !vnode1.data === !vnode2.data ) } function createKeyToOldIdx (children, beginIdx, endIdx) { var i, key; var map = {}; for (i = beginIdx; i <= endIdx; ++i) { key = children[i].key; if (isDef(key)) { map[key] = i; } } return map } function createPatchFunction (backend) { var i, j; var cbs = {}; var modules = backend.modules; var nodeOps = backend.nodeOps; for (i = 0; i < hooks$1.length; ++i) { cbs[hooks$1[i]] = []; for (j = 0; j < modules.length; ++j) { if (modules[j][hooks$1[i]] !== undefined) { cbs[hooks$1[i]].push(modules[j][hooks$1[i]]); } } } function emptyNodeAt (elm) { return new VNode(nodeOps.tagName(elm).toLowerCase(), {}, [], undefined, elm) } function createRmCb (childElm, listeners) { function remove$$1 () { if (--remove$$1.listeners === 0) { removeNode(childElm); } } remove$$1.listeners = listeners; return remove$$1 } function removeNode (el) { var parent = nodeOps.parentNode(el); // element may have already been removed due to v-html / v-text if (parent) { nodeOps.removeChild(parent, el); } } var inPre = 0; function createElm (vnode, insertedVnodeQueue, parentElm, refElm, nested) { vnode.isRootInsert = !nested; // for transition enter check if (createComponent(vnode, insertedVnodeQueue, parentElm, refElm)) { return } var data = vnode.data; var children = vnode.children; var tag = vnode.tag; if (isDef(tag)) { { if (data && data.pre) { inPre++; } if ( !inPre && !vnode.ns && !(config.ignoredElements.length && config.ignoredElements.indexOf(tag) > -1) && config.isUnknownElement(tag) ) { warn( 'Unknown custom element: <' + tag + '> - did you ' + 'register the component correctly? For recursive components, ' + 'make sure to provide the "name" option.', vnode.context ); } } vnode.elm = vnode.ns ? nodeOps.createElementNS(vnode.ns, tag) : nodeOps.createElement(tag, vnode); setScope(vnode); /* istanbul ignore if */ { createChildren(vnode, children, insertedVnodeQueue); if (isDef(data)) { invokeCreateHooks(vnode, insertedVnodeQueue); } insert(parentElm, vnode.elm, refElm); } if ("development" !== 'production' && data && data.pre) { inPre--; } } else if (vnode.isComment) { vnode.elm = nodeOps.createComment(vnode.text); insert(parentElm, vnode.elm, refElm); } else { vnode.elm = nodeOps.createTextNode(vnode.text); insert(parentElm, vnode.elm, refElm); } } function createComponent (vnode, insertedVnodeQueue, parentElm, refElm) { var i = vnode.data; if (isDef(i)) { var isReactivated = isDef(vnode.componentInstance) && i.keepAlive; if (isDef(i = i.hook) && isDef(i = i.init)) { i(vnode, false /* hydrating */, parentElm, refElm); } // after calling the init hook, if the vnode is a child component // it should've created a child instance and mounted it. the child // component also has set the placeholder vnode's elm. // in that case we can just return the element and be done. if (isDef(vnode.componentInstance)) { initComponent(vnode, insertedVnodeQueue); if (isReactivated) { reactivateComponent(vnode, insertedVnodeQueue, parentElm, refElm); } return true } } } function initComponent (vnode, insertedVnodeQueue) { if (vnode.data.pendingInsert) { insertedVnodeQueue.push.apply(insertedVnodeQueue, vnode.data.pendingInsert); } vnode.elm = vnode.componentInstance.$el; if (isPatchable(vnode)) { invokeCreateHooks(vnode, insertedVnodeQueue); setScope(vnode); } else { // empty component root. // skip all element-related modules except for ref (#3455) registerRef(vnode); // make sure to invoke the insert hook insertedVnodeQueue.push(vnode); } } function reactivateComponent (vnode, insertedVnodeQueue, parentElm, refElm) { var i; // hack for #4339: a reactivated component with inner transition // does not trigger because the inner node's created hooks are not called // again. It's not ideal to involve module-specific logic in here but // there doesn't seem to be a better way to do it. var innerNode = vnode; while (innerNode.componentInstance) { innerNode = innerNode.componentInstance._vnode; if (isDef(i = innerNode.data) && isDef(i = i.transition)) { for (i = 0; i < cbs.activate.length; ++i) { cbs.activate[i](emptyNode, innerNode); } insertedVnodeQueue.push(innerNode); break } } // unlike a newly created component, // a reactivated keep-alive component doesn't insert itself insert(parentElm, vnode.elm, refElm); } function insert (parent, elm, ref) { if (parent) { if (ref) { nodeOps.insertBefore(parent, elm, ref); } else { nodeOps.appendChild(parent, elm); } } } function createChildren (vnode, children, insertedVnodeQueue) { if (Array.isArray(children)) { for (var i = 0; i < children.length; ++i) { createElm(children[i], insertedVnodeQueue, vnode.elm, null, true); } } else if (isPrimitive(vnode.text)) { nodeOps.appendChild(vnode.elm, nodeOps.createTextNode(vnode.text)); } } function isPatchable (vnode) { while (vnode.componentInstance) { vnode = vnode.componentInstance._vnode; } return isDef(vnode.tag) } function invokeCreateHooks (vnode, insertedVnodeQueue) { for (var i$1 = 0; i$1 < cbs.create.length; ++i$1) { cbs.create[i$1](emptyNode, vnode); } i = vnode.data.hook; // Reuse variable if (isDef(i)) { if (i.create) { i.create(emptyNode, vnode); } if (i.insert) { insertedVnodeQueue.push(vnode); } } } // set scope id attribute for scoped CSS. // this is implemented as a special case to avoid the overhead // of going through the normal attribute patching process. function setScope (vnode) { var i; if (isDef(i = vnode.context) && isDef(i = i.$options._scopeId)) { nodeOps.setAttribute(vnode.elm, i, ''); } if (isDef(i = activeInstance) && i !== vnode.context && isDef(i = i.$options._scopeId)) { nodeOps.setAttribute(vnode.elm, i, ''); } } function addVnodes (parentElm, refElm, vnodes, startIdx, endIdx, insertedVnodeQueue) { for (; startIdx <= endIdx; ++startIdx) { createElm(vnodes[startIdx], insertedVnodeQueue, parentElm, refElm); } } function invokeDestroyHook (vnode) { var i, j; var data = vnode.data; if (isDef(data)) { if (isDef(i = data.hook) && isDef(i = i.destroy)) { i(vnode); } for (i = 0; i < cbs.destroy.length; ++i) { cbs.destroy[i](vnode); } } if (isDef(i = vnode.children)) { for (j = 0; j < vnode.children.length; ++j) { invokeDestroyHook(vnode.children[j]); } } } function removeVnodes (parentElm, vnodes, startIdx, endIdx) { for (; startIdx <= endIdx; ++startIdx) { var ch = vnodes[startIdx]; if (isDef(ch)) { if (isDef(ch.tag)) { removeAndInvokeRemoveHook(ch); invokeDestroyHook(ch); } else { // Text node removeNode(ch.elm); } } } } function removeAndInvokeRemoveHook (vnode, rm) { if (rm || isDef(vnode.data)) { var listeners = cbs.remove.length + 1; if (!rm) { // directly removing rm = createRmCb(vnode.elm, listeners); } else { // we have a recursively passed down rm callback // increase the listeners count rm.listeners += listeners; } // recursively invoke hooks on child component root node if (isDef(i = vnode.componentInstance) && isDef(i = i._vnode) && isDef(i.data)) { removeAndInvokeRemoveHook(i, rm); } for (i = 0; i < cbs.remove.length; ++i) { cbs.remove[i](vnode, rm); } if (isDef(i = vnode.data.hook) && isDef(i = i.remove)) { i(vnode, rm); } else { rm(); } } else { removeNode(vnode.elm); } } function updateChildren (parentElm, oldCh, newCh, insertedVnodeQueue, removeOnly) { var oldStartIdx = 0; var newStartIdx = 0; var oldEndIdx = oldCh.length - 1; var oldStartVnode = oldCh[0]; var oldEndVnode = oldCh[oldEndIdx]; var newEndIdx = newCh.length - 1; var newStartVnode = newCh[0]; var newEndVnode = newCh[newEndIdx]; var oldKeyToIdx, idxInOld, elmToMove, refElm; // removeOnly is a special flag used only by <transition-group> // to ensure removed elements stay in correct relative positions // during leaving transitions var canMove = !removeOnly; while (oldStartIdx <= oldEndIdx && newStartIdx <= newEndIdx) { if (isUndef(oldStartVnode)) { oldStartVnode = oldCh[++oldStartIdx]; // Vnode has been moved left } else if (isUndef(oldEndVnode)) { oldEndVnode = oldCh[--oldEndIdx]; } else if (sameVnode(oldStartVnode, newStartVnode)) { patchVnode(oldStartVnode, newStartVnode, insertedVnodeQueue); oldStartVnode = oldCh[++oldStartIdx]; newStartVnode = newCh[++newStartIdx]; } else if (sameVnode(oldEndVnode, newEndVnode)) { patchVnode(oldEndVnode, newEndVnode, insertedVnodeQueue); oldEndVnode = oldCh[--oldEndIdx]; newEndVnode = newCh[--newEndIdx]; } else if (sameVnode(oldStartVnode, newEndVnode)) { // Vnode moved right patchVnode(oldStartVnode, newEndVnode, insertedVnodeQueue); canMove && nodeOps.insertBefore(parentElm, oldStartVnode.elm, nodeOps.nextSibling(oldEndVnode.elm)); oldStartVnode = oldCh[++oldStartIdx]; newEndVnode = newCh[--newEndIdx]; } else if (sameVnode(oldEndVnode, newStartVnode)) { // Vnode moved left patchVnode(oldEndVnode, newStartVnode, insertedVnodeQueue); canMove && nodeOps.insertBefore(parentElm, oldEndVnode.elm, oldStartVnode.elm); oldEndVnode = oldCh[--oldEndIdx]; newStartVnode = newCh[++newStartIdx]; } else { if (isUndef(oldKeyToIdx)) { oldKeyToIdx = createKeyToOldIdx(oldCh, oldStartIdx, oldEndIdx); } idxInOld = isDef(newStartVnode.key) ? oldKeyToIdx[newStartVnode.key] : null; if (isUndef(idxInOld)) { // New element createElm(newStartVnode, insertedVnodeQueue, parentElm, oldStartVnode.elm); newStartVnode = newCh[++newStartIdx]; } else { elmToMove = oldCh[idxInOld]; /* istanbul ignore if */ if ("development" !== 'production' && !elmToMove) { warn( 'It seems there are duplicate keys that is causing an update error. ' + 'Make sure each v-for item has a unique key.' ); } if (sameVnode(elmToMove, newStartVnode)) { patchVnode(elmToMove, newStartVnode, insertedVnodeQueue); oldCh[idxInOld] = undefined; canMove && nodeOps.insertBefore(parentElm, newStartVnode.elm, oldStartVnode.elm); newStartVnode = newCh[++newStartIdx]; } else { // same key but different element. treat as new element createElm(newStartVnode, insertedVnodeQueue, parentElm, oldStartVnode.elm); newStartVnode = newCh[++newStartIdx]; } } } } if (oldStartIdx > oldEndIdx) { refElm = isUndef(newCh[newEndIdx + 1]) ? null : newCh[newEndIdx + 1].elm; addVnodes(parentElm, refElm, newCh, newStartIdx, newEndIdx, insertedVnodeQueue); } else if (newStartIdx > newEndIdx) { removeVnodes(parentElm, oldCh, oldStartIdx, oldEndIdx); } } function patchVnode (oldVnode, vnode, insertedVnodeQueue, removeOnly) { if (oldVnode === vnode) { return } // reuse element for static trees. // note we only do this if the vnode is cloned - // if the new node is not cloned it means the render functions have been // reset by the hot-reload-api and we need to do a proper re-render. if (vnode.isStatic && oldVnode.isStatic && vnode.key === oldVnode.key && (vnode.isCloned || vnode.isOnce)) { vnode.elm = oldVnode.elm; vnode.componentInstance = oldVnode.componentInstance; return } var i; var data = vnode.data; var hasData = isDef(data); if (hasData && isDef(i = data.hook) && isDef(i = i.prepatch)) { i(oldVnode, vnode); } var elm = vnode.elm = oldVnode.elm; var oldCh = oldVnode.children; var ch = vnode.children; if (hasData && isPatchable(vnode)) { for (i = 0; i < cbs.update.length; ++i) { cbs.update[i](oldVnode, vnode); } if (isDef(i = data.hook) && isDef(i = i.update)) { i(oldVnode, vnode); } } if (isUndef(vnode.text)) { if (isDef(oldCh) && isDef(ch)) { if (oldCh !== ch) { updateChildren(elm, oldCh, ch, insertedVnodeQueue, removeOnly); } } else if (isDef(ch)) { if (isDef(oldVnode.text)) { nodeOps.setTextContent(elm, ''); } addVnodes(elm, null, ch, 0, ch.length - 1, insertedVnodeQueue); } else if (isDef(oldCh)) { removeVnodes(elm, oldCh, 0, oldCh.length - 1); } else if (isDef(oldVnode.text)) { nodeOps.setTextContent(elm, ''); } } else if (oldVnode.text !== vnode.text) { nodeOps.setTextContent(elm, vnode.text); } if (hasData) { if (isDef(i = data.hook) && isDef(i = i.postpatch)) { i(oldVnode, vnode); } } } function invokeInsertHook (vnode, queue, initial) { // delay insert hooks for component root nodes, invoke them after the // element is really inserted if (initial && vnode.parent) { vnode.parent.data.pendingInsert = queue; } else { for (var i = 0; i < queue.length; ++i) { queue[i].data.hook.insert(queue[i]); } } } var bailed = false; // list of modules that can skip create hook during hydration because they // are already rendered on the client or has no need for initialization var isRenderedModule = makeMap('attrs,style,class,staticClass,staticStyle,key'); // Note: this is a browser-only function so we can assume elms are DOM nodes. function hydrate (elm, vnode, insertedVnodeQueue) { { if (!assertNodeMatch(elm, vnode)) { return false } } vnode.elm = elm; var tag = vnode.tag; var data = vnode.data; var children = vnode.children; if (isDef(data)) { if (isDef(i = data.hook) && isDef(i = i.init)) { i(vnode, true /* hydrating */); } if (isDef(i = vnode.componentInstance)) { // child component. it should have hydrated its own tree. initComponent(vnode, insertedVnodeQueue); return true } } if (isDef(tag)) { if (isDef(children)) { // empty element, allow client to pick up and populate children if (!elm.hasChildNodes()) { createChildren(vnode, children, insertedVnodeQueue); } else { var childrenMatch = true; var childNode = elm.firstChild; for (var i$1 = 0; i$1 < children.length; i$1++) { if (!childNode || !hydrate(childNode, children[i$1], insertedVnodeQueue)) { childrenMatch = false; break } childNode = childNode.nextSibling; } // if childNode is not null, it means the actual childNodes list is // longer than the virtual children list. if (!childrenMatch || childNode) { if ("development" !== 'production' && typeof console !== 'undefined' && !bailed) { bailed = true; console.warn('Parent: ', elm); console.warn('Mismatching childNodes vs. VNodes: ', elm.childNodes, children); } return false } } } if (isDef(data)) { for (var key in data) { if (!isRenderedModule(key)) { invokeCreateHooks(vnode, insertedVnodeQueue); break } } } } else if (elm.data !== vnode.text) { elm.data = vnode.text; } return true } function assertNodeMatch (node, vnode) { if (vnode.tag) { return ( vnode.tag.indexOf('vue-component') === 0 || vnode.tag.toLowerCase() === (node.tagName && node.tagName.toLowerCase()) ) } else { return node.nodeType === (vnode.isComment ? 8 : 3) } } return function patch (oldVnode, vnode, hydrating, removeOnly, parentElm, refElm) { if (!vnode) { if (oldVnode) { invokeDestroyHook(oldVnode); } return } var isInitialPatch = false; var insertedVnodeQueue = []; if (!oldVnode) { // empty mount (likely as component), create new root element isInitialPatch = true; createElm(vnode, insertedVnodeQueue, parentElm, refElm); } else { var isRealElement = isDef(oldVnode.nodeType); if (!isRealElement && sameVnode(oldVnode, vnode)) { // patch existing root node patchVnode(oldVnode, vnode, insertedVnodeQueue, removeOnly); } else { if (isRealElement) { // mounting to a real element // check if this is server-rendered content and if we can perform // a successful hydration. if (oldVnode.nodeType === 1 && oldVnode.hasAttribute('server-rendered')) { oldVnode.removeAttribute('server-rendered'); hydrating = true; } if (hydrating) { if (hydrate(oldVnode, vnode, insertedVnodeQueue)) { invokeInsertHook(vnode, insertedVnodeQueue, true); return oldVnode } else { warn( 'The client-side rendered virtual DOM tree is not matching ' + 'server-rendered content. This is likely caused by incorrect ' + 'HTML markup, for example nesting block-level elements inside ' + '<p>, or missing <tbody>. Bailing hydration and performing ' + 'full client-side render.' ); } } // either not server-rendered, or hydration failed. // create an empty node and replace it oldVnode = emptyNodeAt(oldVnode); } // replacing existing element var oldElm = oldVnode.elm; var parentElm$1 = nodeOps.parentNode(oldElm); createElm( vnode, insertedVnodeQueue, // extremely rare edge case: do not insert if old element is in a // leaving transition. Only happens when combining transition + // keep-alive + HOCs. (#4590) oldElm._leaveCb ? null : parentElm$1, nodeOps.nextSibling(oldElm) ); if (vnode.parent) { // component root element replaced. // update parent placeholder node element, recursively var ancestor = vnode.parent; while (ancestor) { ancestor.elm = vnode.elm; ancestor = ancestor.parent; } if (isPatchable(vnode)) { for (var i = 0; i < cbs.create.length; ++i) { cbs.create[i](emptyNode, vnode.parent); } } } if (parentElm$1 !== null) { removeVnodes(parentElm$1, [oldVnode], 0, 0); } else if (isDef(oldVnode.tag)) { invokeDestroyHook(oldVnode); } } } invokeInsertHook(vnode, insertedVnodeQueue, isInitialPatch); return vnode.elm } } /* */ var directives = { create: updateDirectives, update: updateDirectives, destroy: function unbindDirectives (vnode) { updateDirectives(vnode, emptyNode); } }; function updateDirectives (oldVnode, vnode) { if (oldVnode.data.directives || vnode.data.directives) { _update(oldVnode, vnode); } } function _update (oldVnode, vnode) { var isCreate = oldVnode === emptyNode; var isDestroy = vnode === emptyNode; var oldDirs = normalizeDirectives$1(oldVnode.data.directives, oldVnode.context); var newDirs = normalizeDirectives$1(vnode.data.directives, vnode.context); var dirsWithInsert = []; var dirsWithPostpatch = []; var key, oldDir, dir; for (key in newDirs) { oldDir = oldDirs[key]; dir = newDirs[key]; if (!oldDir) { // new directive, bind callHook$1(dir, 'bind', vnode, oldVnode); if (dir.def && dir.def.inserted) { dirsWithInsert.push(dir); } } else { // existing directive, update dir.oldValue = oldDir.value; callHook$1(dir, 'update', vnode, oldVnode); if (dir.def && dir.def.componentUpdated) { dirsWithPostpatch.push(dir); } } } if (dirsWithInsert.length) { var callInsert = function () { for (var i = 0; i < dirsWithInsert.length; i++) { callHook$1(dirsWithInsert[i], 'inserted', vnode, oldVnode); } }; if (isCreate) { mergeVNodeHook(vnode.data.hook || (vnode.data.hook = {}), 'insert', callInsert, 'dir-insert'); } else { callInsert(); } } if (dirsWithPostpatch.length) { mergeVNodeHook(vnode.data.hook || (vnode.data.hook = {}), 'postpatch', function () { for (var i = 0; i < dirsWithPostpatch.length; i++) { callHook$1(dirsWithPostpatch[i], 'componentUpdated', vnode, oldVnode); } }, 'dir-postpatch'); } if (!isCreate) { for (key in oldDirs) { if (!newDirs[key]) { // no longer present, unbind callHook$1(oldDirs[key], 'unbind', oldVnode, oldVnode, isDestroy); } } } } var emptyModifiers = Object.create(null); function normalizeDirectives$1 ( dirs, vm ) { var res = Object.create(null); if (!dirs) { return res } var i, dir; for (i = 0; i < dirs.length; i++) { dir = dirs[i]; if (!dir.modifiers) { dir.modifiers = emptyModifiers; } res[getRawDirName(dir)] = dir; dir.def = resolveAsset(vm.$options, 'directives', dir.name, true); } return res } function getRawDirName (dir) { return dir.rawName || ((dir.name) + "." + (Object.keys(dir.modifiers || {}).join('.'))) } function callHook$1 (dir, hook, vnode, oldVnode, isDestroy) { var fn = dir.def && dir.def[hook]; if (fn) { fn(vnode.elm, dir, vnode, oldVnode, isDestroy); } } var baseModules = [ ref, directives ]; /* */ function updateAttrs (oldVnode, vnode) { if (!oldVnode.data.attrs && !vnode.data.attrs) { return } var key, cur, old; var elm = vnode.elm; var oldAttrs = oldVnode.data.attrs || {}; var attrs = vnode.data.attrs || {}; // clone observed objects, as the user probably wants to mutate it if (attrs.__ob__) { attrs = vnode.data.attrs = extend({}, attrs); } for (key in attrs) { cur = attrs[key]; old = oldAttrs[key]; if (old !== cur) { setAttr(elm, key, cur); } } // #4391: in IE9, setting type can reset value for input[type=radio] /* istanbul ignore if */ if (isIE9 && attrs.value !== oldAttrs.value) { setAttr(elm, 'value', attrs.value); } for (key in oldAttrs) { if (attrs[key] == null) { if (isXlink(key)) { elm.removeAttributeNS(xlinkNS, getXlinkProp(key)); } else if (!isEnumeratedAttr(key)) { elm.removeAttribute(key); } } } } function setAttr (el, key, value) { if (isBooleanAttr(key)) { // set attribute for blank value // e.g. <option disabled>Select one</option> if (isFalsyAttrValue(value)) { el.removeAttribute(key); } else { el.setAttribute(key, key); } } else if (isEnumeratedAttr(key)) { el.setAttribute(key, isFalsyAttrValue(value) || value === 'false' ? 'false' : 'true'); } else if (isXlink(key)) { if (isFalsyAttrValue(value)) { el.removeAttributeNS(xlinkNS, getXlinkProp(key)); } else { el.setAttributeNS(xlinkNS, key, value); } } else { if (isFalsyAttrValue(value)) { el.removeAttribute(key); } else { el.setAttribute(key, value); } } } var attrs = { create: updateAttrs, update: updateAttrs }; /* */ function updateClass (oldVnode, vnode) { var el = vnode.elm; var data = vnode.data; var oldData = oldVnode.data; if (!data.staticClass && !data.class && (!oldData || (!oldData.staticClass && !oldData.class))) { return } var cls = genClassForVnode(vnode); // handle transition classes var transitionClass = el._transitionClasses; if (transitionClass) { cls = concat(cls, stringifyClass(transitionClass)); } // set the class if (cls !== el._prevClass) { el.setAttribute('class', cls); el._prevClass = cls; } } var klass = { create: updateClass, update: updateClass }; /* */ var target$1; function add$2 ( event, handler, once, capture ) { if (once) { var oldHandler = handler; var _target = target$1; // save current target element in closure handler = function (ev) { remove$3(event, handler, capture, _target); arguments.length === 1 ? oldHandler(ev) : oldHandler.apply(null, arguments); }; } target$1.addEventListener(event, handler, capture); } function remove$3 ( event, handler, capture, _target ) { (_target || target$1).removeEventListener(event, handler, capture); } function updateDOMListeners (oldVnode, vnode) { if (!oldVnode.data.on && !vnode.data.on) { return } var on = vnode.data.on || {}; var oldOn = oldVnode.data.on || {}; target$1 = vnode.elm; updateListeners(on, oldOn, add$2, remove$3, vnode.context); } var events = { create: updateDOMListeners, update: updateDOMListeners }; /* */ function updateDOMProps (oldVnode, vnode) { if (!oldVnode.data.domProps && !vnode.data.domProps) { return } var key, cur; var elm = vnode.elm; var oldProps = oldVnode.data.domProps || {}; var props = vnode.data.domProps || {}; // clone observed objects, as the user probably wants to mutate it if (props.__ob__) { props = vnode.data.domProps = extend({}, props); } for (key in oldProps) { if (props[key] == null) { elm[key] = ''; } } for (key in props) { cur = props[key]; // ignore children if the node has textContent or innerHTML, // as these will throw away existing DOM nodes and cause removal errors // on subsequent patches (#3360) if (key === 'textContent' || key === 'innerHTML') { if (vnode.children) { vnode.children.length = 0; } if (cur === oldProps[key]) { continue } } if (key === 'value') { // store value as _value as well since // non-string values will be stringified elm._value = cur; // avoid resetting cursor position when value is the same var strCur = cur == null ? '' : String(cur); if (shouldUpdateValue(elm, vnode, strCur)) { elm.value = strCur; } } else { elm[key] = cur; } } } // check platforms/web/util/attrs.js acceptValue function shouldUpdateValue ( elm, vnode, checkVal ) { return (!elm.composing && ( vnode.tag === 'option' || isDirty(elm, checkVal) || isInputChanged(vnode, checkVal) )) } function isDirty (elm, checkVal) { // return true when textbox (.number and .trim) loses focus and its value is not equal to the updated value return document.activeElement !== elm && elm.value !== checkVal } function isInputChanged (vnode, newVal) { var value = vnode.elm.value; var modifiers = vnode.elm._vModifiers; // injected by v-model runtime if ((modifiers && modifiers.number) || vnode.elm.type === 'number') { return toNumber(value) !== toNumber(newVal) } if (modifiers && modifiers.trim) { return value.trim() !== newVal.trim() } return value !== newVal } var domProps = { create: updateDOMProps, update: updateDOMProps }; /* */ var parseStyleText = cached(function (cssText) { var res = {}; var listDelimiter = /;(?![^(]*\))/g; var propertyDelimiter = /:(.+)/; cssText.split(listDelimiter).forEach(function (item) { if (item) { var tmp = item.split(propertyDelimiter); tmp.length > 1 && (res[tmp[0].trim()] = tmp[1].trim()); } }); return res }); // merge static and dynamic style data on the same vnode function normalizeStyleData (data) { var style = normalizeStyleBinding(data.style); // static style is pre-processed into an object during compilation // and is always a fresh object, so it's safe to merge into it return data.staticStyle ? extend(data.staticStyle, style) : style } // normalize possible array / string values into Object function normalizeStyleBinding (bindingStyle) { if (Array.isArray(bindingStyle)) { return toObject(bindingStyle) } if (typeof bindingStyle === 'string') { return parseStyleText(bindingStyle) } return bindingStyle } /** * parent component style should be after child's * so that parent component's style could override it */ function getStyle (vnode, checkChild) { var res = {}; var styleData; if (checkChild) { var childNode = vnode; while (childNode.componentInstance) { childNode = childNode.componentInstance._vnode; if (childNode.data && (styleData = normalizeStyleData(childNode.data))) { extend(res, styleData); } } } if ((styleData = normalizeStyleData(vnode.data))) { extend(res, styleData); } var parentNode = vnode; while ((parentNode = parentNode.parent)) { if (parentNode.data && (styleData = normalizeStyleData(parentNode.data))) { extend(res, styleData); } } return res } /* */ var cssVarRE = /^--/; var importantRE = /\s*!important$/; var setProp = function (el, name, val) { /* istanbul ignore if */ if (cssVarRE.test(name)) { el.style.setProperty(name, val); } else if (importantRE.test(val)) { el.style.setProperty(name, val.replace(importantRE, ''), 'important'); } else { el.style[normalize(name)] = val; } }; var prefixes = ['Webkit', 'Moz', 'ms']; var testEl; var normalize = cached(function (prop) { testEl = testEl || document.createElement('div'); prop = camelize(prop); if (prop !== 'filter' && (prop in testEl.style)) { return prop } var upper = prop.charAt(0).toUpperCase() + prop.slice(1); for (var i = 0; i < prefixes.length; i++) { var prefixed = prefixes[i] + upper; if (prefixed in testEl.style) { return prefixed } } }); function updateStyle (oldVnode, vnode) { var data = vnode.data; var oldData = oldVnode.data; if (!data.staticStyle && !data.style && !oldData.staticStyle && !oldData.style) { return } var cur, name; var el = vnode.elm; var oldStaticStyle = oldVnode.data.staticStyle; var oldStyleBinding = oldVnode.data.style || {}; // if static style exists, stylebinding already merged into it when doing normalizeStyleData var oldStyle = oldStaticStyle || oldStyleBinding; var style = normalizeStyleBinding(vnode.data.style) || {}; vnode.data.style = style.__ob__ ? extend({}, style) : style; var newStyle = getStyle(vnode, true); for (name in oldStyle) { if (newStyle[name] == null) { setProp(el, name, ''); } } for (name in newStyle) { cur = newStyle[name]; if (cur !== oldStyle[name]) { // ie9 setting to null has no effect, must use empty string setProp(el, name, cur == null ? '' : cur); } } } var style = { create: updateStyle, update: updateStyle }; /* */ /** * Add class with compatibility for SVG since classList is not supported on * SVG elements in IE */ function addClass (el, cls) { /* istanbul ignore if */ if (!cls || !cls.trim()) { return } /* istanbul ignore else */ if (el.classList) { if (cls.indexOf(' ') > -1) { cls.split(/\s+/).forEach(function (c) { return el.classList.add(c); }); } else { el.classList.add(cls); } } else { var cur = ' ' + el.getAttribute('class') + ' '; if (cur.indexOf(' ' + cls + ' ') < 0) { el.setAttribute('class', (cur + cls).trim()); } } } /** * Remove class with compatibility for SVG since classList is not supported on * SVG elements in IE */ function removeClass (el, cls) { /* istanbul ignore if */ if (!cls || !cls.trim()) { return } /* istanbul ignore else */ if (el.classList) { if (cls.indexOf(' ') > -1) { cls.split(/\s+/).forEach(function (c) { return el.classList.remove(c); }); } else { el.classList.remove(cls); } } else { var cur = ' ' + el.getAttribute('class') + ' '; var tar = ' ' + cls + ' '; while (cur.indexOf(tar) >= 0) { cur = cur.replace(tar, ' '); } el.setAttribute('class', cur.trim()); } } /* */ var hasTransition = inBrowser && !isIE9; var TRANSITION = 'transition'; var ANIMATION = 'animation'; // Transition property/event sniffing var transitionProp = 'transition'; var transitionEndEvent = 'transitionend'; var animationProp = 'animation'; var animationEndEvent = 'animationend'; if (hasTransition) { /* istanbul ignore if */ if (window.ontransitionend === undefined && window.onwebkittransitionend !== undefined) { transitionProp = 'WebkitTransition'; transitionEndEvent = 'webkitTransitionEnd'; } if (window.onanimationend === undefined && window.onwebkitanimationend !== undefined) { animationProp = 'WebkitAnimation'; animationEndEvent = 'webkitAnimationEnd'; } } // binding to window is necessary to make hot reload work in IE in strict mode var raf = inBrowser && window.requestAnimationFrame ? window.requestAnimationFrame.bind(window) : setTimeout; function nextFrame (fn) { raf(function () { raf(fn); }); } function addTransitionClass (el, cls) { (el._transitionClasses || (el._transitionClasses = [])).push(cls); addClass(el, cls); } function removeTransitionClass (el, cls) { if (el._transitionClasses) { remove$1(el._transitionClasses, cls); } removeClass(el, cls); } function whenTransitionEnds ( el, expectedType, cb ) { var ref = getTransitionInfo(el, expectedType); var type = ref.type; var timeout = ref.timeout; var propCount = ref.propCount; if (!type) { return cb() } var event = type === TRANSITION ? transitionEndEvent : animationEndEvent; var ended = 0; var end = function () { el.removeEventListener(event, onEnd); cb(); }; var onEnd = function (e) { if (e.target === el) { if (++ended >= propCount) { end(); } } }; setTimeout(function () { if (ended < propCount) { end(); } }, timeout + 1); el.addEventListener(event, onEnd); } var transformRE = /\b(transform|all)(,|$)/; function getTransitionInfo (el, expectedType) { var styles = window.getComputedStyle(el); var transitioneDelays = styles[transitionProp + 'Delay'].split(', '); var transitionDurations = styles[transitionProp + 'Duration'].split(', '); var transitionTimeout = getTimeout(transitioneDelays, transitionDurations); var animationDelays = styles[animationProp + 'Delay'].split(', '); var animationDurations = styles[animationProp + 'Duration'].split(', '); var animationTimeout = getTimeout(animationDelays, animationDurations); var type; var timeout = 0; var propCount = 0; /* istanbul ignore if */ if (expectedType === TRANSITION) { if (transitionTimeout > 0) { type = TRANSITION; timeout = transitionTimeout; propCount = transitionDurations.length; } } else if (expectedType === ANIMATION) { if (animationTimeout > 0) { type = ANIMATION; timeout = animationTimeout; propCount = animationDurations.length; } } else { timeout = Math.max(transitionTimeout, animationTimeout); type = timeout > 0 ? transitionTimeout > animationTimeout ? TRANSITION : ANIMATION : null; propCount = type ? type === TRANSITION ? transitionDurations.length : animationDurations.length : 0; } var hasTransform = type === TRANSITION && transformRE.test(styles[transitionProp + 'Property']); return { type: type, timeout: timeout, propCount: propCount, hasTransform: hasTransform } } function getTimeout (delays, durations) { /* istanbul ignore next */ while (delays.length < durations.length) { delays = delays.concat(delays); } return Math.max.apply(null, durations.map(function (d, i) { return toMs(d) + toMs(delays[i]) })) } function toMs (s) { return Number(s.slice(0, -1)) * 1000 } /* */ function enter (vnode, toggleDisplay) { var el = vnode.elm; // call leave callback now if (el._leaveCb) { el._leaveCb.cancelled = true; el._leaveCb(); } var data = resolveTransition(vnode.data.transition); if (!data) { return } /* istanbul ignore if */ if (el._enterCb || el.nodeType !== 1) { return } var css = data.css; var type = data.type; var enterClass = data.enterClass; var enterToClass = data.enterToClass; var enterActiveClass = data.enterActiveClass; var appearClass = data.appearClass; var appearToClass = data.appearToClass; var appearActiveClass = data.appearActiveClass; var beforeEnter = data.beforeEnter; var enter = data.enter; var afterEnter = data.afterEnter; var enterCancelled = data.enterCancelled; var beforeAppear = data.beforeAppear; var appear = data.appear; var afterAppear = data.afterAppear; var appearCancelled = data.appearCancelled; // activeInstance will always be the <transition> component managing this // transition. One edge case to check is when the <transition> is placed // as the root node of a child component. In that case we need to check // <transition>'s parent for appear check. var context = activeInstance; var transitionNode = activeInstance.$vnode; while (transitionNode && transitionNode.parent) { transitionNode = transitionNode.parent; context = transitionNode.context; } var isAppear = !context._isMounted || !vnode.isRootInsert; if (isAppear && !appear && appear !== '') { return } var startClass = isAppear ? appearClass : enterClass; var activeClass = isAppear ? appearActiveClass : enterActiveClass; var toClass = isAppear ? appearToClass : enterToClass; var beforeEnterHook = isAppear ? (beforeAppear || beforeEnter) : beforeEnter; var enterHook = isAppear ? (typeof appear === 'function' ? appear : enter) : enter; var afterEnterHook = isAppear ? (afterAppear || afterEnter) : afterEnter; var enterCancelledHook = isAppear ? (appearCancelled || enterCancelled) : enterCancelled; var expectsCSS = css !== false && !isIE9; var userWantsControl = enterHook && // enterHook may be a bound method which exposes // the length of original fn as _length (enterHook._length || enterHook.length) > 1; var cb = el._enterCb = once(function () { if (expectsCSS) { removeTransitionClass(el, toClass); removeTransitionClass(el, activeClass); } if (cb.cancelled) { if (expectsCSS) { removeTransitionClass(el, startClass); } enterCancelledHook && enterCancelledHook(el); } else { afterEnterHook && afterEnterHook(el); } el._enterCb = null; }); if (!vnode.data.show) { // remove pending leave element on enter by injecting an insert hook mergeVNodeHook(vnode.data.hook || (vnode.data.hook = {}), 'insert', function () { var parent = el.parentNode; var pendingNode = parent && parent._pending && parent._pending[vnode.key]; if (pendingNode && pendingNode.tag === vnode.tag && pendingNode.elm._leaveCb) { pendingNode.elm._leaveCb(); } enterHook && enterHook(el, cb); }, 'transition-insert'); } // start enter transition beforeEnterHook && beforeEnterHook(el); if (expectsCSS) { addTransitionClass(el, startClass); addTransitionClass(el, activeClass); nextFrame(function () { addTransitionClass(el, toClass); removeTransitionClass(el, startClass); if (!cb.cancelled && !userWantsControl) { whenTransitionEnds(el, type, cb); } }); } if (vnode.data.show) { toggleDisplay && toggleDisplay(); enterHook && enterHook(el, cb); } if (!expectsCSS && !userWantsControl) { cb(); } } function leave (vnode, rm) { var el = vnode.elm; // call enter callback now if (el._enterCb) { el._enterCb.cancelled = true; el._enterCb(); } var data = resolveTransition(vnode.data.transition); if (!data) { return rm() } /* istanbul ignore if */ if (el._leaveCb || el.nodeType !== 1) { return } var css = data.css; var type = data.type; var leaveClass = data.leaveClass; var leaveToClass = data.leaveToClass; var leaveActiveClass = data.leaveActiveClass; var beforeLeave = data.beforeLeave; var leave = data.leave; var afterLeave = data.afterLeave; var leaveCancelled = data.leaveCancelled; var delayLeave = data.delayLeave; var expectsCSS = css !== false && !isIE9; var userWantsControl = leave && // leave hook may be a bound method which exposes // the length of original fn as _length (leave._length || leave.length) > 1; var cb = el._leaveCb = once(function () { if (el.parentNode && el.parentNode._pending) { el.parentNode._pending[vnode.key] = null; } if (expectsCSS) { removeTransitionClass(el, leaveToClass); removeTransitionClass(el, leaveActiveClass); } if (cb.cancelled) { if (expectsCSS) { removeTransitionClass(el, leaveClass); } leaveCancelled && leaveCancelled(el); } else { rm(); afterLeave && afterLeave(el); } el._leaveCb = null; }); if (delayLeave) { delayLeave(performLeave); } else { performLeave(); } function performLeave () { // the delayed leave may have already been cancelled if (cb.cancelled) { return } // record leaving element if (!vnode.data.show) { (el.parentNode._pending || (el.parentNode._pending = {}))[vnode.key] = vnode; } beforeLeave && beforeLeave(el); if (expectsCSS) { addTransitionClass(el, leaveClass); addTransitionClass(el, leaveActiveClass); nextFrame(function () { addTransitionClass(el, leaveToClass); removeTransitionClass(el, leaveClass); if (!cb.cancelled && !userWantsControl) { whenTransitionEnds(el, type, cb); } }); } leave && leave(el, cb); if (!expectsCSS && !userWantsControl) { cb(); } } } function resolveTransition (def$$1) { if (!def$$1) { return } /* istanbul ignore else */ if (typeof def$$1 === 'object') { var res = {}; if (def$$1.css !== false) { extend(res, autoCssTransition(def$$1.name || 'v')); } extend(res, def$$1); return res } else if (typeof def$$1 === 'string') { return autoCssTransition(def$$1) } } var autoCssTransition = cached(function (name) { return { enterClass: (name + "-enter"), leaveClass: (name + "-leave"), appearClass: (name + "-enter"), enterToClass: (name + "-enter-to"), leaveToClass: (name + "-leave-to"), appearToClass: (name + "-enter-to"), enterActiveClass: (name + "-enter-active"), leaveActiveClass: (name + "-leave-active"), appearActiveClass: (name + "-enter-active") } }); function once (fn) { var called = false; return function () { if (!called) { called = true; fn(); } } } function _enter (_, vnode) { if (!vnode.data.show) { enter(vnode); } } var transition = inBrowser ? { create: _enter, activate: _enter, remove: function remove (vnode, rm) { /* istanbul ignore else */ if (!vnode.data.show) { leave(vnode, rm); } else { rm(); } } } : {}; var platformModules = [ attrs, klass, events, domProps, style, transition ]; /* */ // the directive module should be applied last, after all // built-in modules have been applied. var modules = platformModules.concat(baseModules); var patch$1 = createPatchFunction({ nodeOps: nodeOps, modules: modules }); /** * Not type checking this file because flow doesn't like attaching * properties to Elements. */ var modelableTagRE = /^input|select|textarea|vue-component-[0-9]+(-[0-9a-zA-Z_-]*)?$/; /* istanbul ignore if */ if (isIE9) { // http://www.matts411.com/post/internet-explorer-9-oninput/ document.addEventListener('selectionchange', function () { var el = document.activeElement; if (el && el.vmodel) { trigger(el, 'input'); } }); } var model = { inserted: function inserted (el, binding, vnode) { { if (!modelableTagRE.test(vnode.tag)) { warn( "v-model is not supported on element type: <" + (vnode.tag) + ">. " + 'If you are working with contenteditable, it\'s recommended to ' + 'wrap a library dedicated for that purpose inside a custom component.', vnode.context ); } } if (vnode.tag === 'select') { var cb = function () { setSelected(el, binding, vnode.context); }; cb(); /* istanbul ignore if */ if (isIE || isEdge) { setTimeout(cb, 0); } } else if (vnode.tag === 'textarea' || el.type === 'text') { el._vModifiers = binding.modifiers; if (!binding.modifiers.lazy) { if (!isAndroid) { el.addEventListener('compositionstart', onCompositionStart); el.addEventListener('compositionend', onCompositionEnd); } /* istanbul ignore if */ if (isIE9) { el.vmodel = true; } } } }, componentUpdated: function componentUpdated (el, binding, vnode) { if (vnode.tag === 'select') { setSelected(el, binding, vnode.context); // in case the options rendered by v-for have changed, // it's possible that the value is out-of-sync with the rendered options. // detect such cases and filter out values that no longer has a matching // option in the DOM. var needReset = el.multiple ? binding.value.some(function (v) { return hasNoMatchingOption(v, el.options); }) : binding.value !== binding.oldValue && hasNoMatchingOption(binding.value, el.options); if (needReset) { trigger(el, 'change'); } } } }; function setSelected (el, binding, vm) { var value = binding.value; var isMultiple = el.multiple; if (isMultiple && !Array.isArray(value)) { "development" !== 'production' && warn( "<select multiple v-model=\"" + (binding.expression) + "\"> " + "expects an Array value for its binding, but got " + (Object.prototype.toString.call(value).slice(8, -1)), vm ); return } var selected, option; for (var i = 0, l = el.options.length; i < l; i++) { option = el.options[i]; if (isMultiple) { selected = looseIndexOf(value, getValue(option)) > -1; if (option.selected !== selected) { option.selected = selected; } } else { if (looseEqual(getValue(option), value)) { if (el.selectedIndex !== i) { el.selectedIndex = i; } return } } } if (!isMultiple) { el.selectedIndex = -1; } } function hasNoMatchingOption (value, options) { for (var i = 0, l = options.length; i < l; i++) { if (looseEqual(getValue(options[i]), value)) { return false } } return true } function getValue (option) { return '_value' in option ? option._value : option.value } function onCompositionStart (e) { e.target.composing = true; } function onCompositionEnd (e) { e.target.composing = false; trigger(e.target, 'input'); } function trigger (el, type) { var e = document.createEvent('HTMLEvents'); e.initEvent(type, true, true); el.dispatchEvent(e); } /* */ // recursively search for possible transition defined inside the component root function locateNode (vnode) { return vnode.componentInstance && (!vnode.data || !vnode.data.transition) ? locateNode(vnode.componentInstance._vnode) : vnode } var show = { bind: function bind (el, ref, vnode) { var value = ref.value; vnode = locateNode(vnode); var transition = vnode.data && vnode.data.transition; var originalDisplay = el.__vOriginalDisplay = el.style.display === 'none' ? '' : el.style.display; if (value && transition && !isIE9) { vnode.data.show = true; enter(vnode, function () { el.style.display = originalDisplay; }); } else { el.style.display = value ? originalDisplay : 'none'; } }, update: function update (el, ref, vnode) { var value = ref.value; var oldValue = ref.oldValue; /* istanbul ignore if */ if (value === oldValue) { return } vnode = locateNode(vnode); var transition = vnode.data && vnode.data.transition; if (transition && !isIE9) { vnode.data.show = true; if (value) { enter(vnode, function () { el.style.display = el.__vOriginalDisplay; }); } else { leave(vnode, function () { el.style.display = 'none'; }); } } else { el.style.display = value ? el.__vOriginalDisplay : 'none'; } }, unbind: function unbind ( el, binding, vnode, oldVnode, isDestroy ) { if (!isDestroy) { el.style.display = el.__vOriginalDisplay; } } }; var platformDirectives = { model: model, show: show }; /* */ // Provides transition support for a single element/component. // supports transition mode (out-in / in-out) var transitionProps = { name: String, appear: Boolean, css: Boolean, mode: String, type: String, enterClass: String, leaveClass: String, enterToClass: String, leaveToClass: String, enterActiveClass: String, leaveActiveClass: String, appearClass: String, appearActiveClass: String, appearToClass: String }; // in case the child is also an abstract component, e.g. <keep-alive> // we want to recursively retrieve the real component to be rendered function getRealChild (vnode) { var compOptions = vnode && vnode.componentOptions; if (compOptions && compOptions.Ctor.options.abstract) { return getRealChild(getFirstComponentChild(compOptions.children)) } else { return vnode } } function extractTransitionData (comp) { var data = {}; var options = comp.$options; // props for (var key in options.propsData) { data[key] = comp[key]; } // events. // extract listeners and pass them directly to the transition methods var listeners = options._parentListeners; for (var key$1 in listeners) { data[camelize(key$1)] = listeners[key$1].fn; } return data } function placeholder (h, rawChild) { return /\d-keep-alive$/.test(rawChild.tag) ? h('keep-alive') : null } function hasParentTransition (vnode) { while ((vnode = vnode.parent)) { if (vnode.data.transition) { return true } } } function isSameChild (child, oldChild) { return oldChild.key === child.key && oldChild.tag === child.tag } var Transition = { name: 'transition', props: transitionProps, abstract: true, render: function render (h) { var this$1 = this; var children = this.$slots.default; if (!children) { return } // filter out text nodes (possible whitespaces) children = children.filter(function (c) { return c.tag; }); /* istanbul ignore if */ if (!children.length) { return } // warn multiple elements if ("development" !== 'production' && children.length > 1) { warn( '<transition> can only be used on a single element. Use ' + '<transition-group> for lists.', this.$parent ); } var mode = this.mode; // warn invalid mode if ("development" !== 'production' && mode && mode !== 'in-out' && mode !== 'out-in') { warn( 'invalid <transition> mode: ' + mode, this.$parent ); } var rawChild = children[0]; // if this is a component root node and the component's // parent container node also has transition, skip. if (hasParentTransition(this.$vnode)) { return rawChild } // apply transition data to child // use getRealChild() to ignore abstract components e.g. keep-alive var child = getRealChild(rawChild); /* istanbul ignore if */ if (!child) { return rawChild } if (this._leaving) { return placeholder(h, rawChild) } // ensure a key that is unique to the vnode type and to this transition // component instance. This key will be used to remove pending leaving nodes // during entering. var id = "__transition-" + (this._uid) + "-"; var key = child.key = child.key == null ? id + child.tag : isPrimitive(child.key) ? (String(child.key).indexOf(id) === 0 ? child.key : id + child.key) : child.key; var data = (child.data || (child.data = {})).transition = extractTransitionData(this); var oldRawChild = this._vnode; var oldChild = getRealChild(oldRawChild); // mark v-show // so that the transition module can hand over the control to the directive if (child.data.directives && child.data.directives.some(function (d) { return d.name === 'show'; })) { child.data.show = true; } if (oldChild && oldChild.data && !isSameChild(child, oldChild)) { // replace old child transition data with fresh one // important for dynamic transitions! var oldData = oldChild && (oldChild.data.transition = extend({}, data)); // handle transition mode if (mode === 'out-in') { // return placeholder node and queue update when leave finishes this._leaving = true; mergeVNodeHook(oldData, 'afterLeave', function () { this$1._leaving = false; this$1.$forceUpdate(); }, key); return placeholder(h, rawChild) } else if (mode === 'in-out') { var delayedLeave; var performLeave = function () { delayedLeave(); }; mergeVNodeHook(data, 'afterEnter', performLeave, key); mergeVNodeHook(data, 'enterCancelled', performLeave, key); mergeVNodeHook(oldData, 'delayLeave', function (leave) { delayedLeave = leave; }, key); } } return rawChild } }; /* */ // Provides transition support for list items. // supports move transitions using the FLIP technique. // Because the vdom's children update algorithm is "unstable" - i.e. // it doesn't guarantee the relative positioning of removed elements, // we force transition-group to update its children into two passes: // in the first pass, we remove all nodes that need to be removed, // triggering their leaving transition; in the second pass, we insert/move // into the final disired state. This way in the second pass removed // nodes will remain where they should be. var props = extend({ tag: String, moveClass: String }, transitionProps); delete props.mode; var TransitionGroup = { props: props, render: function render (h) { var tag = this.tag || this.$vnode.data.tag || 'span'; var map = Object.create(null); var prevChildren = this.prevChildren = this.children; var rawChildren = this.$slots.default || []; var children = this.children = []; var transitionData = extractTransitionData(this); for (var i = 0; i < rawChildren.length; i++) { var c = rawChildren[i]; if (c.tag) { if (c.key != null && String(c.key).indexOf('__vlist') !== 0) { children.push(c); map[c.key] = c ;(c.data || (c.data = {})).transition = transitionData; } else { var opts = c.componentOptions; var name = opts ? (opts.Ctor.options.name || opts.tag) : c.tag; warn(("<transition-group> children must be keyed: <" + name + ">")); } } } if (prevChildren) { var kept = []; var removed = []; for (var i$1 = 0; i$1 < prevChildren.length; i$1++) { var c$1 = prevChildren[i$1]; c$1.data.transition = transitionData; c$1.data.pos = c$1.elm.getBoundingClientRect(); if (map[c$1.key]) { kept.push(c$1); } else { removed.push(c$1); } } this.kept = h(tag, null, kept); this.removed = removed; } return h(tag, null, children) }, beforeUpdate: function beforeUpdate () { // force removing pass this.__patch__( this._vnode, this.kept, false, // hydrating true // removeOnly (!important, avoids unnecessary moves) ); this._vnode = this.kept; }, updated: function updated () { var children = this.prevChildren; var moveClass = this.moveClass || ((this.name || 'v') + '-move'); if (!children.length || !this.hasMove(children[0].elm, moveClass)) { return } // we divide the work into three loops to avoid mixing DOM reads and writes // in each iteration - which helps prevent layout thrashing. children.forEach(callPendingCbs); children.forEach(recordPosition); children.forEach(applyTranslation); // force reflow to put everything in position var f = document.body.offsetHeight; // eslint-disable-line children.forEach(function (c) { if (c.data.moved) { var el = c.elm; var s = el.style; addTransitionClass(el, moveClass); s.transform = s.WebkitTransform = s.transitionDuration = ''; el.addEventListener(transitionEndEvent, el._moveCb = function cb (e) { if (!e || /transform$/.test(e.propertyName)) { el.removeEventListener(transitionEndEvent, cb); el._moveCb = null; removeTransitionClass(el, moveClass); } }); } }); }, methods: { hasMove: function hasMove (el, moveClass) { /* istanbul ignore if */ if (!hasTransition) { return false } if (this._hasMove != null) { return this._hasMove } addTransitionClass(el, moveClass); var info = getTransitionInfo(el); removeTransitionClass(el, moveClass); return (this._hasMove = info.hasTransform) } } }; function callPendingCbs (c) { /* istanbul ignore if */ if (c.elm._moveCb) { c.elm._moveCb(); } /* istanbul ignore if */ if (c.elm._enterCb) { c.elm._enterCb(); } } function recordPosition (c) { c.data.newPos = c.elm.getBoundingClientRect(); } function applyTranslation (c) { var oldPos = c.data.pos; var newPos = c.data.newPos; var dx = oldPos.left - newPos.left; var dy = oldPos.top - newPos.top; if (dx || dy) { c.data.moved = true; var s = c.elm.style; s.transform = s.WebkitTransform = "translate(" + dx + "px," + dy + "px)"; s.transitionDuration = '0s'; } } var platformComponents = { Transition: Transition, TransitionGroup: TransitionGroup }; /* */ // install platform specific utils Vue$3.config.isUnknownElement = isUnknownElement; Vue$3.config.isReservedTag = isReservedTag; Vue$3.config.getTagNamespace = getTagNamespace; Vue$3.config.mustUseProp = mustUseProp; // install platform runtime directives & components extend(Vue$3.options.directives, platformDirectives); extend(Vue$3.options.components, platformComponents); // install platform patch function Vue$3.prototype.__patch__ = inBrowser ? patch$1 : noop; // wrap mount Vue$3.prototype.$mount = function ( el, hydrating ) { el = el && inBrowser ? query(el) : undefined; return this._mount(el, hydrating) }; if ("development" !== 'production' && inBrowser && typeof console !== 'undefined') { console[console.info ? 'info' : 'log']( "You are running Vue in development mode.\n" + "Make sure to turn on production mode when deploying for production.\n" + "See more tips at https://vuejs.org/guide/deployment.html" ); } // devtools global hook /* istanbul ignore next */ setTimeout(function () { if (config.devtools) { if (devtools) { devtools.emit('init', Vue$3); } else if ( "development" !== 'production' && inBrowser && !isEdge && /Chrome\/\d+/.test(window.navigator.userAgent) ) { console[console.info ? 'info' : 'log']( 'Download the Vue Devtools extension for a better development experience:\n' + 'https://github.com/vuejs/vue-devtools' ); } } }, 0); /* */ // check whether current browser encodes a char inside attribute values function shouldDecode (content, encoded) { var div = document.createElement('div'); div.innerHTML = "<div a=\"" + content + "\">"; return div.innerHTML.indexOf(encoded) > 0 } // #3663 // IE encodes newlines inside attribute values while other browsers don't var shouldDecodeNewlines = inBrowser ? shouldDecode('\n', '&#10;') : false; /* */ var decoder; function decode (html) { decoder = decoder || document.createElement('div'); decoder.innerHTML = html; return decoder.textContent } /* */ var isUnaryTag = makeMap( 'area,base,br,col,embed,frame,hr,img,input,isindex,keygen,' + 'link,meta,param,source,track,wbr', true ); // Elements that you can, intentionally, leave open // (and which close themselves) var canBeLeftOpenTag = makeMap( 'colgroup,dd,dt,li,options,p,td,tfoot,th,thead,tr,source', true ); // HTML5 tags https://html.spec.whatwg.org/multipage/indices.html#elements-3 // Phrasing Content https://html.spec.whatwg.org/multipage/dom.html#phrasing-content var isNonPhrasingTag = makeMap( 'address,article,aside,base,blockquote,body,caption,col,colgroup,dd,' + 'details,dialog,div,dl,dt,fieldset,figcaption,figure,footer,form,' + 'h1,h2,h3,h4,h5,h6,head,header,hgroup,hr,html,legend,li,menuitem,meta,' + 'optgroup,option,param,rp,rt,source,style,summary,tbody,td,tfoot,th,thead,' + 'title,tr,track', true ); /** * Not type-checking this file because it's mostly vendor code. */ /*! * HTML Parser By John Resig (ejohn.org) * Modified by Juriy "kangax" Zaytsev * Original code by Erik Arvidsson, Mozilla Public License * http://erik.eae.net/simplehtmlparser/simplehtmlparser.js */ // Regular Expressions for parsing tags and attributes var singleAttrIdentifier = /([^\s"'<>/=]+)/; var singleAttrAssign = /(?:=)/; var singleAttrValues = [ // attr value double quotes /"([^"]*)"+/.source, // attr value, single quotes /'([^']*)'+/.source, // attr value, no quotes /([^\s"'=<>`]+)/.source ]; var attribute = new RegExp( '^\\s*' + singleAttrIdentifier.source + '(?:\\s*(' + singleAttrAssign.source + ')' + '\\s*(?:' + singleAttrValues.join('|') + '))?' ); // could use https://www.w3.org/TR/1999/REC-xml-names-19990114/#NT-QName // but for Vue templates we can enforce a simple charset var ncname = '[a-zA-Z_][\\w\\-\\.]*'; var qnameCapture = '((?:' + ncname + '\\:)?' + ncname + ')'; var startTagOpen = new RegExp('^<' + qnameCapture); var startTagClose = /^\s*(\/?)>/; var endTag = new RegExp('^<\\/' + qnameCapture + '[^>]*>'); var doctype = /^<!DOCTYPE [^>]+>/i; var comment = /^<!--/; var conditionalComment = /^<!\[/; var IS_REGEX_CAPTURING_BROKEN = false; 'x'.replace(/x(.)?/g, function (m, g) { IS_REGEX_CAPTURING_BROKEN = g === ''; }); // Special Elements (can contain anything) var isScriptOrStyle = makeMap('script,style', true); var reCache = {}; var ltRE = /&lt;/g; var gtRE = /&gt;/g; var nlRE = /&#10;/g; var ampRE = /&amp;/g; var quoteRE = /&quot;/g; function decodeAttr (value, shouldDecodeNewlines) { if (shouldDecodeNewlines) { value = value.replace(nlRE, '\n'); } return value .replace(ltRE, '<') .replace(gtRE, '>') .replace(ampRE, '&') .replace(quoteRE, '"') } function parseHTML (html, options) { var stack = []; var expectHTML = options.expectHTML; var isUnaryTag$$1 = options.isUnaryTag || no; var index = 0; var last, lastTag; while (html) { last = html; // Make sure we're not in a script or style element if (!lastTag || !isScriptOrStyle(lastTag)) { var textEnd = html.indexOf('<'); if (textEnd === 0) { // Comment: if (comment.test(html)) { var commentEnd = html.indexOf('-->'); if (commentEnd >= 0) { advance(commentEnd + 3); continue } } // http://en.wikipedia.org/wiki/Conditional_comment#Downlevel-revealed_conditional_comment if (conditionalComment.test(html)) { var conditionalEnd = html.indexOf(']>'); if (conditionalEnd >= 0) { advance(conditionalEnd + 2); continue } } // Doctype: var doctypeMatch = html.match(doctype); if (doctypeMatch) { advance(doctypeMatch[0].length); continue } // End tag: var endTagMatch = html.match(endTag); if (endTagMatch) { var curIndex = index; advance(endTagMatch[0].length); parseEndTag(endTagMatch[1], curIndex, index); continue } // Start tag: var startTagMatch = parseStartTag(); if (startTagMatch) { handleStartTag(startTagMatch); continue } } var text = (void 0), rest$1 = (void 0), next = (void 0); if (textEnd > 0) { rest$1 = html.slice(textEnd); while ( !endTag.test(rest$1) && !startTagOpen.test(rest$1) && !comment.test(rest$1) && !conditionalComment.test(rest$1) ) { // < in plain text, be forgiving and treat it as text next = rest$1.indexOf('<', 1); if (next < 0) { break } textEnd += next; rest$1 = html.slice(textEnd); } text = html.substring(0, textEnd); advance(textEnd); } if (textEnd < 0) { text = html; html = ''; } if (options.chars && text) { options.chars(text); } } else { var stackedTag = lastTag.toLowerCase(); var reStackedTag = reCache[stackedTag] || (reCache[stackedTag] = new RegExp('([\\s\\S]*?)(</' + stackedTag + '[^>]*>)', 'i')); var endTagLength = 0; var rest = html.replace(reStackedTag, function (all, text, endTag) { endTagLength = endTag.length; if (stackedTag !== 'script' && stackedTag !== 'style' && stackedTag !== 'noscript') { text = text .replace(/<!--([\s\S]*?)-->/g, '$1') .replace(/<!\[CDATA\[([\s\S]*?)]]>/g, '$1'); } if (options.chars) { options.chars(text); } return '' }); index += html.length - rest.length; html = rest; parseEndTag(stackedTag, index - endTagLength, index); } if (html === last && options.chars) { options.chars(html); break } } // Clean up any remaining tags parseEndTag(); function advance (n) { index += n; html = html.substring(n); } function parseStartTag () { var start = html.match(startTagOpen); if (start) { var match = { tagName: start[1], attrs: [], start: index }; advance(start[0].length); var end, attr; while (!(end = html.match(startTagClose)) && (attr = html.match(attribute))) { advance(attr[0].length); match.attrs.push(attr); } if (end) { match.unarySlash = end[1]; advance(end[0].length); match.end = index; return match } } } function handleStartTag (match) { var tagName = match.tagName; var unarySlash = match.unarySlash; if (expectHTML) { if (lastTag === 'p' && isNonPhrasingTag(tagName)) { parseEndTag(lastTag); } if (canBeLeftOpenTag(tagName) && lastTag === tagName) { parseEndTag(tagName); } } var unary = isUnaryTag$$1(tagName) || tagName === 'html' && lastTag === 'head' || !!unarySlash; var l = match.attrs.length; var attrs = new Array(l); for (var i = 0; i < l; i++) { var args = match.attrs[i]; // hackish work around FF bug https://bugzilla.mozilla.org/show_bug.cgi?id=369778 if (IS_REGEX_CAPTURING_BROKEN && args[0].indexOf('""') === -1) { if (args[3] === '') { delete args[3]; } if (args[4] === '') { delete args[4]; } if (args[5] === '') { delete args[5]; } } var value = args[3] || args[4] || args[5] || ''; attrs[i] = { name: args[1], value: decodeAttr( value, options.shouldDecodeNewlines ) }; } if (!unary) { stack.push({ tag: tagName, lowerCasedTag: tagName.toLowerCase(), attrs: attrs }); lastTag = tagName; unarySlash = ''; } if (options.start) { options.start(tagName, attrs, unary, match.start, match.end); } } function parseEndTag (tagName, start, end) { var pos, lowerCasedTagName; if (start == null) { start = index; } if (end == null) { end = index; } if (tagName) { lowerCasedTagName = tagName.toLowerCase(); } // Find the closest opened tag of the same type if (tagName) { for (pos = stack.length - 1; pos >= 0; pos--) { if (stack[pos].lowerCasedTag === lowerCasedTagName) { break } } } else { // If no tag name is provided, clean shop pos = 0; } if (pos >= 0) { // Close all the open elements, up the stack for (var i = stack.length - 1; i >= pos; i--) { if (options.end) { options.end(stack[i].tag, start, end); } } // Remove the open elements from the stack stack.length = pos; lastTag = pos && stack[pos - 1].tag; } else if (lowerCasedTagName === 'br') { if (options.start) { options.start(tagName, [], true, start, end); } } else if (lowerCasedTagName === 'p') { if (options.start) { options.start(tagName, [], false, start, end); } if (options.end) { options.end(tagName, start, end); } } } } /* */ function parseFilters (exp) { var inSingle = false; var inDouble = false; var inTemplateString = false; var inRegex = false; var curly = 0; var square = 0; var paren = 0; var lastFilterIndex = 0; var c, prev, i, expression, filters; for (i = 0; i < exp.length; i++) { prev = c; c = exp.charCodeAt(i); if (inSingle) { if (c === 0x27 && prev !== 0x5C) { inSingle = false; } } else if (inDouble) { if (c === 0x22 && prev !== 0x5C) { inDouble = false; } } else if (inTemplateString) { if (c === 0x60 && prev !== 0x5C) { inTemplateString = false; } } else if (inRegex) { if (c === 0x2f && prev !== 0x5C) { inRegex = false; } } else if ( c === 0x7C && // pipe exp.charCodeAt(i + 1) !== 0x7C && exp.charCodeAt(i - 1) !== 0x7C && !curly && !square && !paren ) { if (expression === undefined) { // first filter, end of expression lastFilterIndex = i + 1; expression = exp.slice(0, i).trim(); } else { pushFilter(); } } else { switch (c) { case 0x22: inDouble = true; break // " case 0x27: inSingle = true; break // ' case 0x60: inTemplateString = true; break // ` case 0x28: paren++; break // ( case 0x29: paren--; break // ) case 0x5B: square++; break // [ case 0x5D: square--; break // ] case 0x7B: curly++; break // { case 0x7D: curly--; break // } } if (c === 0x2f) { // / var j = i - 1; var p = (void 0); // find first non-whitespace prev char for (; j >= 0; j--) { p = exp.charAt(j); if (p !== ' ') { break } } if (!p || !/[\w$]/.test(p)) { inRegex = true; } } } } if (expression === undefined) { expression = exp.slice(0, i).trim(); } else if (lastFilterIndex !== 0) { pushFilter(); } function pushFilter () { (filters || (filters = [])).push(exp.slice(lastFilterIndex, i).trim()); lastFilterIndex = i + 1; } if (filters) { for (i = 0; i < filters.length; i++) { expression = wrapFilter(expression, filters[i]); } } return expression } function wrapFilter (exp, filter) { var i = filter.indexOf('('); if (i < 0) { // _f: resolveFilter return ("_f(\"" + filter + "\")(" + exp + ")") } else { var name = filter.slice(0, i); var args = filter.slice(i + 1); return ("_f(\"" + name + "\")(" + exp + "," + args) } } /* */ var defaultTagRE = /\{\{((?:.|\n)+?)\}\}/g; var regexEscapeRE = /[-.*+?^${}()|[\]\/\\]/g; var buildRegex = cached(function (delimiters) { var open = delimiters[0].replace(regexEscapeRE, '\\$&'); var close = delimiters[1].replace(regexEscapeRE, '\\$&'); return new RegExp(open + '((?:.|\\n)+?)' + close, 'g') }); function parseText ( text, delimiters ) { var tagRE = delimiters ? buildRegex(delimiters) : defaultTagRE; if (!tagRE.test(text)) { return } var tokens = []; var lastIndex = tagRE.lastIndex = 0; var match, index; while ((match = tagRE.exec(text))) { index = match.index; // push text token if (index > lastIndex) { tokens.push(JSON.stringify(text.slice(lastIndex, index))); } // tag token var exp = parseFilters(match[1].trim()); tokens.push(("_s(" + exp + ")")); lastIndex = index + match[0].length; } if (lastIndex < text.length) { tokens.push(JSON.stringify(text.slice(lastIndex))); } return tokens.join('+') } /* */ function baseWarn (msg) { console.error(("[Vue parser]: " + msg)); } function pluckModuleFunction ( modules, key ) { return modules ? modules.map(function (m) { return m[key]; }).filter(function (_) { return _; }) : [] } function addProp (el, name, value) { (el.props || (el.props = [])).push({ name: name, value: value }); } function addAttr (el, name, value) { (el.attrs || (el.attrs = [])).push({ name: name, value: value }); } function addDirective ( el, name, rawName, value, arg, modifiers ) { (el.directives || (el.directives = [])).push({ name: name, rawName: rawName, value: value, arg: arg, modifiers: modifiers }); } function addHandler ( el, name, value, modifiers, important ) { // check capture modifier if (modifiers && modifiers.capture) { delete modifiers.capture; name = '!' + name; // mark the event as captured } if (modifiers && modifiers.once) { delete modifiers.once; name = '~' + name; // mark the event as once } var events; if (modifiers && modifiers.native) { delete modifiers.native; events = el.nativeEvents || (el.nativeEvents = {}); } else { events = el.events || (el.events = {}); } var newHandler = { value: value, modifiers: modifiers }; var handlers = events[name]; /* istanbul ignore if */ if (Array.isArray(handlers)) { important ? handlers.unshift(newHandler) : handlers.push(newHandler); } else if (handlers) { events[name] = important ? [newHandler, handlers] : [handlers, newHandler]; } else { events[name] = newHandler; } } function getBindingAttr ( el, name, getStatic ) { var dynamicValue = getAndRemoveAttr(el, ':' + name) || getAndRemoveAttr(el, 'v-bind:' + name); if (dynamicValue != null) { return parseFilters(dynamicValue) } else if (getStatic !== false) { var staticValue = getAndRemoveAttr(el, name); if (staticValue != null) { return JSON.stringify(staticValue) } } } function getAndRemoveAttr (el, name) { var val; if ((val = el.attrsMap[name]) != null) { var list = el.attrsList; for (var i = 0, l = list.length; i < l; i++) { if (list[i].name === name) { list.splice(i, 1); break } } } return val } var len; var str; var chr; var index$1; var expressionPos; var expressionEndPos; /** * parse directive model to do the array update transform. a[idx] = val => $$a.splice($$idx, 1, val) * * for loop possible cases: * * - test * - test[idx] * - test[test1[idx]] * - test["a"][idx] * - xxx.test[a[a].test1[idx]] * - test.xxx.a["asa"][test1[idx]] * */ function parseModel (val) { str = val; len = str.length; index$1 = expressionPos = expressionEndPos = 0; if (val.indexOf('[') < 0 || val.lastIndexOf(']') < len - 1) { return { exp: val, idx: null } } while (!eof()) { chr = next(); /* istanbul ignore if */ if (isStringStart(chr)) { parseString(chr); } else if (chr === 0x5B) { parseBracket(chr); } } return { exp: val.substring(0, expressionPos), idx: val.substring(expressionPos + 1, expressionEndPos) } } function next () { return str.charCodeAt(++index$1) } function eof () { return index$1 >= len } function isStringStart (chr) { return chr === 0x22 || chr === 0x27 } function parseBracket (chr) { var inBracket = 1; expressionPos = index$1; while (!eof()) { chr = next(); if (isStringStart(chr)) { parseString(chr); continue } if (chr === 0x5B) { inBracket++; } if (chr === 0x5D) { inBracket--; } if (inBracket === 0) { expressionEndPos = index$1; break } } } function parseString (chr) { var stringQuote = chr; while (!eof()) { chr = next(); if (chr === stringQuote) { break } } } /* */ var dirRE = /^v-|^@|^:/; var forAliasRE = /(.*?)\s+(?:in|of)\s+(.*)/; var forIteratorRE = /\((\{[^}]*\}|[^,]*),([^,]*)(?:,([^,]*))?\)/; var bindRE = /^:|^v-bind:/; var onRE = /^@|^v-on:/; var argRE = /:(.*)$/; var modifierRE = /\.[^.]+/g; var decodeHTMLCached = cached(decode); // configurable state var warn$1; var platformGetTagNamespace; var platformMustUseProp; var platformIsPreTag; var preTransforms; var transforms; var postTransforms; var delimiters; /** * Convert HTML string to AST. */ function parse ( template, options ) { warn$1 = options.warn || baseWarn; platformGetTagNamespace = options.getTagNamespace || no; platformMustUseProp = options.mustUseProp || no; platformIsPreTag = options.isPreTag || no; preTransforms = pluckModuleFunction(options.modules, 'preTransformNode'); transforms = pluckModuleFunction(options.modules, 'transformNode'); postTransforms = pluckModuleFunction(options.modules, 'postTransformNode'); delimiters = options.delimiters; var stack = []; var preserveWhitespace = options.preserveWhitespace !== false; var root; var currentParent; var inVPre = false; var inPre = false; var warned = false; parseHTML(template, { expectHTML: options.expectHTML, isUnaryTag: options.isUnaryTag, shouldDecodeNewlines: options.shouldDecodeNewlines, start: function start (tag, attrs, unary) { // check namespace. // inherit parent ns if there is one var ns = (currentParent && currentParent.ns) || platformGetTagNamespace(tag); // handle IE svg bug /* istanbul ignore if */ if (isIE && ns === 'svg') { attrs = guardIESVGBug(attrs); } var element = { type: 1, tag: tag, attrsList: attrs, attrsMap: makeAttrsMap(attrs), parent: currentParent, children: [] }; if (ns) { element.ns = ns; } if (isForbiddenTag(element) && !isServerRendering()) { element.forbidden = true; "development" !== 'production' && warn$1( 'Templates should only be responsible for mapping the state to the ' + 'UI. Avoid placing tags with side-effects in your templates, such as ' + "<" + tag + ">" + ', as they will not be parsed.' ); } // apply pre-transforms for (var i = 0; i < preTransforms.length; i++) { preTransforms[i](element, options); } if (!inVPre) { processPre(element); if (element.pre) { inVPre = true; } } if (platformIsPreTag(element.tag)) { inPre = true; } if (inVPre) { processRawAttrs(element); } else { processFor(element); processIf(element); processOnce(element); processKey(element); // determine whether this is a plain element after // removing structural attributes element.plain = !element.key && !attrs.length; processRef(element); processSlot(element); processComponent(element); for (var i$1 = 0; i$1 < transforms.length; i$1++) { transforms[i$1](element, options); } processAttrs(element); } function checkRootConstraints (el) { if ("development" !== 'production' && !warned) { if (el.tag === 'slot' || el.tag === 'template') { warned = true; warn$1( "Cannot use <" + (el.tag) + "> as component root element because it may " + 'contain multiple nodes:\n' + template ); } if (el.attrsMap.hasOwnProperty('v-for')) { warned = true; warn$1( 'Cannot use v-for on stateful component root element because ' + 'it renders multiple elements:\n' + template ); } } } // tree management if (!root) { root = element; checkRootConstraints(root); } else if (!stack.length) { // allow root elements with v-if, v-else-if and v-else if (root.if && (element.elseif || element.else)) { checkRootConstraints(element); addIfCondition(root, { exp: element.elseif, block: element }); } else if ("development" !== 'production' && !warned) { warned = true; warn$1( "Component template should contain exactly one root element:" + "\n\n" + template + "\n\n" + "If you are using v-if on multiple elements, " + "use v-else-if to chain them instead." ); } } if (currentParent && !element.forbidden) { if (element.elseif || element.else) { processIfConditions(element, currentParent); } else if (element.slotScope) { // scoped slot currentParent.plain = false; var name = element.slotTarget || 'default';(currentParent.scopedSlots || (currentParent.scopedSlots = {}))[name] = element; } else { currentParent.children.push(element); element.parent = currentParent; } } if (!unary) { currentParent = element; stack.push(element); } // apply post-transforms for (var i$2 = 0; i$2 < postTransforms.length; i$2++) { postTransforms[i$2](element, options); } }, end: function end () { // remove trailing whitespace var element = stack[stack.length - 1]; var lastNode = element.children[element.children.length - 1]; if (lastNode && lastNode.type === 3 && lastNode.text === ' ') { element.children.pop(); } // pop stack stack.length -= 1; currentParent = stack[stack.length - 1]; // check pre state if (element.pre) { inVPre = false; } if (platformIsPreTag(element.tag)) { inPre = false; } }, chars: function chars (text) { if (!currentParent) { if ("development" !== 'production' && !warned && text === template) { warned = true; warn$1( 'Component template requires a root element, rather than just text:\n\n' + template ); } return } // IE textarea placeholder bug /* istanbul ignore if */ if (isIE && currentParent.tag === 'textarea' && currentParent.attrsMap.placeholder === text) { return } var children = currentParent.children; text = inPre || text.trim() ? decodeHTMLCached(text) // only preserve whitespace if its not right after a starting tag : preserveWhitespace && children.length ? ' ' : ''; if (text) { var expression; if (!inVPre && text !== ' ' && (expression = parseText(text, delimiters))) { children.push({ type: 2, expression: expression, text: text }); } else if (text !== ' ' || children[children.length - 1].text !== ' ') { currentParent.children.push({ type: 3, text: text }); } } } }); return root } function processPre (el) { if (getAndRemoveAttr(el, 'v-pre') != null) { el.pre = true; } } function processRawAttrs (el) { var l = el.attrsList.length; if (l) { var attrs = el.attrs = new Array(l); for (var i = 0; i < l; i++) { attrs[i] = { name: el.attrsList[i].name, value: JSON.stringify(el.attrsList[i].value) }; } } else if (!el.pre) { // non root node in pre blocks with no attributes el.plain = true; } } function processKey (el) { var exp = getBindingAttr(el, 'key'); if (exp) { if ("development" !== 'production' && el.tag === 'template') { warn$1("<template> cannot be keyed. Place the key on real elements instead."); } el.key = exp; } } function processRef (el) { var ref = getBindingAttr(el, 'ref'); if (ref) { el.ref = ref; el.refInFor = checkInFor(el); } } function processFor (el) { var exp; if ((exp = getAndRemoveAttr(el, 'v-for'))) { var inMatch = exp.match(forAliasRE); if (!inMatch) { "development" !== 'production' && warn$1( ("Invalid v-for expression: " + exp) ); return } el.for = inMatch[2].trim(); var alias = inMatch[1].trim(); var iteratorMatch = alias.match(forIteratorRE); if (iteratorMatch) { el.alias = iteratorMatch[1].trim(); el.iterator1 = iteratorMatch[2].trim(); if (iteratorMatch[3]) { el.iterator2 = iteratorMatch[3].trim(); } } else { el.alias = alias; } } } function processIf (el) { var exp = getAndRemoveAttr(el, 'v-if'); if (exp) { el.if = exp; addIfCondition(el, { exp: exp, block: el }); } else { if (getAndRemoveAttr(el, 'v-else') != null) { el.else = true; } var elseif = getAndRemoveAttr(el, 'v-else-if'); if (elseif) { el.elseif = elseif; } } } function processIfConditions (el, parent) { var prev = findPrevElement(parent.children); if (prev && prev.if) { addIfCondition(prev, { exp: el.elseif, block: el }); } else { warn$1( "v-" + (el.elseif ? ('else-if="' + el.elseif + '"') : 'else') + " " + "used on element <" + (el.tag) + "> without corresponding v-if." ); } } function findPrevElement (children) { var i = children.length; while (i--) { if (children[i].type === 1) { return children[i] } else { if ("development" !== 'production' && children[i].text !== ' ') { warn$1( "text \"" + (children[i].text.trim()) + "\" between v-if and v-else(-if) " + "will be ignored." ); } children.pop(); } } } function addIfCondition (el, condition) { if (!el.ifConditions) { el.ifConditions = []; } el.ifConditions.push(condition); } function processOnce (el) { var once = getAndRemoveAttr(el, 'v-once'); if (once != null) { el.once = true; } } function processSlot (el) { if (el.tag === 'slot') { el.slotName = getBindingAttr(el, 'name'); if ("development" !== 'production' && el.key) { warn$1( "`key` does not work on <slot> because slots are abstract outlets " + "and can possibly expand into multiple elements. " + "Use the key on a wrapping element instead." ); } } else { var slotTarget = getBindingAttr(el, 'slot'); if (slotTarget) { el.slotTarget = slotTarget === '""' ? '"default"' : slotTarget; } if (el.tag === 'template') { el.slotScope = getAndRemoveAttr(el, 'scope'); } } } function processComponent (el) { var binding; if ((binding = getBindingAttr(el, 'is'))) { el.component = binding; } if (getAndRemoveAttr(el, 'inline-template') != null) { el.inlineTemplate = true; } } function processAttrs (el) { var list = el.attrsList; var i, l, name, rawName, value, arg, modifiers, isProp; for (i = 0, l = list.length; i < l; i++) { name = rawName = list[i].name; value = list[i].value; if (dirRE.test(name)) { // mark element as dynamic el.hasBindings = true; // modifiers modifiers = parseModifiers(name); if (modifiers) { name = name.replace(modifierRE, ''); } if (bindRE.test(name)) { // v-bind name = name.replace(bindRE, ''); value = parseFilters(value); isProp = false; if (modifiers) { if (modifiers.prop) { isProp = true; name = camelize(name); if (name === 'innerHtml') { name = 'innerHTML'; } } if (modifiers.camel) { name = camelize(name); } } if (isProp || platformMustUseProp(el.tag, el.attrsMap.type, name)) { addProp(el, name, value); } else { addAttr(el, name, value); } } else if (onRE.test(name)) { // v-on name = name.replace(onRE, ''); addHandler(el, name, value, modifiers); } else { // normal directives name = name.replace(dirRE, ''); // parse arg var argMatch = name.match(argRE); if (argMatch && (arg = argMatch[1])) { name = name.slice(0, -(arg.length + 1)); } addDirective(el, name, rawName, value, arg, modifiers); if ("development" !== 'production' && name === 'model') { checkForAliasModel(el, value); } } } else { // literal attribute { var expression = parseText(value, delimiters); if (expression) { warn$1( name + "=\"" + value + "\": " + 'Interpolation inside attributes has been removed. ' + 'Use v-bind or the colon shorthand instead. For example, ' + 'instead of <div id="{{ val }}">, use <div :id="val">.' ); } } addAttr(el, name, JSON.stringify(value)); } } } function checkInFor (el) { var parent = el; while (parent) { if (parent.for !== undefined) { return true } parent = parent.parent; } return false } function parseModifiers (name) { var match = name.match(modifierRE); if (match) { var ret = {}; match.forEach(function (m) { ret[m.slice(1)] = true; }); return ret } } function makeAttrsMap (attrs) { var map = {}; for (var i = 0, l = attrs.length; i < l; i++) { if ("development" !== 'production' && map[attrs[i].name] && !isIE) { warn$1('duplicate attribute: ' + attrs[i].name); } map[attrs[i].name] = attrs[i].value; } return map } function isForbiddenTag (el) { return ( el.tag === 'style' || (el.tag === 'script' && ( !el.attrsMap.type || el.attrsMap.type === 'text/javascript' )) ) } var ieNSBug = /^xmlns:NS\d+/; var ieNSPrefix = /^NS\d+:/; /* istanbul ignore next */ function guardIESVGBug (attrs) { var res = []; for (var i = 0; i < attrs.length; i++) { var attr = attrs[i]; if (!ieNSBug.test(attr.name)) { attr.name = attr.name.replace(ieNSPrefix, ''); res.push(attr); } } return res } function checkForAliasModel (el, value) { var _el = el; while (_el) { if (_el.for && _el.alias === value) { warn$1( "<" + (el.tag) + " v-model=\"" + value + "\">: " + "You are binding v-model directly to a v-for iteration alias. " + "This will not be able to modify the v-for source array because " + "writing to the alias is like modifying a function local variable. " + "Consider using an array of objects and use v-model on an object property instead." ); } _el = _el.parent; } } /* */ var isStaticKey; var isPlatformReservedTag; var genStaticKeysCached = cached(genStaticKeys$1); /** * Goal of the optimizer: walk the generated template AST tree * and detect sub-trees that are purely static, i.e. parts of * the DOM that never needs to change. * * Once we detect these sub-trees, we can: * * 1. Hoist them into constants, so that we no longer need to * create fresh nodes for them on each re-render; * 2. Completely skip them in the patching process. */ function optimize (root, options) { if (!root) { return } isStaticKey = genStaticKeysCached(options.staticKeys || ''); isPlatformReservedTag = options.isReservedTag || no; // first pass: mark all non-static nodes. markStatic(root); // second pass: mark static roots. markStaticRoots(root, false); } function genStaticKeys$1 (keys) { return makeMap( 'type,tag,attrsList,attrsMap,plain,parent,children,attrs' + (keys ? ',' + keys : '') ) } function markStatic (node) { node.static = isStatic(node); if (node.type === 1) { // do not make component slot content static. this avoids // 1. components not able to mutate slot nodes // 2. static slot content fails for hot-reloading if ( !isPlatformReservedTag(node.tag) && node.tag !== 'slot' && node.attrsMap['inline-template'] == null ) { return } for (var i = 0, l = node.children.length; i < l; i++) { var child = node.children[i]; markStatic(child); if (!child.static) { node.static = false; } } } } function markStaticRoots (node, isInFor) { if (node.type === 1) { if (node.static || node.once) { node.staticInFor = isInFor; } // For a node to qualify as a static root, it should have children that // are not just static text. Otherwise the cost of hoisting out will // outweigh the benefits and it's better off to just always render it fresh. if (node.static && node.children.length && !( node.children.length === 1 && node.children[0].type === 3 )) { node.staticRoot = true; return } else { node.staticRoot = false; } if (node.children) { for (var i = 0, l = node.children.length; i < l; i++) { markStaticRoots(node.children[i], isInFor || !!node.for); } } if (node.ifConditions) { walkThroughConditionsBlocks(node.ifConditions, isInFor); } } } function walkThroughConditionsBlocks (conditionBlocks, isInFor) { for (var i = 1, len = conditionBlocks.length; i < len; i++) { markStaticRoots(conditionBlocks[i].block, isInFor); } } function isStatic (node) { if (node.type === 2) { // expression return false } if (node.type === 3) { // text return true } return !!(node.pre || ( !node.hasBindings && // no dynamic bindings !node.if && !node.for && // not v-if or v-for or v-else !isBuiltInTag(node.tag) && // not a built-in isPlatformReservedTag(node.tag) && // not a component !isDirectChildOfTemplateFor(node) && Object.keys(node).every(isStaticKey) )) } function isDirectChildOfTemplateFor (node) { while (node.parent) { node = node.parent; if (node.tag !== 'template') { return false } if (node.for) { return true } } return false } /* */ var fnExpRE = /^\s*([\w$_]+|\([^)]*?\))\s*=>|^function\s*\(/; var simplePathRE = /^\s*[A-Za-z_$][\w$]*(?:\.[A-Za-z_$][\w$]*|\['.*?']|\[".*?"]|\[\d+]|\[[A-Za-z_$][\w$]*])*\s*$/; // keyCode aliases var keyCodes = { esc: 27, tab: 9, enter: 13, space: 32, up: 38, left: 37, right: 39, down: 40, 'delete': [8, 46] }; var modifierCode = { stop: '$event.stopPropagation();', prevent: '$event.preventDefault();', self: 'if($event.target !== $event.currentTarget)return;', ctrl: 'if(!$event.ctrlKey)return;', shift: 'if(!$event.shiftKey)return;', alt: 'if(!$event.altKey)return;', meta: 'if(!$event.metaKey)return;' }; function genHandlers (events, native) { var res = native ? 'nativeOn:{' : 'on:{'; for (var name in events) { res += "\"" + name + "\":" + (genHandler(name, events[name])) + ","; } return res.slice(0, -1) + '}' } function genHandler ( name, handler ) { if (!handler) { return 'function(){}' } else if (Array.isArray(handler)) { return ("[" + (handler.map(function (handler) { return genHandler(name, handler); }).join(',')) + "]") } else if (!handler.modifiers) { return fnExpRE.test(handler.value) || simplePathRE.test(handler.value) ? handler.value : ("function($event){" + (handler.value) + "}") } else { var code = ''; var keys = []; for (var key in handler.modifiers) { if (modifierCode[key]) { code += modifierCode[key]; } else { keys.push(key); } } if (keys.length) { code = genKeyFilter(keys) + code; } var handlerCode = simplePathRE.test(handler.value) ? handler.value + '($event)' : handler.value; return 'function($event){' + code + handlerCode + '}' } } function genKeyFilter (keys) { return ("if(" + (keys.map(genFilterCode).join('&&')) + ")return;") } function genFilterCode (key) { var keyVal = parseInt(key, 10); if (keyVal) { return ("$event.keyCode!==" + keyVal) } var alias = keyCodes[key]; return ("_k($event.keyCode," + (JSON.stringify(key)) + (alias ? ',' + JSON.stringify(alias) : '') + ")") } /* */ function bind$2 (el, dir) { el.wrapData = function (code) { return ("_b(" + code + ",'" + (el.tag) + "'," + (dir.value) + (dir.modifiers && dir.modifiers.prop ? ',true' : '') + ")") }; } /* */ var baseDirectives = { bind: bind$2, cloak: noop }; /* */ // configurable state var warn$2; var transforms$1; var dataGenFns; var platformDirectives$1; var isPlatformReservedTag$1; var staticRenderFns; var onceCount; var currentOptions; function generate ( ast, options ) { // save previous staticRenderFns so generate calls can be nested var prevStaticRenderFns = staticRenderFns; var currentStaticRenderFns = staticRenderFns = []; var prevOnceCount = onceCount; onceCount = 0; currentOptions = options; warn$2 = options.warn || baseWarn; transforms$1 = pluckModuleFunction(options.modules, 'transformCode'); dataGenFns = pluckModuleFunction(options.modules, 'genData'); platformDirectives$1 = options.directives || {}; isPlatformReservedTag$1 = options.isReservedTag || no; var code = ast ? genElement(ast) : '_c("div")'; staticRenderFns = prevStaticRenderFns; onceCount = prevOnceCount; return { render: ("with(this){return " + code + "}"), staticRenderFns: currentStaticRenderFns } } function genElement (el) { if (el.staticRoot && !el.staticProcessed) { return genStatic(el) } else if (el.once && !el.onceProcessed) { return genOnce(el) } else if (el.for && !el.forProcessed) { return genFor(el) } else if (el.if && !el.ifProcessed) { return genIf(el) } else if (el.tag === 'template' && !el.slotTarget) { return genChildren(el) || 'void 0' } else if (el.tag === 'slot') { return genSlot(el) } else { // component or element var code; if (el.component) { code = genComponent(el.component, el); } else { var data = el.plain ? undefined : genData(el); var children = el.inlineTemplate ? null : genChildren(el, true); code = "_c('" + (el.tag) + "'" + (data ? ("," + data) : '') + (children ? ("," + children) : '') + ")"; } // module transforms for (var i = 0; i < transforms$1.length; i++) { code = transforms$1[i](el, code); } return code } } // hoist static sub-trees out function genStatic (el) { el.staticProcessed = true; staticRenderFns.push(("with(this){return " + (genElement(el)) + "}")); return ("_m(" + (staticRenderFns.length - 1) + (el.staticInFor ? ',true' : '') + ")") } // v-once function genOnce (el) { el.onceProcessed = true; if (el.if && !el.ifProcessed) { return genIf(el) } else if (el.staticInFor) { var key = ''; var parent = el.parent; while (parent) { if (parent.for) { key = parent.key; break } parent = parent.parent; } if (!key) { "development" !== 'production' && warn$2( "v-once can only be used inside v-for that is keyed. " ); return genElement(el) } return ("_o(" + (genElement(el)) + "," + (onceCount++) + (key ? ("," + key) : "") + ")") } else { return genStatic(el) } } function genIf (el) { el.ifProcessed = true; // avoid recursion return genIfConditions(el.ifConditions.slice()) } function genIfConditions (conditions) { if (!conditions.length) { return '_e()' } var condition = conditions.shift(); if (condition.exp) { return ("(" + (condition.exp) + ")?" + (genTernaryExp(condition.block)) + ":" + (genIfConditions(conditions))) } else { return ("" + (genTernaryExp(condition.block))) } // v-if with v-once should generate code like (a)?_m(0):_m(1) function genTernaryExp (el) { return el.once ? genOnce(el) : genElement(el) } } function genFor (el) { var exp = el.for; var alias = el.alias; var iterator1 = el.iterator1 ? ("," + (el.iterator1)) : ''; var iterator2 = el.iterator2 ? ("," + (el.iterator2)) : ''; el.forProcessed = true; // avoid recursion return "_l((" + exp + ")," + "function(" + alias + iterator1 + iterator2 + "){" + "return " + (genElement(el)) + '})' } function genData (el) { var data = '{'; // directives first. // directives may mutate the el's other properties before they are generated. var dirs = genDirectives(el); if (dirs) { data += dirs + ','; } // key if (el.key) { data += "key:" + (el.key) + ","; } // ref if (el.ref) { data += "ref:" + (el.ref) + ","; } if (el.refInFor) { data += "refInFor:true,"; } // pre if (el.pre) { data += "pre:true,"; } // record original tag name for components using "is" attribute if (el.component) { data += "tag:\"" + (el.tag) + "\","; } // module data generation functions for (var i = 0; i < dataGenFns.length; i++) { data += dataGenFns[i](el); } // attributes if (el.attrs) { data += "attrs:{" + (genProps(el.attrs)) + "},"; } // DOM props if (el.props) { data += "domProps:{" + (genProps(el.props)) + "},"; } // event handlers if (el.events) { data += (genHandlers(el.events)) + ","; } if (el.nativeEvents) { data += (genHandlers(el.nativeEvents, true)) + ","; } // slot target if (el.slotTarget) { data += "slot:" + (el.slotTarget) + ","; } // scoped slots if (el.scopedSlots) { data += (genScopedSlots(el.scopedSlots)) + ","; } // inline-template if (el.inlineTemplate) { var inlineTemplate = genInlineTemplate(el); if (inlineTemplate) { data += inlineTemplate + ","; } } data = data.replace(/,$/, '') + '}'; // v-bind data wrap if (el.wrapData) { data = el.wrapData(data); } return data } function genDirectives (el) { var dirs = el.directives; if (!dirs) { return } var res = 'directives:['; var hasRuntime = false; var i, l, dir, needRuntime; for (i = 0, l = dirs.length; i < l; i++) { dir = dirs[i]; needRuntime = true; var gen = platformDirectives$1[dir.name] || baseDirectives[dir.name]; if (gen) { // compile-time directive that manipulates AST. // returns true if it also needs a runtime counterpart. needRuntime = !!gen(el, dir, warn$2); } if (needRuntime) { hasRuntime = true; res += "{name:\"" + (dir.name) + "\",rawName:\"" + (dir.rawName) + "\"" + (dir.value ? (",value:(" + (dir.value) + "),expression:" + (JSON.stringify(dir.value))) : '') + (dir.arg ? (",arg:\"" + (dir.arg) + "\"") : '') + (dir.modifiers ? (",modifiers:" + (JSON.stringify(dir.modifiers))) : '') + "},"; } } if (hasRuntime) { return res.slice(0, -1) + ']' } } function genInlineTemplate (el) { var ast = el.children[0]; if ("development" !== 'production' && ( el.children.length > 1 || ast.type !== 1 )) { warn$2('Inline-template components must have exactly one child element.'); } if (ast.type === 1) { var inlineRenderFns = generate(ast, currentOptions); return ("inlineTemplate:{render:function(){" + (inlineRenderFns.render) + "},staticRenderFns:[" + (inlineRenderFns.staticRenderFns.map(function (code) { return ("function(){" + code + "}"); }).join(',')) + "]}") } } function genScopedSlots (slots) { return ("scopedSlots:{" + (Object.keys(slots).map(function (key) { return genScopedSlot(key, slots[key]); }).join(',')) + "}") } function genScopedSlot (key, el) { return key + ":function(" + (String(el.attrsMap.scope)) + "){" + "return " + (el.tag === 'template' ? genChildren(el) || 'void 0' : genElement(el)) + "}" } function genChildren (el, checkSkip) { var children = el.children; if (children.length) { var el$1 = children[0]; // optimize single v-for if (children.length === 1 && el$1.for && el$1.tag !== 'template' && el$1.tag !== 'slot') { return genElement(el$1) } var normalizationType = getNormalizationType(children); return ("[" + (children.map(genNode).join(',')) + "]" + (checkSkip ? normalizationType ? ("," + normalizationType) : '' : '')) } } // determine the normalization needed for the children array. // 0: no normalization needed // 1: simple normalization needed (possible 1-level deep nested array) // 2: full normalization needed function getNormalizationType (children) { var res = 0; for (var i = 0; i < children.length; i++) { var el = children[i]; if (el.type !== 1) { continue } if (needsNormalization(el) || (el.ifConditions && el.ifConditions.some(function (c) { return needsNormalization(c.block); }))) { res = 2; break } if (maybeComponent(el) || (el.ifConditions && el.ifConditions.some(function (c) { return maybeComponent(c.block); }))) { res = 1; } } return res } function needsNormalization (el) { return el.for !== undefined || el.tag === 'template' || el.tag === 'slot' } function maybeComponent (el) { return !isPlatformReservedTag$1(el.tag) } function genNode (node) { if (node.type === 1) { return genElement(node) } else { return genText(node) } } function genText (text) { return ("_v(" + (text.type === 2 ? text.expression // no need for () because already wrapped in _s() : transformSpecialNewlines(JSON.stringify(text.text))) + ")") } function genSlot (el) { var slotName = el.slotName || '"default"'; var children = genChildren(el); var res = "_t(" + slotName + (children ? ("," + children) : ''); var attrs = el.attrs && ("{" + (el.attrs.map(function (a) { return ((camelize(a.name)) + ":" + (a.value)); }).join(',')) + "}"); var bind$$1 = el.attrsMap['v-bind']; if ((attrs || bind$$1) && !children) { res += ",null"; } if (attrs) { res += "," + attrs; } if (bind$$1) { res += (attrs ? '' : ',null') + "," + bind$$1; } return res + ')' } // componentName is el.component, take it as argument to shun flow's pessimistic refinement function genComponent (componentName, el) { var children = el.inlineTemplate ? null : genChildren(el, true); return ("_c(" + componentName + "," + (genData(el)) + (children ? ("," + children) : '') + ")") } function genProps (props) { var res = ''; for (var i = 0; i < props.length; i++) { var prop = props[i]; res += "\"" + (prop.name) + "\":" + (transformSpecialNewlines(prop.value)) + ","; } return res.slice(0, -1) } // #3895, #4268 function transformSpecialNewlines (text) { return text .replace(/\u2028/g, '\\u2028') .replace(/\u2029/g, '\\u2029') } /* */ /** * Compile a template. */ function compile$1 ( template, options ) { var ast = parse(template.trim(), options); optimize(ast, options); var code = generate(ast, options); return { ast: ast, render: code.render, staticRenderFns: code.staticRenderFns } } /* */ // operators like typeof, instanceof and in are allowed var prohibitedKeywordRE = new RegExp('\\b' + ( 'do,if,for,let,new,try,var,case,else,with,await,break,catch,class,const,' + 'super,throw,while,yield,delete,export,import,return,switch,default,' + 'extends,finally,continue,debugger,function,arguments' ).split(',').join('\\b|\\b') + '\\b'); // check valid identifier for v-for var identRE = /[A-Za-z_$][\w$]*/; // strip strings in expressions var stripStringRE = /'(?:[^'\\]|\\.)*'|"(?:[^"\\]|\\.)*"|`(?:[^`\\]|\\.)*\$\{|\}(?:[^`\\]|\\.)*`|`(?:[^`\\]|\\.)*`/g; // detect problematic expressions in a template function detectErrors (ast) { var errors = []; if (ast) { checkNode(ast, errors); } return errors } function checkNode (node, errors) { if (node.type === 1) { for (var name in node.attrsMap) { if (dirRE.test(name)) { var value = node.attrsMap[name]; if (value) { if (name === 'v-for') { checkFor(node, ("v-for=\"" + value + "\""), errors); } else { checkExpression(value, (name + "=\"" + value + "\""), errors); } } } } if (node.children) { for (var i = 0; i < node.children.length; i++) { checkNode(node.children[i], errors); } } } else if (node.type === 2) { checkExpression(node.expression, node.text, errors); } } function checkFor (node, text, errors) { checkExpression(node.for || '', text, errors); checkIdentifier(node.alias, 'v-for alias', text, errors); checkIdentifier(node.iterator1, 'v-for iterator', text, errors); checkIdentifier(node.iterator2, 'v-for iterator', text, errors); } function checkIdentifier (ident, type, text, errors) { if (typeof ident === 'string' && !identRE.test(ident)) { errors.push(("- invalid " + type + " \"" + ident + "\" in expression: " + text)); } } function checkExpression (exp, text, errors) { try { new Function(("return " + exp)); } catch (e) { var keywordMatch = exp.replace(stripStringRE, '').match(prohibitedKeywordRE); if (keywordMatch) { errors.push( "- avoid using JavaScript keyword as property name: " + "\"" + (keywordMatch[0]) + "\" in expression " + text ); } else { errors.push(("- invalid expression: " + text)); } } } /* */ function transformNode (el, options) { var warn = options.warn || baseWarn; var staticClass = getAndRemoveAttr(el, 'class'); if ("development" !== 'production' && staticClass) { var expression = parseText(staticClass, options.delimiters); if (expression) { warn( "class=\"" + staticClass + "\": " + 'Interpolation inside attributes has been removed. ' + 'Use v-bind or the colon shorthand instead. For example, ' + 'instead of <div class="{{ val }}">, use <div :class="val">.' ); } } if (staticClass) { el.staticClass = JSON.stringify(staticClass); } var classBinding = getBindingAttr(el, 'class', false /* getStatic */); if (classBinding) { el.classBinding = classBinding; } } function genData$1 (el) { var data = ''; if (el.staticClass) { data += "staticClass:" + (el.staticClass) + ","; } if (el.classBinding) { data += "class:" + (el.classBinding) + ","; } return data } var klass$1 = { staticKeys: ['staticClass'], transformNode: transformNode, genData: genData$1 }; /* */ function transformNode$1 (el, options) { var warn = options.warn || baseWarn; var staticStyle = getAndRemoveAttr(el, 'style'); if (staticStyle) { /* istanbul ignore if */ { var expression = parseText(staticStyle, options.delimiters); if (expression) { warn( "style=\"" + staticStyle + "\": " + 'Interpolation inside attributes has been removed. ' + 'Use v-bind or the colon shorthand instead. For example, ' + 'instead of <div style="{{ val }}">, use <div :style="val">.' ); } } el.staticStyle = JSON.stringify(parseStyleText(staticStyle)); } var styleBinding = getBindingAttr(el, 'style', false /* getStatic */); if (styleBinding) { el.styleBinding = styleBinding; } } function genData$2 (el) { var data = ''; if (el.staticStyle) { data += "staticStyle:" + (el.staticStyle) + ","; } if (el.styleBinding) { data += "style:(" + (el.styleBinding) + "),"; } return data } var style$1 = { staticKeys: ['staticStyle'], transformNode: transformNode$1, genData: genData$2 }; var modules$1 = [ klass$1, style$1 ]; /* */ var warn$3; function model$1 ( el, dir, _warn ) { warn$3 = _warn; var value = dir.value; var modifiers = dir.modifiers; var tag = el.tag; var type = el.attrsMap.type; { var dynamicType = el.attrsMap['v-bind:type'] || el.attrsMap[':type']; if (tag === 'input' && dynamicType) { warn$3( "<input :type=\"" + dynamicType + "\" v-model=\"" + value + "\">:\n" + "v-model does not support dynamic input types. Use v-if branches instead." ); } } if (tag === 'select') { genSelect(el, value, modifiers); } else if (tag === 'input' && type === 'checkbox') { genCheckboxModel(el, value, modifiers); } else if (tag === 'input' && type === 'radio') { genRadioModel(el, value, modifiers); } else { genDefaultModel(el, value, modifiers); } // ensure runtime directive metadata return true } function genCheckboxModel ( el, value, modifiers ) { if ("development" !== 'production' && el.attrsMap.checked != null) { warn$3( "<" + (el.tag) + " v-model=\"" + value + "\" checked>:\n" + "inline checked attributes will be ignored when using v-model. " + 'Declare initial values in the component\'s data option instead.' ); } var number = modifiers && modifiers.number; var valueBinding = getBindingAttr(el, 'value') || 'null'; var trueValueBinding = getBindingAttr(el, 'true-value') || 'true'; var falseValueBinding = getBindingAttr(el, 'false-value') || 'false'; addProp(el, 'checked', "Array.isArray(" + value + ")" + "?_i(" + value + "," + valueBinding + ")>-1" + ( trueValueBinding === 'true' ? (":(" + value + ")") : (":_q(" + value + "," + trueValueBinding + ")") ) ); addHandler(el, 'click', "var $$a=" + value + "," + '$$el=$event.target,' + "$$c=$$el.checked?(" + trueValueBinding + "):(" + falseValueBinding + ");" + 'if(Array.isArray($$a)){' + "var $$v=" + (number ? '_n(' + valueBinding + ')' : valueBinding) + "," + '$$i=_i($$a,$$v);' + "if($$c){$$i<0&&(" + value + "=$$a.concat($$v))}" + "else{$$i>-1&&(" + value + "=$$a.slice(0,$$i).concat($$a.slice($$i+1)))}" + "}else{" + value + "=$$c}", null, true ); } function genRadioModel ( el, value, modifiers ) { if ("development" !== 'production' && el.attrsMap.checked != null) { warn$3( "<" + (el.tag) + " v-model=\"" + value + "\" checked>:\n" + "inline checked attributes will be ignored when using v-model. " + 'Declare initial values in the component\'s data option instead.' ); } var number = modifiers && modifiers.number; var valueBinding = getBindingAttr(el, 'value') || 'null'; valueBinding = number ? ("_n(" + valueBinding + ")") : valueBinding; addProp(el, 'checked', ("_q(" + value + "," + valueBinding + ")")); addHandler(el, 'click', genAssignmentCode(value, valueBinding), null, true); } function genDefaultModel ( el, value, modifiers ) { { if (el.tag === 'input' && el.attrsMap.value) { warn$3( "<" + (el.tag) + " v-model=\"" + value + "\" value=\"" + (el.attrsMap.value) + "\">:\n" + 'inline value attributes will be ignored when using v-model. ' + 'Declare initial values in the component\'s data option instead.' ); } if (el.tag === 'textarea' && el.children.length) { warn$3( "<textarea v-model=\"" + value + "\">:\n" + 'inline content inside <textarea> will be ignored when using v-model. ' + 'Declare initial values in the component\'s data option instead.' ); } } var type = el.attrsMap.type; var ref = modifiers || {}; var lazy = ref.lazy; var number = ref.number; var trim = ref.trim; var event = lazy || (isIE && type === 'range') ? 'change' : 'input'; var needCompositionGuard = !lazy && type !== 'range'; var isNative = el.tag === 'input' || el.tag === 'textarea'; var valueExpression = isNative ? ("$event.target.value" + (trim ? '.trim()' : '')) : trim ? "(typeof $event === 'string' ? $event.trim() : $event)" : "$event"; valueExpression = number || type === 'number' ? ("_n(" + valueExpression + ")") : valueExpression; var code = genAssignmentCode(value, valueExpression); if (isNative && needCompositionGuard) { code = "if($event.target.composing)return;" + code; } // inputs with type="file" are read only and setting the input's // value will throw an error. if ("development" !== 'production' && type === 'file') { warn$3( "<" + (el.tag) + " v-model=\"" + value + "\" type=\"file\">:\n" + "File inputs are read only. Use a v-on:change listener instead." ); } addProp(el, 'value', isNative ? ("_s(" + value + ")") : ("(" + value + ")")); addHandler(el, event, code, null, true); if (trim || number || type === 'number') { addHandler(el, 'blur', '$forceUpdate()'); } } function genSelect ( el, value, modifiers ) { { el.children.some(checkOptionWarning); } var number = modifiers && modifiers.number; var assignment = "Array.prototype.filter" + ".call($event.target.options,function(o){return o.selected})" + ".map(function(o){var val = \"_value\" in o ? o._value : o.value;" + "return " + (number ? '_n(val)' : 'val') + "})" + (el.attrsMap.multiple == null ? '[0]' : ''); var code = genAssignmentCode(value, assignment); addHandler(el, 'change', code, null, true); } function checkOptionWarning (option) { if (option.type === 1 && option.tag === 'option' && option.attrsMap.selected != null) { warn$3( "<select v-model=\"" + (option.parent.attrsMap['v-model']) + "\">:\n" + 'inline selected attributes on <option> will be ignored when using v-model. ' + 'Declare initial values in the component\'s data option instead.' ); return true } return false } function genAssignmentCode (value, assignment) { var modelRs = parseModel(value); if (modelRs.idx === null) { return (value + "=" + assignment) } else { return "var $$exp = " + (modelRs.exp) + ", $$idx = " + (modelRs.idx) + ";" + "if (!Array.isArray($$exp)){" + value + "=" + assignment + "}" + "else{$$exp.splice($$idx, 1, " + assignment + ")}" } } /* */ function text (el, dir) { if (dir.value) { addProp(el, 'textContent', ("_s(" + (dir.value) + ")")); } } /* */ function html (el, dir) { if (dir.value) { addProp(el, 'innerHTML', ("_s(" + (dir.value) + ")")); } } var directives$1 = { model: model$1, text: text, html: html }; /* */ var cache = Object.create(null); var baseOptions = { expectHTML: true, modules: modules$1, staticKeys: genStaticKeys(modules$1), directives: directives$1, isReservedTag: isReservedTag, isUnaryTag: isUnaryTag, mustUseProp: mustUseProp, getTagNamespace: getTagNamespace, isPreTag: isPreTag }; function compile$$1 ( template, options ) { options = options ? extend(extend({}, baseOptions), options) : baseOptions; return compile$1(template, options) } function compileToFunctions ( template, options, vm ) { var _warn = (options && options.warn) || warn; // detect possible CSP restriction /* istanbul ignore if */ { try { new Function('return 1'); } catch (e) { if (e.toString().match(/unsafe-eval|CSP/)) { _warn( 'It seems you are using the standalone build of Vue.js in an ' + 'environment with Content Security Policy that prohibits unsafe-eval. ' + 'The template compiler cannot work in this environment. Consider ' + 'relaxing the policy to allow unsafe-eval or pre-compiling your ' + 'templates into render functions.' ); } } } var key = options && options.delimiters ? String(options.delimiters) + template : template; if (cache[key]) { return cache[key] } var res = {}; var compiled = compile$$1(template, options); res.render = makeFunction(compiled.render); var l = compiled.staticRenderFns.length; res.staticRenderFns = new Array(l); for (var i = 0; i < l; i++) { res.staticRenderFns[i] = makeFunction(compiled.staticRenderFns[i]); } { if (res.render === noop || res.staticRenderFns.some(function (fn) { return fn === noop; })) { _warn( "failed to compile template:\n\n" + template + "\n\n" + detectErrors(compiled.ast).join('\n') + '\n\n', vm ); } } return (cache[key] = res) } function makeFunction (code) { try { return new Function(code) } catch (e) { return noop } } /* */ var idToTemplate = cached(function (id) { var el = query(id); return el && el.innerHTML }); var mount = Vue$3.prototype.$mount; Vue$3.prototype.$mount = function ( el, hydrating ) { el = el && query(el); /* istanbul ignore if */ if (el === document.body || el === document.documentElement) { "development" !== 'production' && warn( "Do not mount Vue to <html> or <body> - mount to normal elements instead." ); return this } var options = this.$options; // resolve template/el and convert to render function if (!options.render) { var template = options.template; if (template) { if (typeof template === 'string') { if (template.charAt(0) === '#') { template = idToTemplate(template); /* istanbul ignore if */ if ("development" !== 'production' && !template) { warn( ("Template element not found or is empty: " + (options.template)), this ); } } } else if (template.nodeType) { template = template.innerHTML; } else { { warn('invalid template option:' + template, this); } return this } } else if (el) { template = getOuterHTML(el); } if (template) { var ref = compileToFunctions(template, { warn: warn, shouldDecodeNewlines: shouldDecodeNewlines, delimiters: options.delimiters }, this); var render = ref.render; var staticRenderFns = ref.staticRenderFns; options.render = render; options.staticRenderFns = staticRenderFns; } } return mount.call(this, el, hydrating) }; /** * Get outerHTML of elements, taking care * of SVG elements in IE as well. */ function getOuterHTML (el) { if (el.outerHTML) { return el.outerHTML } else { var container = document.createElement('div'); container.appendChild(el.cloneNode(true)); return container.innerHTML } } Vue$3.compile = compileToFunctions; return Vue$3; })));
packages/material-ui-icons/src/Battery80Sharp.js
allanalexandre/material-ui
import React from 'react'; import createSvgIcon from './utils/createSvgIcon'; export default createSvgIcon( <React.Fragment><path fill="none" d="M0 0h24v24H0V0z" /><g><path fillOpacity=".3" d="M17 4h-3V2h-4v2H7v5h10V4z" /><path d="M7 9v13h10V9H7z" /></g></React.Fragment> , 'Battery80Sharp');
src/lib/components/popup/popup.js
lighter-cd/ezui_react_one
import React, { Component } from 'react'; import PropTypes from 'prop-types'; import injectSheet from 'react-jss'; import classNames from 'classnames'; import { Mask } from '../mask'; const styles = { popup: { position: 'fixed', left: 0, bottom: 0, transform: 'translate(0, 100%)', backfaceVisibility: 'hidden', zIndex: 5000, width: '100%', backgroundColor: '#FFF', // slide up animation transition: 'transform .3s', }, // popup aniamtion popup_toggle: { transform: 'translate(0, 0)', }, }; /** * An Popup modal from bottom * */ class Popup extends Component { static propTypes = { /** * display the component * */ show: PropTypes.bool, /** * show mask * */ enableMask: PropTypes.bool, }; static defaultProps = { show: false, enableMask: false, } render() { const { classes, className, children, show, onRequestClose, enableMask, sheet, theme, ...others } = this.props; const cls = classNames(classes.popup, { [classes.popup_toggle]: show, }, className); return ( <div> <Mask transparent={enableMask} style={{ display: show ? 'block' : 'none' }} onClick={onRequestClose} /> <div className={cls} {...others} > { children } </div> </div> ); } } export default injectSheet(styles)(Popup);
admin/client/App/shared/Popout/PopoutBody.js
concoursbyappointment/keystoneRedux
/** * Render the body of a popout */ import React from 'react'; import blacklist from 'blacklist'; import classnames from 'classnames'; var PopoutBody = React.createClass({ displayName: 'PopoutBody', propTypes: { children: React.PropTypes.node.isRequired, className: React.PropTypes.string, scrollable: React.PropTypes.bool, }, render () { const className = classnames('Popout__body', { 'Popout__scrollable-area': this.props.scrollable, }, this.props.className); const props = blacklist(this.props, 'className', 'scrollable'); return ( <div className={className} {...props} /> ); }, }); module.exports = PopoutBody;
src/parser/druid/guardian/modules/features/IronFurGoEProcs.js
FaideWW/WoWAnalyzer
import React from 'react'; import { formatPercentage } from 'common/format'; import SpellIcon from 'common/SpellIcon'; import StatisticBox, { STATISTIC_ORDER } from 'interface/others/StatisticBox'; import SPELLS from 'common/SPELLS'; import Analyzer from 'parser/core/Analyzer'; import GuardianOfElune from './GuardianOfElune'; class IronFurGoEProcs extends Analyzer { static dependencies = { guardianOfElune: GuardianOfElune, }; constructor(...args) { super(...args); this.active = this.selectedCombatant.hasTalent(SPELLS.GUARDIAN_OF_ELUNE_TALENT.id); } statistic() { const nonGoEIronFur = this.guardianOfElune.nonGoEIronFur; const GoEIronFur = this.guardianOfElune.GoEIronFur; return ( <StatisticBox icon={<SpellIcon id={SPELLS.IRONFUR.id} />} value={`${formatPercentage(nonGoEIronFur / (nonGoEIronFur + GoEIronFur))}%`} label="Unbuffed Ironfur" tooltip={`You cast <b>${nonGoEIronFur + GoEIronFur}</b> total ${SPELLS.IRONFUR.name} and <b>${GoEIronFur}</b> were buffed by 2s.`} /> ); } statisticOrder = STATISTIC_ORDER.CORE(9); } export default IronFurGoEProcs;
ajax/libs/shariff/1.4.7/shariff.complete.js
magoni/cdnjs
/* * shariff - v1.4.5 - 02.12.2014 * https://github.com/heiseonline/shariff * Copyright (c) 2014 Ines Pauer, Philipp Busse, Sebastian Hilbig, Erich Kramer, Deniz Sesli * Licensed under the MIT <http://www.opensource.org/licenses/mit-license.php> license */ (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<r.length;o++)s(r[o]);return s})({1:[function(require,module,exports){ !function(e,t){"object"==typeof module&&"object"==typeof module.exports?module.exports=e.document?t(e,!0):function(e){if(!e.document)throw new Error("jQuery requires a window with a document");return t(e)}:t(e)}("undefined"!=typeof window?window:this,function(e,t){function n(e){var t=e.length,n=it.type(e);return"function"===n||it.isWindow(e)?!1:1===e.nodeType&&t?!0:"array"===n||0===t||"number"==typeof t&&t>0&&t-1 in e}function r(e,t,n){if(it.isFunction(t))return it.grep(e,function(e,r){return!!t.call(e,r,e)!==n});if(t.nodeType)return it.grep(e,function(e){return e===t!==n});if("string"==typeof t){if(ft.test(t))return it.filter(t,e,n);t=it.filter(t,e)}return it.grep(e,function(e){return it.inArray(e,t)>=0!==n})}function i(e,t){do e=e[t];while(e&&1!==e.nodeType);return e}function o(e){var t=xt[e]={};return it.each(e.match(bt)||[],function(e,n){t[n]=!0}),t}function a(){ht.addEventListener?(ht.removeEventListener("DOMContentLoaded",s,!1),e.removeEventListener("load",s,!1)):(ht.detachEvent("onreadystatechange",s),e.detachEvent("onload",s))}function s(){(ht.addEventListener||"load"===event.type||"complete"===ht.readyState)&&(a(),it.ready())}function l(e,t,n){if(void 0===n&&1===e.nodeType){var r="data-"+t.replace(Et,"-$1").toLowerCase();if(n=e.getAttribute(r),"string"==typeof n){try{n="true"===n?!0:"false"===n?!1:"null"===n?null:+n+""===n?+n:Nt.test(n)?it.parseJSON(n):n}catch(i){}it.data(e,t,n)}else n=void 0}return n}function u(e){var t;for(t in e)if(("data"!==t||!it.isEmptyObject(e[t]))&&"toJSON"!==t)return!1;return!0}function c(e,t,n,r){if(it.acceptData(e)){var i,o,a=it.expando,s=e.nodeType,l=s?it.cache:e,u=s?e[a]:e[a]&&a;if(u&&l[u]&&(r||l[u].data)||void 0!==n||"string"!=typeof t)return u||(u=s?e[a]=J.pop()||it.guid++:a),l[u]||(l[u]=s?{}:{toJSON:it.noop}),("object"==typeof t||"function"==typeof t)&&(r?l[u]=it.extend(l[u],t):l[u].data=it.extend(l[u].data,t)),o=l[u],r||(o.data||(o.data={}),o=o.data),void 0!==n&&(o[it.camelCase(t)]=n),"string"==typeof t?(i=o[t],null==i&&(i=o[it.camelCase(t)])):i=o,i}}function d(e,t,n){if(it.acceptData(e)){var r,i,o=e.nodeType,a=o?it.cache:e,s=o?e[it.expando]:it.expando;if(a[s]){if(t&&(r=n?a[s]:a[s].data)){it.isArray(t)?t=t.concat(it.map(t,it.camelCase)):t in r?t=[t]:(t=it.camelCase(t),t=t in r?[t]:t.split(" ")),i=t.length;for(;i--;)delete r[t[i]];if(n?!u(r):!it.isEmptyObject(r))return}(n||(delete a[s].data,u(a[s])))&&(o?it.cleanData([e],!0):nt.deleteExpando||a!=a.window?delete a[s]:a[s]=null)}}}function f(){return!0}function p(){return!1}function h(){try{return ht.activeElement}catch(e){}}function m(e){var t=Ot.split("|"),n=e.createDocumentFragment();if(n.createElement)for(;t.length;)n.createElement(t.pop());return n}function g(e,t){var n,r,i=0,o=typeof e.getElementsByTagName!==Ct?e.getElementsByTagName(t||"*"):typeof e.querySelectorAll!==Ct?e.querySelectorAll(t||"*"):void 0;if(!o)for(o=[],n=e.childNodes||e;null!=(r=n[i]);i++)!t||it.nodeName(r,t)?o.push(r):it.merge(o,g(r,t));return void 0===t||t&&it.nodeName(e,t)?it.merge([e],o):o}function v(e){jt.test(e.type)&&(e.defaultChecked=e.checked)}function y(e,t){return it.nodeName(e,"table")&&it.nodeName(11!==t.nodeType?t:t.firstChild,"tr")?e.getElementsByTagName("tbody")[0]||e.appendChild(e.ownerDocument.createElement("tbody")):e}function b(e){return e.type=(null!==it.find.attr(e,"type"))+"/"+e.type,e}function x(e){var t=Vt.exec(e.type);return t?e.type=t[1]:e.removeAttribute("type"),e}function w(e,t){for(var n,r=0;null!=(n=e[r]);r++)it._data(n,"globalEval",!t||it._data(t[r],"globalEval"))}function T(e,t){if(1===t.nodeType&&it.hasData(e)){var n,r,i,o=it._data(e),a=it._data(t,o),s=o.events;if(s){delete a.handle,a.events={};for(n in s)for(r=0,i=s[n].length;i>r;r++)it.event.add(t,n,s[n][r])}a.data&&(a.data=it.extend({},a.data))}}function C(e,t){var n,r,i;if(1===t.nodeType){if(n=t.nodeName.toLowerCase(),!nt.noCloneEvent&&t[it.expando]){i=it._data(t);for(r in i.events)it.removeEvent(t,r,i.handle);t.removeAttribute(it.expando)}"script"===n&&t.text!==e.text?(b(t).text=e.text,x(t)):"object"===n?(t.parentNode&&(t.outerHTML=e.outerHTML),nt.html5Clone&&e.innerHTML&&!it.trim(t.innerHTML)&&(t.innerHTML=e.innerHTML)):"input"===n&&jt.test(e.type)?(t.defaultChecked=t.checked=e.checked,t.value!==e.value&&(t.value=e.value)):"option"===n?t.defaultSelected=t.selected=e.defaultSelected:("input"===n||"textarea"===n)&&(t.defaultValue=e.defaultValue)}}function N(t,n){var r,i=it(n.createElement(t)).appendTo(n.body),o=e.getDefaultComputedStyle&&(r=e.getDefaultComputedStyle(i[0]))?r.display:it.css(i[0],"display");return i.detach(),o}function E(e){var t=ht,n=Zt[e];return n||(n=N(e,t),"none"!==n&&n||(Kt=(Kt||it("<iframe frameborder='0' width='0' height='0'/>")).appendTo(t.documentElement),t=(Kt[0].contentWindow||Kt[0].contentDocument).document,t.write(),t.close(),n=N(e,t),Kt.detach()),Zt[e]=n),n}function k(e,t){return{get:function(){var n=e();if(null!=n)return n?void delete this.get:(this.get=t).apply(this,arguments)}}}function S(e,t){if(t in e)return t;for(var n=t.charAt(0).toUpperCase()+t.slice(1),r=t,i=pn.length;i--;)if(t=pn[i]+n,t in e)return t;return r}function A(e,t){for(var n,r,i,o=[],a=0,s=e.length;s>a;a++)r=e[a],r.style&&(o[a]=it._data(r,"olddisplay"),n=r.style.display,t?(o[a]||"none"!==n||(r.style.display=""),""===r.style.display&&At(r)&&(o[a]=it._data(r,"olddisplay",E(r.nodeName)))):(i=At(r),(n&&"none"!==n||!i)&&it._data(r,"olddisplay",i?n:it.css(r,"display"))));for(a=0;s>a;a++)r=e[a],r.style&&(t&&"none"!==r.style.display&&""!==r.style.display||(r.style.display=t?o[a]||"":"none"));return e}function D(e,t,n){var r=un.exec(t);return r?Math.max(0,r[1]-(n||0))+(r[2]||"px"):t}function j(e,t,n,r,i){for(var o=n===(r?"border":"content")?4:"width"===t?1:0,a=0;4>o;o+=2)"margin"===n&&(a+=it.css(e,n+St[o],!0,i)),r?("content"===n&&(a-=it.css(e,"padding"+St[o],!0,i)),"margin"!==n&&(a-=it.css(e,"border"+St[o]+"Width",!0,i))):(a+=it.css(e,"padding"+St[o],!0,i),"padding"!==n&&(a+=it.css(e,"border"+St[o]+"Width",!0,i)));return a}function L(e,t,n){var r=!0,i="width"===t?e.offsetWidth:e.offsetHeight,o=en(e),a=nt.boxSizing&&"border-box"===it.css(e,"boxSizing",!1,o);if(0>=i||null==i){if(i=tn(e,t,o),(0>i||null==i)&&(i=e.style[t]),rn.test(i))return i;r=a&&(nt.boxSizingReliable()||i===e.style[t]),i=parseFloat(i)||0}return i+j(e,t,n||(a?"border":"content"),r,o)+"px"}function H(e,t,n,r,i){return new H.prototype.init(e,t,n,r,i)}function _(){return setTimeout(function(){hn=void 0}),hn=it.now()}function q(e,t){var n,r={height:e},i=0;for(t=t?1:0;4>i;i+=2-t)n=St[i],r["margin"+n]=r["padding"+n]=e;return t&&(r.opacity=r.width=e),r}function M(e,t,n){for(var r,i=(xn[t]||[]).concat(xn["*"]),o=0,a=i.length;a>o;o++)if(r=i[o].call(n,t,e))return r}function O(e,t,n){var r,i,o,a,s,l,u,c,d=this,f={},p=e.style,h=e.nodeType&&At(e),m=it._data(e,"fxshow");n.queue||(s=it._queueHooks(e,"fx"),null==s.unqueued&&(s.unqueued=0,l=s.empty.fire,s.empty.fire=function(){s.unqueued||l()}),s.unqueued++,d.always(function(){d.always(function(){s.unqueued--,it.queue(e,"fx").length||s.empty.fire()})})),1===e.nodeType&&("height"in t||"width"in t)&&(n.overflow=[p.overflow,p.overflowX,p.overflowY],u=it.css(e,"display"),c="none"===u?it._data(e,"olddisplay")||E(e.nodeName):u,"inline"===c&&"none"===it.css(e,"float")&&(nt.inlineBlockNeedsLayout&&"inline"!==E(e.nodeName)?p.zoom=1:p.display="inline-block")),n.overflow&&(p.overflow="hidden",nt.shrinkWrapBlocks()||d.always(function(){p.overflow=n.overflow[0],p.overflowX=n.overflow[1],p.overflowY=n.overflow[2]}));for(r in t)if(i=t[r],gn.exec(i)){if(delete t[r],o=o||"toggle"===i,i===(h?"hide":"show")){if("show"!==i||!m||void 0===m[r])continue;h=!0}f[r]=m&&m[r]||it.style(e,r)}else u=void 0;if(it.isEmptyObject(f))"inline"===("none"===u?E(e.nodeName):u)&&(p.display=u);else{m?"hidden"in m&&(h=m.hidden):m=it._data(e,"fxshow",{}),o&&(m.hidden=!h),h?it(e).show():d.done(function(){it(e).hide()}),d.done(function(){var t;it._removeData(e,"fxshow");for(t in f)it.style(e,t,f[t])});for(r in f)a=M(h?m[r]:0,r,d),r in m||(m[r]=a.start,h&&(a.end=a.start,a.start="width"===r||"height"===r?1:0))}}function F(e,t){var n,r,i,o,a;for(n in e)if(r=it.camelCase(n),i=t[r],o=e[n],it.isArray(o)&&(i=o[1],o=e[n]=o[0]),n!==r&&(e[r]=o,delete e[n]),a=it.cssHooks[r],a&&"expand"in a){o=a.expand(o),delete e[r];for(n in o)n in e||(e[n]=o[n],t[n]=i)}else t[r]=i}function B(e,t,n){var r,i,o=0,a=bn.length,s=it.Deferred().always(function(){delete l.elem}),l=function(){if(i)return!1;for(var t=hn||_(),n=Math.max(0,u.startTime+u.duration-t),r=n/u.duration||0,o=1-r,a=0,l=u.tweens.length;l>a;a++)u.tweens[a].run(o);return s.notifyWith(e,[u,o,n]),1>o&&l?n:(s.resolveWith(e,[u]),!1)},u=s.promise({elem:e,props:it.extend({},t),opts:it.extend(!0,{specialEasing:{}},n),originalProperties:t,originalOptions:n,startTime:hn||_(),duration:n.duration,tweens:[],createTween:function(t,n){var r=it.Tween(e,u.opts,t,n,u.opts.specialEasing[t]||u.opts.easing);return u.tweens.push(r),r},stop:function(t){var n=0,r=t?u.tweens.length:0;if(i)return this;for(i=!0;r>n;n++)u.tweens[n].run(1);return t?s.resolveWith(e,[u,t]):s.rejectWith(e,[u,t]),this}}),c=u.props;for(F(c,u.opts.specialEasing);a>o;o++)if(r=bn[o].call(u,e,c,u.opts))return r;return it.map(c,M,u),it.isFunction(u.opts.start)&&u.opts.start.call(e,u),it.fx.timer(it.extend(l,{elem:e,anim:u,queue:u.opts.queue})),u.progress(u.opts.progress).done(u.opts.done,u.opts.complete).fail(u.opts.fail).always(u.opts.always)}function P(e){return function(t,n){"string"!=typeof t&&(n=t,t="*");var r,i=0,o=t.toLowerCase().match(bt)||[];if(it.isFunction(n))for(;r=o[i++];)"+"===r.charAt(0)?(r=r.slice(1)||"*",(e[r]=e[r]||[]).unshift(n)):(e[r]=e[r]||[]).push(n)}}function R(e,t,n,r){function i(s){var l;return o[s]=!0,it.each(e[s]||[],function(e,s){var u=s(t,n,r);return"string"!=typeof u||a||o[u]?a?!(l=u):void 0:(t.dataTypes.unshift(u),i(u),!1)}),l}var o={},a=e===In;return i(t.dataTypes[0])||!o["*"]&&i("*")}function W(e,t){var n,r,i=it.ajaxSettings.flatOptions||{};for(r in t)void 0!==t[r]&&((i[r]?e:n||(n={}))[r]=t[r]);return n&&it.extend(!0,e,n),e}function $(e,t,n){for(var r,i,o,a,s=e.contents,l=e.dataTypes;"*"===l[0];)l.shift(),void 0===i&&(i=e.mimeType||t.getResponseHeader("Content-Type"));if(i)for(a in s)if(s[a]&&s[a].test(i)){l.unshift(a);break}if(l[0]in n)o=l[0];else{for(a in n){if(!l[0]||e.converters[a+" "+l[0]]){o=a;break}r||(r=a)}o=o||r}return o?(o!==l[0]&&l.unshift(o),n[o]):void 0}function z(e,t,n,r){var i,o,a,s,l,u={},c=e.dataTypes.slice();if(c[1])for(a in e.converters)u[a.toLowerCase()]=e.converters[a];for(o=c.shift();o;)if(e.responseFields[o]&&(n[e.responseFields[o]]=t),!l&&r&&e.dataFilter&&(t=e.dataFilter(t,e.dataType)),l=o,o=c.shift())if("*"===o)o=l;else if("*"!==l&&l!==o){if(a=u[l+" "+o]||u["* "+o],!a)for(i in u)if(s=i.split(" "),s[1]===o&&(a=u[l+" "+s[0]]||u["* "+s[0]])){a===!0?a=u[i]:u[i]!==!0&&(o=s[0],c.unshift(s[1]));break}if(a!==!0)if(a&&e["throws"])t=a(t);else try{t=a(t)}catch(d){return{state:"parsererror",error:a?d:"No conversion from "+l+" to "+o}}}return{state:"success",data:t}}function I(e,t,n,r){var i;if(it.isArray(t))it.each(t,function(t,i){n||Jn.test(e)?r(e,i):I(e+"["+("object"==typeof i?t:"")+"]",i,n,r)});else if(n||"object"!==it.type(t))r(e,t);else for(i in t)I(e+"["+i+"]",t[i],n,r)}function X(){try{return new e.XMLHttpRequest}catch(t){}}function U(){try{return new e.ActiveXObject("Microsoft.XMLHTTP")}catch(t){}}function V(e){return it.isWindow(e)?e:9===e.nodeType?e.defaultView||e.parentWindow:!1}var J=[],Y=J.slice,G=J.concat,Q=J.push,K=J.indexOf,Z={},et=Z.toString,tt=Z.hasOwnProperty,nt={},rt="1.11.1",it=function(e,t){return new it.fn.init(e,t)},ot=/^[\s\uFEFF\xA0]+|[\s\uFEFF\xA0]+$/g,at=/^-ms-/,st=/-([\da-z])/gi,lt=function(e,t){return t.toUpperCase()};it.fn=it.prototype={jquery:rt,constructor:it,selector:"",length:0,toArray:function(){return Y.call(this)},get:function(e){return null!=e?0>e?this[e+this.length]:this[e]:Y.call(this)},pushStack:function(e){var t=it.merge(this.constructor(),e);return t.prevObject=this,t.context=this.context,t},each:function(e,t){return it.each(this,e,t)},map:function(e){return this.pushStack(it.map(this,function(t,n){return e.call(t,n,t)}))},slice:function(){return this.pushStack(Y.apply(this,arguments))},first:function(){return this.eq(0)},last:function(){return this.eq(-1)},eq:function(e){var t=this.length,n=+e+(0>e?t:0);return this.pushStack(n>=0&&t>n?[this[n]]:[])},end:function(){return this.prevObject||this.constructor(null)},push:Q,sort:J.sort,splice:J.splice},it.extend=it.fn.extend=function(){var e,t,n,r,i,o,a=arguments[0]||{},s=1,l=arguments.length,u=!1;for("boolean"==typeof a&&(u=a,a=arguments[s]||{},s++),"object"==typeof a||it.isFunction(a)||(a={}),s===l&&(a=this,s--);l>s;s++)if(null!=(i=arguments[s]))for(r in i)e=a[r],n=i[r],a!==n&&(u&&n&&(it.isPlainObject(n)||(t=it.isArray(n)))?(t?(t=!1,o=e&&it.isArray(e)?e:[]):o=e&&it.isPlainObject(e)?e:{},a[r]=it.extend(u,o,n)):void 0!==n&&(a[r]=n));return a},it.extend({expando:"jQuery"+(rt+Math.random()).replace(/\D/g,""),isReady:!0,error:function(e){throw new Error(e)},noop:function(){},isFunction:function(e){return"function"===it.type(e)},isArray:Array.isArray||function(e){return"array"===it.type(e)},isWindow:function(e){return null!=e&&e==e.window},isNumeric:function(e){return!it.isArray(e)&&e-parseFloat(e)>=0},isEmptyObject:function(e){var t;for(t in e)return!1;return!0},isPlainObject:function(e){var t;if(!e||"object"!==it.type(e)||e.nodeType||it.isWindow(e))return!1;try{if(e.constructor&&!tt.call(e,"constructor")&&!tt.call(e.constructor.prototype,"isPrototypeOf"))return!1}catch(n){return!1}if(nt.ownLast)for(t in e)return tt.call(e,t);for(t in e);return void 0===t||tt.call(e,t)},type:function(e){return null==e?e+"":"object"==typeof e||"function"==typeof e?Z[et.call(e)]||"object":typeof e},globalEval:function(t){t&&it.trim(t)&&(e.execScript||function(t){e.eval.call(e,t)})(t)},camelCase:function(e){return e.replace(at,"ms-").replace(st,lt)},nodeName:function(e,t){return e.nodeName&&e.nodeName.toLowerCase()===t.toLowerCase()},each:function(e,t,r){var i,o=0,a=e.length,s=n(e);if(r){if(s)for(;a>o&&(i=t.apply(e[o],r),i!==!1);o++);else for(o in e)if(i=t.apply(e[o],r),i===!1)break}else if(s)for(;a>o&&(i=t.call(e[o],o,e[o]),i!==!1);o++);else for(o in e)if(i=t.call(e[o],o,e[o]),i===!1)break;return e},trim:function(e){return null==e?"":(e+"").replace(ot,"")},makeArray:function(e,t){var r=t||[];return null!=e&&(n(Object(e))?it.merge(r,"string"==typeof e?[e]:e):Q.call(r,e)),r},inArray:function(e,t,n){var r;if(t){if(K)return K.call(t,e,n);for(r=t.length,n=n?0>n?Math.max(0,r+n):n:0;r>n;n++)if(n in t&&t[n]===e)return n}return-1},merge:function(e,t){for(var n=+t.length,r=0,i=e.length;n>r;)e[i++]=t[r++];if(n!==n)for(;void 0!==t[r];)e[i++]=t[r++];return e.length=i,e},grep:function(e,t,n){for(var r,i=[],o=0,a=e.length,s=!n;a>o;o++)r=!t(e[o],o),r!==s&&i.push(e[o]);return i},map:function(e,t,r){var i,o=0,a=e.length,s=n(e),l=[];if(s)for(;a>o;o++)i=t(e[o],o,r),null!=i&&l.push(i);else for(o in e)i=t(e[o],o,r),null!=i&&l.push(i);return G.apply([],l)},guid:1,proxy:function(e,t){var n,r,i;return"string"==typeof t&&(i=e[t],t=e,e=i),it.isFunction(e)?(n=Y.call(arguments,2),r=function(){return e.apply(t||this,n.concat(Y.call(arguments)))},r.guid=e.guid=e.guid||it.guid++,r):void 0},now:function(){return+new Date},support:nt}),it.each("Boolean Number String Function Array Date RegExp Object Error".split(" "),function(e,t){Z["[object "+t+"]"]=t.toLowerCase()});var ut=function(e){function t(e,t,n,r){var i,o,a,s,l,u,d,p,h,m;if((t?t.ownerDocument||t:R)!==H&&L(t),t=t||H,n=n||[],!e||"string"!=typeof e)return n;if(1!==(s=t.nodeType)&&9!==s)return[];if(q&&!r){if(i=yt.exec(e))if(a=i[1]){if(9===s){if(o=t.getElementById(a),!o||!o.parentNode)return n;if(o.id===a)return n.push(o),n}else if(t.ownerDocument&&(o=t.ownerDocument.getElementById(a))&&B(t,o)&&o.id===a)return n.push(o),n}else{if(i[2])return Z.apply(n,t.getElementsByTagName(e)),n;if((a=i[3])&&w.getElementsByClassName&&t.getElementsByClassName)return Z.apply(n,t.getElementsByClassName(a)),n}if(w.qsa&&(!M||!M.test(e))){if(p=d=P,h=t,m=9===s&&e,1===s&&"object"!==t.nodeName.toLowerCase()){for(u=E(e),(d=t.getAttribute("id"))?p=d.replace(xt,"\\$&"):t.setAttribute("id",p),p="[id='"+p+"'] ",l=u.length;l--;)u[l]=p+f(u[l]);h=bt.test(e)&&c(t.parentNode)||t,m=u.join(",")}if(m)try{return Z.apply(n,h.querySelectorAll(m)),n}catch(g){}finally{d||t.removeAttribute("id")}}}return S(e.replace(lt,"$1"),t,n,r)}function n(){function e(n,r){return t.push(n+" ")>T.cacheLength&&delete e[t.shift()],e[n+" "]=r}var t=[];return e}function r(e){return e[P]=!0,e}function i(e){var t=H.createElement("div");try{return!!e(t)}catch(n){return!1}finally{t.parentNode&&t.parentNode.removeChild(t),t=null}}function o(e,t){for(var n=e.split("|"),r=e.length;r--;)T.attrHandle[n[r]]=t}function a(e,t){var n=t&&e,r=n&&1===e.nodeType&&1===t.nodeType&&(~t.sourceIndex||J)-(~e.sourceIndex||J);if(r)return r;if(n)for(;n=n.nextSibling;)if(n===t)return-1;return e?1:-1}function s(e){return function(t){var n=t.nodeName.toLowerCase();return"input"===n&&t.type===e}}function l(e){return function(t){var n=t.nodeName.toLowerCase();return("input"===n||"button"===n)&&t.type===e}}function u(e){return r(function(t){return t=+t,r(function(n,r){for(var i,o=e([],n.length,t),a=o.length;a--;)n[i=o[a]]&&(n[i]=!(r[i]=n[i]))})})}function c(e){return e&&typeof e.getElementsByTagName!==V&&e}function d(){}function f(e){for(var t=0,n=e.length,r="";n>t;t++)r+=e[t].value;return r}function p(e,t,n){var r=t.dir,i=n&&"parentNode"===r,o=$++;return t.first?function(t,n,o){for(;t=t[r];)if(1===t.nodeType||i)return e(t,n,o)}:function(t,n,a){var s,l,u=[W,o];if(a){for(;t=t[r];)if((1===t.nodeType||i)&&e(t,n,a))return!0}else for(;t=t[r];)if(1===t.nodeType||i){if(l=t[P]||(t[P]={}),(s=l[r])&&s[0]===W&&s[1]===o)return u[2]=s[2];if(l[r]=u,u[2]=e(t,n,a))return!0}}}function h(e){return e.length>1?function(t,n,r){for(var i=e.length;i--;)if(!e[i](t,n,r))return!1;return!0}:e[0]}function m(e,n,r){for(var i=0,o=n.length;o>i;i++)t(e,n[i],r);return r}function g(e,t,n,r,i){for(var o,a=[],s=0,l=e.length,u=null!=t;l>s;s++)(o=e[s])&&(!n||n(o,r,i))&&(a.push(o),u&&t.push(s));return a}function v(e,t,n,i,o,a){return i&&!i[P]&&(i=v(i)),o&&!o[P]&&(o=v(o,a)),r(function(r,a,s,l){var u,c,d,f=[],p=[],h=a.length,v=r||m(t||"*",s.nodeType?[s]:s,[]),y=!e||!r&&t?v:g(v,f,e,s,l),b=n?o||(r?e:h||i)?[]:a:y;if(n&&n(y,b,s,l),i)for(u=g(b,p),i(u,[],s,l),c=u.length;c--;)(d=u[c])&&(b[p[c]]=!(y[p[c]]=d));if(r){if(o||e){if(o){for(u=[],c=b.length;c--;)(d=b[c])&&u.push(y[c]=d);o(null,b=[],u,l)}for(c=b.length;c--;)(d=b[c])&&(u=o?tt.call(r,d):f[c])>-1&&(r[u]=!(a[u]=d))}}else b=g(b===a?b.splice(h,b.length):b),o?o(null,a,b,l):Z.apply(a,b)})}function y(e){for(var t,n,r,i=e.length,o=T.relative[e[0].type],a=o||T.relative[" "],s=o?1:0,l=p(function(e){return e===t},a,!0),u=p(function(e){return tt.call(t,e)>-1},a,!0),c=[function(e,n,r){return!o&&(r||n!==A)||((t=n).nodeType?l(e,n,r):u(e,n,r))}];i>s;s++)if(n=T.relative[e[s].type])c=[p(h(c),n)];else{if(n=T.filter[e[s].type].apply(null,e[s].matches),n[P]){for(r=++s;i>r&&!T.relative[e[r].type];r++);return v(s>1&&h(c),s>1&&f(e.slice(0,s-1).concat({value:" "===e[s-2].type?"*":""})).replace(lt,"$1"),n,r>s&&y(e.slice(s,r)),i>r&&y(e=e.slice(r)),i>r&&f(e))}c.push(n)}return h(c)}function b(e,n){var i=n.length>0,o=e.length>0,a=function(r,a,s,l,u){var c,d,f,p=0,h="0",m=r&&[],v=[],y=A,b=r||o&&T.find.TAG("*",u),x=W+=null==y?1:Math.random()||.1,w=b.length;for(u&&(A=a!==H&&a);h!==w&&null!=(c=b[h]);h++){if(o&&c){for(d=0;f=e[d++];)if(f(c,a,s)){l.push(c);break}u&&(W=x)}i&&((c=!f&&c)&&p--,r&&m.push(c))}if(p+=h,i&&h!==p){for(d=0;f=n[d++];)f(m,v,a,s);if(r){if(p>0)for(;h--;)m[h]||v[h]||(v[h]=Q.call(l));v=g(v)}Z.apply(l,v),u&&!r&&v.length>0&&p+n.length>1&&t.uniqueSort(l)}return u&&(W=x,A=y),m};return i?r(a):a}var x,w,T,C,N,E,k,S,A,D,j,L,H,_,q,M,O,F,B,P="sizzle"+-new Date,R=e.document,W=0,$=0,z=n(),I=n(),X=n(),U=function(e,t){return e===t&&(j=!0),0},V="undefined",J=1<<31,Y={}.hasOwnProperty,G=[],Q=G.pop,K=G.push,Z=G.push,et=G.slice,tt=G.indexOf||function(e){for(var t=0,n=this.length;n>t;t++)if(this[t]===e)return t;return-1},nt="checked|selected|async|autofocus|autoplay|controls|defer|disabled|hidden|ismap|loop|multiple|open|readonly|required|scoped",rt="[\\x20\\t\\r\\n\\f]",it="(?:\\\\.|[\\w-]|[^\\x00-\\xa0])+",ot=it.replace("w","w#"),at="\\["+rt+"*("+it+")(?:"+rt+"*([*^$|!~]?=)"+rt+"*(?:'((?:\\\\.|[^\\\\'])*)'|\"((?:\\\\.|[^\\\\\"])*)\"|("+ot+"))|)"+rt+"*\\]",st=":("+it+")(?:\\((('((?:\\\\.|[^\\\\'])*)'|\"((?:\\\\.|[^\\\\\"])*)\")|((?:\\\\.|[^\\\\()[\\]]|"+at+")*)|.*)\\)|)",lt=new RegExp("^"+rt+"+|((?:^|[^\\\\])(?:\\\\.)*)"+rt+"+$","g"),ut=new RegExp("^"+rt+"*,"+rt+"*"),ct=new RegExp("^"+rt+"*([>+~]|"+rt+")"+rt+"*"),dt=new RegExp("="+rt+"*([^\\]'\"]*?)"+rt+"*\\]","g"),ft=new RegExp(st),pt=new RegExp("^"+ot+"$"),ht={ID:new RegExp("^#("+it+")"),CLASS:new RegExp("^\\.("+it+")"),TAG:new RegExp("^("+it.replace("w","w*")+")"),ATTR:new RegExp("^"+at),PSEUDO:new RegExp("^"+st),CHILD:new RegExp("^:(only|first|last|nth|nth-last)-(child|of-type)(?:\\("+rt+"*(even|odd|(([+-]|)(\\d*)n|)"+rt+"*(?:([+-]|)"+rt+"*(\\d+)|))"+rt+"*\\)|)","i"),bool:new RegExp("^(?:"+nt+")$","i"),needsContext:new RegExp("^"+rt+"*[>+~]|:(even|odd|eq|gt|lt|nth|first|last)(?:\\("+rt+"*((?:-\\d)?\\d*)"+rt+"*\\)|)(?=[^-]|$)","i")},mt=/^(?:input|select|textarea|button)$/i,gt=/^h\d$/i,vt=/^[^{]+\{\s*\[native \w/,yt=/^(?:#([\w-]+)|(\w+)|\.([\w-]+))$/,bt=/[+~]/,xt=/'|\\/g,wt=new RegExp("\\\\([\\da-f]{1,6}"+rt+"?|("+rt+")|.)","ig"),Tt=function(e,t,n){var r="0x"+t-65536;return r!==r||n?t:0>r?String.fromCharCode(r+65536):String.fromCharCode(r>>10|55296,1023&r|56320)};try{Z.apply(G=et.call(R.childNodes),R.childNodes),G[R.childNodes.length].nodeType}catch(Ct){Z={apply:G.length?function(e,t){K.apply(e,et.call(t))}:function(e,t){for(var n=e.length,r=0;e[n++]=t[r++];);e.length=n-1}}}w=t.support={},N=t.isXML=function(e){var t=e&&(e.ownerDocument||e).documentElement;return t?"HTML"!==t.nodeName:!1},L=t.setDocument=function(e){var t,n=e?e.ownerDocument||e:R,r=n.defaultView;return n!==H&&9===n.nodeType&&n.documentElement?(H=n,_=n.documentElement,q=!N(n),r&&r!==r.top&&(r.addEventListener?r.addEventListener("unload",function(){L()},!1):r.attachEvent&&r.attachEvent("onunload",function(){L()})),w.attributes=i(function(e){return e.className="i",!e.getAttribute("className")}),w.getElementsByTagName=i(function(e){return e.appendChild(n.createComment("")),!e.getElementsByTagName("*").length}),w.getElementsByClassName=vt.test(n.getElementsByClassName)&&i(function(e){return e.innerHTML="<div class='a'></div><div class='a i'></div>",e.firstChild.className="i",2===e.getElementsByClassName("i").length}),w.getById=i(function(e){return _.appendChild(e).id=P,!n.getElementsByName||!n.getElementsByName(P).length}),w.getById?(T.find.ID=function(e,t){if(typeof t.getElementById!==V&&q){var n=t.getElementById(e);return n&&n.parentNode?[n]:[]}},T.filter.ID=function(e){var t=e.replace(wt,Tt);return function(e){return e.getAttribute("id")===t}}):(delete T.find.ID,T.filter.ID=function(e){var t=e.replace(wt,Tt);return function(e){var n=typeof e.getAttributeNode!==V&&e.getAttributeNode("id");return n&&n.value===t}}),T.find.TAG=w.getElementsByTagName?function(e,t){return typeof t.getElementsByTagName!==V?t.getElementsByTagName(e):void 0}:function(e,t){var n,r=[],i=0,o=t.getElementsByTagName(e);if("*"===e){for(;n=o[i++];)1===n.nodeType&&r.push(n);return r}return o},T.find.CLASS=w.getElementsByClassName&&function(e,t){return typeof t.getElementsByClassName!==V&&q?t.getElementsByClassName(e):void 0},O=[],M=[],(w.qsa=vt.test(n.querySelectorAll))&&(i(function(e){e.innerHTML="<select msallowclip=''><option selected=''></option></select>",e.querySelectorAll("[msallowclip^='']").length&&M.push("[*^$]="+rt+"*(?:''|\"\")"),e.querySelectorAll("[selected]").length||M.push("\\["+rt+"*(?:value|"+nt+")"),e.querySelectorAll(":checked").length||M.push(":checked")}),i(function(e){var t=n.createElement("input");t.setAttribute("type","hidden"),e.appendChild(t).setAttribute("name","D"),e.querySelectorAll("[name=d]").length&&M.push("name"+rt+"*[*^$|!~]?="),e.querySelectorAll(":enabled").length||M.push(":enabled",":disabled"),e.querySelectorAll("*,:x"),M.push(",.*:")})),(w.matchesSelector=vt.test(F=_.matches||_.webkitMatchesSelector||_.mozMatchesSelector||_.oMatchesSelector||_.msMatchesSelector))&&i(function(e){w.disconnectedMatch=F.call(e,"div"),F.call(e,"[s!='']:x"),O.push("!=",st)}),M=M.length&&new RegExp(M.join("|")),O=O.length&&new RegExp(O.join("|")),t=vt.test(_.compareDocumentPosition),B=t||vt.test(_.contains)?function(e,t){var n=9===e.nodeType?e.documentElement:e,r=t&&t.parentNode;return e===r||!(!r||1!==r.nodeType||!(n.contains?n.contains(r):e.compareDocumentPosition&&16&e.compareDocumentPosition(r)))}:function(e,t){if(t)for(;t=t.parentNode;)if(t===e)return!0;return!1},U=t?function(e,t){if(e===t)return j=!0,0;var r=!e.compareDocumentPosition-!t.compareDocumentPosition;return r?r:(r=(e.ownerDocument||e)===(t.ownerDocument||t)?e.compareDocumentPosition(t):1,1&r||!w.sortDetached&&t.compareDocumentPosition(e)===r?e===n||e.ownerDocument===R&&B(R,e)?-1:t===n||t.ownerDocument===R&&B(R,t)?1:D?tt.call(D,e)-tt.call(D,t):0:4&r?-1:1)}:function(e,t){if(e===t)return j=!0,0;var r,i=0,o=e.parentNode,s=t.parentNode,l=[e],u=[t];if(!o||!s)return e===n?-1:t===n?1:o?-1:s?1:D?tt.call(D,e)-tt.call(D,t):0;if(o===s)return a(e,t);for(r=e;r=r.parentNode;)l.unshift(r);for(r=t;r=r.parentNode;)u.unshift(r);for(;l[i]===u[i];)i++;return i?a(l[i],u[i]):l[i]===R?-1:u[i]===R?1:0},n):H},t.matches=function(e,n){return t(e,null,null,n)},t.matchesSelector=function(e,n){if((e.ownerDocument||e)!==H&&L(e),n=n.replace(dt,"='$1']"),!(!w.matchesSelector||!q||O&&O.test(n)||M&&M.test(n)))try{var r=F.call(e,n);if(r||w.disconnectedMatch||e.document&&11!==e.document.nodeType)return r}catch(i){}return t(n,H,null,[e]).length>0},t.contains=function(e,t){return(e.ownerDocument||e)!==H&&L(e),B(e,t)},t.attr=function(e,t){(e.ownerDocument||e)!==H&&L(e);var n=T.attrHandle[t.toLowerCase()],r=n&&Y.call(T.attrHandle,t.toLowerCase())?n(e,t,!q):void 0;return void 0!==r?r:w.attributes||!q?e.getAttribute(t):(r=e.getAttributeNode(t))&&r.specified?r.value:null},t.error=function(e){throw new Error("Syntax error, unrecognized expression: "+e)},t.uniqueSort=function(e){var t,n=[],r=0,i=0;if(j=!w.detectDuplicates,D=!w.sortStable&&e.slice(0),e.sort(U),j){for(;t=e[i++];)t===e[i]&&(r=n.push(i));for(;r--;)e.splice(n[r],1)}return D=null,e},C=t.getText=function(e){var t,n="",r=0,i=e.nodeType;if(i){if(1===i||9===i||11===i){if("string"==typeof e.textContent)return e.textContent;for(e=e.firstChild;e;e=e.nextSibling)n+=C(e)}else if(3===i||4===i)return e.nodeValue}else for(;t=e[r++];)n+=C(t);return n},T=t.selectors={cacheLength:50,createPseudo:r,match:ht,attrHandle:{},find:{},relative:{">":{dir:"parentNode",first:!0}," ":{dir:"parentNode"},"+":{dir:"previousSibling",first:!0},"~":{dir:"previousSibling"}},preFilter:{ATTR:function(e){return e[1]=e[1].replace(wt,Tt),e[3]=(e[3]||e[4]||e[5]||"").replace(wt,Tt),"~="===e[2]&&(e[3]=" "+e[3]+" "),e.slice(0,4)},CHILD:function(e){return e[1]=e[1].toLowerCase(),"nth"===e[1].slice(0,3)?(e[3]||t.error(e[0]),e[4]=+(e[4]?e[5]+(e[6]||1):2*("even"===e[3]||"odd"===e[3])),e[5]=+(e[7]+e[8]||"odd"===e[3])):e[3]&&t.error(e[0]),e},PSEUDO:function(e){var t,n=!e[6]&&e[2];return ht.CHILD.test(e[0])?null:(e[3]?e[2]=e[4]||e[5]||"":n&&ft.test(n)&&(t=E(n,!0))&&(t=n.indexOf(")",n.length-t)-n.length)&&(e[0]=e[0].slice(0,t),e[2]=n.slice(0,t)),e.slice(0,3))}},filter:{TAG:function(e){var t=e.replace(wt,Tt).toLowerCase();return"*"===e?function(){return!0}:function(e){return e.nodeName&&e.nodeName.toLowerCase()===t}},CLASS:function(e){var t=z[e+" "];return t||(t=new RegExp("(^|"+rt+")"+e+"("+rt+"|$)"))&&z(e,function(e){return t.test("string"==typeof e.className&&e.className||typeof e.getAttribute!==V&&e.getAttribute("class")||"")})},ATTR:function(e,n,r){return function(i){var o=t.attr(i,e);return null==o?"!="===n:n?(o+="","="===n?o===r:"!="===n?o!==r:"^="===n?r&&0===o.indexOf(r):"*="===n?r&&o.indexOf(r)>-1:"$="===n?r&&o.slice(-r.length)===r:"~="===n?(" "+o+" ").indexOf(r)>-1:"|="===n?o===r||o.slice(0,r.length+1)===r+"-":!1):!0}},CHILD:function(e,t,n,r,i){var o="nth"!==e.slice(0,3),a="last"!==e.slice(-4),s="of-type"===t;return 1===r&&0===i?function(e){return!!e.parentNode}:function(t,n,l){var u,c,d,f,p,h,m=o!==a?"nextSibling":"previousSibling",g=t.parentNode,v=s&&t.nodeName.toLowerCase(),y=!l&&!s;if(g){if(o){for(;m;){for(d=t;d=d[m];)if(s?d.nodeName.toLowerCase()===v:1===d.nodeType)return!1;h=m="only"===e&&!h&&"nextSibling"}return!0}if(h=[a?g.firstChild:g.lastChild],a&&y){for(c=g[P]||(g[P]={}),u=c[e]||[],p=u[0]===W&&u[1],f=u[0]===W&&u[2],d=p&&g.childNodes[p];d=++p&&d&&d[m]||(f=p=0)||h.pop();)if(1===d.nodeType&&++f&&d===t){c[e]=[W,p,f];break}}else if(y&&(u=(t[P]||(t[P]={}))[e])&&u[0]===W)f=u[1];else for(;(d=++p&&d&&d[m]||(f=p=0)||h.pop())&&((s?d.nodeName.toLowerCase()!==v:1!==d.nodeType)||!++f||(y&&((d[P]||(d[P]={}))[e]=[W,f]),d!==t)););return f-=i,f===r||f%r===0&&f/r>=0}}},PSEUDO:function(e,n){var i,o=T.pseudos[e]||T.setFilters[e.toLowerCase()]||t.error("unsupported pseudo: "+e);return o[P]?o(n):o.length>1?(i=[e,e,"",n],T.setFilters.hasOwnProperty(e.toLowerCase())?r(function(e,t){for(var r,i=o(e,n),a=i.length;a--;)r=tt.call(e,i[a]),e[r]=!(t[r]=i[a])}):function(e){return o(e,0,i)}):o}},pseudos:{not:r(function(e){var t=[],n=[],i=k(e.replace(lt,"$1"));return i[P]?r(function(e,t,n,r){for(var o,a=i(e,null,r,[]),s=e.length;s--;)(o=a[s])&&(e[s]=!(t[s]=o))}):function(e,r,o){return t[0]=e,i(t,null,o,n),!n.pop()}}),has:r(function(e){return function(n){return t(e,n).length>0}}),contains:r(function(e){return function(t){return(t.textContent||t.innerText||C(t)).indexOf(e)>-1}}),lang:r(function(e){return pt.test(e||"")||t.error("unsupported lang: "+e),e=e.replace(wt,Tt).toLowerCase(),function(t){var n;do if(n=q?t.lang:t.getAttribute("xml:lang")||t.getAttribute("lang"))return n=n.toLowerCase(),n===e||0===n.indexOf(e+"-");while((t=t.parentNode)&&1===t.nodeType);return!1}}),target:function(t){var n=e.location&&e.location.hash;return n&&n.slice(1)===t.id},root:function(e){return e===_},focus:function(e){return e===H.activeElement&&(!H.hasFocus||H.hasFocus())&&!!(e.type||e.href||~e.tabIndex)},enabled:function(e){return e.disabled===!1},disabled:function(e){return e.disabled===!0},checked:function(e){var t=e.nodeName.toLowerCase();return"input"===t&&!!e.checked||"option"===t&&!!e.selected},selected:function(e){return e.parentNode&&e.parentNode.selectedIndex,e.selected===!0},empty:function(e){for(e=e.firstChild;e;e=e.nextSibling)if(e.nodeType<6)return!1;return!0},parent:function(e){return!T.pseudos.empty(e)},header:function(e){return gt.test(e.nodeName)},input:function(e){return mt.test(e.nodeName)},button:function(e){var t=e.nodeName.toLowerCase();return"input"===t&&"button"===e.type||"button"===t},text:function(e){var t;return"input"===e.nodeName.toLowerCase()&&"text"===e.type&&(null==(t=e.getAttribute("type"))||"text"===t.toLowerCase())},first:u(function(){return[0]}),last:u(function(e,t){return[t-1]}),eq:u(function(e,t,n){return[0>n?n+t:n]}),even:u(function(e,t){for(var n=0;t>n;n+=2)e.push(n);return e}),odd:u(function(e,t){for(var n=1;t>n;n+=2)e.push(n);return e}),lt:u(function(e,t,n){for(var r=0>n?n+t:n;--r>=0;)e.push(r);return e}),gt:u(function(e,t,n){for(var r=0>n?n+t:n;++r<t;)e.push(r);return e})}},T.pseudos.nth=T.pseudos.eq;for(x in{radio:!0,checkbox:!0,file:!0,password:!0,image:!0})T.pseudos[x]=s(x);for(x in{submit:!0,reset:!0})T.pseudos[x]=l(x);return d.prototype=T.filters=T.pseudos,T.setFilters=new d,E=t.tokenize=function(e,n){var r,i,o,a,s,l,u,c=I[e+" "];if(c)return n?0:c.slice(0);for(s=e,l=[],u=T.preFilter;s;){(!r||(i=ut.exec(s)))&&(i&&(s=s.slice(i[0].length)||s),l.push(o=[])),r=!1,(i=ct.exec(s))&&(r=i.shift(),o.push({value:r,type:i[0].replace(lt," ")}),s=s.slice(r.length));for(a in T.filter)!(i=ht[a].exec(s))||u[a]&&!(i=u[a](i))||(r=i.shift(),o.push({value:r,type:a,matches:i}),s=s.slice(r.length)); if(!r)break}return n?s.length:s?t.error(e):I(e,l).slice(0)},k=t.compile=function(e,t){var n,r=[],i=[],o=X[e+" "];if(!o){for(t||(t=E(e)),n=t.length;n--;)o=y(t[n]),o[P]?r.push(o):i.push(o);o=X(e,b(i,r)),o.selector=e}return o},S=t.select=function(e,t,n,r){var i,o,a,s,l,u="function"==typeof e&&e,d=!r&&E(e=u.selector||e);if(n=n||[],1===d.length){if(o=d[0]=d[0].slice(0),o.length>2&&"ID"===(a=o[0]).type&&w.getById&&9===t.nodeType&&q&&T.relative[o[1].type]){if(t=(T.find.ID(a.matches[0].replace(wt,Tt),t)||[])[0],!t)return n;u&&(t=t.parentNode),e=e.slice(o.shift().value.length)}for(i=ht.needsContext.test(e)?0:o.length;i--&&(a=o[i],!T.relative[s=a.type]);)if((l=T.find[s])&&(r=l(a.matches[0].replace(wt,Tt),bt.test(o[0].type)&&c(t.parentNode)||t))){if(o.splice(i,1),e=r.length&&f(o),!e)return Z.apply(n,r),n;break}}return(u||k(e,d))(r,t,!q,n,bt.test(e)&&c(t.parentNode)||t),n},w.sortStable=P.split("").sort(U).join("")===P,w.detectDuplicates=!!j,L(),w.sortDetached=i(function(e){return 1&e.compareDocumentPosition(H.createElement("div"))}),i(function(e){return e.innerHTML="<a href='#'></a>","#"===e.firstChild.getAttribute("href")})||o("type|href|height|width",function(e,t,n){return n?void 0:e.getAttribute(t,"type"===t.toLowerCase()?1:2)}),w.attributes&&i(function(e){return e.innerHTML="<input/>",e.firstChild.setAttribute("value",""),""===e.firstChild.getAttribute("value")})||o("value",function(e,t,n){return n||"input"!==e.nodeName.toLowerCase()?void 0:e.defaultValue}),i(function(e){return null==e.getAttribute("disabled")})||o(nt,function(e,t,n){var r;return n?void 0:e[t]===!0?t.toLowerCase():(r=e.getAttributeNode(t))&&r.specified?r.value:null}),t}(e);it.find=ut,it.expr=ut.selectors,it.expr[":"]=it.expr.pseudos,it.unique=ut.uniqueSort,it.text=ut.getText,it.isXMLDoc=ut.isXML,it.contains=ut.contains;var ct=it.expr.match.needsContext,dt=/^<(\w+)\s*\/?>(?:<\/\1>|)$/,ft=/^.[^:#\[\.,]*$/;it.filter=function(e,t,n){var r=t[0];return n&&(e=":not("+e+")"),1===t.length&&1===r.nodeType?it.find.matchesSelector(r,e)?[r]:[]:it.find.matches(e,it.grep(t,function(e){return 1===e.nodeType}))},it.fn.extend({find:function(e){var t,n=[],r=this,i=r.length;if("string"!=typeof e)return this.pushStack(it(e).filter(function(){for(t=0;i>t;t++)if(it.contains(r[t],this))return!0}));for(t=0;i>t;t++)it.find(e,r[t],n);return n=this.pushStack(i>1?it.unique(n):n),n.selector=this.selector?this.selector+" "+e:e,n},filter:function(e){return this.pushStack(r(this,e||[],!1))},not:function(e){return this.pushStack(r(this,e||[],!0))},is:function(e){return!!r(this,"string"==typeof e&&ct.test(e)?it(e):e||[],!1).length}});var pt,ht=e.document,mt=/^(?:\s*(<[\w\W]+>)[^>]*|#([\w-]*))$/,gt=it.fn.init=function(e,t){var n,r;if(!e)return this;if("string"==typeof e){if(n="<"===e.charAt(0)&&">"===e.charAt(e.length-1)&&e.length>=3?[null,e,null]:mt.exec(e),!n||!n[1]&&t)return!t||t.jquery?(t||pt).find(e):this.constructor(t).find(e);if(n[1]){if(t=t instanceof it?t[0]:t,it.merge(this,it.parseHTML(n[1],t&&t.nodeType?t.ownerDocument||t:ht,!0)),dt.test(n[1])&&it.isPlainObject(t))for(n in t)it.isFunction(this[n])?this[n](t[n]):this.attr(n,t[n]);return this}if(r=ht.getElementById(n[2]),r&&r.parentNode){if(r.id!==n[2])return pt.find(e);this.length=1,this[0]=r}return this.context=ht,this.selector=e,this}return e.nodeType?(this.context=this[0]=e,this.length=1,this):it.isFunction(e)?"undefined"!=typeof pt.ready?pt.ready(e):e(it):(void 0!==e.selector&&(this.selector=e.selector,this.context=e.context),it.makeArray(e,this))};gt.prototype=it.fn,pt=it(ht);var vt=/^(?:parents|prev(?:Until|All))/,yt={children:!0,contents:!0,next:!0,prev:!0};it.extend({dir:function(e,t,n){for(var r=[],i=e[t];i&&9!==i.nodeType&&(void 0===n||1!==i.nodeType||!it(i).is(n));)1===i.nodeType&&r.push(i),i=i[t];return r},sibling:function(e,t){for(var n=[];e;e=e.nextSibling)1===e.nodeType&&e!==t&&n.push(e);return n}}),it.fn.extend({has:function(e){var t,n=it(e,this),r=n.length;return this.filter(function(){for(t=0;r>t;t++)if(it.contains(this,n[t]))return!0})},closest:function(e,t){for(var n,r=0,i=this.length,o=[],a=ct.test(e)||"string"!=typeof e?it(e,t||this.context):0;i>r;r++)for(n=this[r];n&&n!==t;n=n.parentNode)if(n.nodeType<11&&(a?a.index(n)>-1:1===n.nodeType&&it.find.matchesSelector(n,e))){o.push(n);break}return this.pushStack(o.length>1?it.unique(o):o)},index:function(e){return e?"string"==typeof e?it.inArray(this[0],it(e)):it.inArray(e.jquery?e[0]:e,this):this[0]&&this[0].parentNode?this.first().prevAll().length:-1},add:function(e,t){return this.pushStack(it.unique(it.merge(this.get(),it(e,t))))},addBack:function(e){return this.add(null==e?this.prevObject:this.prevObject.filter(e))}}),it.each({parent:function(e){var t=e.parentNode;return t&&11!==t.nodeType?t:null},parents:function(e){return it.dir(e,"parentNode")},parentsUntil:function(e,t,n){return it.dir(e,"parentNode",n)},next:function(e){return i(e,"nextSibling")},prev:function(e){return i(e,"previousSibling")},nextAll:function(e){return it.dir(e,"nextSibling")},prevAll:function(e){return it.dir(e,"previousSibling")},nextUntil:function(e,t,n){return it.dir(e,"nextSibling",n)},prevUntil:function(e,t,n){return it.dir(e,"previousSibling",n)},siblings:function(e){return it.sibling((e.parentNode||{}).firstChild,e)},children:function(e){return it.sibling(e.firstChild)},contents:function(e){return it.nodeName(e,"iframe")?e.contentDocument||e.contentWindow.document:it.merge([],e.childNodes)}},function(e,t){it.fn[e]=function(n,r){var i=it.map(this,t,n);return"Until"!==e.slice(-5)&&(r=n),r&&"string"==typeof r&&(i=it.filter(r,i)),this.length>1&&(yt[e]||(i=it.unique(i)),vt.test(e)&&(i=i.reverse())),this.pushStack(i)}});var bt=/\S+/g,xt={};it.Callbacks=function(e){e="string"==typeof e?xt[e]||o(e):it.extend({},e);var t,n,r,i,a,s,l=[],u=!e.once&&[],c=function(o){for(n=e.memory&&o,r=!0,a=s||0,s=0,i=l.length,t=!0;l&&i>a;a++)if(l[a].apply(o[0],o[1])===!1&&e.stopOnFalse){n=!1;break}t=!1,l&&(u?u.length&&c(u.shift()):n?l=[]:d.disable())},d={add:function(){if(l){var r=l.length;!function o(t){it.each(t,function(t,n){var r=it.type(n);"function"===r?e.unique&&d.has(n)||l.push(n):n&&n.length&&"string"!==r&&o(n)})}(arguments),t?i=l.length:n&&(s=r,c(n))}return this},remove:function(){return l&&it.each(arguments,function(e,n){for(var r;(r=it.inArray(n,l,r))>-1;)l.splice(r,1),t&&(i>=r&&i--,a>=r&&a--)}),this},has:function(e){return e?it.inArray(e,l)>-1:!(!l||!l.length)},empty:function(){return l=[],i=0,this},disable:function(){return l=u=n=void 0,this},disabled:function(){return!l},lock:function(){return u=void 0,n||d.disable(),this},locked:function(){return!u},fireWith:function(e,n){return!l||r&&!u||(n=n||[],n=[e,n.slice?n.slice():n],t?u.push(n):c(n)),this},fire:function(){return d.fireWith(this,arguments),this},fired:function(){return!!r}};return d},it.extend({Deferred:function(e){var t=[["resolve","done",it.Callbacks("once memory"),"resolved"],["reject","fail",it.Callbacks("once memory"),"rejected"],["notify","progress",it.Callbacks("memory")]],n="pending",r={state:function(){return n},always:function(){return i.done(arguments).fail(arguments),this},then:function(){var e=arguments;return it.Deferred(function(n){it.each(t,function(t,o){var a=it.isFunction(e[t])&&e[t];i[o[1]](function(){var e=a&&a.apply(this,arguments);e&&it.isFunction(e.promise)?e.promise().done(n.resolve).fail(n.reject).progress(n.notify):n[o[0]+"With"](this===r?n.promise():this,a?[e]:arguments)})}),e=null}).promise()},promise:function(e){return null!=e?it.extend(e,r):r}},i={};return r.pipe=r.then,it.each(t,function(e,o){var a=o[2],s=o[3];r[o[1]]=a.add,s&&a.add(function(){n=s},t[1^e][2].disable,t[2][2].lock),i[o[0]]=function(){return i[o[0]+"With"](this===i?r:this,arguments),this},i[o[0]+"With"]=a.fireWith}),r.promise(i),e&&e.call(i,i),i},when:function(e){var t,n,r,i=0,o=Y.call(arguments),a=o.length,s=1!==a||e&&it.isFunction(e.promise)?a:0,l=1===s?e:it.Deferred(),u=function(e,n,r){return function(i){n[e]=this,r[e]=arguments.length>1?Y.call(arguments):i,r===t?l.notifyWith(n,r):--s||l.resolveWith(n,r)}};if(a>1)for(t=new Array(a),n=new Array(a),r=new Array(a);a>i;i++)o[i]&&it.isFunction(o[i].promise)?o[i].promise().done(u(i,r,o)).fail(l.reject).progress(u(i,n,t)):--s;return s||l.resolveWith(r,o),l.promise()}});var wt;it.fn.ready=function(e){return it.ready.promise().done(e),this},it.extend({isReady:!1,readyWait:1,holdReady:function(e){e?it.readyWait++:it.ready(!0)},ready:function(e){if(e===!0?!--it.readyWait:!it.isReady){if(!ht.body)return setTimeout(it.ready);it.isReady=!0,e!==!0&&--it.readyWait>0||(wt.resolveWith(ht,[it]),it.fn.triggerHandler&&(it(ht).triggerHandler("ready"),it(ht).off("ready")))}}}),it.ready.promise=function(t){if(!wt)if(wt=it.Deferred(),"complete"===ht.readyState)setTimeout(it.ready);else if(ht.addEventListener)ht.addEventListener("DOMContentLoaded",s,!1),e.addEventListener("load",s,!1);else{ht.attachEvent("onreadystatechange",s),e.attachEvent("onload",s);var n=!1;try{n=null==e.frameElement&&ht.documentElement}catch(r){}n&&n.doScroll&&!function i(){if(!it.isReady){try{n.doScroll("left")}catch(e){return setTimeout(i,50)}a(),it.ready()}}()}return wt.promise(t)};var Tt,Ct="undefined";for(Tt in it(nt))break;nt.ownLast="0"!==Tt,nt.inlineBlockNeedsLayout=!1,it(function(){var e,t,n,r;n=ht.getElementsByTagName("body")[0],n&&n.style&&(t=ht.createElement("div"),r=ht.createElement("div"),r.style.cssText="position:absolute;border:0;width:0;height:0;top:0;left:-9999px",n.appendChild(r).appendChild(t),typeof t.style.zoom!==Ct&&(t.style.cssText="display:inline;margin:0;border:0;padding:1px;width:1px;zoom:1",nt.inlineBlockNeedsLayout=e=3===t.offsetWidth,e&&(n.style.zoom=1)),n.removeChild(r))}),function(){var e=ht.createElement("div");if(null==nt.deleteExpando){nt.deleteExpando=!0;try{delete e.test}catch(t){nt.deleteExpando=!1}}e=null}(),it.acceptData=function(e){var t=it.noData[(e.nodeName+" ").toLowerCase()],n=+e.nodeType||1;return 1!==n&&9!==n?!1:!t||t!==!0&&e.getAttribute("classid")===t};var Nt=/^(?:\{[\w\W]*\}|\[[\w\W]*\])$/,Et=/([A-Z])/g;it.extend({cache:{},noData:{"applet ":!0,"embed ":!0,"object ":"clsid:D27CDB6E-AE6D-11cf-96B8-444553540000"},hasData:function(e){return e=e.nodeType?it.cache[e[it.expando]]:e[it.expando],!!e&&!u(e)},data:function(e,t,n){return c(e,t,n)},removeData:function(e,t){return d(e,t)},_data:function(e,t,n){return c(e,t,n,!0)},_removeData:function(e,t){return d(e,t,!0)}}),it.fn.extend({data:function(e,t){var n,r,i,o=this[0],a=o&&o.attributes;if(void 0===e){if(this.length&&(i=it.data(o),1===o.nodeType&&!it._data(o,"parsedAttrs"))){for(n=a.length;n--;)a[n]&&(r=a[n].name,0===r.indexOf("data-")&&(r=it.camelCase(r.slice(5)),l(o,r,i[r])));it._data(o,"parsedAttrs",!0)}return i}return"object"==typeof e?this.each(function(){it.data(this,e)}):arguments.length>1?this.each(function(){it.data(this,e,t)}):o?l(o,e,it.data(o,e)):void 0},removeData:function(e){return this.each(function(){it.removeData(this,e)})}}),it.extend({queue:function(e,t,n){var r;return e?(t=(t||"fx")+"queue",r=it._data(e,t),n&&(!r||it.isArray(n)?r=it._data(e,t,it.makeArray(n)):r.push(n)),r||[]):void 0},dequeue:function(e,t){t=t||"fx";var n=it.queue(e,t),r=n.length,i=n.shift(),o=it._queueHooks(e,t),a=function(){it.dequeue(e,t)};"inprogress"===i&&(i=n.shift(),r--),i&&("fx"===t&&n.unshift("inprogress"),delete o.stop,i.call(e,a,o)),!r&&o&&o.empty.fire()},_queueHooks:function(e,t){var n=t+"queueHooks";return it._data(e,n)||it._data(e,n,{empty:it.Callbacks("once memory").add(function(){it._removeData(e,t+"queue"),it._removeData(e,n)})})}}),it.fn.extend({queue:function(e,t){var n=2;return"string"!=typeof e&&(t=e,e="fx",n--),arguments.length<n?it.queue(this[0],e):void 0===t?this:this.each(function(){var n=it.queue(this,e,t);it._queueHooks(this,e),"fx"===e&&"inprogress"!==n[0]&&it.dequeue(this,e)})},dequeue:function(e){return this.each(function(){it.dequeue(this,e)})},clearQueue:function(e){return this.queue(e||"fx",[])},promise:function(e,t){var n,r=1,i=it.Deferred(),o=this,a=this.length,s=function(){--r||i.resolveWith(o,[o])};for("string"!=typeof e&&(t=e,e=void 0),e=e||"fx";a--;)n=it._data(o[a],e+"queueHooks"),n&&n.empty&&(r++,n.empty.add(s));return s(),i.promise(t)}});var kt=/[+-]?(?:\d*\.|)\d+(?:[eE][+-]?\d+|)/.source,St=["Top","Right","Bottom","Left"],At=function(e,t){return e=t||e,"none"===it.css(e,"display")||!it.contains(e.ownerDocument,e)},Dt=it.access=function(e,t,n,r,i,o,a){var s=0,l=e.length,u=null==n;if("object"===it.type(n)){i=!0;for(s in n)it.access(e,t,s,n[s],!0,o,a)}else if(void 0!==r&&(i=!0,it.isFunction(r)||(a=!0),u&&(a?(t.call(e,r),t=null):(u=t,t=function(e,t,n){return u.call(it(e),n)})),t))for(;l>s;s++)t(e[s],n,a?r:r.call(e[s],s,t(e[s],n)));return i?e:u?t.call(e):l?t(e[0],n):o},jt=/^(?:checkbox|radio)$/i;!function(){var e=ht.createElement("input"),t=ht.createElement("div"),n=ht.createDocumentFragment();if(t.innerHTML=" <link/><table></table><a href='/a'>a</a><input type='checkbox'/>",nt.leadingWhitespace=3===t.firstChild.nodeType,nt.tbody=!t.getElementsByTagName("tbody").length,nt.htmlSerialize=!!t.getElementsByTagName("link").length,nt.html5Clone="<:nav></:nav>"!==ht.createElement("nav").cloneNode(!0).outerHTML,e.type="checkbox",e.checked=!0,n.appendChild(e),nt.appendChecked=e.checked,t.innerHTML="<textarea>x</textarea>",nt.noCloneChecked=!!t.cloneNode(!0).lastChild.defaultValue,n.appendChild(t),t.innerHTML="<input type='radio' checked='checked' name='t'/>",nt.checkClone=t.cloneNode(!0).cloneNode(!0).lastChild.checked,nt.noCloneEvent=!0,t.attachEvent&&(t.attachEvent("onclick",function(){nt.noCloneEvent=!1}),t.cloneNode(!0).click()),null==nt.deleteExpando){nt.deleteExpando=!0;try{delete t.test}catch(r){nt.deleteExpando=!1}}}(),function(){var t,n,r=ht.createElement("div");for(t in{submit:!0,change:!0,focusin:!0})n="on"+t,(nt[t+"Bubbles"]=n in e)||(r.setAttribute(n,"t"),nt[t+"Bubbles"]=r.attributes[n].expando===!1);r=null}();var Lt=/^(?:input|select|textarea)$/i,Ht=/^key/,_t=/^(?:mouse|pointer|contextmenu)|click/,qt=/^(?:focusinfocus|focusoutblur)$/,Mt=/^([^.]*)(?:\.(.+)|)$/;it.event={global:{},add:function(e,t,n,r,i){var o,a,s,l,u,c,d,f,p,h,m,g=it._data(e);if(g){for(n.handler&&(l=n,n=l.handler,i=l.selector),n.guid||(n.guid=it.guid++),(a=g.events)||(a=g.events={}),(c=g.handle)||(c=g.handle=function(e){return typeof it===Ct||e&&it.event.triggered===e.type?void 0:it.event.dispatch.apply(c.elem,arguments)},c.elem=e),t=(t||"").match(bt)||[""],s=t.length;s--;)o=Mt.exec(t[s])||[],p=m=o[1],h=(o[2]||"").split(".").sort(),p&&(u=it.event.special[p]||{},p=(i?u.delegateType:u.bindType)||p,u=it.event.special[p]||{},d=it.extend({type:p,origType:m,data:r,handler:n,guid:n.guid,selector:i,needsContext:i&&it.expr.match.needsContext.test(i),namespace:h.join(".")},l),(f=a[p])||(f=a[p]=[],f.delegateCount=0,u.setup&&u.setup.call(e,r,h,c)!==!1||(e.addEventListener?e.addEventListener(p,c,!1):e.attachEvent&&e.attachEvent("on"+p,c))),u.add&&(u.add.call(e,d),d.handler.guid||(d.handler.guid=n.guid)),i?f.splice(f.delegateCount++,0,d):f.push(d),it.event.global[p]=!0);e=null}},remove:function(e,t,n,r,i){var o,a,s,l,u,c,d,f,p,h,m,g=it.hasData(e)&&it._data(e);if(g&&(c=g.events)){for(t=(t||"").match(bt)||[""],u=t.length;u--;)if(s=Mt.exec(t[u])||[],p=m=s[1],h=(s[2]||"").split(".").sort(),p){for(d=it.event.special[p]||{},p=(r?d.delegateType:d.bindType)||p,f=c[p]||[],s=s[2]&&new RegExp("(^|\\.)"+h.join("\\.(?:.*\\.|)")+"(\\.|$)"),l=o=f.length;o--;)a=f[o],!i&&m!==a.origType||n&&n.guid!==a.guid||s&&!s.test(a.namespace)||r&&r!==a.selector&&("**"!==r||!a.selector)||(f.splice(o,1),a.selector&&f.delegateCount--,d.remove&&d.remove.call(e,a));l&&!f.length&&(d.teardown&&d.teardown.call(e,h,g.handle)!==!1||it.removeEvent(e,p,g.handle),delete c[p])}else for(p in c)it.event.remove(e,p+t[u],n,r,!0);it.isEmptyObject(c)&&(delete g.handle,it._removeData(e,"events"))}},trigger:function(t,n,r,i){var o,a,s,l,u,c,d,f=[r||ht],p=tt.call(t,"type")?t.type:t,h=tt.call(t,"namespace")?t.namespace.split("."):[];if(s=c=r=r||ht,3!==r.nodeType&&8!==r.nodeType&&!qt.test(p+it.event.triggered)&&(p.indexOf(".")>=0&&(h=p.split("."),p=h.shift(),h.sort()),a=p.indexOf(":")<0&&"on"+p,t=t[it.expando]?t:new it.Event(p,"object"==typeof t&&t),t.isTrigger=i?2:3,t.namespace=h.join("."),t.namespace_re=t.namespace?new RegExp("(^|\\.)"+h.join("\\.(?:.*\\.|)")+"(\\.|$)"):null,t.result=void 0,t.target||(t.target=r),n=null==n?[t]:it.makeArray(n,[t]),u=it.event.special[p]||{},i||!u.trigger||u.trigger.apply(r,n)!==!1)){if(!i&&!u.noBubble&&!it.isWindow(r)){for(l=u.delegateType||p,qt.test(l+p)||(s=s.parentNode);s;s=s.parentNode)f.push(s),c=s;c===(r.ownerDocument||ht)&&f.push(c.defaultView||c.parentWindow||e)}for(d=0;(s=f[d++])&&!t.isPropagationStopped();)t.type=d>1?l:u.bindType||p,o=(it._data(s,"events")||{})[t.type]&&it._data(s,"handle"),o&&o.apply(s,n),o=a&&s[a],o&&o.apply&&it.acceptData(s)&&(t.result=o.apply(s,n),t.result===!1&&t.preventDefault());if(t.type=p,!i&&!t.isDefaultPrevented()&&(!u._default||u._default.apply(f.pop(),n)===!1)&&it.acceptData(r)&&a&&r[p]&&!it.isWindow(r)){c=r[a],c&&(r[a]=null),it.event.triggered=p;try{r[p]()}catch(m){}it.event.triggered=void 0,c&&(r[a]=c)}return t.result}},dispatch:function(e){e=it.event.fix(e);var t,n,r,i,o,a=[],s=Y.call(arguments),l=(it._data(this,"events")||{})[e.type]||[],u=it.event.special[e.type]||{};if(s[0]=e,e.delegateTarget=this,!u.preDispatch||u.preDispatch.call(this,e)!==!1){for(a=it.event.handlers.call(this,e,l),t=0;(i=a[t++])&&!e.isPropagationStopped();)for(e.currentTarget=i.elem,o=0;(r=i.handlers[o++])&&!e.isImmediatePropagationStopped();)(!e.namespace_re||e.namespace_re.test(r.namespace))&&(e.handleObj=r,e.data=r.data,n=((it.event.special[r.origType]||{}).handle||r.handler).apply(i.elem,s),void 0!==n&&(e.result=n)===!1&&(e.preventDefault(),e.stopPropagation()));return u.postDispatch&&u.postDispatch.call(this,e),e.result}},handlers:function(e,t){var n,r,i,o,a=[],s=t.delegateCount,l=e.target;if(s&&l.nodeType&&(!e.button||"click"!==e.type))for(;l!=this;l=l.parentNode||this)if(1===l.nodeType&&(l.disabled!==!0||"click"!==e.type)){for(i=[],o=0;s>o;o++)r=t[o],n=r.selector+" ",void 0===i[n]&&(i[n]=r.needsContext?it(n,this).index(l)>=0:it.find(n,this,null,[l]).length),i[n]&&i.push(r);i.length&&a.push({elem:l,handlers:i})}return s<t.length&&a.push({elem:this,handlers:t.slice(s)}),a},fix:function(e){if(e[it.expando])return e;var t,n,r,i=e.type,o=e,a=this.fixHooks[i];for(a||(this.fixHooks[i]=a=_t.test(i)?this.mouseHooks:Ht.test(i)?this.keyHooks:{}),r=a.props?this.props.concat(a.props):this.props,e=new it.Event(o),t=r.length;t--;)n=r[t],e[n]=o[n];return e.target||(e.target=o.srcElement||ht),3===e.target.nodeType&&(e.target=e.target.parentNode),e.metaKey=!!e.metaKey,a.filter?a.filter(e,o):e},props:"altKey bubbles cancelable ctrlKey currentTarget eventPhase metaKey relatedTarget shiftKey target timeStamp view which".split(" "),fixHooks:{},keyHooks:{props:"char charCode key keyCode".split(" "),filter:function(e,t){return null==e.which&&(e.which=null!=t.charCode?t.charCode:t.keyCode),e}},mouseHooks:{props:"button buttons clientX clientY fromElement offsetX offsetY pageX pageY screenX screenY toElement".split(" "),filter:function(e,t){var n,r,i,o=t.button,a=t.fromElement;return null==e.pageX&&null!=t.clientX&&(r=e.target.ownerDocument||ht,i=r.documentElement,n=r.body,e.pageX=t.clientX+(i&&i.scrollLeft||n&&n.scrollLeft||0)-(i&&i.clientLeft||n&&n.clientLeft||0),e.pageY=t.clientY+(i&&i.scrollTop||n&&n.scrollTop||0)-(i&&i.clientTop||n&&n.clientTop||0)),!e.relatedTarget&&a&&(e.relatedTarget=a===e.target?t.toElement:a),e.which||void 0===o||(e.which=1&o?1:2&o?3:4&o?2:0),e}},special:{load:{noBubble:!0},focus:{trigger:function(){if(this!==h()&&this.focus)try{return this.focus(),!1}catch(e){}},delegateType:"focusin"},blur:{trigger:function(){return this===h()&&this.blur?(this.blur(),!1):void 0},delegateType:"focusout"},click:{trigger:function(){return it.nodeName(this,"input")&&"checkbox"===this.type&&this.click?(this.click(),!1):void 0},_default:function(e){return it.nodeName(e.target,"a")}},beforeunload:{postDispatch:function(e){void 0!==e.result&&e.originalEvent&&(e.originalEvent.returnValue=e.result)}}},simulate:function(e,t,n,r){var i=it.extend(new it.Event,n,{type:e,isSimulated:!0,originalEvent:{}});r?it.event.trigger(i,null,t):it.event.dispatch.call(t,i),i.isDefaultPrevented()&&n.preventDefault()}},it.removeEvent=ht.removeEventListener?function(e,t,n){e.removeEventListener&&e.removeEventListener(t,n,!1)}:function(e,t,n){var r="on"+t;e.detachEvent&&(typeof e[r]===Ct&&(e[r]=null),e.detachEvent(r,n))},it.Event=function(e,t){return this instanceof it.Event?(e&&e.type?(this.originalEvent=e,this.type=e.type,this.isDefaultPrevented=e.defaultPrevented||void 0===e.defaultPrevented&&e.returnValue===!1?f:p):this.type=e,t&&it.extend(this,t),this.timeStamp=e&&e.timeStamp||it.now(),void(this[it.expando]=!0)):new it.Event(e,t)},it.Event.prototype={isDefaultPrevented:p,isPropagationStopped:p,isImmediatePropagationStopped:p,preventDefault:function(){var e=this.originalEvent;this.isDefaultPrevented=f,e&&(e.preventDefault?e.preventDefault():e.returnValue=!1)},stopPropagation:function(){var e=this.originalEvent;this.isPropagationStopped=f,e&&(e.stopPropagation&&e.stopPropagation(),e.cancelBubble=!0)},stopImmediatePropagation:function(){var e=this.originalEvent;this.isImmediatePropagationStopped=f,e&&e.stopImmediatePropagation&&e.stopImmediatePropagation(),this.stopPropagation()}},it.each({mouseenter:"mouseover",mouseleave:"mouseout",pointerenter:"pointerover",pointerleave:"pointerout"},function(e,t){it.event.special[e]={delegateType:t,bindType:t,handle:function(e){var n,r=this,i=e.relatedTarget,o=e.handleObj;return(!i||i!==r&&!it.contains(r,i))&&(e.type=o.origType,n=o.handler.apply(this,arguments),e.type=t),n}}}),nt.submitBubbles||(it.event.special.submit={setup:function(){return it.nodeName(this,"form")?!1:void it.event.add(this,"click._submit keypress._submit",function(e){var t=e.target,n=it.nodeName(t,"input")||it.nodeName(t,"button")?t.form:void 0;n&&!it._data(n,"submitBubbles")&&(it.event.add(n,"submit._submit",function(e){e._submit_bubble=!0}),it._data(n,"submitBubbles",!0))})},postDispatch:function(e){e._submit_bubble&&(delete e._submit_bubble,this.parentNode&&!e.isTrigger&&it.event.simulate("submit",this.parentNode,e,!0))},teardown:function(){return it.nodeName(this,"form")?!1:void it.event.remove(this,"._submit")}}),nt.changeBubbles||(it.event.special.change={setup:function(){return Lt.test(this.nodeName)?(("checkbox"===this.type||"radio"===this.type)&&(it.event.add(this,"propertychange._change",function(e){"checked"===e.originalEvent.propertyName&&(this._just_changed=!0)}),it.event.add(this,"click._change",function(e){this._just_changed&&!e.isTrigger&&(this._just_changed=!1),it.event.simulate("change",this,e,!0)})),!1):void it.event.add(this,"beforeactivate._change",function(e){var t=e.target;Lt.test(t.nodeName)&&!it._data(t,"changeBubbles")&&(it.event.add(t,"change._change",function(e){!this.parentNode||e.isSimulated||e.isTrigger||it.event.simulate("change",this.parentNode,e,!0)}),it._data(t,"changeBubbles",!0))})},handle:function(e){var t=e.target;return this!==t||e.isSimulated||e.isTrigger||"radio"!==t.type&&"checkbox"!==t.type?e.handleObj.handler.apply(this,arguments):void 0},teardown:function(){return it.event.remove(this,"._change"),!Lt.test(this.nodeName)}}),nt.focusinBubbles||it.each({focus:"focusin",blur:"focusout"},function(e,t){var n=function(e){it.event.simulate(t,e.target,it.event.fix(e),!0)};it.event.special[t]={setup:function(){var r=this.ownerDocument||this,i=it._data(r,t);i||r.addEventListener(e,n,!0),it._data(r,t,(i||0)+1)},teardown:function(){var r=this.ownerDocument||this,i=it._data(r,t)-1;i?it._data(r,t,i):(r.removeEventListener(e,n,!0),it._removeData(r,t))}}}),it.fn.extend({on:function(e,t,n,r,i){var o,a;if("object"==typeof e){"string"!=typeof t&&(n=n||t,t=void 0);for(o in e)this.on(o,t,n,e[o],i);return this}if(null==n&&null==r?(r=t,n=t=void 0):null==r&&("string"==typeof t?(r=n,n=void 0):(r=n,n=t,t=void 0)),r===!1)r=p;else if(!r)return this;return 1===i&&(a=r,r=function(e){return it().off(e),a.apply(this,arguments)},r.guid=a.guid||(a.guid=it.guid++)),this.each(function(){it.event.add(this,e,r,n,t)})},one:function(e,t,n,r){return this.on(e,t,n,r,1)},off:function(e,t,n){var r,i;if(e&&e.preventDefault&&e.handleObj)return r=e.handleObj,it(e.delegateTarget).off(r.namespace?r.origType+"."+r.namespace:r.origType,r.selector,r.handler),this;if("object"==typeof e){for(i in e)this.off(i,t,e[i]);return this}return(t===!1||"function"==typeof t)&&(n=t,t=void 0),n===!1&&(n=p),this.each(function(){it.event.remove(this,e,n,t)})},trigger:function(e,t){return this.each(function(){it.event.trigger(e,t,this)})},triggerHandler:function(e,t){var n=this[0];return n?it.event.trigger(e,t,n,!0):void 0}});var Ot="abbr|article|aside|audio|bdi|canvas|data|datalist|details|figcaption|figure|footer|header|hgroup|mark|meter|nav|output|progress|section|summary|time|video",Ft=/ jQuery\d+="(?:null|\d+)"/g,Bt=new RegExp("<(?:"+Ot+")[\\s/>]","i"),Pt=/^\s+/,Rt=/<(?!area|br|col|embed|hr|img|input|link|meta|param)(([\w:]+)[^>]*)\/>/gi,Wt=/<([\w:]+)/,$t=/<tbody/i,zt=/<|&#?\w+;/,It=/<(?:script|style|link)/i,Xt=/checked\s*(?:[^=]|=\s*.checked.)/i,Ut=/^$|\/(?:java|ecma)script/i,Vt=/^true\/(.*)/,Jt=/^\s*<!(?:\[CDATA\[|--)|(?:\]\]|--)>\s*$/g,Yt={option:[1,"<select multiple='multiple'>","</select>"],legend:[1,"<fieldset>","</fieldset>"],area:[1,"<map>","</map>"],param:[1,"<object>","</object>"],thead:[1,"<table>","</table>"],tr:[2,"<table><tbody>","</tbody></table>"],col:[2,"<table><tbody></tbody><colgroup>","</colgroup></table>"],td:[3,"<table><tbody><tr>","</tr></tbody></table>"],_default:nt.htmlSerialize?[0,"",""]:[1,"X<div>","</div>"]},Gt=m(ht),Qt=Gt.appendChild(ht.createElement("div"));Yt.optgroup=Yt.option,Yt.tbody=Yt.tfoot=Yt.colgroup=Yt.caption=Yt.thead,Yt.th=Yt.td,it.extend({clone:function(e,t,n){var r,i,o,a,s,l=it.contains(e.ownerDocument,e);if(nt.html5Clone||it.isXMLDoc(e)||!Bt.test("<"+e.nodeName+">")?o=e.cloneNode(!0):(Qt.innerHTML=e.outerHTML,Qt.removeChild(o=Qt.firstChild)),!(nt.noCloneEvent&&nt.noCloneChecked||1!==e.nodeType&&11!==e.nodeType||it.isXMLDoc(e)))for(r=g(o),s=g(e),a=0;null!=(i=s[a]);++a)r[a]&&C(i,r[a]);if(t)if(n)for(s=s||g(e),r=r||g(o),a=0;null!=(i=s[a]);a++)T(i,r[a]);else T(e,o);return r=g(o,"script"),r.length>0&&w(r,!l&&g(e,"script")),r=s=i=null,o},buildFragment:function(e,t,n,r){for(var i,o,a,s,l,u,c,d=e.length,f=m(t),p=[],h=0;d>h;h++)if(o=e[h],o||0===o)if("object"===it.type(o))it.merge(p,o.nodeType?[o]:o);else if(zt.test(o)){for(s=s||f.appendChild(t.createElement("div")),l=(Wt.exec(o)||["",""])[1].toLowerCase(),c=Yt[l]||Yt._default,s.innerHTML=c[1]+o.replace(Rt,"<$1></$2>")+c[2],i=c[0];i--;)s=s.lastChild;if(!nt.leadingWhitespace&&Pt.test(o)&&p.push(t.createTextNode(Pt.exec(o)[0])),!nt.tbody)for(o="table"!==l||$t.test(o)?"<table>"!==c[1]||$t.test(o)?0:s:s.firstChild,i=o&&o.childNodes.length;i--;)it.nodeName(u=o.childNodes[i],"tbody")&&!u.childNodes.length&&o.removeChild(u);for(it.merge(p,s.childNodes),s.textContent="";s.firstChild;)s.removeChild(s.firstChild);s=f.lastChild}else p.push(t.createTextNode(o));for(s&&f.removeChild(s),nt.appendChecked||it.grep(g(p,"input"),v),h=0;o=p[h++];)if((!r||-1===it.inArray(o,r))&&(a=it.contains(o.ownerDocument,o),s=g(f.appendChild(o),"script"),a&&w(s),n))for(i=0;o=s[i++];)Ut.test(o.type||"")&&n.push(o);return s=null,f},cleanData:function(e,t){for(var n,r,i,o,a=0,s=it.expando,l=it.cache,u=nt.deleteExpando,c=it.event.special;null!=(n=e[a]);a++)if((t||it.acceptData(n))&&(i=n[s],o=i&&l[i])){if(o.events)for(r in o.events)c[r]?it.event.remove(n,r):it.removeEvent(n,r,o.handle);l[i]&&(delete l[i],u?delete n[s]:typeof n.removeAttribute!==Ct?n.removeAttribute(s):n[s]=null,J.push(i))}}}),it.fn.extend({text:function(e){return Dt(this,function(e){return void 0===e?it.text(this):this.empty().append((this[0]&&this[0].ownerDocument||ht).createTextNode(e))},null,e,arguments.length)},append:function(){return this.domManip(arguments,function(e){if(1===this.nodeType||11===this.nodeType||9===this.nodeType){var t=y(this,e);t.appendChild(e)}})},prepend:function(){return this.domManip(arguments,function(e){if(1===this.nodeType||11===this.nodeType||9===this.nodeType){var t=y(this,e);t.insertBefore(e,t.firstChild)}})},before:function(){return this.domManip(arguments,function(e){this.parentNode&&this.parentNode.insertBefore(e,this)})},after:function(){return this.domManip(arguments,function(e){this.parentNode&&this.parentNode.insertBefore(e,this.nextSibling)})},remove:function(e,t){for(var n,r=e?it.filter(e,this):this,i=0;null!=(n=r[i]);i++)t||1!==n.nodeType||it.cleanData(g(n)),n.parentNode&&(t&&it.contains(n.ownerDocument,n)&&w(g(n,"script")),n.parentNode.removeChild(n));return this},empty:function(){for(var e,t=0;null!=(e=this[t]);t++){for(1===e.nodeType&&it.cleanData(g(e,!1));e.firstChild;)e.removeChild(e.firstChild);e.options&&it.nodeName(e,"select")&&(e.options.length=0)}return this},clone:function(e,t){return e=null==e?!1:e,t=null==t?e:t,this.map(function(){return it.clone(this,e,t)})},html:function(e){return Dt(this,function(e){var t=this[0]||{},n=0,r=this.length;if(void 0===e)return 1===t.nodeType?t.innerHTML.replace(Ft,""):void 0;if(!("string"!=typeof e||It.test(e)||!nt.htmlSerialize&&Bt.test(e)||!nt.leadingWhitespace&&Pt.test(e)||Yt[(Wt.exec(e)||["",""])[1].toLowerCase()])){e=e.replace(Rt,"<$1></$2>");try{for(;r>n;n++)t=this[n]||{},1===t.nodeType&&(it.cleanData(g(t,!1)),t.innerHTML=e);t=0}catch(i){}}t&&this.empty().append(e)},null,e,arguments.length)},replaceWith:function(){var e=arguments[0];return this.domManip(arguments,function(t){e=this.parentNode,it.cleanData(g(this)),e&&e.replaceChild(t,this)}),e&&(e.length||e.nodeType)?this:this.remove()},detach:function(e){return this.remove(e,!0)},domManip:function(e,t){e=G.apply([],e);var n,r,i,o,a,s,l=0,u=this.length,c=this,d=u-1,f=e[0],p=it.isFunction(f);if(p||u>1&&"string"==typeof f&&!nt.checkClone&&Xt.test(f))return this.each(function(n){var r=c.eq(n);p&&(e[0]=f.call(this,n,r.html())),r.domManip(e,t)});if(u&&(s=it.buildFragment(e,this[0].ownerDocument,!1,this),n=s.firstChild,1===s.childNodes.length&&(s=n),n)){for(o=it.map(g(s,"script"),b),i=o.length;u>l;l++)r=s,l!==d&&(r=it.clone(r,!0,!0),i&&it.merge(o,g(r,"script"))),t.call(this[l],r,l);if(i)for(a=o[o.length-1].ownerDocument,it.map(o,x),l=0;i>l;l++)r=o[l],Ut.test(r.type||"")&&!it._data(r,"globalEval")&&it.contains(a,r)&&(r.src?it._evalUrl&&it._evalUrl(r.src):it.globalEval((r.text||r.textContent||r.innerHTML||"").replace(Jt,"")));s=n=null}return this}}),it.each({appendTo:"append",prependTo:"prepend",insertBefore:"before",insertAfter:"after",replaceAll:"replaceWith"},function(e,t){it.fn[e]=function(e){for(var n,r=0,i=[],o=it(e),a=o.length-1;a>=r;r++)n=r===a?this:this.clone(!0),it(o[r])[t](n),Q.apply(i,n.get());return this.pushStack(i)}});var Kt,Zt={};!function(){var e;nt.shrinkWrapBlocks=function(){if(null!=e)return e;e=!1;var t,n,r;return n=ht.getElementsByTagName("body")[0],n&&n.style?(t=ht.createElement("div"),r=ht.createElement("div"),r.style.cssText="position:absolute;border:0;width:0;height:0;top:0;left:-9999px",n.appendChild(r).appendChild(t),typeof t.style.zoom!==Ct&&(t.style.cssText="-webkit-box-sizing:content-box;-moz-box-sizing:content-box;box-sizing:content-box;display:block;margin:0;border:0;padding:1px;width:1px;zoom:1",t.appendChild(ht.createElement("div")).style.width="5px",e=3!==t.offsetWidth),n.removeChild(r),e):void 0}}();var en,tn,nn=/^margin/,rn=new RegExp("^("+kt+")(?!px)[a-z%]+$","i"),on=/^(top|right|bottom|left)$/;e.getComputedStyle?(en=function(e){return e.ownerDocument.defaultView.getComputedStyle(e,null)},tn=function(e,t,n){var r,i,o,a,s=e.style;return n=n||en(e),a=n?n.getPropertyValue(t)||n[t]:void 0,n&&(""!==a||it.contains(e.ownerDocument,e)||(a=it.style(e,t)),rn.test(a)&&nn.test(t)&&(r=s.width,i=s.minWidth,o=s.maxWidth,s.minWidth=s.maxWidth=s.width=a,a=n.width,s.width=r,s.minWidth=i,s.maxWidth=o)),void 0===a?a:a+""}):ht.documentElement.currentStyle&&(en=function(e){return e.currentStyle },tn=function(e,t,n){var r,i,o,a,s=e.style;return n=n||en(e),a=n?n[t]:void 0,null==a&&s&&s[t]&&(a=s[t]),rn.test(a)&&!on.test(t)&&(r=s.left,i=e.runtimeStyle,o=i&&i.left,o&&(i.left=e.currentStyle.left),s.left="fontSize"===t?"1em":a,a=s.pixelLeft+"px",s.left=r,o&&(i.left=o)),void 0===a?a:a+""||"auto"}),function(){function t(){var t,n,r,i;n=ht.getElementsByTagName("body")[0],n&&n.style&&(t=ht.createElement("div"),r=ht.createElement("div"),r.style.cssText="position:absolute;border:0;width:0;height:0;top:0;left:-9999px",n.appendChild(r).appendChild(t),t.style.cssText="-webkit-box-sizing:border-box;-moz-box-sizing:border-box;box-sizing:border-box;display:block;margin-top:1%;top:1%;border:1px;padding:1px;width:4px;position:absolute",o=a=!1,l=!0,e.getComputedStyle&&(o="1%"!==(e.getComputedStyle(t,null)||{}).top,a="4px"===(e.getComputedStyle(t,null)||{width:"4px"}).width,i=t.appendChild(ht.createElement("div")),i.style.cssText=t.style.cssText="-webkit-box-sizing:content-box;-moz-box-sizing:content-box;box-sizing:content-box;display:block;margin:0;border:0;padding:0",i.style.marginRight=i.style.width="0",t.style.width="1px",l=!parseFloat((e.getComputedStyle(i,null)||{}).marginRight)),t.innerHTML="<table><tr><td></td><td>t</td></tr></table>",i=t.getElementsByTagName("td"),i[0].style.cssText="margin:0;border:0;padding:0;display:none",s=0===i[0].offsetHeight,s&&(i[0].style.display="",i[1].style.display="none",s=0===i[0].offsetHeight),n.removeChild(r))}var n,r,i,o,a,s,l;n=ht.createElement("div"),n.innerHTML=" <link/><table></table><a href='/a'>a</a><input type='checkbox'/>",i=n.getElementsByTagName("a")[0],r=i&&i.style,r&&(r.cssText="float:left;opacity:.5",nt.opacity="0.5"===r.opacity,nt.cssFloat=!!r.cssFloat,n.style.backgroundClip="content-box",n.cloneNode(!0).style.backgroundClip="",nt.clearCloneStyle="content-box"===n.style.backgroundClip,nt.boxSizing=""===r.boxSizing||""===r.MozBoxSizing||""===r.WebkitBoxSizing,it.extend(nt,{reliableHiddenOffsets:function(){return null==s&&t(),s},boxSizingReliable:function(){return null==a&&t(),a},pixelPosition:function(){return null==o&&t(),o},reliableMarginRight:function(){return null==l&&t(),l}}))}(),it.swap=function(e,t,n,r){var i,o,a={};for(o in t)a[o]=e.style[o],e.style[o]=t[o];i=n.apply(e,r||[]);for(o in t)e.style[o]=a[o];return i};var an=/alpha\([^)]*\)/i,sn=/opacity\s*=\s*([^)]*)/,ln=/^(none|table(?!-c[ea]).+)/,un=new RegExp("^("+kt+")(.*)$","i"),cn=new RegExp("^([+-])=("+kt+")","i"),dn={position:"absolute",visibility:"hidden",display:"block"},fn={letterSpacing:"0",fontWeight:"400"},pn=["Webkit","O","Moz","ms"];it.extend({cssHooks:{opacity:{get:function(e,t){if(t){var n=tn(e,"opacity");return""===n?"1":n}}}},cssNumber:{columnCount:!0,fillOpacity:!0,flexGrow:!0,flexShrink:!0,fontWeight:!0,lineHeight:!0,opacity:!0,order:!0,orphans:!0,widows:!0,zIndex:!0,zoom:!0},cssProps:{"float":nt.cssFloat?"cssFloat":"styleFloat"},style:function(e,t,n,r){if(e&&3!==e.nodeType&&8!==e.nodeType&&e.style){var i,o,a,s=it.camelCase(t),l=e.style;if(t=it.cssProps[s]||(it.cssProps[s]=S(l,s)),a=it.cssHooks[t]||it.cssHooks[s],void 0===n)return a&&"get"in a&&void 0!==(i=a.get(e,!1,r))?i:l[t];if(o=typeof n,"string"===o&&(i=cn.exec(n))&&(n=(i[1]+1)*i[2]+parseFloat(it.css(e,t)),o="number"),null!=n&&n===n&&("number"!==o||it.cssNumber[s]||(n+="px"),nt.clearCloneStyle||""!==n||0!==t.indexOf("background")||(l[t]="inherit"),!(a&&"set"in a&&void 0===(n=a.set(e,n,r)))))try{l[t]=n}catch(u){}}},css:function(e,t,n,r){var i,o,a,s=it.camelCase(t);return t=it.cssProps[s]||(it.cssProps[s]=S(e.style,s)),a=it.cssHooks[t]||it.cssHooks[s],a&&"get"in a&&(o=a.get(e,!0,n)),void 0===o&&(o=tn(e,t,r)),"normal"===o&&t in fn&&(o=fn[t]),""===n||n?(i=parseFloat(o),n===!0||it.isNumeric(i)?i||0:o):o}}),it.each(["height","width"],function(e,t){it.cssHooks[t]={get:function(e,n,r){return n?ln.test(it.css(e,"display"))&&0===e.offsetWidth?it.swap(e,dn,function(){return L(e,t,r)}):L(e,t,r):void 0},set:function(e,n,r){var i=r&&en(e);return D(e,n,r?j(e,t,r,nt.boxSizing&&"border-box"===it.css(e,"boxSizing",!1,i),i):0)}}}),nt.opacity||(it.cssHooks.opacity={get:function(e,t){return sn.test((t&&e.currentStyle?e.currentStyle.filter:e.style.filter)||"")?.01*parseFloat(RegExp.$1)+"":t?"1":""},set:function(e,t){var n=e.style,r=e.currentStyle,i=it.isNumeric(t)?"alpha(opacity="+100*t+")":"",o=r&&r.filter||n.filter||"";n.zoom=1,(t>=1||""===t)&&""===it.trim(o.replace(an,""))&&n.removeAttribute&&(n.removeAttribute("filter"),""===t||r&&!r.filter)||(n.filter=an.test(o)?o.replace(an,i):o+" "+i)}}),it.cssHooks.marginRight=k(nt.reliableMarginRight,function(e,t){return t?it.swap(e,{display:"inline-block"},tn,[e,"marginRight"]):void 0}),it.each({margin:"",padding:"",border:"Width"},function(e,t){it.cssHooks[e+t]={expand:function(n){for(var r=0,i={},o="string"==typeof n?n.split(" "):[n];4>r;r++)i[e+St[r]+t]=o[r]||o[r-2]||o[0];return i}},nn.test(e)||(it.cssHooks[e+t].set=D)}),it.fn.extend({css:function(e,t){return Dt(this,function(e,t,n){var r,i,o={},a=0;if(it.isArray(t)){for(r=en(e),i=t.length;i>a;a++)o[t[a]]=it.css(e,t[a],!1,r);return o}return void 0!==n?it.style(e,t,n):it.css(e,t)},e,t,arguments.length>1)},show:function(){return A(this,!0)},hide:function(){return A(this)},toggle:function(e){return"boolean"==typeof e?e?this.show():this.hide():this.each(function(){At(this)?it(this).show():it(this).hide()})}}),it.Tween=H,H.prototype={constructor:H,init:function(e,t,n,r,i,o){this.elem=e,this.prop=n,this.easing=i||"swing",this.options=t,this.start=this.now=this.cur(),this.end=r,this.unit=o||(it.cssNumber[n]?"":"px")},cur:function(){var e=H.propHooks[this.prop];return e&&e.get?e.get(this):H.propHooks._default.get(this)},run:function(e){var t,n=H.propHooks[this.prop];return this.pos=t=this.options.duration?it.easing[this.easing](e,this.options.duration*e,0,1,this.options.duration):e,this.now=(this.end-this.start)*t+this.start,this.options.step&&this.options.step.call(this.elem,this.now,this),n&&n.set?n.set(this):H.propHooks._default.set(this),this}},H.prototype.init.prototype=H.prototype,H.propHooks={_default:{get:function(e){var t;return null==e.elem[e.prop]||e.elem.style&&null!=e.elem.style[e.prop]?(t=it.css(e.elem,e.prop,""),t&&"auto"!==t?t:0):e.elem[e.prop]},set:function(e){it.fx.step[e.prop]?it.fx.step[e.prop](e):e.elem.style&&(null!=e.elem.style[it.cssProps[e.prop]]||it.cssHooks[e.prop])?it.style(e.elem,e.prop,e.now+e.unit):e.elem[e.prop]=e.now}}},H.propHooks.scrollTop=H.propHooks.scrollLeft={set:function(e){e.elem.nodeType&&e.elem.parentNode&&(e.elem[e.prop]=e.now)}},it.easing={linear:function(e){return e},swing:function(e){return.5-Math.cos(e*Math.PI)/2}},it.fx=H.prototype.init,it.fx.step={};var hn,mn,gn=/^(?:toggle|show|hide)$/,vn=new RegExp("^(?:([+-])=|)("+kt+")([a-z%]*)$","i"),yn=/queueHooks$/,bn=[O],xn={"*":[function(e,t){var n=this.createTween(e,t),r=n.cur(),i=vn.exec(t),o=i&&i[3]||(it.cssNumber[e]?"":"px"),a=(it.cssNumber[e]||"px"!==o&&+r)&&vn.exec(it.css(n.elem,e)),s=1,l=20;if(a&&a[3]!==o){o=o||a[3],i=i||[],a=+r||1;do s=s||".5",a/=s,it.style(n.elem,e,a+o);while(s!==(s=n.cur()/r)&&1!==s&&--l)}return i&&(a=n.start=+a||+r||0,n.unit=o,n.end=i[1]?a+(i[1]+1)*i[2]:+i[2]),n}]};it.Animation=it.extend(B,{tweener:function(e,t){it.isFunction(e)?(t=e,e=["*"]):e=e.split(" ");for(var n,r=0,i=e.length;i>r;r++)n=e[r],xn[n]=xn[n]||[],xn[n].unshift(t)},prefilter:function(e,t){t?bn.unshift(e):bn.push(e)}}),it.speed=function(e,t,n){var r=e&&"object"==typeof e?it.extend({},e):{complete:n||!n&&t||it.isFunction(e)&&e,duration:e,easing:n&&t||t&&!it.isFunction(t)&&t};return r.duration=it.fx.off?0:"number"==typeof r.duration?r.duration:r.duration in it.fx.speeds?it.fx.speeds[r.duration]:it.fx.speeds._default,(null==r.queue||r.queue===!0)&&(r.queue="fx"),r.old=r.complete,r.complete=function(){it.isFunction(r.old)&&r.old.call(this),r.queue&&it.dequeue(this,r.queue)},r},it.fn.extend({fadeTo:function(e,t,n,r){return this.filter(At).css("opacity",0).show().end().animate({opacity:t},e,n,r)},animate:function(e,t,n,r){var i=it.isEmptyObject(e),o=it.speed(t,n,r),a=function(){var t=B(this,it.extend({},e),o);(i||it._data(this,"finish"))&&t.stop(!0)};return a.finish=a,i||o.queue===!1?this.each(a):this.queue(o.queue,a)},stop:function(e,t,n){var r=function(e){var t=e.stop;delete e.stop,t(n)};return"string"!=typeof e&&(n=t,t=e,e=void 0),t&&e!==!1&&this.queue(e||"fx",[]),this.each(function(){var t=!0,i=null!=e&&e+"queueHooks",o=it.timers,a=it._data(this);if(i)a[i]&&a[i].stop&&r(a[i]);else for(i in a)a[i]&&a[i].stop&&yn.test(i)&&r(a[i]);for(i=o.length;i--;)o[i].elem!==this||null!=e&&o[i].queue!==e||(o[i].anim.stop(n),t=!1,o.splice(i,1));(t||!n)&&it.dequeue(this,e)})},finish:function(e){return e!==!1&&(e=e||"fx"),this.each(function(){var t,n=it._data(this),r=n[e+"queue"],i=n[e+"queueHooks"],o=it.timers,a=r?r.length:0;for(n.finish=!0,it.queue(this,e,[]),i&&i.stop&&i.stop.call(this,!0),t=o.length;t--;)o[t].elem===this&&o[t].queue===e&&(o[t].anim.stop(!0),o.splice(t,1));for(t=0;a>t;t++)r[t]&&r[t].finish&&r[t].finish.call(this);delete n.finish})}}),it.each(["toggle","show","hide"],function(e,t){var n=it.fn[t];it.fn[t]=function(e,r,i){return null==e||"boolean"==typeof e?n.apply(this,arguments):this.animate(q(t,!0),e,r,i)}}),it.each({slideDown:q("show"),slideUp:q("hide"),slideToggle:q("toggle"),fadeIn:{opacity:"show"},fadeOut:{opacity:"hide"},fadeToggle:{opacity:"toggle"}},function(e,t){it.fn[e]=function(e,n,r){return this.animate(t,e,n,r)}}),it.timers=[],it.fx.tick=function(){var e,t=it.timers,n=0;for(hn=it.now();n<t.length;n++)e=t[n],e()||t[n]!==e||t.splice(n--,1);t.length||it.fx.stop(),hn=void 0},it.fx.timer=function(e){it.timers.push(e),e()?it.fx.start():it.timers.pop()},it.fx.interval=13,it.fx.start=function(){mn||(mn=setInterval(it.fx.tick,it.fx.interval))},it.fx.stop=function(){clearInterval(mn),mn=null},it.fx.speeds={slow:600,fast:200,_default:400},it.fn.delay=function(e,t){return e=it.fx?it.fx.speeds[e]||e:e,t=t||"fx",this.queue(t,function(t,n){var r=setTimeout(t,e);n.stop=function(){clearTimeout(r)}})},function(){var e,t,n,r,i;t=ht.createElement("div"),t.setAttribute("className","t"),t.innerHTML=" <link/><table></table><a href='/a'>a</a><input type='checkbox'/>",r=t.getElementsByTagName("a")[0],n=ht.createElement("select"),i=n.appendChild(ht.createElement("option")),e=t.getElementsByTagName("input")[0],r.style.cssText="top:1px",nt.getSetAttribute="t"!==t.className,nt.style=/top/.test(r.getAttribute("style")),nt.hrefNormalized="/a"===r.getAttribute("href"),nt.checkOn=!!e.value,nt.optSelected=i.selected,nt.enctype=!!ht.createElement("form").enctype,n.disabled=!0,nt.optDisabled=!i.disabled,e=ht.createElement("input"),e.setAttribute("value",""),nt.input=""===e.getAttribute("value"),e.value="t",e.setAttribute("type","radio"),nt.radioValue="t"===e.value}();var wn=/\r/g;it.fn.extend({val:function(e){var t,n,r,i=this[0];{if(arguments.length)return r=it.isFunction(e),this.each(function(n){var i;1===this.nodeType&&(i=r?e.call(this,n,it(this).val()):e,null==i?i="":"number"==typeof i?i+="":it.isArray(i)&&(i=it.map(i,function(e){return null==e?"":e+""})),t=it.valHooks[this.type]||it.valHooks[this.nodeName.toLowerCase()],t&&"set"in t&&void 0!==t.set(this,i,"value")||(this.value=i))});if(i)return t=it.valHooks[i.type]||it.valHooks[i.nodeName.toLowerCase()],t&&"get"in t&&void 0!==(n=t.get(i,"value"))?n:(n=i.value,"string"==typeof n?n.replace(wn,""):null==n?"":n)}}}),it.extend({valHooks:{option:{get:function(e){var t=it.find.attr(e,"value");return null!=t?t:it.trim(it.text(e))}},select:{get:function(e){for(var t,n,r=e.options,i=e.selectedIndex,o="select-one"===e.type||0>i,a=o?null:[],s=o?i+1:r.length,l=0>i?s:o?i:0;s>l;l++)if(n=r[l],!(!n.selected&&l!==i||(nt.optDisabled?n.disabled:null!==n.getAttribute("disabled"))||n.parentNode.disabled&&it.nodeName(n.parentNode,"optgroup"))){if(t=it(n).val(),o)return t;a.push(t)}return a},set:function(e,t){for(var n,r,i=e.options,o=it.makeArray(t),a=i.length;a--;)if(r=i[a],it.inArray(it.valHooks.option.get(r),o)>=0)try{r.selected=n=!0}catch(s){r.scrollHeight}else r.selected=!1;return n||(e.selectedIndex=-1),i}}}}),it.each(["radio","checkbox"],function(){it.valHooks[this]={set:function(e,t){return it.isArray(t)?e.checked=it.inArray(it(e).val(),t)>=0:void 0}},nt.checkOn||(it.valHooks[this].get=function(e){return null===e.getAttribute("value")?"on":e.value})});var Tn,Cn,Nn=it.expr.attrHandle,En=/^(?:checked|selected)$/i,kn=nt.getSetAttribute,Sn=nt.input;it.fn.extend({attr:function(e,t){return Dt(this,it.attr,e,t,arguments.length>1)},removeAttr:function(e){return this.each(function(){it.removeAttr(this,e)})}}),it.extend({attr:function(e,t,n){var r,i,o=e.nodeType;if(e&&3!==o&&8!==o&&2!==o)return typeof e.getAttribute===Ct?it.prop(e,t,n):(1===o&&it.isXMLDoc(e)||(t=t.toLowerCase(),r=it.attrHooks[t]||(it.expr.match.bool.test(t)?Cn:Tn)),void 0===n?r&&"get"in r&&null!==(i=r.get(e,t))?i:(i=it.find.attr(e,t),null==i?void 0:i):null!==n?r&&"set"in r&&void 0!==(i=r.set(e,n,t))?i:(e.setAttribute(t,n+""),n):void it.removeAttr(e,t))},removeAttr:function(e,t){var n,r,i=0,o=t&&t.match(bt);if(o&&1===e.nodeType)for(;n=o[i++];)r=it.propFix[n]||n,it.expr.match.bool.test(n)?Sn&&kn||!En.test(n)?e[r]=!1:e[it.camelCase("default-"+n)]=e[r]=!1:it.attr(e,n,""),e.removeAttribute(kn?n:r)},attrHooks:{type:{set:function(e,t){if(!nt.radioValue&&"radio"===t&&it.nodeName(e,"input")){var n=e.value;return e.setAttribute("type",t),n&&(e.value=n),t}}}}}),Cn={set:function(e,t,n){return t===!1?it.removeAttr(e,n):Sn&&kn||!En.test(n)?e.setAttribute(!kn&&it.propFix[n]||n,n):e[it.camelCase("default-"+n)]=e[n]=!0,n}},it.each(it.expr.match.bool.source.match(/\w+/g),function(e,t){var n=Nn[t]||it.find.attr;Nn[t]=Sn&&kn||!En.test(t)?function(e,t,r){var i,o;return r||(o=Nn[t],Nn[t]=i,i=null!=n(e,t,r)?t.toLowerCase():null,Nn[t]=o),i}:function(e,t,n){return n?void 0:e[it.camelCase("default-"+t)]?t.toLowerCase():null}}),Sn&&kn||(it.attrHooks.value={set:function(e,t,n){return it.nodeName(e,"input")?void(e.defaultValue=t):Tn&&Tn.set(e,t,n)}}),kn||(Tn={set:function(e,t,n){var r=e.getAttributeNode(n);return r||e.setAttributeNode(r=e.ownerDocument.createAttribute(n)),r.value=t+="","value"===n||t===e.getAttribute(n)?t:void 0}},Nn.id=Nn.name=Nn.coords=function(e,t,n){var r;return n?void 0:(r=e.getAttributeNode(t))&&""!==r.value?r.value:null},it.valHooks.button={get:function(e,t){var n=e.getAttributeNode(t);return n&&n.specified?n.value:void 0},set:Tn.set},it.attrHooks.contenteditable={set:function(e,t,n){Tn.set(e,""===t?!1:t,n)}},it.each(["width","height"],function(e,t){it.attrHooks[t]={set:function(e,n){return""===n?(e.setAttribute(t,"auto"),n):void 0}}})),nt.style||(it.attrHooks.style={get:function(e){return e.style.cssText||void 0},set:function(e,t){return e.style.cssText=t+""}});var An=/^(?:input|select|textarea|button|object)$/i,Dn=/^(?:a|area)$/i;it.fn.extend({prop:function(e,t){return Dt(this,it.prop,e,t,arguments.length>1)},removeProp:function(e){return e=it.propFix[e]||e,this.each(function(){try{this[e]=void 0,delete this[e]}catch(t){}})}}),it.extend({propFix:{"for":"htmlFor","class":"className"},prop:function(e,t,n){var r,i,o,a=e.nodeType;if(e&&3!==a&&8!==a&&2!==a)return o=1!==a||!it.isXMLDoc(e),o&&(t=it.propFix[t]||t,i=it.propHooks[t]),void 0!==n?i&&"set"in i&&void 0!==(r=i.set(e,n,t))?r:e[t]=n:i&&"get"in i&&null!==(r=i.get(e,t))?r:e[t]},propHooks:{tabIndex:{get:function(e){var t=it.find.attr(e,"tabindex");return t?parseInt(t,10):An.test(e.nodeName)||Dn.test(e.nodeName)&&e.href?0:-1}}}}),nt.hrefNormalized||it.each(["href","src"],function(e,t){it.propHooks[t]={get:function(e){return e.getAttribute(t,4)}}}),nt.optSelected||(it.propHooks.selected={get:function(e){var t=e.parentNode;return t&&(t.selectedIndex,t.parentNode&&t.parentNode.selectedIndex),null}}),it.each(["tabIndex","readOnly","maxLength","cellSpacing","cellPadding","rowSpan","colSpan","useMap","frameBorder","contentEditable"],function(){it.propFix[this.toLowerCase()]=this}),nt.enctype||(it.propFix.enctype="encoding");var jn=/[\t\r\n\f]/g;it.fn.extend({addClass:function(e){var t,n,r,i,o,a,s=0,l=this.length,u="string"==typeof e&&e;if(it.isFunction(e))return this.each(function(t){it(this).addClass(e.call(this,t,this.className))});if(u)for(t=(e||"").match(bt)||[];l>s;s++)if(n=this[s],r=1===n.nodeType&&(n.className?(" "+n.className+" ").replace(jn," "):" ")){for(o=0;i=t[o++];)r.indexOf(" "+i+" ")<0&&(r+=i+" ");a=it.trim(r),n.className!==a&&(n.className=a)}return this},removeClass:function(e){var t,n,r,i,o,a,s=0,l=this.length,u=0===arguments.length||"string"==typeof e&&e;if(it.isFunction(e))return this.each(function(t){it(this).removeClass(e.call(this,t,this.className))});if(u)for(t=(e||"").match(bt)||[];l>s;s++)if(n=this[s],r=1===n.nodeType&&(n.className?(" "+n.className+" ").replace(jn," "):"")){for(o=0;i=t[o++];)for(;r.indexOf(" "+i+" ")>=0;)r=r.replace(" "+i+" "," ");a=e?it.trim(r):"",n.className!==a&&(n.className=a)}return this},toggleClass:function(e,t){var n=typeof e;return"boolean"==typeof t&&"string"===n?t?this.addClass(e):this.removeClass(e):this.each(it.isFunction(e)?function(n){it(this).toggleClass(e.call(this,n,this.className,t),t)}:function(){if("string"===n)for(var t,r=0,i=it(this),o=e.match(bt)||[];t=o[r++];)i.hasClass(t)?i.removeClass(t):i.addClass(t);else(n===Ct||"boolean"===n)&&(this.className&&it._data(this,"__className__",this.className),this.className=this.className||e===!1?"":it._data(this,"__className__")||"")})},hasClass:function(e){for(var t=" "+e+" ",n=0,r=this.length;r>n;n++)if(1===this[n].nodeType&&(" "+this[n].className+" ").replace(jn," ").indexOf(t)>=0)return!0;return!1}}),it.each("blur focus focusin focusout load resize scroll unload click dblclick mousedown mouseup mousemove mouseover mouseout mouseenter mouseleave change select submit keydown keypress keyup error contextmenu".split(" "),function(e,t){it.fn[t]=function(e,n){return arguments.length>0?this.on(t,null,e,n):this.trigger(t)}}),it.fn.extend({hover:function(e,t){return this.mouseenter(e).mouseleave(t||e)},bind:function(e,t,n){return this.on(e,null,t,n)},unbind:function(e,t){return this.off(e,null,t)},delegate:function(e,t,n,r){return this.on(t,e,n,r)},undelegate:function(e,t,n){return 1===arguments.length?this.off(e,"**"):this.off(t,e||"**",n)}});var Ln=it.now(),Hn=/\?/,_n=/(,)|(\[|{)|(}|])|"(?:[^"\\\r\n]|\\["\\\/bfnrt]|\\u[\da-fA-F]{4})*"\s*:?|true|false|null|-?(?!0\d)\d+(?:\.\d+|)(?:[eE][+-]?\d+|)/g;it.parseJSON=function(t){if(e.JSON&&e.JSON.parse)return e.JSON.parse(t+"");var n,r=null,i=it.trim(t+"");return i&&!it.trim(i.replace(_n,function(e,t,i,o){return n&&t&&(r=0),0===r?e:(n=i||t,r+=!o-!i,"")}))?Function("return "+i)():it.error("Invalid JSON: "+t)},it.parseXML=function(t){var n,r;if(!t||"string"!=typeof t)return null;try{e.DOMParser?(r=new DOMParser,n=r.parseFromString(t,"text/xml")):(n=new ActiveXObject("Microsoft.XMLDOM"),n.async="false",n.loadXML(t))}catch(i){n=void 0}return n&&n.documentElement&&!n.getElementsByTagName("parsererror").length||it.error("Invalid XML: "+t),n};var qn,Mn,On=/#.*$/,Fn=/([?&])_=[^&]*/,Bn=/^(.*?):[ \t]*([^\r\n]*)\r?$/gm,Pn=/^(?:about|app|app-storage|.+-extension|file|res|widget):$/,Rn=/^(?:GET|HEAD)$/,Wn=/^\/\//,$n=/^([\w.+-]+:)(?:\/\/(?:[^\/?#]*@|)([^\/?#:]*)(?::(\d+)|)|)/,zn={},In={},Xn="*/".concat("*");try{Mn=location.href}catch(Un){Mn=ht.createElement("a"),Mn.href="",Mn=Mn.href}qn=$n.exec(Mn.toLowerCase())||[],it.extend({active:0,lastModified:{},etag:{},ajaxSettings:{url:Mn,type:"GET",isLocal:Pn.test(qn[1]),global:!0,processData:!0,async:!0,contentType:"application/x-www-form-urlencoded; charset=UTF-8",accepts:{"*":Xn,text:"text/plain",html:"text/html",xml:"application/xml, text/xml",json:"application/json, text/javascript"},contents:{xml:/xml/,html:/html/,json:/json/},responseFields:{xml:"responseXML",text:"responseText",json:"responseJSON"},converters:{"* text":String,"text html":!0,"text json":it.parseJSON,"text xml":it.parseXML},flatOptions:{url:!0,context:!0}},ajaxSetup:function(e,t){return t?W(W(e,it.ajaxSettings),t):W(it.ajaxSettings,e)},ajaxPrefilter:P(zn),ajaxTransport:P(In),ajax:function(e,t){function n(e,t,n,r){var i,c,v,y,x,T=t;2!==b&&(b=2,s&&clearTimeout(s),u=void 0,a=r||"",w.readyState=e>0?4:0,i=e>=200&&300>e||304===e,n&&(y=$(d,w,n)),y=z(d,y,w,i),i?(d.ifModified&&(x=w.getResponseHeader("Last-Modified"),x&&(it.lastModified[o]=x),x=w.getResponseHeader("etag"),x&&(it.etag[o]=x)),204===e||"HEAD"===d.type?T="nocontent":304===e?T="notmodified":(T=y.state,c=y.data,v=y.error,i=!v)):(v=T,(e||!T)&&(T="error",0>e&&(e=0))),w.status=e,w.statusText=(t||T)+"",i?h.resolveWith(f,[c,T,w]):h.rejectWith(f,[w,T,v]),w.statusCode(g),g=void 0,l&&p.trigger(i?"ajaxSuccess":"ajaxError",[w,d,i?c:v]),m.fireWith(f,[w,T]),l&&(p.trigger("ajaxComplete",[w,d]),--it.active||it.event.trigger("ajaxStop")))}"object"==typeof e&&(t=e,e=void 0),t=t||{};var r,i,o,a,s,l,u,c,d=it.ajaxSetup({},t),f=d.context||d,p=d.context&&(f.nodeType||f.jquery)?it(f):it.event,h=it.Deferred(),m=it.Callbacks("once memory"),g=d.statusCode||{},v={},y={},b=0,x="canceled",w={readyState:0,getResponseHeader:function(e){var t;if(2===b){if(!c)for(c={};t=Bn.exec(a);)c[t[1].toLowerCase()]=t[2];t=c[e.toLowerCase()]}return null==t?null:t},getAllResponseHeaders:function(){return 2===b?a:null},setRequestHeader:function(e,t){var n=e.toLowerCase();return b||(e=y[n]=y[n]||e,v[e]=t),this},overrideMimeType:function(e){return b||(d.mimeType=e),this},statusCode:function(e){var t;if(e)if(2>b)for(t in e)g[t]=[g[t],e[t]];else w.always(e[w.status]);return this},abort:function(e){var t=e||x;return u&&u.abort(t),n(0,t),this}};if(h.promise(w).complete=m.add,w.success=w.done,w.error=w.fail,d.url=((e||d.url||Mn)+"").replace(On,"").replace(Wn,qn[1]+"//"),d.type=t.method||t.type||d.method||d.type,d.dataTypes=it.trim(d.dataType||"*").toLowerCase().match(bt)||[""],null==d.crossDomain&&(r=$n.exec(d.url.toLowerCase()),d.crossDomain=!(!r||r[1]===qn[1]&&r[2]===qn[2]&&(r[3]||("http:"===r[1]?"80":"443"))===(qn[3]||("http:"===qn[1]?"80":"443")))),d.data&&d.processData&&"string"!=typeof d.data&&(d.data=it.param(d.data,d.traditional)),R(zn,d,t,w),2===b)return w;l=d.global,l&&0===it.active++&&it.event.trigger("ajaxStart"),d.type=d.type.toUpperCase(),d.hasContent=!Rn.test(d.type),o=d.url,d.hasContent||(d.data&&(o=d.url+=(Hn.test(o)?"&":"?")+d.data,delete d.data),d.cache===!1&&(d.url=Fn.test(o)?o.replace(Fn,"$1_="+Ln++):o+(Hn.test(o)?"&":"?")+"_="+Ln++)),d.ifModified&&(it.lastModified[o]&&w.setRequestHeader("If-Modified-Since",it.lastModified[o]),it.etag[o]&&w.setRequestHeader("If-None-Match",it.etag[o])),(d.data&&d.hasContent&&d.contentType!==!1||t.contentType)&&w.setRequestHeader("Content-Type",d.contentType),w.setRequestHeader("Accept",d.dataTypes[0]&&d.accepts[d.dataTypes[0]]?d.accepts[d.dataTypes[0]]+("*"!==d.dataTypes[0]?", "+Xn+"; q=0.01":""):d.accepts["*"]);for(i in d.headers)w.setRequestHeader(i,d.headers[i]);if(d.beforeSend&&(d.beforeSend.call(f,w,d)===!1||2===b))return w.abort();x="abort";for(i in{success:1,error:1,complete:1})w[i](d[i]);if(u=R(In,d,t,w)){w.readyState=1,l&&p.trigger("ajaxSend",[w,d]),d.async&&d.timeout>0&&(s=setTimeout(function(){w.abort("timeout")},d.timeout));try{b=1,u.send(v,n)}catch(T){if(!(2>b))throw T;n(-1,T)}}else n(-1,"No Transport");return w},getJSON:function(e,t,n){return it.get(e,t,n,"json")},getScript:function(e,t){return it.get(e,void 0,t,"script")}}),it.each(["get","post"],function(e,t){it[t]=function(e,n,r,i){return it.isFunction(n)&&(i=i||r,r=n,n=void 0),it.ajax({url:e,type:t,dataType:i,data:n,success:r})}}),it.each(["ajaxStart","ajaxStop","ajaxComplete","ajaxError","ajaxSuccess","ajaxSend"],function(e,t){it.fn[t]=function(e){return this.on(t,e)}}),it._evalUrl=function(e){return it.ajax({url:e,type:"GET",dataType:"script",async:!1,global:!1,"throws":!0})},it.fn.extend({wrapAll:function(e){if(it.isFunction(e))return this.each(function(t){it(this).wrapAll(e.call(this,t))});if(this[0]){var t=it(e,this[0].ownerDocument).eq(0).clone(!0);this[0].parentNode&&t.insertBefore(this[0]),t.map(function(){for(var e=this;e.firstChild&&1===e.firstChild.nodeType;)e=e.firstChild;return e}).append(this)}return this},wrapInner:function(e){return this.each(it.isFunction(e)?function(t){it(this).wrapInner(e.call(this,t))}:function(){var t=it(this),n=t.contents();n.length?n.wrapAll(e):t.append(e)})},wrap:function(e){var t=it.isFunction(e);return this.each(function(n){it(this).wrapAll(t?e.call(this,n):e)})},unwrap:function(){return this.parent().each(function(){it.nodeName(this,"body")||it(this).replaceWith(this.childNodes)}).end()}}),it.expr.filters.hidden=function(e){return e.offsetWidth<=0&&e.offsetHeight<=0||!nt.reliableHiddenOffsets()&&"none"===(e.style&&e.style.display||it.css(e,"display"))},it.expr.filters.visible=function(e){return!it.expr.filters.hidden(e)};var Vn=/%20/g,Jn=/\[\]$/,Yn=/\r?\n/g,Gn=/^(?:submit|button|image|reset|file)$/i,Qn=/^(?:input|select|textarea|keygen)/i;it.param=function(e,t){var n,r=[],i=function(e,t){t=it.isFunction(t)?t():null==t?"":t,r[r.length]=encodeURIComponent(e)+"="+encodeURIComponent(t)};if(void 0===t&&(t=it.ajaxSettings&&it.ajaxSettings.traditional),it.isArray(e)||e.jquery&&!it.isPlainObject(e))it.each(e,function(){i(this.name,this.value)});else for(n in e)I(n,e[n],t,i);return r.join("&").replace(Vn,"+")},it.fn.extend({serialize:function(){return it.param(this.serializeArray())},serializeArray:function(){return this.map(function(){var e=it.prop(this,"elements");return e?it.makeArray(e):this}).filter(function(){var e=this.type;return this.name&&!it(this).is(":disabled")&&Qn.test(this.nodeName)&&!Gn.test(e)&&(this.checked||!jt.test(e))}).map(function(e,t){var n=it(this).val();return null==n?null:it.isArray(n)?it.map(n,function(e){return{name:t.name,value:e.replace(Yn,"\r\n")}}):{name:t.name,value:n.replace(Yn,"\r\n")}}).get()}}),it.ajaxSettings.xhr=void 0!==e.ActiveXObject?function(){return!this.isLocal&&/^(get|post|head|put|delete|options)$/i.test(this.type)&&X()||U()}:X;var Kn=0,Zn={},er=it.ajaxSettings.xhr();e.ActiveXObject&&it(e).on("unload",function(){for(var e in Zn)Zn[e](void 0,!0)}),nt.cors=!!er&&"withCredentials"in er,er=nt.ajax=!!er,er&&it.ajaxTransport(function(e){if(!e.crossDomain||nt.cors){var t;return{send:function(n,r){var i,o=e.xhr(),a=++Kn;if(o.open(e.type,e.url,e.async,e.username,e.password),e.xhrFields)for(i in e.xhrFields)o[i]=e.xhrFields[i];e.mimeType&&o.overrideMimeType&&o.overrideMimeType(e.mimeType),e.crossDomain||n["X-Requested-With"]||(n["X-Requested-With"]="XMLHttpRequest");for(i in n)void 0!==n[i]&&o.setRequestHeader(i,n[i]+"");o.send(e.hasContent&&e.data||null),t=function(n,i){var s,l,u;if(t&&(i||4===o.readyState))if(delete Zn[a],t=void 0,o.onreadystatechange=it.noop,i)4!==o.readyState&&o.abort();else{u={},s=o.status,"string"==typeof o.responseText&&(u.text=o.responseText);try{l=o.statusText}catch(c){l=""}s||!e.isLocal||e.crossDomain?1223===s&&(s=204):s=u.text?200:404}u&&r(s,l,u,o.getAllResponseHeaders())},e.async?4===o.readyState?setTimeout(t):o.onreadystatechange=Zn[a]=t:t()},abort:function(){t&&t(void 0,!0)}}}}),it.ajaxSetup({accepts:{script:"text/javascript, application/javascript, application/ecmascript, application/x-ecmascript"},contents:{script:/(?:java|ecma)script/},converters:{"text script":function(e){return it.globalEval(e),e}}}),it.ajaxPrefilter("script",function(e){void 0===e.cache&&(e.cache=!1),e.crossDomain&&(e.type="GET",e.global=!1)}),it.ajaxTransport("script",function(e){if(e.crossDomain){var t,n=ht.head||it("head")[0]||ht.documentElement;return{send:function(r,i){t=ht.createElement("script"),t.async=!0,e.scriptCharset&&(t.charset=e.scriptCharset),t.src=e.url,t.onload=t.onreadystatechange=function(e,n){(n||!t.readyState||/loaded|complete/.test(t.readyState))&&(t.onload=t.onreadystatechange=null,t.parentNode&&t.parentNode.removeChild(t),t=null,n||i(200,"success"))},n.insertBefore(t,n.firstChild)},abort:function(){t&&t.onload(void 0,!0)}}}});var tr=[],nr=/(=)\?(?=&|$)|\?\?/;it.ajaxSetup({jsonp:"callback",jsonpCallback:function(){var e=tr.pop()||it.expando+"_"+Ln++;return this[e]=!0,e}}),it.ajaxPrefilter("json jsonp",function(t,n,r){var i,o,a,s=t.jsonp!==!1&&(nr.test(t.url)?"url":"string"==typeof t.data&&!(t.contentType||"").indexOf("application/x-www-form-urlencoded")&&nr.test(t.data)&&"data");return s||"jsonp"===t.dataTypes[0]?(i=t.jsonpCallback=it.isFunction(t.jsonpCallback)?t.jsonpCallback():t.jsonpCallback,s?t[s]=t[s].replace(nr,"$1"+i):t.jsonp!==!1&&(t.url+=(Hn.test(t.url)?"&":"?")+t.jsonp+"="+i),t.converters["script json"]=function(){return a||it.error(i+" was not called"),a[0]},t.dataTypes[0]="json",o=e[i],e[i]=function(){a=arguments},r.always(function(){e[i]=o,t[i]&&(t.jsonpCallback=n.jsonpCallback,tr.push(i)),a&&it.isFunction(o)&&o(a[0]),a=o=void 0}),"script"):void 0}),it.parseHTML=function(e,t,n){if(!e||"string"!=typeof e)return null;"boolean"==typeof t&&(n=t,t=!1),t=t||ht;var r=dt.exec(e),i=!n&&[];return r?[t.createElement(r[1])]:(r=it.buildFragment([e],t,i),i&&i.length&&it(i).remove(),it.merge([],r.childNodes))};var rr=it.fn.load;it.fn.load=function(e,t,n){if("string"!=typeof e&&rr)return rr.apply(this,arguments);var r,i,o,a=this,s=e.indexOf(" ");return s>=0&&(r=it.trim(e.slice(s,e.length)),e=e.slice(0,s)),it.isFunction(t)?(n=t,t=void 0):t&&"object"==typeof t&&(o="POST"),a.length>0&&it.ajax({url:e,type:o,dataType:"html",data:t}).done(function(e){i=arguments,a.html(r?it("<div>").append(it.parseHTML(e)).find(r):e)}).complete(n&&function(e,t){a.each(n,i||[e.responseText,t,e])}),this},it.expr.filters.animated=function(e){return it.grep(it.timers,function(t){return e===t.elem}).length};var ir=e.document.documentElement;it.offset={setOffset:function(e,t,n){var r,i,o,a,s,l,u,c=it.css(e,"position"),d=it(e),f={};"static"===c&&(e.style.position="relative"),s=d.offset(),o=it.css(e,"top"),l=it.css(e,"left"),u=("absolute"===c||"fixed"===c)&&it.inArray("auto",[o,l])>-1,u?(r=d.position(),a=r.top,i=r.left):(a=parseFloat(o)||0,i=parseFloat(l)||0),it.isFunction(t)&&(t=t.call(e,n,s)),null!=t.top&&(f.top=t.top-s.top+a),null!=t.left&&(f.left=t.left-s.left+i),"using"in t?t.using.call(e,f):d.css(f)}},it.fn.extend({offset:function(e){if(arguments.length)return void 0===e?this:this.each(function(t){it.offset.setOffset(this,e,t)});var t,n,r={top:0,left:0},i=this[0],o=i&&i.ownerDocument;if(o)return t=o.documentElement,it.contains(t,i)?(typeof i.getBoundingClientRect!==Ct&&(r=i.getBoundingClientRect()),n=V(o),{top:r.top+(n.pageYOffset||t.scrollTop)-(t.clientTop||0),left:r.left+(n.pageXOffset||t.scrollLeft)-(t.clientLeft||0)}):r},position:function(){if(this[0]){var e,t,n={top:0,left:0},r=this[0];return"fixed"===it.css(r,"position")?t=r.getBoundingClientRect():(e=this.offsetParent(),t=this.offset(),it.nodeName(e[0],"html")||(n=e.offset()),n.top+=it.css(e[0],"borderTopWidth",!0),n.left+=it.css(e[0],"borderLeftWidth",!0)),{top:t.top-n.top-it.css(r,"marginTop",!0),left:t.left-n.left-it.css(r,"marginLeft",!0)}}},offsetParent:function(){return this.map(function(){for(var e=this.offsetParent||ir;e&&!it.nodeName(e,"html")&&"static"===it.css(e,"position");)e=e.offsetParent;return e||ir})}}),it.each({scrollLeft:"pageXOffset",scrollTop:"pageYOffset"},function(e,t){var n=/Y/.test(t);it.fn[e]=function(r){return Dt(this,function(e,r,i){var o=V(e);return void 0===i?o?t in o?o[t]:o.document.documentElement[r]:e[r]:void(o?o.scrollTo(n?it(o).scrollLeft():i,n?i:it(o).scrollTop()):e[r]=i)},e,r,arguments.length,null)}}),it.each(["top","left"],function(e,t){it.cssHooks[t]=k(nt.pixelPosition,function(e,n){return n?(n=tn(e,t),rn.test(n)?it(e).position()[t]+"px":n):void 0})}),it.each({Height:"height",Width:"width"},function(e,t){it.each({padding:"inner"+e,content:t,"":"outer"+e},function(n,r){it.fn[r]=function(r,i){var o=arguments.length&&(n||"boolean"!=typeof r),a=n||(r===!0||i===!0?"margin":"border");return Dt(this,function(t,n,r){var i;return it.isWindow(t)?t.document.documentElement["client"+e]:9===t.nodeType?(i=t.documentElement,Math.max(t.body["scroll"+e],i["scroll"+e],t.body["offset"+e],i["offset"+e],i["client"+e])):void 0===r?it.css(t,n,a):it.style(t,n,r,a) },t,o?r:void 0,o,null)}})}),it.fn.size=function(){return this.length},it.fn.andSelf=it.fn.addBack,"function"==typeof define&&define.amd&&define("jquery",[],function(){return it});var or=e.jQuery,ar=e.$;return it.noConflict=function(t){return e.$===it&&(e.$=ar),t&&e.jQuery===it&&(e.jQuery=or),it},typeof t===Ct&&(e.jQuery=e.$=it),it}); },{}],2:[function(require,module,exports){ "use strict";module.exports=function(e){var r=encodeURIComponent(e.getURL());return{popup:!0,shareText:{de:"teilen",en:"share"},name:"facebook",title:{de:"Bei Facebook teilen",en:"Share on Facebook"},shareUrl:"https://www.facebook.com/sharer/sharer.php?u="+r+e.getReferrerTrack()}}; },{}],3:[function(require,module,exports){ "use strict";module.exports=function(e){return{popup:!0,shareText:"+1",name:"googleplus",title:{de:"Bei Google+ teilen",en:"Share on Google+"},shareUrl:"https://plus.google.com/share?url="+e.getURL()+e.getReferrerTrack()}}; },{}],4:[function(require,module,exports){ "use strict";module.exports=function(e){return{popup:!1,shareText:"Info",name:"info",title:{de:"weitere Informationen",en:"more information"},shareUrl:e.getInfoUrl()}}; },{}],5:[function(require,module,exports){ "use strict";module.exports=function(e){return{popup:!1,shareText:"mail",name:"mail",title:{de:"Per E-Mail versenden",en:"Send by email"},shareUrl:e.getURL()+"?view=mail"}}; },{}],6:[function(require,module,exports){ "use strict";var $=require("jquery");module.exports=function(e){return{popup:!0,shareText:"tweet",name:"twitter",title:{de:"Bei Twitter teilen",en:"Share on Twitter"},shareUrl:"https://twitter.com/intent/tweet?text="+e.getShareText()+"&url="+e.getURL()+e.getReferrerTrack()}}; },{"jquery":1}],7:[function(require,module,exports){ "use strict";module.exports=function(e){return{popup:!1,shareText:"WhatsApp",name:"whatsapp",title:{de:"Bei Whatsapp teilen",en:"Share on Whatsapp"},shareUrl:"whatsapp://send?text="+e.getShareText()+"%20"+e.getURL()+e.getReferrerTrack()}}; },{}],8:[function(require,module,exports){ (function (global){ "use strict";var $=require("jquery"),_Shariff=function(t,e){var r=this;this.element=t,this.options=$.extend({},this.defaults,e,$(t).data());var n=[require("./services/facebook"),require("./services/googleplus"),require("./services/twitter"),require("./services/whatsapp"),require("./services/mail"),require("./services/info")];this.services=$.map(this.options.services,function(t){var e;return n.forEach(function(n){return n=n(r),n.name===t?(e=n,null):void 0}),e}),this._addButtonList(),null!==this.options.backendUrl&&this.getShares().then($.proxy(this._updateCounts,this))};_Shariff.prototype={defaults:{theme:"color",backendUrl:null,infoUrl:"http://ct.de/-2467514",lang:"de",orientation:"horizontal",referrerTrack:null,services:["twitter","facebook","googleplus","info"],url:function(){var t=global.document.location.href,e=$("link[rel=canonical]").attr("href")||this.getMeta("og:url")||"";return e.length>0&&(e.indexOf("http")<0&&(e=global.document.location.protocol+"//"+global.document.location.host+e),t=e),t}},$socialshareElement:function(){return $(this.element)},getLocalized:function(t,e){return"object"==typeof t[e]?t[e][this.options.lang]:"string"==typeof t[e]?t[e]:void 0},getMeta:function(t){var e=$('meta[name="'+t+'"],[property="'+t+'"]').attr("content");return e||""},getInfoUrl:function(){return this.options.infoUrl},getURL:function(){var t=this.options.url;return"function"==typeof t?$.proxy(t,this)():t},getReferrerTrack:function(){return this.options.referrerTrack||""},getShares:function(){return $.getJSON(this.options.backendUrl+"?url="+encodeURIComponent(this.getURL()))},_updateCounts:function(t){var e=this;$.each(t,function(t,r){r>=1e3&&(r=Math.round(r/1e3)+"k"),$(e.element).find("."+t+" a").append('<span class="share_count">'+r)})},_addButtonList:function(){var t=this,e=this.$socialshareElement(),r="theme-"+this.options.theme,n="orientation-"+this.options.orientation,i=$("<ul>").addClass(r).addClass(n);this.services.forEach(function(e){var r=$('<li class="shariff-button">').addClass(e.name),n='<span class="share_text">'+t.getLocalized(e,"shareText"),o=$("<a>").attr("href",e.shareUrl).append(n);e.popup?o.attr("rel","popup"):o.attr("target","_blank"),o.attr("title",t.getLocalized(e,"title")),r.append(o),i.append(r)}),i.on("click",'[rel="popup"]',function(t){t.preventDefault();var e=$(this).attr("href"),r=$(this).attr("title"),n="600",i="460",o="width="+n+",height="+i;global.window.open(e,r,o)}),e.append(i)},abbreviateText:function(t,e){var r=decodeURIComponent(t);if(r.length<=e)return t;var n=r.substring(0,e-1).lastIndexOf(" ");return r=encodeURIComponent(r.substring(0,n))+"…"},getShareText:function(){var t=this.getMeta("DC.title"),e=this.getMeta("DC.creator");return t.length>0&&e.length>0?t+=" - "+e:t=$("title").text(),encodeURIComponent(this.abbreviateText(t,120))}},module.exports=_Shariff,$(".shariff").each(function(){this.shariff=new _Shariff(this)}); }).call(this,typeof global !== "undefined" ? global : typeof self !== "undefined" ? self : typeof window !== "undefined" ? window : {}) },{"./services/facebook":2,"./services/googleplus":3,"./services/info":4,"./services/mail":5,"./services/twitter":6,"./services/whatsapp":7,"jquery":1}]},{},[8]);
pootle/static/js/shared/components/ModalContainer.js
translate/pootle
/* * Copyright (C) Pootle contributors. * * This file is a part of the Pootle project. It is distributed under the GPL3 * or later license. See the LICENSE file for a copy of the license and the * AUTHORS file for copyright and authorship information. */ import cx from 'classnames'; import React from 'react'; import tabInScope from 'utils/tabInScope'; import './lightbox.css'; const classNames = { lock: 'lightbox-lock', }; const keys = { ESC: 27, TAB: 9, }; const ModalContainer = React.createClass({ propTypes: { children: React.PropTypes.node.isRequired, onClose: React.PropTypes.func.isRequired, className: React.PropTypes.string, style: React.PropTypes.object, }, /* Lifecycle */ componentWillMount() { this._previousFocus = document.activeElement; }, componentDidMount() { if (!document.body.classList.contains(classNames.lock)) { this._ownsLock = true; document.body.classList.add(classNames.lock); document.addEventListener('keydown', this.handleKeyDown); } }, componentWillUnmount() { if (this._ownsLock) { document.body.classList.remove(classNames.lock); document.removeEventListener('keydown', this.handleKeyDown); } this._previousFocus.focus(); }, _previousFocus: null, _ownsLock: false, /* Handlers */ handleKeyDown(e) { if (e.keyCode === keys.TAB) { tabInScope(this.refs.body, e); } if (e.keyCode === keys.ESC) { this.props.onClose(); } }, /* Layout */ render() { return ( <div className="lightbox-bg"> <div className="lightbox-container"> <div className={cx('lightbox-body', this.props.className)} ref="body" style={this.props.style} tabIndex="-1" > {this.props.children} </div> </div> </div> ); }, }); export default ModalContainer;
src/components/ReplOutputObject.js
antonyr/Mancy
import React from 'react'; import _ from 'lodash'; import ReplOutput from '../common/ReplOutput'; import ReplCommon from '../common/ReplCommon'; export default class ReplOutputObject extends React.Component { constructor(props) { super(props); this.state = { collapse: true } this.onToggleCollapse = this.onToggleCollapse.bind(this); this.getType = this.getType.bind(this); this.getAllProps = this.getAllProps.bind(this); } onToggleCollapse() { this.setState({ collapse: !this.state.collapse }); } getType(obj) { let type = obj ? ReplCommon.type(obj) : 'Object'; return ` ${type !== 'Undefined' ? type : 'Object'} {}`; } getAllProps() { let names = Object.getOwnPropertyNames(this.props.object); let symbols = Object.getOwnPropertySymbols(this.props.object); return _.sortBy(names.concat(symbols), (value) => { return value.toString(); }); } render() { let label = ReplCommon.highlight(this.props.label || this.getType(this.props.object)); return ( <span className='repl-entry-message-output-object-folds'> { this.state.collapse ? <span className='repl-entry-message-output-object'> <i className='fa fa-play' onClick={this.onToggleCollapse}></i> <span className='object-desc' dangerouslySetInnerHTML={{__html:label}}></span> </span> : <span className='repl-entry-message-output-object'> <i className='fa fa-play fa-rotate-90' onClick={this.onToggleCollapse}></i> <span className='object-desc' dangerouslySetInnerHTML={{__html:label}}></span> <span className='object-rec'> { _.map(this.getAllProps(), (key) => { let value = ReplOutput.readProperty(this.props.object, key); let keyClass = this.props.object.propertyIsEnumerable(key) ? 'object-key' : 'object-key dull'; return ( <div className='object-entry' key={key.toString()}> { <span className={keyClass}> {key.toString()} <span className='object-colon'>: </span> </span> } { value && value._isReactElement ? {value} : ReplOutput.transformObject(value) } </div> ) }) } { this.props.object.__proto__ ? <div className='object-entry' key='prototype'> __proto__ <span className='object-colon'>: </span> <ReplOutputObject object={Object.getPrototypeOf(this.props.object)} label={this.getType(this.props.object.__proto__)} primitive={false}/> </div> : null } { this.props.primitive ? <div className='object-entry' key='[[PrimitiveValue]]'> { <span className='object-key dull'> [[PrimitiveValue]] <span className='object-colon'>: </span> </span> } { ReplOutput.transformObject(this.props.object.toString()) } </div> : null } </span> </span> } </span> ); } }
src/TextareaAutosize.js
nickpresta/react-textarea-autosize
/** * <TextareaAutosize /> */ import React from 'react'; import calculateNodeHeight from './calculateNodeHeight'; const emptyFunction = function(){}; export default class TextareaAutosize extends React.Component { static propTypes = { /** * Current textarea value. */ value: React.PropTypes.string, /** * Callback on value change. */ onChange: React.PropTypes.func, /** * Callback on height changes. */ onHeightChange: React.PropTypes.func, /** * Try to cache DOM measurements performed by component so that we don't * touch DOM when it's not needed. * * This optimization doesn't work if we dynamically style <textarea /> * component. */ useCacheForDOMMeasurements: React.PropTypes.bool, /** * Minimal numbder of rows to show. */ rows: React.PropTypes.number, /** * Alias for `rows`. */ minRows: React.PropTypes.number, /** * Maximum number of rows to show. */ maxRows: React.PropTypes.number } static defaultProps = { onChange: emptyFunction, onHeightChange: emptyFunction, useCacheForDOMMeasurements: false } constructor(props) { super(props); this.state = { height: null, minHeight: -Infinity, maxHeight: Infinity }; this._onChange = this._onChange.bind(this); this._resizeComponent = this._resizeComponent.bind(this); } render() { let {valueLink, onChange, ...props} = this.props; props = {...props}; if (typeof valueLink === 'object') { props.value = this.props.valueLink.value; } props.style = { ...props.style, height: this.state.height }; let maxHeight = Math.max( props.style.maxHeight ? props.style.maxHeight : Infinity, this.state.maxHeight); if (maxHeight < this.state.height) { props.style.overflow = 'hidden'; } return <textarea {...props} onChange={this._onChange} />; } componentDidMount() { this._resizeComponent(); } componentWillReceiveProps() { // Re-render with the new content then recalculate the height as required. this.clearNextFrame(); this.onNextFrameActionId = onNextFrame(this._resizeComponent); } componentDidUpdate(prevProps, prevState) { // Invoke callback when old height does not equal to new one. if (this.state.height !== prevState.height) { this.props.onHeightChange(this.state.height); } } componentWillUnmount() { //remove any scheduled events to prevent manipulating the node after it's //been unmounted this.clearNextFrame(); } clearNextFrame() { if (this.onNextFrameActionId) { clearNextFrameAction(this.onNextFrameActionId); } } _onChange(e) { this._resizeComponent(); let {valueLink, onChange} = this.props; if (valueLink) { valueLink.requestChange(e.target.value); } else { onChange(e); } } _resizeComponent() { let {useCacheForDOMMeasurements} = this.props; this.setState(calculateNodeHeight( React.findDOMNode(this), useCacheForDOMMeasurements, this.props.rows || this.props.minRows, this.props.maxRows)); } /** * Read the current value of <textarea /> from DOM. */ get value(): string { return React.findDOMNode(this).value; } /** * Put focus on a <textarea /> DOM element. */ focus() { React.findDOMNode(this).focus(); } } function onNextFrame(cb) { if (window.requestAnimationFrame) { return window.requestAnimationFrame(cb); } return window.setTimeout(cb, 1); } function clearNextFrameAction(nextFrameId) { if (window.cancelAnimationFrame) { window.cancelAnimationFrame(nextFrameId); } else { window.clearTimeout(nextFrameId); } }
src/svg-icons/device/location-disabled.js
hwo411/material-ui
import React from 'react'; import pure from 'recompose/pure'; import SvgIcon from '../../SvgIcon'; let DeviceLocationDisabled = (props) => ( <SvgIcon {...props}> <path d="M20.94 11c-.46-4.17-3.77-7.48-7.94-7.94V1h-2v2.06c-1.13.12-2.19.46-3.16.97l1.5 1.5C10.16 5.19 11.06 5 12 5c3.87 0 7 3.13 7 7 0 .94-.19 1.84-.52 2.65l1.5 1.5c.5-.96.84-2.02.97-3.15H23v-2h-2.06zM3 4.27l2.04 2.04C3.97 7.62 3.25 9.23 3.06 11H1v2h2.06c.46 4.17 3.77 7.48 7.94 7.94V23h2v-2.06c1.77-.2 3.38-.91 4.69-1.98L19.73 21 21 19.73 4.27 3 3 4.27zm13.27 13.27C15.09 18.45 13.61 19 12 19c-3.87 0-7-3.13-7-7 0-1.61.55-3.09 1.46-4.27l9.81 9.81z"/> </SvgIcon> ); DeviceLocationDisabled = pure(DeviceLocationDisabled); DeviceLocationDisabled.displayName = 'DeviceLocationDisabled'; DeviceLocationDisabled.muiName = 'SvgIcon'; export default DeviceLocationDisabled;
node_modules/react-bootstrap/es/ModalFooter.js
ProjectSunday/rooibus
import _extends from 'babel-runtime/helpers/extends'; import _objectWithoutProperties from 'babel-runtime/helpers/objectWithoutProperties'; import _classCallCheck from 'babel-runtime/helpers/classCallCheck'; import _possibleConstructorReturn from 'babel-runtime/helpers/possibleConstructorReturn'; import _inherits from 'babel-runtime/helpers/inherits'; import classNames from 'classnames'; import React from 'react'; import elementType from 'react-prop-types/lib/elementType'; import { bsClass, getClassSet, splitBsProps } from './utils/bootstrapUtils'; var propTypes = { componentClass: elementType }; var defaultProps = { componentClass: 'div' }; var ModalFooter = function (_React$Component) { _inherits(ModalFooter, _React$Component); function ModalFooter() { _classCallCheck(this, ModalFooter); return _possibleConstructorReturn(this, _React$Component.apply(this, arguments)); } ModalFooter.prototype.render = function render() { var _props = this.props, Component = _props.componentClass, className = _props.className, props = _objectWithoutProperties(_props, ['componentClass', 'className']); var _splitBsProps = splitBsProps(props), bsProps = _splitBsProps[0], elementProps = _splitBsProps[1]; var classes = getClassSet(bsProps); return React.createElement(Component, _extends({}, elementProps, { className: classNames(className, classes) })); }; return ModalFooter; }(React.Component); ModalFooter.propTypes = propTypes; ModalFooter.defaultProps = defaultProps; export default bsClass('modal-footer', ModalFooter);
subschema/test/resolvers/type-test.js
jspears/subschema-devel
import { expect } from 'chai'; import React, { Component } from 'react'; import PropTypes from 'subschema-prop-types'; import ValueManager from 'subschema-valuemanager'; import { intoWithContext } from 'subschema-test-support'; import { newSubschemaContext } from 'subschema'; describe('subschema-resolver-type', function () { let injector, loader, valueManager; class TestStuff extends Component { static propTypes = { value: PropTypes.value }; static defaultProps = { value: "more" }; render() { return <div>{this.props.value}</div>; } } class TargetTest extends Component { static propTypes = { custom: PropTypes.type, path : PropTypes.path }; static defaultProps = { custom: 'TestStuff' }; render() { const TestStuff = this.props.custom; return <div><TestStuff/></div> } } beforeEach(() => { const ctx = newSubschemaContext(); injector = ctx.injector; loader = ctx.loader; loader.addType({ TestStuff, TargetTest }); }); it('should follow inject types', function () { const Injected = injector.inject(TargetTest); const valueManager = ValueManager({ more: 'd' }); const inst = intoWithContext(<Injected path="hello"/>, { valueManager, loader, injector }, true); expect(inst.find(TestStuff).prop('value')).to.eql('d'); valueManager.update('more', 'stuff'); inst.update(); expect(inst.find(TestStuff).prop('value')).to.eql('stuff'); }); it('should inject configured types', function () { const Injected = injector.inject(TargetTest, {}); const valueManager = ValueManager({ 'other': 'stuff', more: 'd' }); const inst = intoWithContext(<Injected custom={{ type: 'TestStuff', path: 'other' }}/>, { valueManager, loader, injector }, true, PropTypes.contextTypes); expect(inst.find(TestStuff).prop('value')).to.eql('d'); valueManager.update('more', 'other'); inst.update(); expect(inst.find(TestStuff).prop('value')).to.eql('other'); }); });
ajax/libs/yui/3.9.0pr2/scrollview-base/scrollview-base.js
holtkamp/cdnjs
YUI.add('scrollview-base', function (Y, NAME) { /** * The scrollview-base module provides a basic ScrollView Widget, without scrollbar indicators * * @module scrollview * @submodule scrollview-base */ var getClassName = Y.ClassNameManager.getClassName, DOCUMENT = Y.config.doc, IE = Y.UA.ie, NATIVE_TRANSITIONS = Y.Transition.useNative, vendorPrefix = Y.Transition._VENDOR_PREFIX, // Todo: This is a private property, and alternative approaches should be investigated SCROLLVIEW = 'scrollview', CLASS_NAMES = { vertical: getClassName(SCROLLVIEW, 'vert'), horizontal: getClassName(SCROLLVIEW, 'horiz') }, EV_SCROLL_END = 'scrollEnd', FLICK = 'flick', DRAG = 'drag', MOUSEWHEEL = 'mousewheel', UI = 'ui', TOP = 'top', LEFT = 'left', PX = 'px', AXIS = 'axis', SCROLL_Y = 'scrollY', SCROLL_X = 'scrollX', BOUNCE = 'bounce', DISABLED = 'disabled', DECELERATION = 'deceleration', DIM_X = 'x', DIM_Y = 'y', BOUNDING_BOX = 'boundingBox', CONTENT_BOX = 'contentBox', GESTURE_MOVE = 'gesturemove', START = 'start', END = 'end', EMPTY = '', ZERO = '0s', SNAP_DURATION = 'snapDuration', SNAP_EASING = 'snapEasing', EASING = 'easing', FRAME_DURATION = 'frameDuration', BOUNCE_RANGE = 'bounceRange', _constrain = function (val, min, max) { return Math.min(Math.max(val, min), max); }; /** * ScrollView provides a scrollable widget, supporting flick gestures, * across both touch and mouse based devices. * * @class ScrollView * @param config {Object} Object literal with initial attribute values * @extends Widget * @constructor */ function ScrollView() { ScrollView.superclass.constructor.apply(this, arguments); } Y.ScrollView = Y.extend(ScrollView, Y.Widget, { // *** Y.ScrollView prototype /** * Flag driving whether or not we should try and force H/W acceleration when transforming. Currently enabled by default for Webkit. * Used by the _transform method. * * @property _forceHWTransforms * @type boolean * @protected */ _forceHWTransforms: Y.UA.webkit ? true : false, /** * <p>Used to control whether or not ScrollView's internal * gesturemovestart, gesturemove and gesturemoveend * event listeners should preventDefault. The value is an * object, with "start", "move" and "end" properties used to * specify which events should preventDefault and which shouldn't:</p> * * <pre> * { * start: false, * move: true, * end: false * } * </pre> * * <p>The default values are set up in order to prevent panning, * on touch devices, while allowing click listeners on elements inside * the ScrollView to be notified as expected.</p> * * @property _prevent * @type Object * @protected */ _prevent: { start: false, move: true, end: false }, /** * Contains the distance (postive or negative) in pixels by which * the scrollview was last scrolled. This is useful when setting up * click listeners on the scrollview content, which on mouse based * devices are always fired, even after a drag/flick. * * <p>Touch based devices don't currently fire a click event, * if the finger has been moved (beyond a threshold) so this * check isn't required, if working in a purely touch based environment</p> * * @property lastScrolledAmt * @type Number * @public * @default 0 */ lastScrolledAmt: 0, /** * Designated initializer * * @method initializer * @param {config} Configuration object for the plugin */ initializer: function () { var sv = this; // Cache these values, since they aren't going to change. sv._bb = sv.get(BOUNDING_BOX); sv._cb = sv.get(CONTENT_BOX); // Cache some attributes sv._cAxis = sv.get(AXIS); sv._cBounce = sv.get(BOUNCE); sv._cBounceRange = sv.get(BOUNCE_RANGE); sv._cDeceleration = sv.get(DECELERATION); sv._cFrameDuration = sv.get(FRAME_DURATION); }, /** * bindUI implementation * * Hooks up events for the widget * @method bindUI */ bindUI: function () { var sv = this; // Bind interaction listers sv._bindFlick(sv.get(FLICK)); sv._bindDrag(sv.get(DRAG)); sv._bindMousewheel(true); // Bind change events sv._bindAttrs(); // IE SELECT HACK. See if we can do this non-natively and in the gesture for a future release. if (IE) { sv._fixIESelect(sv._bb, sv._cb); } // Set any deprecated static properties if (ScrollView.SNAP_DURATION) { sv.set(SNAP_DURATION, ScrollView.SNAP_DURATION); } if (ScrollView.SNAP_EASING) { sv.set(SNAP_EASING, ScrollView.SNAP_EASING); } if (ScrollView.EASING) { sv.set(EASING, ScrollView.EASING); } if (ScrollView.FRAME_STEP) { sv.set(FRAME_DURATION, ScrollView.FRAME_STEP); } if (ScrollView.BOUNCE_RANGE) { sv.set(BOUNCE_RANGE, ScrollView.BOUNCE_RANGE); } // Recalculate dimension properties // TODO: This should be throttled. // Y.one(WINDOW).after('resize', sv._afterDimChange, sv); }, /** * Bind event listeners * * @method _bindAttrs * @private */ _bindAttrs: function () { var sv = this, scrollChangeHandler = sv._afterScrollChange, dimChangeHandler = sv._afterDimChange; // Bind any change event listeners sv.after({ 'scrollEnd': sv._afterScrollEnd, 'disabledChange': sv._afterDisabledChange, 'flickChange': sv._afterFlickChange, 'dragChange': sv._afterDragChange, 'axisChange': sv._afterAxisChange, 'scrollYChange': scrollChangeHandler, 'scrollXChange': scrollChangeHandler, 'heightChange': dimChangeHandler, 'widthChange': dimChangeHandler }); }, /** * Bind (or unbind) gesture move listeners required for drag support * * @method _bindDrag * @param drag {boolean} If true, the method binds listener to enable * drag (gesturemovestart). If false, the method unbinds gesturemove * listeners for drag support. * @private */ _bindDrag: function (drag) { var sv = this, bb = sv._bb; // Unbind any previous 'drag' listeners bb.detach(DRAG + '|*'); if (drag) { bb.on(DRAG + '|' + GESTURE_MOVE + START, Y.bind(sv._onGestureMoveStart, sv)); } }, /** * Bind (or unbind) flick listeners. * * @method _bindFlick * @param flick {Object|boolean} If truthy, the method binds listeners for * flick support. If false, the method unbinds flick listeners. * @private */ _bindFlick: function (flick) { var sv = this, bb = sv._bb; // Unbind any previous 'flick' listeners bb.detach(FLICK + '|*'); if (flick) { bb.on(FLICK + '|' + FLICK, Y.bind(sv._flick, sv), flick); // Rebind Drag, becuase _onGestureMoveEnd always has to fire -after- _flick sv._bindDrag(sv.get(DRAG)); } }, /** * Bind (or unbind) mousewheel listeners. * * @method _bindMousewheel * @param mousewheel {Object|boolean} If truthy, the method binds listeners for * mousewheel support. If false, the method unbinds mousewheel listeners. * @private */ _bindMousewheel: function (mousewheel) { var sv = this, bb = sv._bb; // Unbind any previous 'mousewheel' listeners // TODO: This doesn't actually appear to work properly. Fix. #2532743 bb.detach(MOUSEWHEEL + '|*'); // Only enable for vertical scrollviews if (mousewheel) { // Bound to document, because that's where mousewheel events fire off of. Y.one(DOCUMENT).on(MOUSEWHEEL, Y.bind(sv._mousewheel, sv)); } }, /** * syncUI implementation. * * Update the scroll position, based on the current value of scrollX/scrollY. * * @method syncUI */ syncUI: function () { var sv = this, scrollDims = sv._getScrollDims(), width = scrollDims.offsetWidth, height = scrollDims.offsetHeight, scrollWidth = scrollDims.scrollWidth, scrollHeight = scrollDims.scrollHeight; // If the axis is undefined, auto-calculate it if (sv._cAxis === undefined) { // This should only ever be run once (for now). // In the future SV might post-load axis changes sv._cAxis = { x: (scrollWidth > width), y: (scrollHeight > height) }; sv._set(AXIS, sv._cAxis); } // get text direction on or inherited by scrollview node sv.rtl = (sv._cb.getComputedStyle('direction') === 'rtl'); // Cache the disabled value sv._cDisabled = sv.get(DISABLED); // Run this to set initial values sv._uiDimensionsChange(); // If we're out-of-bounds, snap back. if (sv._isOutOfBounds()) { sv._snapBack(); } }, /** * Utility method to obtain widget dimensions * * @method _getScrollDims * @return {Object} The offsetWidth, offsetHeight, scrollWidth and * scrollHeight as an array: [offsetWidth, offsetHeight, scrollWidth, * scrollHeight] * @private */ _getScrollDims: function () { var sv = this, cb = sv._cb, bb = sv._bb, TRANS = ScrollView._TRANSITION, // Ideally using CSSMatrix - don't think we have it normalized yet though. // origX = (new WebKitCSSMatrix(cb.getComputedStyle("transform"))).e, // origY = (new WebKitCSSMatrix(cb.getComputedStyle("transform"))).f, origX = sv.get(SCROLL_X), origY = sv.get(SCROLL_Y), origHWTransform, dims; // TODO: Is this OK? Just in case it's called 'during' a transition. if (NATIVE_TRANSITIONS) { cb.setStyle(TRANS.DURATION, ZERO); cb.setStyle(TRANS.PROPERTY, EMPTY); } origHWTransform = sv._forceHWTransforms; sv._forceHWTransforms = false; // the z translation was causing issues with picking up accurate scrollWidths in Chrome/Mac. sv._moveTo(cb, 0, 0); dims = { 'offsetWidth': bb.get('offsetWidth'), 'offsetHeight': bb.get('offsetHeight'), 'scrollWidth': bb.get('scrollWidth'), 'scrollHeight': bb.get('scrollHeight') }; sv._moveTo(cb, -(origX), -(origY)); sv._forceHWTransforms = origHWTransform; return dims; }, /** * This method gets invoked whenever the height or width attributes change, * allowing us to determine which scrolling axes need to be enabled. * * @method _uiDimensionsChange * @protected */ _uiDimensionsChange: function () { var sv = this, bb = sv._bb, scrollDims = sv._getScrollDims(), width = scrollDims.offsetWidth, height = scrollDims.offsetHeight, scrollWidth = scrollDims.scrollWidth, scrollHeight = scrollDims.scrollHeight, rtl = sv.rtl, svAxis = sv._cAxis; if (svAxis && svAxis.x) { bb.addClass(CLASS_NAMES.horizontal); } if (svAxis && svAxis.y) { bb.addClass(CLASS_NAMES.vertical); } /** * Internal state, defines the minimum amount that the scrollview can be scrolled along the X axis * * @property _minScrollX * @type number * @protected */ sv._minScrollX = (rtl) ? Math.min(0, -(scrollWidth - width)) : 0; /** * Internal state, defines the maximum amount that the scrollview can be scrolled along the X axis * * @property _maxScrollX * @type number * @protected */ sv._maxScrollX = (rtl) ? 0 : Math.max(0, scrollWidth - width); /** * Internal state, defines the minimum amount that the scrollview can be scrolled along the Y axis * * @property _minScrollY * @type number * @protected */ sv._minScrollY = 0; /** * Internal state, defines the maximum amount that the scrollview can be scrolled along the Y axis * * @property _maxScrollY * @type number * @protected */ sv._maxScrollY = Math.max(0, scrollHeight - height); }, /** * Scroll the element to a given xy coordinate * * @method scrollTo * @param x {Number} The x-position to scroll to. (null for no movement) * @param y {Number} The y-position to scroll to. (null for no movement) * @param {Number} [duration] ms of the scroll animation. (default is 0) * @param {String} [easing] An easing equation if duration is set. (default is `easing` attribute) * @param {String} [node] The node to transform. Setting this can be useful in * dual-axis paginated instances. (default is the instance's contentBox) */ scrollTo: function (x, y, duration, easing, node) { // Check to see if widget is disabled if (this._cDisabled) { return; } var sv = this, cb = sv._cb, TRANS = ScrollView._TRANSITION, callback = Y.bind(sv._onTransEnd, sv), // @Todo : cache this newX = 0, newY = 0, transition = {}, transform; // default the optional arguments duration = duration || 0; easing = easing || sv.get(EASING); // @TODO: Cache this node = node || cb; if (x !== null) { sv.set(SCROLL_X, x, {src:UI}); newX = -(x); } if (y !== null) { sv.set(SCROLL_Y, y, {src:UI}); newY = -(y); } transform = sv._transform(newX, newY); if (NATIVE_TRANSITIONS) { // ANDROID WORKAROUND - try and stop existing transition, before kicking off new one. node.setStyle(TRANS.DURATION, ZERO).setStyle(TRANS.PROPERTY, EMPTY); } // Move if (duration === 0) { if (NATIVE_TRANSITIONS) { node.setStyle('transform', transform); } else { // TODO: If both set, batch them in the same update // Update: Nope, setStyles() just loops through each property and applies it. if (x !== null) { node.setStyle(LEFT, newX + PX); } if (y !== null) { node.setStyle(TOP, newY + PX); } } } // Animate else { transition.easing = easing; transition.duration = duration / 1000; if (NATIVE_TRANSITIONS) { transition.transform = transform; } else { transition.left = newX + PX; transition.top = newY + PX; } node.transition(transition, callback); } }, /** * Utility method, to create the translate transform string with the * x, y translation amounts provided. * * @method _transform * @param {Number} x Number of pixels to translate along the x axis * @param {Number} y Number of pixels to translate along the y axis * @private */ _transform: function (x, y) { // TODO: Would we be better off using a Matrix for this? var prop = 'translate(' + x + 'px, ' + y + 'px)'; if (this._forceHWTransforms) { prop += ' translateZ(0)'; } return prop; }, /** * Utility method, to move the given element to the given xy position * * @method _moveTo * @param node {Node} The node to move * @param x {Number} The x-position to move to * @param y {Number} The y-position to move to * @private */ _moveTo : function(node, x, y) { if (NATIVE_TRANSITIONS) { node.setStyle('transform', this._transform(x, y)); } else { node.setStyle(LEFT, x + PX); node.setStyle(TOP, y + PX); } }, /** * Content box transition callback * * @method _onTransEnd * @param {Event.Facade} e The event facade * @private */ _onTransEnd: function () { var sv = this; /** * Notification event fired at the end of a scroll transition * * @event scrollEnd * @param e {EventFacade} The default event facade. */ sv.fire(EV_SCROLL_END); }, /** * gesturemovestart event handler * * @method _onGestureMoveStart * @param e {Event.Facade} The gesturemovestart event facade * @private */ _onGestureMoveStart: function (e) { if (this._cDisabled) { return false; } var sv = this, bb = sv._bb, currentX = sv.get(SCROLL_X), currentY = sv.get(SCROLL_Y), clientX = e.clientX, clientY = e.clientY; if (sv._prevent.start) { e.preventDefault(); } // if a flick animation is in progress, cancel it if (sv._flickAnim) { // Cancel and delete sv._flickAnim sv._flickAnim.cancel(); delete sv._flickAnim; sv._onTransEnd(); } // TODO: Review if neccesary (#2530129) e.stopPropagation(); // Reset lastScrolledAmt sv.lastScrolledAmt = 0; // Stores data for this gesture cycle. Cleaned up later sv._gesture = { // Will hold the axis value axis: null, // The current attribute values startX: currentX, startY: currentY, // The X/Y coordinates where the event began startClientX: clientX, startClientY: clientY, // The X/Y coordinates where the event will end endClientX: null, endClientY: null, // The current delta of the event deltaX: null, deltaY: null, // Will be populated for flicks flick: null, // Create some listeners for the rest of the gesture cycle onGestureMove: bb.on(DRAG + '|' + GESTURE_MOVE, Y.bind(sv._onGestureMove, sv)), // @TODO: Don't bind gestureMoveEnd if it's a Flick? onGestureMoveEnd: bb.on(DRAG + '|' + GESTURE_MOVE + END, Y.bind(sv._onGestureMoveEnd, sv)) }; }, /** * gesturemove event handler * * @method _onGestureMove * @param e {Event.Facade} The gesturemove event facade * @private */ _onGestureMove: function (e) { var sv = this, gesture = sv._gesture, svAxis = sv._cAxis, svAxisX = svAxis.x, svAxisY = svAxis.y, startX = gesture.startX, startY = gesture.startY, startClientX = gesture.startClientX, startClientY = gesture.startClientY, clientX = e.clientX, clientY = e.clientY; if (sv._prevent.move) { e.preventDefault(); } gesture.deltaX = startClientX - clientX; gesture.deltaY = startClientY - clientY; // Determine if this is a vertical or horizontal movement // @TODO: This is crude, but it works. Investigate more intelligent ways to detect intent if (gesture.axis === null) { gesture.axis = (Math.abs(gesture.deltaX) > Math.abs(gesture.deltaY)) ? DIM_X : DIM_Y; } // Move X or Y. @TODO: Move both if dualaxis. if (gesture.axis === DIM_X && svAxisX) { sv.set(SCROLL_X, startX + gesture.deltaX); } else if (gesture.axis === DIM_Y && svAxisY) { sv.set(SCROLL_Y, startY + gesture.deltaY); } }, /** * gesturemoveend event handler * * @method _onGestureMoveEnd * @param e {Event.Facade} The gesturemoveend event facade * @private */ _onGestureMoveEnd: function (e) { var sv = this, gesture = sv._gesture, flick = gesture.flick, clientX = e.clientX, clientY = e.clientY; if (sv._prevent.end) { e.preventDefault(); } // Store the end X/Y coordinates gesture.endClientX = clientX; gesture.endClientY = clientY; // Cleanup the event handlers gesture.onGestureMove.detach(); gesture.onGestureMoveEnd.detach(); // If this wasn't a flick, wrap up the gesture cycle if (!flick) { // @TODO: Be more intelligent about this. Look at the Flick attribute to see // if it is safe to assume _flick did or didn't fire. // Then, the order _flick and _onGestureMoveEnd fire doesn't matter? // If there was movement (_onGestureMove fired) if (gesture.deltaX !== null && gesture.deltaY !== null) { // If we're out-out-bounds, then snapback if (sv._isOutOfBounds()) { sv._snapBack(); } // Inbounds else { // Don't fire scrollEnd on the gesture axis is the same as paginator's // Not totally confident this is ideal to access a plugin's properties from a host, @TODO revisit if (sv.pages && !sv.pages.get(AXIS)[gesture.axis]) { sv._onTransEnd(); } } } } }, /** * Execute a flick at the end of a scroll action * * @method _flick * @param e {Event.Facade} The Flick event facade * @private */ _flick: function (e) { if (this._cDisabled) { return false; } var sv = this, svAxis = sv._cAxis, flick = e.flick, flickAxis = flick.axis, flickVelocity = flick.velocity, axisAttr = flickAxis === DIM_X ? SCROLL_X : SCROLL_Y, startPosition = sv.get(axisAttr); // Sometimes flick is enabled, but drag is disabled if (sv._gesture) { sv._gesture.flick = flick; } // Prevent unneccesary firing of _flickFrame if we can't scroll on the flick axis if (svAxis[flickAxis]) { sv._flickFrame(flickVelocity, flickAxis, startPosition); } }, /** * Execute a single frame in the flick animation * * @method _flickFrame * @param velocity {Number} The velocity of this animated frame * @param flickAxis {String} The axis on which to animate * @param startPosition {Number} The starting X/Y point to flick from * @protected */ _flickFrame: function (velocity, flickAxis, startPosition) { var sv = this, axisAttr = flickAxis === DIM_X ? SCROLL_X : SCROLL_Y, // Localize cached values bounce = sv._cBounce, bounceRange = sv._cBounceRange, deceleration = sv._cDeceleration, frameDuration = sv._cFrameDuration, // Calculate newVelocity = velocity * deceleration, newPosition = startPosition - (frameDuration * newVelocity), // Some convinience conditions min = flickAxis === DIM_X ? sv._minScrollX : sv._minScrollY, max = flickAxis === DIM_X ? sv._maxScrollX : sv._maxScrollY, belowMin = (newPosition < min), belowMax = (newPosition < max), aboveMin = (newPosition > min), aboveMax = (newPosition > max), belowMinRange = (newPosition < (min - bounceRange)), withinMinRange = (belowMin && (newPosition > (min - bounceRange))), withinMaxRange = (aboveMax && (newPosition < (max + bounceRange))), aboveMaxRange = (newPosition > (max + bounceRange)), tooSlow; // If we're within the range but outside min/max, dampen the velocity if (withinMinRange || withinMaxRange) { newVelocity *= bounce; } // Is the velocity too slow to bother? tooSlow = (Math.abs(newVelocity).toFixed(4) < 0.015); // If the velocity is too slow or we're outside the range if (tooSlow || belowMinRange || aboveMaxRange) { // Cancel and delete sv._flickAnim if (sv._flickAnim) { sv._flickAnim.cancel(); delete sv._flickAnim; } // If we're inside the scroll area, just end if (aboveMin && belowMax) { sv._onTransEnd(); } // We're outside the scroll area, so we need to snap back else { sv._snapBack(); } } // Otherwise, animate to the next frame else { // @TODO: maybe use requestAnimationFrame instead sv._flickAnim = Y.later(frameDuration, sv, '_flickFrame', [newVelocity, flickAxis, newPosition]); sv.set(axisAttr, newPosition); } }, /** * Handle mousewheel events on the widget * * @method _mousewheel * @param e {Event.Facade} The mousewheel event facade * @private */ _mousewheel: function (e) { var sv = this, scrollY = sv.get(SCROLL_Y), bb = sv._bb, scrollOffset = 10, // 10px isForward = (e.wheelDelta > 0), scrollToY = scrollY - ((isForward ? 1 : -1) * scrollOffset); scrollToY = _constrain(scrollToY, sv._minScrollY, sv._maxScrollY); // Because Mousewheel events fire off 'document', every ScrollView widget will react // to any mousewheel anywhere on the page. This check will ensure that the mouse is currently // over this specific ScrollView. Also, only allow mousewheel scrolling on Y-axis, // becuase otherwise the 'prevent' will block page scrolling. if (bb.contains(e.target) && sv._cAxis[DIM_Y]) { // Reset lastScrolledAmt sv.lastScrolledAmt = 0; // Jump to the new offset sv.set(SCROLL_Y, scrollToY); // if we have scrollbars plugin, update & set the flash timer on the scrollbar // @TODO: This probably shouldn't be in this module if (sv.scrollbars) { // @TODO: The scrollbars should handle this themselves sv.scrollbars._update(); sv.scrollbars.flash(); // or just this // sv.scrollbars._hostDimensionsChange(); } // Fire the 'scrollEnd' event sv._onTransEnd(); // prevent browser default behavior on mouse scroll e.preventDefault(); } }, /** * Checks to see the current scrollX/scrollY position beyond the min/max boundary * * @method _isOutOfBounds * @param x {Number} [optional] The X position to check * @param y {Number} [optional] The Y position to check * @return {boolen} Whether the current X/Y position is out of bounds (true) or not (false) * @private */ _isOutOfBounds: function (x, y) { var sv = this, svAxis = sv._cAxis, svAxisX = svAxis.x, svAxisY = svAxis.y, currentX = x || sv.get(SCROLL_X), currentY = y || sv.get(SCROLL_Y), minX = sv._minScrollX, minY = sv._minScrollY, maxX = sv._maxScrollX, maxY = sv._maxScrollY; return (svAxisX && (currentX < minX || currentX > maxX)) || (svAxisY && (currentY < minY || currentY > maxY)); }, /** * Bounces back * @TODO: Should be more generalized and support both X and Y detection * * @method _snapBack * @private */ _snapBack: function () { var sv = this, currentX = sv.get(SCROLL_X), currentY = sv.get(SCROLL_Y), minX = sv._minScrollX, minY = sv._minScrollY, maxX = sv._maxScrollX, maxY = sv._maxScrollY, newY = _constrain(currentY, minY, maxY), newX = _constrain(currentX, minX, maxX), duration = sv.get(SNAP_DURATION), easing = sv.get(SNAP_EASING); if (newX !== currentX) { sv.set(SCROLL_X, newX, {duration:duration, easing:easing}); } else if (newY !== currentY) { sv.set(SCROLL_Y, newY, {duration:duration, easing:easing}); } else { // It shouldn't ever get here, but in case it does, fire scrollEnd sv._onTransEnd(); } }, /** * After listener for changes to the scrollX or scrollY attribute * * @method _afterScrollChange * @param e {Event.Facade} The event facade * @protected */ _afterScrollChange: function (e) { if (e.src === ScrollView.UI_SRC) { return false; } var sv = this, duration = e.duration, easing = e.easing, val = e.newVal, scrollToArgs = []; // Set the scrolled value sv.lastScrolledAmt = sv.lastScrolledAmt + (e.newVal - e.prevVal); // Generate the array of args to pass to scrollTo() if (e.attrName === SCROLL_X) { scrollToArgs.push(val); scrollToArgs.push(sv.get(SCROLL_Y)); } else { scrollToArgs.push(sv.get(SCROLL_X)); scrollToArgs.push(val); } scrollToArgs.push(duration); scrollToArgs.push(easing); sv.scrollTo.apply(sv, scrollToArgs); }, /** * After listener for changes to the flick attribute * * @method _afterFlickChange * @param e {Event.Facade} The event facade * @protected */ _afterFlickChange: function (e) { this._bindFlick(e.newVal); }, /** * After listener for changes to the disabled attribute * * @method _afterDisabledChange * @param e {Event.Facade} The event facade * @protected */ _afterDisabledChange: function (e) { // Cache for performance - we check during move this._cDisabled = e.newVal; }, /** * After listener for the axis attribute * * @method _afterAxisChange * @param e {Event.Facade} The event facade * @protected */ _afterAxisChange: function (e) { this._cAxis = e.newVal; }, /** * After listener for changes to the drag attribute * * @method _afterDragChange * @param e {Event.Facade} The event facade * @protected */ _afterDragChange: function (e) { this._bindDrag(e.newVal); }, /** * After listener for the height or width attribute * * @method _afterDimChange * @param e {Event.Facade} The event facade * @protected */ _afterDimChange: function () { this._uiDimensionsChange(); }, /** * After listener for scrollEnd, for cleanup * * @method _afterScrollEnd * @param e {Event.Facade} The event facade * @protected */ _afterScrollEnd: function () { var sv = this; // @TODO: Move to sv._cancelFlick() if (sv._flickAnim) { // Cancel the flick (if it exists) sv._flickAnim.cancel(); // Also delete it, otherwise _onGestureMoveStart will think we're still flicking delete sv._flickAnim; } // If for some reason we're OOB, snapback if (sv._isOutOfBounds()) { sv._snapBack(); } // Ideally this should be removed, but doing so causing some JS errors with fast swiping // because _gesture is being deleted after the previous one has been overwritten // delete sv._gesture; // TODO: Move to sv.prevGesture? }, /** * Setter for 'axis' attribute * * @method _axisSetter * @param val {Mixed} A string ('x', 'y', 'xy') to specify which axis/axes to allow scrolling on * @param name {String} The attribute name * @return {Object} An object to specify scrollability on the x & y axes * * @protected */ _axisSetter: function (val) { // Turn a string into an axis object if (Y.Lang.isString(val)) { return { x: val.match(/x/i) ? true : false, y: val.match(/y/i) ? true : false }; } }, /** * The scrollX, scrollY setter implementation * * @method _setScroll * @private * @param {Number} val * @param {String} dim * * @return {Number} The value */ _setScroll : function(val) { // Just ensure the widget is not disabled if (this._cDisabled) { val = Y.Attribute.INVALID_VALUE; } return val; }, /** * Setter for the scrollX attribute * * @method _setScrollX * @param val {Number} The new scrollX value * @return {Number} The normalized value * @protected */ _setScrollX: function(val) { return this._setScroll(val, DIM_X); }, /** * Setter for the scrollY ATTR * * @method _setScrollY * @param val {Number} The new scrollY value * @return {Number} The normalized value * @protected */ _setScrollY: function(val) { return this._setScroll(val, DIM_Y); } // End prototype properties }, { // Static properties /** * The identity of the widget. * * @property NAME * @type String * @default 'scrollview' * @readOnly * @protected * @static */ NAME: 'scrollview', /** * Static property used to define the default attribute configuration of * the Widget. * * @property ATTRS * @type {Object} * @protected * @static */ ATTRS: { /** * Specifies ability to scroll on x, y, or x and y axis/axes. * * @attribute axis * @type String */ axis: { setter: '_axisSetter', writeOnce: 'initOnly' }, /** * The current scroll position in the x-axis * * @attribute scrollX * @type Number * @default 0 */ scrollX: { value: 0, setter: '_setScrollX' }, /** * The current scroll position in the y-axis * * @attribute scrollY * @type Number * @default 0 */ scrollY: { value: 0, setter: '_setScrollY' }, /** * Drag coefficent for inertial scrolling. The closer to 1 this * value is, the less friction during scrolling. * * @attribute deceleration * @default 0.93 */ deceleration: { value: 0.93 }, /** * Drag coefficient for intertial scrolling at the upper * and lower boundaries of the scrollview. Set to 0 to * disable "rubber-banding". * * @attribute bounce * @type Number * @default 0.1 */ bounce: { value: 0.1 }, /** * The minimum distance and/or velocity which define a flick. Can be set to false, * to disable flick support (note: drag support is enabled/disabled separately) * * @attribute flick * @type Object * @default Object with properties minDistance = 10, minVelocity = 0.3. */ flick: { value: { minDistance: 10, minVelocity: 0.3 } }, /** * Enable/Disable dragging the ScrollView content (note: flick support is enabled/disabled separately) * @attribute drag * @type boolean * @default true */ drag: { value: true }, /** * The default duration to use when animating the bounce snap back. * * @attribute snapDuration * @type Number * @default 400 */ snapDuration: { value: 400 }, /** * The default easing to use when animating the bounce snap back. * * @attribute snapEasing * @type String * @default 'ease-out' */ snapEasing: { value: 'ease-out' }, /** * The default easing used when animating the flick * * @attribute easing * @type String * @default 'cubic-bezier(0, 0.1, 0, 1.0)' */ easing: { value: 'cubic-bezier(0, 0.1, 0, 1.0)' }, /** * The interval (ms) used when animating the flick for JS-timer animations * * @attribute frameDuration * @type Number * @default 15 */ frameDuration: { value: 15 }, /** * The default bounce distance in pixels * * @attribute bounceRange * @type Number * @default 150 */ bounceRange: { value: 150 } }, /** * List of class names used in the scrollview's DOM * * @property CLASS_NAMES * @type Object * @static */ CLASS_NAMES: CLASS_NAMES, /** * Flag used to source property changes initiated from the DOM * * @property UI_SRC * @type String * @static * @default 'ui' */ UI_SRC: UI, /** * Object map of style property names used to set transition properties. * Defaults to the vendor prefix established by the Transition module. * The configured property names are `_TRANSITION.DURATION` (e.g. "WebkitTransitionDuration") and * `_TRANSITION.PROPERTY (e.g. "WebkitTransitionProperty"). * * @property _TRANSITION * @private */ _TRANSITION: { DURATION: (vendorPrefix ? vendorPrefix + 'TransitionDuration' : 'transitionDuration'), PROPERTY: (vendorPrefix ? vendorPrefix + 'TransitionProperty' : 'transitionProperty') }, /** * The default bounce distance in pixels * * @property BOUNCE_RANGE * @type Number * @static * @default false * @deprecated (in 3.7.0) */ BOUNCE_RANGE: false, /** * The interval (ms) used when animating the flick * * @property FRAME_STEP * @type Number * @static * @default false * @deprecated (in 3.7.0) */ FRAME_STEP: false, /** * The default easing used when animating the flick * * @property EASING * @type String * @static * @default false * @deprecated (in 3.7.0) */ EASING: false, /** * The default easing to use when animating the bounce snap back. * * @property SNAP_EASING * @type String * @static * @default false * @deprecated (in 3.7.0) */ SNAP_EASING: false, /** * The default duration to use when animating the bounce snap back. * * @property SNAP_DURATION * @type Number * @static * @default false * @deprecated (in 3.7.0) */ SNAP_DURATION: false // End static properties }); }, '@VERSION@', {"requires": ["widget", "event-gestures", "event-mousewheel", "transition"], "skinnable": true});
app/containers/UGTourPage/attendantaddpopover.js
perry-ugroop/ugroop-react-dup2
/** * Created by yunzhou on 26/11/2016. */ import React from 'react'; import A from '../../components/A'; import { Overlay } from 'react-bootstrap'; import messages from './messages'; import { connect } from 'react-redux'; import BSRow from '../BootStrap/BSRow'; import BSFormGroup from '../BootStrap/BSFormGroup'; import Input from './Input'; import SubmitButton from './SubmitButton'; import CancelButton from './CancelButton'; import BSColumnLG6 from '../BootStrap/BSColumnLG6'; import BSColumnAll from '../BootStrap/BSColumnAll'; import { PARTICIPANT_ATTENDANT, PARTICIPANT_ORGANIZER, PARTICIPANT_VIEWER } from './constants'; export class AttendantAddPopover extends React.Component { constructor(props) { super(props); this.state = { showPopover: false, }; } closeCancel() { this.setState({ showPopover: false }); } closeSave() { this.setState({ showPopover: false }); } open() { this.setState({ showPopover: true }); } render() { // const tourId = this.props.tourId; const attendType = this.props.attendType; let title = ''; if (attendType === PARTICIPANT_ATTENDANT) { title = messages.addParticipantsLink.defaultMessage; } else if (attendType === PARTICIPANT_ORGANIZER) { title = messages.addOrganizerLink.defaultMessage; } else if (attendType === PARTICIPANT_VIEWER) { title = messages.addViewersLink.defaultMessage; } return ( <span > <A onClick={() => this.open()}>{title}</A> <Overlay show={this.state.showPopover} onHide={() => this.setState({ showPopover: false })} placement="bottom" container={this} > <div style={{ backgroundColor: '#EEE', boxShadow: '0 5px 10px rgba(0, 0, 0, 0.2)', border: '1px solid #CCC', borderRadius: 3, marginLeft: -5, marginTop: 5, padding: 10, }} > <BSRow> <BSColumnLG6> <BSFormGroup> <Input type="text" name="firstname" placeholder={messages.firstNameField.defaultMessage} value={this.props.firstName} /> </BSFormGroup> </BSColumnLG6> <BSColumnLG6> <BSFormGroup> <Input type="text" name="lastName" placeholder={messages.lastNameField.defaultMessage} value={this.props.lastName} /> </BSFormGroup> </BSColumnLG6> <BSColumnAll> <BSFormGroup> <Input type="text" name="email" placeholder={messages.emailField.defaultMessage} value={this.props.email} /> </BSFormGroup> </BSColumnAll> <BSColumnAll> <BSFormGroup> <SubmitButton onClick={() => this.closeSave()}> {messages.saveButton.defaultMessage} </SubmitButton> &nbsp; <CancelButton onClick={() => this.closeCancel()}>{messages.cancelButton.defaultMessage}</CancelButton> </BSFormGroup> </BSColumnAll> </BSRow> </div> </Overlay> </span> ); } } AttendantAddPopover.propTypes = { // tourId: React.PropTypes.string, attendType: React.PropTypes.string, firstName: React.PropTypes.string, lastName: React.PropTypes.string, email: React.PropTypes.string, }; export default connect()(AttendantAddPopover);
packages/material-ui-icons/src/LocalShippingRounded.js
Kagami/material-ui
import React from 'react'; import createSvgIcon from './utils/createSvgIcon'; export default createSvgIcon( <React.Fragment><path fill="none" d="M0 0h24v24H0V0z" /><path d="M19.5 8H17V6c0-1.1-.9-2-2-2H3c-1.1 0-2 .9-2 2v9c0 1.1.9 2 2 2 0 1.66 1.34 3 3 3s3-1.34 3-3h6c0 1.66 1.34 3 3 3s3-1.34 3-3h1c.55 0 1-.45 1-1v-3.33c0-.43-.14-.85-.4-1.2L20.3 8.4c-.19-.25-.49-.4-.8-.4zM6 18c-.55 0-1-.45-1-1s.45-1 1-1 1 .45 1 1-.45 1-1 1zm13.5-8.5l1.96 2.5H17V9.5h2.5zM18 18c-.55 0-1-.45-1-1s.45-1 1-1 1 .45 1 1-.45 1-1 1z" /></React.Fragment> , 'LocalShippingRounded');
packages/material-ui-icons/src/PermDataSettingTwoTone.js
Kagami/material-ui
import React from 'react'; import createSvgIcon from './utils/createSvgIcon'; export default createSvgIcon( <React.Fragment><path fill="none" d="M0 0h24v24H0V0z" /><path d="M17.99 11.57H20V0L0 20h11.56v-2H4.83L17.99 4.83v6.74z" /><path d="M23.77 20.32l-1.07-.83c.02-.16.04-.32.04-.49 0-.17-.01-.33-.04-.49l1.06-.83c.09-.08.12-.21.06-.32l-1-1.73c-.06-.11-.19-.15-.31-.11l-1.24.5c-.26-.2-.54-.37-.85-.49l-.19-1.32c-.01-.12-.12-.21-.24-.21h-2c-.12 0-.23.09-.25.21l-.19 1.32c-.3.13-.59.29-.85.49l-1.24-.5c-.11-.04-.24 0-.31.11l-1 1.73c-.06.11-.04.24.06.32l1.06.83c-.02.16-.03.32-.03.49 0 .17.01.33.03.49l-1.06.83c-.09.08-.12.21-.06.32l1 1.73c.06.11.19.15.31.11l1.24-.5c.26.2.54.37.85.49l.19 1.32c.02.12.12.21.25.21h2c.12 0 .23-.09.25-.21l.19-1.32c.3-.13.59-.29.84-.49l1.25.5c.11.04.24 0 .31-.11l1-1.73c.06-.11.03-.24-.06-.32zm-4.78.18c-.83 0-1.5-.67-1.5-1.5s.67-1.5 1.5-1.5 1.5.67 1.5 1.5-.67 1.5-1.5 1.5z" /></React.Fragment> , 'PermDataSettingTwoTone');
src/svg-icons/action/speaker-notes-off.js
kittyjumbalaya/material-components-web
import React from 'react'; import pure from 'recompose/pure'; import SvgIcon from '../../SvgIcon'; let ActionSpeakerNotesOff = (props) => ( <SvgIcon {...props}> <path d="M10.54 11l-.54-.54L7.54 8 6 6.46 2.38 2.84 1.27 1.73 0 3l2.01 2.01L2 22l4-4h9l5.73 5.73L22 22.46 17.54 18l-7-7zM8 14H6v-2h2v2zm-2-3V9l2 2H6zm14-9H4.08L10 7.92V6h8v2h-7.92l1 1H18v2h-4.92l6.99 6.99C21.14 17.95 22 17.08 22 16V4c0-1.1-.9-2-2-2z"/> </SvgIcon> ); ActionSpeakerNotesOff = pure(ActionSpeakerNotesOff); ActionSpeakerNotesOff.displayName = 'ActionSpeakerNotesOff'; ActionSpeakerNotesOff.muiName = 'SvgIcon'; export default ActionSpeakerNotesOff;
ajax/libs/forerunnerdb/1.3.488/fdb-core+persist.js
brix/cdnjs
(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<r.length;o++)s(r[o]);return s})({1:[function(_dereq_,module,exports){ var Core = _dereq_('./core'), Persist = _dereq_('../lib/Persist'); if (typeof window !== 'undefined') { window.ForerunnerDB = Core; } module.exports = Core; },{"../lib/Persist":26,"./core":2}],2:[function(_dereq_,module,exports){ var Core = _dereq_('../lib/Core'), ShimIE8 = _dereq_('../lib/Shim.IE8'); if (typeof window !== 'undefined') { window.ForerunnerDB = Core; } module.exports = Core; },{"../lib/Core":6,"../lib/Shim.IE8":32}],3:[function(_dereq_,module,exports){ "use strict"; var Shared = _dereq_('./Shared'), Path = _dereq_('./Path'); var BinaryTree = function (data, compareFunc, hashFunc) { this.init.apply(this, arguments); }; BinaryTree.prototype.init = function (data, index, compareFunc, hashFunc) { this._store = []; this._keys = []; if (index !== undefined) { this.index(index); } if (compareFunc !== undefined) { this.compareFunc(compareFunc); } if (hashFunc !== undefined) { this.hashFunc(hashFunc); } if (data !== undefined) { this.data(data); } }; Shared.addModule('BinaryTree', BinaryTree); Shared.mixin(BinaryTree.prototype, 'Mixin.ChainReactor'); Shared.mixin(BinaryTree.prototype, 'Mixin.Sorting'); Shared.mixin(BinaryTree.prototype, 'Mixin.Common'); Shared.synthesize(BinaryTree.prototype, 'compareFunc'); Shared.synthesize(BinaryTree.prototype, 'hashFunc'); Shared.synthesize(BinaryTree.prototype, 'indexDir'); Shared.synthesize(BinaryTree.prototype, 'keys'); Shared.synthesize(BinaryTree.prototype, 'index', function (index) { if (index !== undefined) { // Convert the index object to an array of key val objects this.keys(this.extractKeys(index)); } return this.$super.call(this, index); }); BinaryTree.prototype.extractKeys = function (obj) { var i, keys = []; for (i in obj) { if (obj.hasOwnProperty(i)) { keys.push({ key: i, val: obj[i] }); } } return keys; }; BinaryTree.prototype.data = function (val) { if (val !== undefined) { this._data = val; if (this._hashFunc) { this._hash = this._hashFunc(val); } return this; } return this._data; }; /** * Pushes an item to the binary tree node's store array. * @param {*} val The item to add to the store. * @returns {*} */ BinaryTree.prototype.push = function (val) { if (val !== undefined) { this._store.push(val); return this; } return false; }; /** * Pulls an item from the binary tree node's store array. * @param {*} val The item to remove from the store. * @returns {*} */ BinaryTree.prototype.pull = function (val) { if (val !== undefined) { var index = this._store.indexOf(val); if (index > -1) { this._store.splice(index, 1); return this; } } return false; }; /** * Default compare method. Can be overridden. * @param a * @param b * @returns {number} * @private */ BinaryTree.prototype._compareFunc = function (a, b) { // Loop the index array var i, indexData, result = 0; for (i = 0; i < this._keys.length; i++) { indexData = this._keys[i]; if (indexData.val === 1) { result = this.sortAsc(a[indexData.key], b[indexData.key]); } else if (indexData.val === -1) { result = this.sortDesc(a[indexData.key], b[indexData.key]); } if (result !== 0) { return result; } } return result; }; /** * Default hash function. Can be overridden. * @param obj * @private */ BinaryTree.prototype._hashFunc = function (obj) { /*var i, indexData, hash = ''; for (i = 0; i < this._keys.length; i++) { indexData = this._keys[i]; if (hash) { hash += '_'; } hash += obj[indexData.key]; } return hash;*/ return obj[this._keys[0].key]; }; BinaryTree.prototype.insert = function (data) { var result, inserted, failed, i; if (data instanceof Array) { // Insert array of data inserted = []; failed = []; for (i = 0; i < data.length; i++) { if (this.insert(data[i])) { inserted.push(data[i]); } else { failed.push(data[i]); } } return { inserted: inserted, failed: failed }; } if (!this._data) { // Insert into this node (overwrite) as there is no data this.data(data); //this.push(data); return true; } result = this._compareFunc(this._data, data); if (result === 0) { this.push(data); // Less than this node if (this._left) { // Propagate down the left branch this._left.insert(data); } else { // Assign to left branch this._left = new BinaryTree(data, this._index, this._compareFunc, this._hashFunc); } return true; } if (result === -1) { // Greater than this node if (this._right) { // Propagate down the right branch this._right.insert(data); } else { // Assign to right branch this._right = new BinaryTree(data, this._index, this._compareFunc, this._hashFunc); } return true; } if (result === 1) { // Less than this node if (this._left) { // Propagate down the left branch this._left.insert(data); } else { // Assign to left branch this._left = new BinaryTree(data, this._index, this._compareFunc, this._hashFunc); } return true; } return false; }; BinaryTree.prototype.lookup = function (data, resultArr) { var result = this._compareFunc(this._data, data); resultArr = resultArr || []; if (result === 0) { if (this._left) { this._left.lookup(data, resultArr); } resultArr.push(this._data); if (this._right) { this._right.lookup(data, resultArr); } } if (result === -1) { if (this._right) { this._right.lookup(data, resultArr); } } if (result === 1) { if (this._left) { this._left.lookup(data, resultArr); } } return resultArr; }; BinaryTree.prototype.inOrder = function (type, resultArr) { resultArr = resultArr || []; if (this._left) { this._left.inOrder(type, resultArr); } switch (type) { case 'hash': resultArr.push(this._hash); break; case 'data': resultArr.push(this._data); break; default: resultArr.push({ key: this._data, arr: this._store }); break; } if (this._right) { this._right.inOrder(type, resultArr); } return resultArr; }; /*BinaryTree.prototype.find = function (type, search, resultArr) { resultArr = resultArr || []; if (this._left) { this._left.find(type, search, resultArr); } // Check if this node's data is greater or less than the from value var fromResult = this.sortAsc(this._data[key], from), toResult = this.sortAsc(this._data[key], to); if ((fromResult === 0 || fromResult === 1) && (toResult === 0 || toResult === -1)) { // This data node is greater than or equal to the from value, // and less than or equal to the to value so include it switch (type) { case 'hash': resultArr.push(this._hash); break; case 'data': resultArr.push(this._data); break; default: resultArr.push({ key: this._data, arr: this._store }); break; } } if (this._right) { this._right.find(type, search, resultArr); } return resultArr; };*/ /** * * @param {String} type * @param {String} key The data key / path to range search against. * @param {Number} from Range search from this value (inclusive) * @param {Number} to Range search to this value (inclusive) * @param {Array=} resultArr Leave undefined when calling (internal use), * passes the result array between recursive calls to be returned when * the recursion chain completes. * @param {Path=} pathResolver Leave undefined when calling (internal use), * caches the path resolver instance for performance. * @returns {Array} Array of matching document objects */ BinaryTree.prototype.findRange = function (type, key, from, to, resultArr, pathResolver) { resultArr = resultArr || []; pathResolver = pathResolver || new Path(key); if (this._left) { this._left.findRange(type, key, from, to, resultArr, pathResolver); } // Check if this node's data is greater or less than the from value var pathVal = pathResolver.value(this._data), fromResult = this.sortAsc(pathVal, from), toResult = this.sortAsc(pathVal, to); if ((fromResult === 0 || fromResult === 1) && (toResult === 0 || toResult === -1)) { // This data node is greater than or equal to the from value, // and less than or equal to the to value so include it switch (type) { case 'hash': resultArr.push(this._hash); break; case 'data': resultArr.push(this._data); break; default: resultArr.push({ key: this._data, arr: this._store }); break; } } if (this._right) { this._right.findRange(type, key, from, to, resultArr, pathResolver); } return resultArr; }; /*BinaryTree.prototype.findRegExp = function (type, key, pattern, resultArr) { resultArr = resultArr || []; if (this._left) { this._left.findRegExp(type, key, pattern, resultArr); } // Check if this node's data is greater or less than the from value var fromResult = this.sortAsc(this._data[key], from), toResult = this.sortAsc(this._data[key], to); if ((fromResult === 0 || fromResult === 1) && (toResult === 0 || toResult === -1)) { // This data node is greater than or equal to the from value, // and less than or equal to the to value so include it switch (type) { case 'hash': resultArr.push(this._hash); break; case 'data': resultArr.push(this._data); break; default: resultArr.push({ key: this._data, arr: this._store }); break; } } if (this._right) { this._right.findRegExp(type, key, pattern, resultArr); } return resultArr; };*/ BinaryTree.prototype.match = function (query, options) { // Check if the passed query has data in the keys our index // operates on and if so, is the query sort matching our order var pathSolver = new Path(), indexKeyArr, queryArr, matchedKeys = [], matchedKeyCount = 0, i; indexKeyArr = pathSolver.parseArr(this._index, { verbose: true }); queryArr = pathSolver.parseArr(query, { ignore:/\$/, verbose: true }); // Loop the query array and check the order of keys against the // index key array to see if this index can be used for (i = 0; i < indexKeyArr.length; i++) { if (queryArr[i] === indexKeyArr[i]) { matchedKeyCount++; matchedKeys.push(queryArr[i]); } } return { matchedKeys: matchedKeys, totalKeyCount: queryArr.length, score: matchedKeyCount }; //return pathSolver.countObjectPaths(this._keys, query); }; Shared.finishModule('BinaryTree'); module.exports = BinaryTree; },{"./Path":25,"./Shared":31}],4:[function(_dereq_,module,exports){ "use strict"; var Shared, Db, Metrics, KeyValueStore, Path, IndexHashMap, IndexBinaryTree, Crc, Overload, ReactorIO; Shared = _dereq_('./Shared'); /** * Creates a new collection. Collections store multiple documents and * handle CRUD against those documents. * @constructor */ var Collection = function (name) { this.init.apply(this, arguments); }; Collection.prototype.init = function (name, options) { this._primaryKey = '_id'; this._primaryIndex = new KeyValueStore('primary'); this._primaryCrc = new KeyValueStore('primaryCrc'); this._crcLookup = new KeyValueStore('crcLookup'); this._name = name; this._data = []; this._metrics = new Metrics(); this._options = options || { changeTimestamp: false }; // Create an object to store internal protected data this._metaData = {}; this._deferQueue = { insert: [], update: [], remove: [], upsert: [] }; this._deferThreshold = { insert: 100, update: 100, remove: 100, upsert: 100 }; this._deferTime = { insert: 1, update: 1, remove: 1, upsert: 1 }; this._deferredCalls = true; // Set the subset to itself since it is the root collection this.subsetOf(this); }; Shared.addModule('Collection', Collection); Shared.mixin(Collection.prototype, 'Mixin.Common'); Shared.mixin(Collection.prototype, 'Mixin.Events'); Shared.mixin(Collection.prototype, 'Mixin.ChainReactor'); Shared.mixin(Collection.prototype, 'Mixin.CRUD'); Shared.mixin(Collection.prototype, 'Mixin.Constants'); Shared.mixin(Collection.prototype, 'Mixin.Triggers'); Shared.mixin(Collection.prototype, 'Mixin.Sorting'); Shared.mixin(Collection.prototype, 'Mixin.Matching'); Shared.mixin(Collection.prototype, 'Mixin.Updating'); Shared.mixin(Collection.prototype, 'Mixin.Tags'); Metrics = _dereq_('./Metrics'); KeyValueStore = _dereq_('./KeyValueStore'); Path = _dereq_('./Path'); IndexHashMap = _dereq_('./IndexHashMap'); IndexBinaryTree = _dereq_('./IndexBinaryTree'); Crc = _dereq_('./Crc'); Db = Shared.modules.Db; Overload = _dereq_('./Overload'); ReactorIO = _dereq_('./ReactorIO'); /** * Returns a checksum of a string. * @param {String} string The string to checksum. * @return {String} The checksum generated. */ Collection.prototype.crc = Crc; /** * Gets / sets the deferred calls flag. If set to true (default) * then operations on large data sets can be broken up and done * over multiple CPU cycles (creating an async state). For purely * synchronous behaviour set this to false. * @param {Boolean=} val The value to set. * @returns {Boolean} */ Shared.synthesize(Collection.prototype, 'deferredCalls'); /** * Gets / sets the current state. * @param {String=} val The name of the state to set. * @returns {*} */ Shared.synthesize(Collection.prototype, 'state'); /** * Gets / sets the name of the collection. * @param {String=} val The name of the collection to set. * @returns {*} */ Shared.synthesize(Collection.prototype, 'name'); /** * Gets / sets the metadata stored in the collection. */ Shared.synthesize(Collection.prototype, 'metaData'); /** * Gets / sets boolean to determine if the collection should be * capped or not. */ Shared.synthesize(Collection.prototype, 'capped'); /** * Gets / sets capped collection size. This is the maximum number * of records that the capped collection will store. */ Shared.synthesize(Collection.prototype, 'cappedSize'); /** * Get the data array that represents the collection's data. * This data is returned by reference and should not be altered outside * of the provided CRUD functionality of the collection as doing so * may cause unstable index behaviour within the collection. * @returns {Array} */ Collection.prototype.data = function () { return this._data; }; /** * Drops a collection and all it's stored data from the database. * @returns {boolean} True on success, false on failure. */ Collection.prototype.drop = function (callback) { var key; if (!this.isDropped()) { if (this._db && this._db._collection && this._name) { if (this.debug()) { console.log(this.logIdentifier() + ' Dropping'); } this._state = 'dropped'; this.emit('drop', this); delete this._db._collection[this._name]; // Remove any reactor IO chain links if (this._collate) { for (key in this._collate) { if (this._collate.hasOwnProperty(key)) { this.collateRemove(key); } } } delete this._primaryKey; delete this._primaryIndex; delete this._primaryCrc; delete this._crcLookup; delete this._name; delete this._data; delete this._metrics; if (callback) { callback(false, true); } return true; } } else { if (callback) { callback(false, true); } return true; } if (callback) { callback(false, true); } return false; }; /** * Gets / sets the primary key for this collection. * @param {String=} keyName The name of the primary key. * @returns {*} */ Collection.prototype.primaryKey = function (keyName) { if (keyName !== undefined) { if (this._primaryKey !== keyName) { var oldKey = this._primaryKey; this._primaryKey = keyName; // Set the primary key index primary key this._primaryIndex.primaryKey(keyName); // Rebuild the primary key index this.rebuildPrimaryKeyIndex(); // Propagate change down the chain this.chainSend('primaryKey', keyName, {oldData: oldKey}); } return this; } return this._primaryKey; }; /** * Handles insert events and routes changes to binds and views as required. * @param {Array} inserted An array of inserted documents. * @param {Array} failed An array of documents that failed to insert. * @private */ Collection.prototype._onInsert = function (inserted, failed) { this.emit('insert', inserted, failed); }; /** * Handles update events and routes changes to binds and views as required. * @param {Array} items An array of updated documents. * @private */ Collection.prototype._onUpdate = function (items) { this.emit('update', items); }; /** * Handles remove events and routes changes to binds and views as required. * @param {Array} items An array of removed documents. * @private */ Collection.prototype._onRemove = function (items) { this.emit('remove', items); }; /** * Handles any change to the collection. * @private */ Collection.prototype._onChange = function () { if (this._options.changeTimestamp) { // Record the last change timestamp this._metaData.lastChange = new Date(); } }; /** * Gets / sets the db instance this class instance belongs to. * @param {Db=} db The db instance. * @returns {*} */ Shared.synthesize(Collection.prototype, 'db', function (db) { if (db) { if (this.primaryKey() === '_id') { // Set primary key to the db's key by default this.primaryKey(db.primaryKey()); // Apply the same debug settings this.debug(db.debug()); } } return this.$super.apply(this, arguments); }); /** * Gets / sets mongodb emulation mode. * @param {Boolean=} val True to enable, false to disable. * @returns {*} */ Shared.synthesize(Collection.prototype, 'mongoEmulation'); /** * Sets the collection's data to the array / documents passed. If any * data already exists in the collection it will be removed before the * new data is set. * @param {Array|Object} data The array of documents or a single document * that will be set as the collections data. * @param options Optional options object. * @param callback Optional callback function. */ Collection.prototype.setData = function (data, options, callback) { if (this.isDropped()) { throw(this.logIdentifier() + ' Cannot operate in a dropped state!'); } if (data) { var op = this._metrics.create('setData'); op.start(); options = this.options(options); this.preSetData(data, options, callback); if (options.$decouple) { data = this.decouple(data); } if (!(data instanceof Array)) { data = [data]; } op.time('transformIn'); data = this.transformIn(data); op.time('transformIn'); var oldData = [].concat(this._data); this._dataReplace(data); // Update the primary key index op.time('Rebuild Primary Key Index'); this.rebuildPrimaryKeyIndex(options); op.time('Rebuild Primary Key Index'); // Rebuild all other indexes op.time('Rebuild All Other Indexes'); this._rebuildIndexes(); op.time('Rebuild All Other Indexes'); op.time('Resolve chains'); this.chainSend('setData', data, {oldData: oldData}); op.time('Resolve chains'); op.stop(); this._onChange(); this.emit('setData', this._data, oldData); } if (callback) { callback(false); } return this; }; /** * Drops and rebuilds the primary key index for all documents in the collection. * @param {Object=} options An optional options object. * @private */ Collection.prototype.rebuildPrimaryKeyIndex = function (options) { options = options || { $ensureKeys: undefined, $violationCheck: undefined }; var ensureKeys = options && options.$ensureKeys !== undefined ? options.$ensureKeys : true, violationCheck = options && options.$violationCheck !== undefined ? options.$violationCheck : true, arr, arrCount, arrItem, pIndex = this._primaryIndex, crcIndex = this._primaryCrc, crcLookup = this._crcLookup, pKey = this._primaryKey, jString; // Drop the existing primary index pIndex.truncate(); crcIndex.truncate(); crcLookup.truncate(); // Loop the data and check for a primary key in each object arr = this._data; arrCount = arr.length; while (arrCount--) { arrItem = arr[arrCount]; if (ensureKeys) { // Make sure the item has a primary key this.ensurePrimaryKey(arrItem); } if (violationCheck) { // Check for primary key violation if (!pIndex.uniqueSet(arrItem[pKey], arrItem)) { // Primary key violation throw(this.logIdentifier() + ' Call to setData on collection failed because your data violates the primary key unique constraint. One or more documents are using the same primary key: ' + arrItem[this._primaryKey]); } } else { pIndex.set(arrItem[pKey], arrItem); } // Generate a CRC string jString = this.jStringify(arrItem); crcIndex.set(arrItem[pKey], jString); crcLookup.set(jString, arrItem); } }; /** * Checks for a primary key on the document and assigns one if none * currently exists. * @param {Object} obj The object to check a primary key against. * @private */ Collection.prototype.ensurePrimaryKey = function (obj) { if (obj[this._primaryKey] === undefined) { // Assign a primary key automatically obj[this._primaryKey] = this.objectId(); } }; /** * Clears all data from the collection. * @returns {Collection} */ Collection.prototype.truncate = function () { if (this.isDropped()) { throw(this.logIdentifier() + ' Cannot operate in a dropped state!'); } this.emit('truncate', this._data); // Clear all the data from the collection this._data.length = 0; // Re-create the primary index data this._primaryIndex = new KeyValueStore('primary'); this._primaryCrc = new KeyValueStore('primaryCrc'); this._crcLookup = new KeyValueStore('crcLookup'); this._onChange(); this.deferEmit('change', {type: 'truncate'}); return this; }; /** * Modifies an existing document or documents in a collection. This will update * all matches for 'query' with the data held in 'update'. It will not overwrite * the matched documents with the update document. * * @param {Object} obj The document object to upsert or an array containing * documents to upsert. * * If the document contains a primary key field (based on the collections's primary * key) then the database will search for an existing document with a matching id. * If a matching document is found, the document will be updated. Any keys that * match keys on the existing document will be overwritten with new data. Any keys * that do not currently exist on the document will be added to the document. * * If the document does not contain an id or the id passed does not match an existing * document, an insert is performed instead. If no id is present a new primary key * id is provided for the item. * * @param {Function=} callback Optional callback method. * @returns {Object} An object containing two keys, "op" contains either "insert" or * "update" depending on the type of operation that was performed and "result" * contains the return data from the operation used. */ Collection.prototype.upsert = function (obj, callback) { if (this.isDropped()) { throw(this.logIdentifier() + ' Cannot operate in a dropped state!'); } if (obj) { var queue = this._deferQueue.upsert, deferThreshold = this._deferThreshold.upsert, returnData = {}, query, i; // Determine if the object passed is an array or not if (obj instanceof Array) { if (this._deferredCalls && obj.length > deferThreshold) { // Break up upsert into blocks this._deferQueue.upsert = queue.concat(obj); // Fire off the insert queue handler this.processQueue('upsert', callback); return {}; } else { // Loop the array and upsert each item returnData = []; for (i = 0; i < obj.length; i++) { returnData.push(this.upsert(obj[i])); } if (callback) { callback(); } return returnData; } } // Determine if the operation is an insert or an update if (obj[this._primaryKey]) { // Check if an object with this primary key already exists query = {}; query[this._primaryKey] = obj[this._primaryKey]; if (this._primaryIndex.lookup(query)[0]) { // The document already exists with this id, this operation is an update returnData.op = 'update'; } else { // No document with this id exists, this operation is an insert returnData.op = 'insert'; } } else { // The document passed does not contain an id, this operation is an insert returnData.op = 'insert'; } switch (returnData.op) { case 'insert': returnData.result = this.insert(obj); break; case 'update': returnData.result = this.update(query, obj); break; default: break; } return returnData; } else { if (callback) { callback(); } } return {}; }; /** * Executes a method against each document that matches query and returns an * array of documents that may have been modified by the method. * @param {Object} query The query object. * @param {Function} func The method that each document is passed to. If this method * returns false for a particular document it is excluded from the results. * @param {Object=} options Optional options object. * @returns {Array} */ Collection.prototype.filter = function (query, func, options) { return (this.find(query, options)).filter(func); }; /** * Executes a method against each document that matches query and then executes * an update based on the return data of the method. * @param {Object} query The query object. * @param {Function} func The method that each document is passed to. If this method * returns false for a particular document it is excluded from the update. * @param {Object=} options Optional options object passed to the initial find call. * @returns {Array} */ Collection.prototype.filterUpdate = function (query, func, options) { var items = this.find(query, options), results = [], singleItem, singleQuery, singleUpdate, pk = this.primaryKey(), i; for (i = 0; i < items.length; i++) { singleItem = items[i]; singleUpdate = func(singleItem); if (singleUpdate) { singleQuery = {}; singleQuery[pk] = singleItem[pk]; results.push(this.update(singleQuery, singleUpdate)); } } return results; }; /** * Modifies an existing document or documents in a collection. This will update * all matches for 'query' with the data held in 'update'. It will not overwrite * the matched documents with the update document. * * @param {Object} query The query that must be matched for a document to be * operated on. * @param {Object} update The object containing updated key/values. Any keys that * match keys on the existing document will be overwritten with this data. Any * keys that do not currently exist on the document will be added to the document. * @param {Object=} options An options object. * @returns {Array} The items that were updated. */ Collection.prototype.update = function (query, update, options) { if (this.isDropped()) { throw(this.logIdentifier() + ' Cannot operate in a dropped state!'); } // Decouple the update data update = this.decouple(update); // Convert queries from mongo dot notation to forerunner queries if (this.mongoEmulation()) { this.convertToFdb(query); this.convertToFdb(update); } // Handle transform update = this.transformIn(update); if (this.debug()) { console.log(this.logIdentifier() + ' Updating some data'); } var self = this, op = this._metrics.create('update'), dataSet, updated, updateCall = function (referencedDoc) { var oldDoc = self.decouple(referencedDoc), newDoc, triggerOperation, result; if (self.willTrigger(self.TYPE_UPDATE, self.PHASE_BEFORE) || self.willTrigger(self.TYPE_UPDATE, self.PHASE_AFTER)) { newDoc = self.decouple(referencedDoc); triggerOperation = { type: 'update', query: self.decouple(query), update: self.decouple(update), options: self.decouple(options), op: op }; // Update newDoc with the update criteria so we know what the data will look // like AFTER the update is processed result = self.updateObject(newDoc, triggerOperation.update, triggerOperation.query, triggerOperation.options, ''); if (self.processTrigger(triggerOperation, self.TYPE_UPDATE, self.PHASE_BEFORE, referencedDoc, newDoc) !== false) { // No triggers complained so let's execute the replacement of the existing // object with the new one result = self.updateObject(referencedDoc, newDoc, triggerOperation.query, triggerOperation.options, ''); // NOTE: If for some reason we would only like to fire this event if changes are actually going // to occur on the object from the proposed update then we can add "result &&" to the if self.processTrigger(triggerOperation, self.TYPE_UPDATE, self.PHASE_AFTER, oldDoc, newDoc); } else { // Trigger cancelled operation so tell result that it was not updated result = false; } } else { // No triggers complained so let's execute the replacement of the existing // object with the new one result = self.updateObject(referencedDoc, update, query, options, ''); } // Inform indexes of the change self._updateIndexes(oldDoc, referencedDoc); return result; }; op.start(); op.time('Retrieve documents to update'); dataSet = this.find(query, {$decouple: false}); op.time('Retrieve documents to update'); if (dataSet.length) { op.time('Update documents'); updated = dataSet.filter(updateCall); op.time('Update documents'); if (updated.length) { op.time('Resolve chains'); this.chainSend('update', { query: query, update: update, dataSet: updated }, options); op.time('Resolve chains'); this._onUpdate(updated); this._onChange(); this.deferEmit('change', {type: 'update', data: updated}); } } op.stop(); // TODO: Should we decouple the updated array before return by default? return updated || []; }; /** * Replaces an existing object with data from the new object without * breaking data references. * @param {Object} currentObj The object to alter. * @param {Object} newObj The new object to overwrite the existing one with. * @returns {*} Chain. * @private */ Collection.prototype._replaceObj = function (currentObj, newObj) { var i; // Check if the new document has a different primary key value from the existing one // Remove item from indexes this._removeFromIndexes(currentObj); // Remove existing keys from current object for (i in currentObj) { if (currentObj.hasOwnProperty(i)) { delete currentObj[i]; } } // Add new keys to current object for (i in newObj) { if (newObj.hasOwnProperty(i)) { currentObj[i] = newObj[i]; } } // Update the item in the primary index if (!this._insertIntoIndexes(currentObj)) { throw(this.logIdentifier() + ' Primary key violation in update! Key violated: ' + currentObj[this._primaryKey]); } // Update the object in the collection data //this._data.splice(this._data.indexOf(currentObj), 1, newObj); return this; }; /** * Helper method to update a document from it's id. * @param {String} id The id of the document. * @param {Object} update The object containing the key/values to update to. * @returns {Array} The items that were updated. */ Collection.prototype.updateById = function (id, update) { var searchObj = {}; searchObj[this._primaryKey] = id; return this.update(searchObj, update); }; /** * Internal method for document updating. * @param {Object} doc The document to update. * @param {Object} update The object with key/value pairs to update the document with. * @param {Object} query The query object that we need to match to perform an update. * @param {Object} options An options object. * @param {String} path The current recursive path. * @param {String} opType The type of update operation to perform, if none is specified * default is to set new data against matching fields. * @returns {Boolean} True if the document was updated with new / changed data or * false if it was not updated because the data was the same. * @private */ Collection.prototype.updateObject = function (doc, update, query, options, path, opType) { // TODO: This method is long, try to break it into smaller pieces update = this.decouple(update); // Clear leading dots from path path = path || ''; if (path.substr(0, 1) === '.') { path = path.substr(1, path.length -1); } //var oldDoc = this.decouple(doc), var updated = false, recurseUpdated = false, operation, tmpArray, tmpIndex, tmpCount, tempIndex, pathInstance, sourceIsArray, updateIsArray, i; // Loop each key in the update object for (i in update) { if (update.hasOwnProperty(i)) { // Reset operation flag operation = false; // Check if the property starts with a dollar (function) if (i.substr(0, 1) === '$') { // Check for commands switch (i) { case '$key': case '$index': case '$data': case '$min': case '$max': // Ignore some operators operation = true; break; case '$each': operation = true; // Loop over the array of updates and run each one tmpCount = update.$each.length; for (tmpIndex = 0; tmpIndex < tmpCount; tmpIndex++) { recurseUpdated = this.updateObject(doc, update.$each[tmpIndex], query, options, path); if (recurseUpdated) { updated = true; } } updated = updated || recurseUpdated; break; default: operation = true; // Now run the operation recurseUpdated = this.updateObject(doc, update[i], query, options, path, i); updated = updated || recurseUpdated; break; } } // Check if the key has a .$ at the end, denoting an array lookup if (this._isPositionalKey(i)) { operation = true; // Modify i to be the name of the field i = i.substr(0, i.length - 2); pathInstance = new Path(path + '.' + i); // Check if the key is an array and has items if (doc[i] && doc[i] instanceof Array && doc[i].length) { tmpArray = []; // Loop the array and find matches to our search for (tmpIndex = 0; tmpIndex < doc[i].length; tmpIndex++) { if (this._match(doc[i][tmpIndex], pathInstance.value(query)[0], options, '', {})) { tmpArray.push(tmpIndex); } } // Loop the items that matched and update them for (tmpIndex = 0; tmpIndex < tmpArray.length; tmpIndex++) { recurseUpdated = this.updateObject(doc[i][tmpArray[tmpIndex]], update[i + '.$'], query, options, path + '.' + i, opType); updated = updated || recurseUpdated; } } } if (!operation) { if (!opType && typeof(update[i]) === 'object') { if (doc[i] !== null && typeof(doc[i]) === 'object') { // Check if we are dealing with arrays sourceIsArray = doc[i] instanceof Array; updateIsArray = update[i] instanceof Array; if (sourceIsArray || updateIsArray) { // Check if the update is an object and the doc is an array if (!updateIsArray && sourceIsArray) { // Update is an object, source is an array so match the array items // with our query object to find the one to update inside this array // Loop the array and find matches to our search for (tmpIndex = 0; tmpIndex < doc[i].length; tmpIndex++) { recurseUpdated = this.updateObject(doc[i][tmpIndex], update[i], query, options, path + '.' + i, opType); updated = updated || recurseUpdated; } } else { // Either both source and update are arrays or the update is // an array and the source is not, so set source to update if (doc[i] !== update[i]) { this._updateProperty(doc, i, update[i]); updated = true; } } } else { // The doc key is an object so traverse the // update further recurseUpdated = this.updateObject(doc[i], update[i], query, options, path + '.' + i, opType); updated = updated || recurseUpdated; } } else { if (doc[i] !== update[i]) { this._updateProperty(doc, i, update[i]); updated = true; } } } else { switch (opType) { case '$inc': var doUpdate = true; // Check for a $min / $max operator if (update[i] > 0) { if (update.$max) { // Check current value if (doc[i] >= update.$max) { // Don't update doUpdate = false; } } } else if (update[i] < 0) { if (update.$min) { // Check current value if (doc[i] <= update.$min) { // Don't update doUpdate = false; } } } if (doUpdate) { this._updateIncrement(doc, i, update[i]); updated = true; } break; case '$cast': // Casts a property to the type specified if it is not already // that type. If the cast is an array or an object and the property // is not already that type a new array or object is created and // set to the property, overwriting the previous value switch (update[i]) { case 'array': if (!(doc[i] instanceof Array)) { // Cast to an array this._updateProperty(doc, i, update.$data || []); updated = true; } break; case 'object': if (!(doc[i] instanceof Object) || (doc[i] instanceof Array)) { // Cast to an object this._updateProperty(doc, i, update.$data || {}); updated = true; } break; case 'number': if (typeof doc[i] !== 'number') { // Cast to a number this._updateProperty(doc, i, Number(doc[i])); updated = true; } break; case 'string': if (typeof doc[i] !== 'string') { // Cast to a string this._updateProperty(doc, i, String(doc[i])); updated = true; } break; default: throw(this.logIdentifier() + ' Cannot update cast to unknown type: ' + update[i]); } break; case '$push': // Check if the target key is undefined and if so, create an array if (doc[i] === undefined) { // Initialise a new array this._updateProperty(doc, i, []); } // Check that the target key is an array if (doc[i] instanceof Array) { // Check for a $position modifier with an $each if (update[i].$position !== undefined && update[i].$each instanceof Array) { // Grab the position to insert at tempIndex = update[i].$position; // Loop the each array and push each item tmpCount = update[i].$each.length; for (tmpIndex = 0; tmpIndex < tmpCount; tmpIndex++) { this._updateSplicePush(doc[i], tempIndex + tmpIndex, update[i].$each[tmpIndex]); } } else if (update[i].$each instanceof Array) { // Do a loop over the each to push multiple items tmpCount = update[i].$each.length; for (tmpIndex = 0; tmpIndex < tmpCount; tmpIndex++) { this._updatePush(doc[i], update[i].$each[tmpIndex]); } } else { // Do a standard push this._updatePush(doc[i], update[i]); } updated = true; } else { throw(this.logIdentifier() + ' Cannot push to a key that is not an array! (' + i + ')'); } break; case '$pull': if (doc[i] instanceof Array) { tmpArray = []; // Loop the array and find matches to our search for (tmpIndex = 0; tmpIndex < doc[i].length; tmpIndex++) { if (this._match(doc[i][tmpIndex], update[i], options, '', {})) { tmpArray.push(tmpIndex); } } tmpCount = tmpArray.length; // Now loop the pull array and remove items to be pulled while (tmpCount--) { this._updatePull(doc[i], tmpArray[tmpCount]); updated = true; } } break; case '$pullAll': if (doc[i] instanceof Array) { if (update[i] instanceof Array) { tmpArray = doc[i]; tmpCount = tmpArray.length; if (tmpCount > 0) { // Now loop the pull array and remove items to be pulled while (tmpCount--) { for (tempIndex = 0; tempIndex < update[i].length; tempIndex++) { if (tmpArray[tmpCount] === update[i][tempIndex]) { this._updatePull(doc[i], tmpCount); tmpCount--; updated = true; } } if (tmpCount < 0) { break; } } } } else { throw(this.logIdentifier() + ' Cannot pullAll without being given an array of values to pull! (' + i + ')'); } } break; case '$addToSet': // Check if the target key is undefined and if so, create an array if (doc[i] === undefined) { // Initialise a new array this._updateProperty(doc, i, []); } // Check that the target key is an array if (doc[i] instanceof Array) { // Loop the target array and check for existence of item var targetArr = doc[i], targetArrIndex, targetArrCount = targetArr.length, objHash, addObj = true, optionObj = (options && options.$addToSet), hashMode, pathSolver; // Check if we have an options object for our operation if (update[i].$key) { hashMode = false; pathSolver = new Path(update[i].$key); objHash = pathSolver.value(update[i])[0]; // Remove the key from the object before we add it delete update[i].$key; } else if (optionObj && optionObj.key) { hashMode = false; pathSolver = new Path(optionObj.key); objHash = pathSolver.value(update[i])[0]; } else { objHash = this.jStringify(update[i]); hashMode = true; } for (targetArrIndex = 0; targetArrIndex < targetArrCount; targetArrIndex++) { if (hashMode) { // Check if objects match via a string hash (JSON) if (this.jStringify(targetArr[targetArrIndex]) === objHash) { // The object already exists, don't add it addObj = false; break; } } else { // Check if objects match based on the path if (objHash === pathSolver.value(targetArr[targetArrIndex])[0]) { // The object already exists, don't add it addObj = false; break; } } } if (addObj) { this._updatePush(doc[i], update[i]); updated = true; } } else { throw(this.logIdentifier() + ' Cannot addToSet on a key that is not an array! (' + i + ')'); } break; case '$splicePush': // Check if the target key is undefined and if so, create an array if (doc[i] === undefined) { // Initialise a new array this._updateProperty(doc, i, []); } // Check that the target key is an array if (doc[i] instanceof Array) { tempIndex = update.$index; if (tempIndex !== undefined) { delete update.$index; // Check for out of bounds index if (tempIndex > doc[i].length) { tempIndex = doc[i].length; } this._updateSplicePush(doc[i], tempIndex, update[i]); updated = true; } else { throw(this.logIdentifier() + ' Cannot splicePush without a $index integer value!'); } } else { throw(this.logIdentifier() + ' Cannot splicePush with a key that is not an array! (' + i + ')'); } break; case '$move': if (doc[i] instanceof Array) { // Loop the array and find matches to our search for (tmpIndex = 0; tmpIndex < doc[i].length; tmpIndex++) { if (this._match(doc[i][tmpIndex], update[i], options, '', {})) { var moveToIndex = update.$index; if (moveToIndex !== undefined) { delete update.$index; this._updateSpliceMove(doc[i], tmpIndex, moveToIndex); updated = true; } else { throw(this.logIdentifier() + ' Cannot move without a $index integer value!'); } break; } } } else { throw(this.logIdentifier() + ' Cannot move on a key that is not an array! (' + i + ')'); } break; case '$mul': this._updateMultiply(doc, i, update[i]); updated = true; break; case '$rename': this._updateRename(doc, i, update[i]); updated = true; break; case '$overwrite': this._updateOverwrite(doc, i, update[i]); updated = true; break; case '$unset': this._updateUnset(doc, i); updated = true; break; case '$clear': this._updateClear(doc, i); updated = true; break; case '$pop': if (doc[i] instanceof Array) { if (this._updatePop(doc[i], update[i])) { updated = true; } } else { throw(this.logIdentifier() + ' Cannot pop from a key that is not an array! (' + i + ')'); } break; case '$toggle': // Toggle the boolean property between true and false this._updateProperty(doc, i, !doc[i]); updated = true; break; default: if (doc[i] !== update[i]) { this._updateProperty(doc, i, update[i]); updated = true; } break; } } } } } return updated; }; /** * Determines if the passed key has an array positional mark (a dollar at the end * of its name). * @param {String} key The key to check. * @returns {Boolean} True if it is a positional or false if not. * @private */ Collection.prototype._isPositionalKey = function (key) { return key.substr(key.length - 2, 2) === '.$'; }; /** * Removes any documents from the collection that match the search query * key/values. * @param {Object} query The query object. * @param {Object=} options An options object. * @param {Function=} callback A callback method. * @returns {Array} An array of the documents that were removed. */ Collection.prototype.remove = function (query, options, callback) { if (this.isDropped()) { throw(this.logIdentifier() + ' Cannot operate in a dropped state!'); } var self = this, dataSet, index, arrIndex, returnArr, removeMethod, triggerOperation, doc, newDoc; if (typeof(options) === 'function') { callback = options; options = {}; } // Convert queries from mongo dot notation to forerunner queries if (this.mongoEmulation()) { this.convertToFdb(query); } if (query instanceof Array) { returnArr = []; for (arrIndex = 0; arrIndex < query.length; arrIndex++) { returnArr.push(this.remove(query[arrIndex], {noEmit: true})); } if (!options || (options && !options.noEmit)) { this._onRemove(returnArr); } if (callback) { callback(false, returnArr); } return returnArr; } else { returnArr = []; dataSet = this.find(query, {$decouple: false}); if (dataSet.length) { removeMethod = function (dataItem) { // Remove the item from the collection's indexes self._removeFromIndexes(dataItem); // Remove data from internal stores index = self._data.indexOf(dataItem); self._dataRemoveAtIndex(index); returnArr.push(dataItem); }; // Remove the data from the collection for (var i = 0; i < dataSet.length; i++) { doc = dataSet[i]; if (self.willTrigger(self.TYPE_REMOVE, self.PHASE_BEFORE) || self.willTrigger(self.TYPE_REMOVE, self.PHASE_AFTER)) { triggerOperation = { type: 'remove' }; newDoc = self.decouple(doc); if (self.processTrigger(triggerOperation, self.TYPE_REMOVE, self.PHASE_BEFORE, newDoc, newDoc) !== false) { // The trigger didn't ask to cancel so execute the removal method removeMethod(doc); self.processTrigger(triggerOperation, self.TYPE_REMOVE, self.PHASE_AFTER, newDoc, newDoc); } } else { // No triggers to execute removeMethod(doc); } } if (returnArr.length) { //op.time('Resolve chains'); self.chainSend('remove', { query: query, dataSet: returnArr }, options); //op.time('Resolve chains'); if (!options || (options && !options.noEmit)) { this._onRemove(returnArr); } this._onChange(); this.deferEmit('change', {type: 'remove', data: returnArr}); } } if (callback) { callback(false, returnArr); } return returnArr; } }; /** * Helper method that removes a document that matches the given id. * @param {String} id The id of the document to remove. * @returns {Array} An array of documents that were removed. */ Collection.prototype.removeById = function (id) { var searchObj = {}; searchObj[this._primaryKey] = id; return this.remove(searchObj); }; /** * Processes a deferred action queue. * @param {String} type The queue name to process. * @param {Function} callback A method to call when the queue has processed. * @param {Object=} resultObj A temp object to hold results in. */ Collection.prototype.processQueue = function (type, callback, resultObj) { var self = this, queue = this._deferQueue[type], deferThreshold = this._deferThreshold[type], deferTime = this._deferTime[type], dataArr, result; resultObj = resultObj || { deferred: true }; if (queue.length) { // Process items up to the threshold if (queue.length) { if (queue.length > deferThreshold) { // Grab items up to the threshold value dataArr = queue.splice(0, deferThreshold); } else { // Grab all the remaining items dataArr = queue.splice(0, queue.length); } result = self[type](dataArr); switch (type) { case 'insert': resultObj.inserted = resultObj.inserted || []; resultObj.failed = resultObj.failed || []; resultObj.inserted = resultObj.inserted.concat(result.inserted); resultObj.failed = resultObj.failed.concat(result.failed); break; } } // Queue another process setTimeout(function () { self.processQueue.call(self, type, callback, resultObj); }, deferTime); } else { if (callback) { callback(resultObj); } } // Check if all queues are complete if (!this.isProcessingQueue()) { this.emit('queuesComplete'); } }; /** * Checks if any CRUD operations have been deferred and are still waiting to * be processed. * @returns {Boolean} True if there are still deferred CRUD operations to process * or false if all queues are clear. */ Collection.prototype.isProcessingQueue = function () { var i; for (i in this._deferQueue) { if (this._deferQueue.hasOwnProperty(i)) { if (this._deferQueue[i].length) { return true; } } } return false; }; /** * Inserts a document or array of documents into the collection. * @param {Object|Array} data Either a document object or array of document * @param {Number=} index Optional index to insert the record at. * @param {Function=} callback Optional callback called once action is complete. * objects to insert into the collection. */ Collection.prototype.insert = function (data, index, callback) { if (this.isDropped()) { throw(this.logIdentifier() + ' Cannot operate in a dropped state!'); } if (typeof(index) === 'function') { callback = index; index = this._data.length; } else if (index === undefined) { index = this._data.length; } data = this.transformIn(data); return this._insertHandle(data, index, callback); }; /** * Inserts a document or array of documents into the collection. * @param {Object|Array} data Either a document object or array of document * @param {Number=} index Optional index to insert the record at. * @param {Function=} callback Optional callback called once action is complete. * objects to insert into the collection. */ Collection.prototype._insertHandle = function (data, index, callback) { var //self = this, queue = this._deferQueue.insert, deferThreshold = this._deferThreshold.insert, //deferTime = this._deferTime.insert, inserted = [], failed = [], insertResult, resultObj, i; if (data instanceof Array) { // Check if there are more insert items than the insert defer // threshold, if so, break up inserts so we don't tie up the // ui or thread if (this._deferredCalls && data.length > deferThreshold) { // Break up insert into blocks this._deferQueue.insert = queue.concat(data); // Fire off the insert queue handler this.processQueue('insert', callback); return; } else { // Loop the array and add items for (i = 0; i < data.length; i++) { insertResult = this._insert(data[i], index + i); if (insertResult === true) { inserted.push(data[i]); } else { failed.push({ doc: data[i], reason: insertResult }); } } } } else { // Store the data item insertResult = this._insert(data, index); if (insertResult === true) { inserted.push(data); } else { failed.push({ doc: data, reason: insertResult }); } } resultObj = { deferred: false, inserted: inserted, failed: failed }; this._onInsert(inserted, failed); if (callback) { callback(resultObj); } this._onChange(); this.deferEmit('change', {type: 'insert', data: inserted}); return resultObj; }; /** * Internal method to insert a document into the collection. Will * check for index violations before allowing the document to be inserted. * @param {Object} doc The document to insert after passing index violation * tests. * @param {Number=} index Optional index to insert the document at. * @returns {Boolean|Object} True on success, false if no document passed, * or an object containing details about an index violation if one occurred. * @private */ Collection.prototype._insert = function (doc, index) { if (doc) { var self = this, indexViolation, triggerOperation, insertMethod, newDoc, capped = this.capped(), cappedSize = this.cappedSize(); this.ensurePrimaryKey(doc); // Check indexes are not going to be broken by the document indexViolation = this.insertIndexViolation(doc); insertMethod = function (doc) { // Add the item to the collection's indexes self._insertIntoIndexes(doc); // Check index overflow if (index > self._data.length) { index = self._data.length; } // Insert the document self._dataInsertAtIndex(index, doc); // Check capped collection status and remove first record // if we are over the threshold if (capped && self._data.length > cappedSize) { // Remove the first item in the data array self.removeById(self._data[0][self._primaryKey]); } //op.time('Resolve chains'); self.chainSend('insert', doc, {index: index}); //op.time('Resolve chains'); }; if (!indexViolation) { if (self.willTrigger(self.TYPE_INSERT, self.PHASE_BEFORE) || self.willTrigger(self.TYPE_INSERT, self.PHASE_AFTER)) { triggerOperation = { type: 'insert' }; if (self.processTrigger(triggerOperation, self.TYPE_INSERT, self.PHASE_BEFORE, {}, doc) !== false) { insertMethod(doc); if (self.willTrigger(self.TYPE_INSERT, self.PHASE_AFTER)) { // Clone the doc so that the programmer cannot update the internal document // on the "after" phase trigger newDoc = self.decouple(doc); self.processTrigger(triggerOperation, self.TYPE_INSERT, self.PHASE_AFTER, {}, newDoc); } } else { // The trigger just wants to cancel the operation return 'Trigger cancelled operation'; } } else { // No triggers to execute insertMethod(doc); } return true; } else { return 'Index violation in index: ' + indexViolation; } } return 'No document passed to insert'; }; /** * Inserts a document into the internal collection data array at * Inserts a document into the internal collection data array at * the specified index. * @param {number} index The index to insert at. * @param {object} doc The document to insert. * @private */ Collection.prototype._dataInsertAtIndex = function (index, doc) { this._data.splice(index, 0, doc); }; /** * Removes a document from the internal collection data array at * the specified index. * @param {number} index The index to remove from. * @private */ Collection.prototype._dataRemoveAtIndex = function (index) { this._data.splice(index, 1); }; /** * Replaces all data in the collection's internal data array with * the passed array of data. * @param {array} data The array of data to replace existing data with. * @private */ Collection.prototype._dataReplace = function (data) { // Clear the array - using a while loop with pop is by far the // fastest way to clear an array currently while (this._data.length) { this._data.pop(); } // Append new items to the array this._data = this._data.concat(data); }; /** * Inserts a document into the collection indexes. * @param {Object} doc The document to insert. * @private */ Collection.prototype._insertIntoIndexes = function (doc) { var arr = this._indexByName, arrIndex, violated, jString = this.jStringify(doc); // Insert to primary key index violated = this._primaryIndex.uniqueSet(doc[this._primaryKey], doc); this._primaryCrc.uniqueSet(doc[this._primaryKey], jString); this._crcLookup.uniqueSet(jString, doc); // Insert into other indexes for (arrIndex in arr) { if (arr.hasOwnProperty(arrIndex)) { arr[arrIndex].insert(doc); } } return violated; }; /** * Removes a document from the collection indexes. * @param {Object} doc The document to remove. * @private */ Collection.prototype._removeFromIndexes = function (doc) { var arr = this._indexByName, arrIndex, jString = this.jStringify(doc); // Remove from primary key index this._primaryIndex.unSet(doc[this._primaryKey]); this._primaryCrc.unSet(doc[this._primaryKey]); this._crcLookup.unSet(jString); // Remove from other indexes for (arrIndex in arr) { if (arr.hasOwnProperty(arrIndex)) { arr[arrIndex].remove(doc); } } }; /** * Updates collection index data for the passed document. * @param {Object} oldDoc The old document as it was before the update. * @param {Object} newDoc The document as it now is after the update. * @private */ Collection.prototype._updateIndexes = function (oldDoc, newDoc) { this._removeFromIndexes(oldDoc); this._insertIntoIndexes(newDoc); }; /** * Rebuild collection indexes. * @private */ Collection.prototype._rebuildIndexes = function () { var arr = this._indexByName, arrIndex; // Remove from other indexes for (arrIndex in arr) { if (arr.hasOwnProperty(arrIndex)) { arr[arrIndex].rebuild(); } } }; /** * Uses the passed query to generate a new collection with results * matching the query parameters. * * @param {Object} query The query object to generate the subset with. * @param {Object=} options An options object. * @returns {*} */ Collection.prototype.subset = function (query, options) { var result = this.find(query, options); return new Collection() .subsetOf(this) .primaryKey(this._primaryKey) .setData(result); }; /** * Gets / sets the collection that this collection is a subset of. * @param {Collection=} collection The collection to set as the parent of this subset. * @returns {Collection} */ Shared.synthesize(Collection.prototype, 'subsetOf'); /** * Checks if the collection is a subset of the passed collection. * @param {Collection} collection The collection to test against. * @returns {Boolean} True if the passed collection is the parent of * the current collection. */ Collection.prototype.isSubsetOf = function (collection) { return this._subsetOf === collection; }; /** * Find the distinct values for a specified field across a single collection and * returns the results in an array. * @param {String} key The field path to return distinct values for e.g. "person.name". * @param {Object=} query The query to use to filter the documents used to return values from. * @param {Object=} options The query options to use when running the query. * @returns {Array} */ Collection.prototype.distinct = function (key, query, options) { if (this.isDropped()) { throw(this.logIdentifier() + ' Cannot operate in a dropped state!'); } var data = this.find(query, options), pathSolver = new Path(key), valueUsed = {}, distinctValues = [], value, i; // Loop the data and build array of distinct values for (i = 0; i < data.length; i++) { value = pathSolver.value(data[i])[0]; if (value && !valueUsed[value]) { valueUsed[value] = true; distinctValues.push(value); } } return distinctValues; }; /** * Helper method to find a document by it's id. * @param {String} id The id of the document. * @param {Object=} options The options object, allowed keys are sort and limit. * @returns {Array} The items that were updated. */ Collection.prototype.findById = function (id, options) { var searchObj = {}; searchObj[this._primaryKey] = id; return this.find(searchObj, options)[0]; }; /** * Finds all documents that contain the passed string or search object * regardless of where the string might occur within the document. This * will match strings from the start, middle or end of the document's * string (partial match). * @param search The string to search for. Case sensitive. * @param options A standard find() options object. * @returns {Array} An array of documents that matched the search string. */ Collection.prototype.peek = function (search, options) { // Loop all items var arr = this._data, arrCount = arr.length, arrIndex, arrItem, tempColl = new Collection(), typeOfSearch = typeof search; if (typeOfSearch === 'string') { for (arrIndex = 0; arrIndex < arrCount; arrIndex++) { // Get json representation of object arrItem = this.jStringify(arr[arrIndex]); // Check if string exists in object json if (arrItem.indexOf(search) > -1) { // Add this item to the temp collection tempColl.insert(arr[arrIndex]); } } return tempColl.find({}, options); } else { return this.find(search, options); } }; /** * Provides a query plan / operations log for a query. * @param {Object} query The query to execute. * @param {Object=} options Optional options object. * @returns {Object} The query plan. */ Collection.prototype.explain = function (query, options) { var result = this.find(query, options); return result.__fdbOp._data; }; /** * Generates an options object with default values or adds default * values to a passed object if those values are not currently set * to anything. * @param {object=} obj Optional options object to modify. * @returns {object} The options object. */ Collection.prototype.options = function (obj) { obj = obj || {}; obj.$decouple = obj.$decouple !== undefined ? obj.$decouple : true; obj.$explain = obj.$explain !== undefined ? obj.$explain : false; return obj; }; /** * Queries the collection based on the query object passed. * @param {Object} query The query key/values that a document must match in * order for it to be returned in the result array. * @param {Object=} options An optional options object. * @param {Function=} callback !! DO NOT USE, THIS IS NON-OPERATIONAL !! * Optional callback. If specified the find process * will not return a value and will assume that you wish to operate under an * async mode. This will break up large find requests into smaller chunks and * process them in a non-blocking fashion allowing large datasets to be queried * without causing the browser UI to pause. Results from this type of operation * will be passed back to the callback once completed. * * @returns {Array} The results array from the find operation, containing all * documents that matched the query. */ Collection.prototype.find = function (query, options, callback) { // Convert queries from mongo dot notation to forerunner queries if (this.mongoEmulation()) { this.convertToFdb(query); } if (callback) { // Check the size of the collection's data array // Split operation into smaller tasks and callback when complete callback('Callbacks for the find() operation are not yet implemented!', []); return []; } return this._find.apply(this, arguments); }; Collection.prototype._find = function (query, options) { if (this.isDropped()) { throw(this.logIdentifier() + ' Cannot operate in a dropped state!'); } // TODO: This method is quite long, break into smaller pieces query = query || {}; options = this.options(options); var op = this._metrics.create('find'), pk = this.primaryKey(), self = this, analysis, scanLength, requiresTableScan = true, resultArr, joinCollectionIndex, joinIndex, joinCollection = {}, joinQuery, joinPath, joinCollectionName, joinCollectionInstance, joinMatch, joinMatchIndex, joinSearchQuery, joinSearchOptions, joinMulti, joinRequire, joinFindResults, joinFindResult, joinItem, joinPrefix, resultCollectionName, resultIndex, resultRemove = [], index, i, j, k, l, fieldListOn = [], fieldListOff = [], elemMatchPathSolver, elemMatchSubArr, elemMatchSpliceArr, matcherTmpOptions = {}, result, cursor = {}, pathSolver, //renameFieldMethod, //renameFieldPath, matcher = function (doc) { return self._match(doc, query, options, 'and', matcherTmpOptions); }; op.start(); if (query) { // Get query analysis to execute best optimised code path op.time('analyseQuery'); analysis = this._analyseQuery(self.decouple(query), options, op); op.time('analyseQuery'); op.data('analysis', analysis); if (analysis.hasJoin && analysis.queriesJoin) { // The query has a join and tries to limit by it's joined data // Get an instance reference to the join collections op.time('joinReferences'); for (joinIndex = 0; joinIndex < analysis.joinsOn.length; joinIndex++) { joinCollectionName = analysis.joinsOn[joinIndex]; joinPath = new Path(analysis.joinQueries[joinCollectionName]); joinQuery = joinPath.value(query)[0]; joinCollection[analysis.joinsOn[joinIndex]] = this._db.collection(analysis.joinsOn[joinIndex]).subset(joinQuery); // Remove join clause from main query delete query[analysis.joinQueries[joinCollectionName]]; } op.time('joinReferences'); } // Check if an index lookup can be used to return this result if (analysis.indexMatch.length && (!options || (options && !options.$skipIndex))) { op.data('index.potential', analysis.indexMatch); op.data('index.used', analysis.indexMatch[0].index); // Get the data from the index op.time('indexLookup'); resultArr = analysis.indexMatch[0].lookup || []; op.time('indexLookup'); // Check if the index coverage is all keys, if not we still need to table scan it if (analysis.indexMatch[0].keyData.totalKeyCount === analysis.indexMatch[0].keyData.score) { // Don't require a table scan to find relevant documents requiresTableScan = false; } } else { op.flag('usedIndex', false); } if (requiresTableScan) { if (resultArr && resultArr.length) { scanLength = resultArr.length; op.time('tableScan: ' + scanLength); // Filter the source data and return the result resultArr = resultArr.filter(matcher); } else { // Filter the source data and return the result scanLength = this._data.length; op.time('tableScan: ' + scanLength); resultArr = this._data.filter(matcher); } op.time('tableScan: ' + scanLength); } // Order the array if we were passed a sort clause if (options.$orderBy) { op.time('sort'); resultArr = this.sort(options.$orderBy, resultArr); op.time('sort'); } if (options.$page !== undefined && options.$limit !== undefined) { // Record paging data cursor.page = options.$page; cursor.pages = Math.ceil(resultArr.length / options.$limit); cursor.records = resultArr.length; // Check if we actually need to apply the paging logic if (options.$page && options.$limit > 0) { op.data('cursor', cursor); // Skip to the page specified based on limit resultArr.splice(0, options.$page * options.$limit); } } if (options.$skip) { cursor.skip = options.$skip; // Skip past the number of records specified resultArr.splice(0, options.$skip); op.data('skip', options.$skip); } if (options.$limit && resultArr && resultArr.length > options.$limit) { cursor.limit = options.$limit; resultArr.length = options.$limit; op.data('limit', options.$limit); } if (options.$decouple) { // Now decouple the data from the original objects op.time('decouple'); resultArr = this.decouple(resultArr); op.time('decouple'); op.data('flag.decouple', true); } // Now process any joins on the final data if (options.$join) { for (joinCollectionIndex = 0; joinCollectionIndex < options.$join.length; joinCollectionIndex++) { for (joinCollectionName in options.$join[joinCollectionIndex]) { if (options.$join[joinCollectionIndex].hasOwnProperty(joinCollectionName)) { // Set the key to store the join result in to the collection name by default resultCollectionName = joinCollectionName; // Get the join collection instance from the DB if (joinCollection[joinCollectionName]) { joinCollectionInstance = joinCollection[joinCollectionName]; } else { joinCollectionInstance = this._db.collection(joinCollectionName); } // Get the match data for the join joinMatch = options.$join[joinCollectionIndex][joinCollectionName]; // Loop our result data array for (resultIndex = 0; resultIndex < resultArr.length; resultIndex++) { // Loop the join conditions and build a search object from them joinSearchQuery = {}; joinMulti = false; joinRequire = false; joinPrefix = ''; for (joinMatchIndex in joinMatch) { if (joinMatch.hasOwnProperty(joinMatchIndex)) { // Check the join condition name for a special command operator if (joinMatchIndex.substr(0, 1) === '$') { // Special command switch (joinMatchIndex) { case '$where': if (joinMatch[joinMatchIndex].query) { // Commented old code here, new one does dynamic reverse lookups //joinSearchQuery = joinMatch[joinMatchIndex].query; joinSearchQuery = self._resolveDynamicQuery(joinMatch[joinMatchIndex].query, resultArr[resultIndex]); } if (joinMatch[joinMatchIndex].options) { joinSearchOptions = joinMatch[joinMatchIndex].options; } break; case '$as': // Rename the collection when stored in the result document resultCollectionName = joinMatch[joinMatchIndex]; break; case '$multi': // Return an array of documents instead of a single matching document joinMulti = joinMatch[joinMatchIndex]; break; case '$require': // Remove the result item if no matching join data is found joinRequire = joinMatch[joinMatchIndex]; break; case '$prefix': // Add a prefix to properties mixed in joinPrefix = joinMatch[joinMatchIndex]; break; default: break; } } else { // Get the data to match against and store in the search object // Resolve complex referenced query joinSearchQuery[joinMatchIndex] = self._resolveDynamicQuery(joinMatch[joinMatchIndex], resultArr[resultIndex]); } } } // Do a find on the target collection against the match data joinFindResults = joinCollectionInstance.find(joinSearchQuery, joinSearchOptions); // Check if we require a joined row to allow the result item if (!joinRequire || (joinRequire && joinFindResults[0])) { // Join is not required or condition is met if (resultCollectionName === '$root') { // The property name to store the join results in is $root // which means we need to mixin the results but this only // works if joinMulti is disabled if (joinMulti !== false) { // Throw an exception here as this join is not physically possible! throw(this.logIdentifier() + ' Cannot combine [$as: "$root"] with [$multi: true] in $join clause!'); } // Mixin the result joinFindResult = joinFindResults[0]; joinItem = resultArr[resultIndex]; for (l in joinFindResult) { if (joinFindResult.hasOwnProperty(l) && joinItem[joinPrefix + l] === undefined) { // Properties are only mixed in if they do not already exist // in the target item (are undefined). Using a prefix denoted via // $prefix is a good way to prevent property name conflicts joinItem[joinPrefix + l] = joinFindResult[l]; } } } else { resultArr[resultIndex][resultCollectionName] = joinMulti === false ? joinFindResults[0] : joinFindResults; } } else { // Join required but condition not met, add item to removal queue resultRemove.push(resultArr[resultIndex]); } } } } } op.data('flag.join', true); } // Process removal queue if (resultRemove.length) { op.time('removalQueue'); for (i = 0; i < resultRemove.length; i++) { index = resultArr.indexOf(resultRemove[i]); if (index > -1) { resultArr.splice(index, 1); } } op.time('removalQueue'); } if (options.$transform) { op.time('transform'); for (i = 0; i < resultArr.length; i++) { resultArr.splice(i, 1, options.$transform(resultArr[i])); } op.time('transform'); op.data('flag.transform', true); } // Process transforms if (this._transformEnabled && this._transformOut) { op.time('transformOut'); resultArr = this.transformOut(resultArr); op.time('transformOut'); } op.data('results', resultArr.length); } else { resultArr = []; } // Check for an $as operator in the options object and if it exists // iterate over the fields and generate a rename function that will // operate over the entire returned data array and rename each object's // fields to their new names // TODO: Enable $as in collection find to allow renaming fields /*if (options.$as) { renameFieldPath = new Path(); renameFieldMethod = function (obj, oldFieldPath, newFieldName) { renameFieldPath.path(oldFieldPath); renameFieldPath.rename(newFieldName); }; for (i in options.$as) { if (options.$as.hasOwnProperty(i)) { } } }*/ if (!options.$aggregate) { // Generate a list of fields to limit data by // Each property starts off being enabled by default (= 1) then // if any property is explicitly specified as 1 then all switch to // zero except _id. // // Any that are explicitly set to zero are switched off. op.time('scanFields'); for (i in options) { if (options.hasOwnProperty(i) && i.indexOf('$') !== 0) { if (options[i] === 1) { fieldListOn.push(i); } else if (options[i] === 0) { fieldListOff.push(i); } } } op.time('scanFields'); // Limit returned fields by the options data if (fieldListOn.length || fieldListOff.length) { op.data('flag.limitFields', true); op.data('limitFields.on', fieldListOn); op.data('limitFields.off', fieldListOff); op.time('limitFields'); // We have explicit fields switched on or off for (i = 0; i < resultArr.length; i++) { result = resultArr[i]; for (j in result) { if (result.hasOwnProperty(j)) { if (fieldListOn.length) { // We have explicit fields switched on so remove all fields // that are not explicitly switched on // Check if the field name is not the primary key if (j !== pk) { if (fieldListOn.indexOf(j) === -1) { // This field is not in the on list, remove it delete result[j]; } } } if (fieldListOff.length) { // We have explicit fields switched off so remove fields // that are explicitly switched off if (fieldListOff.indexOf(j) > -1) { // This field is in the off list, remove it delete result[j]; } } } } } op.time('limitFields'); } // Now run any projections on the data required if (options.$elemMatch) { op.data('flag.elemMatch', true); op.time('projection-elemMatch'); for (i in options.$elemMatch) { if (options.$elemMatch.hasOwnProperty(i)) { elemMatchPathSolver = new Path(i); // Loop the results array for (j = 0; j < resultArr.length; j++) { elemMatchSubArr = elemMatchPathSolver.value(resultArr[j])[0]; // Check we have a sub-array to loop if (elemMatchSubArr && elemMatchSubArr.length) { // Loop the sub-array and check for projection query matches for (k = 0; k < elemMatchSubArr.length; k++) { // Check if the current item in the sub-array matches the projection query if (self._match(elemMatchSubArr[k], options.$elemMatch[i], options, '', {})) { // The item matches the projection query so set the sub-array // to an array that ONLY contains the matching item and then // exit the loop since we only want to match the first item elemMatchPathSolver.set(resultArr[j], i, [elemMatchSubArr[k]]); break; } } } } } } op.time('projection-elemMatch'); } if (options.$elemsMatch) { op.data('flag.elemsMatch', true); op.time('projection-elemsMatch'); for (i in options.$elemsMatch) { if (options.$elemsMatch.hasOwnProperty(i)) { elemMatchPathSolver = new Path(i); // Loop the results array for (j = 0; j < resultArr.length; j++) { elemMatchSubArr = elemMatchPathSolver.value(resultArr[j])[0]; // Check we have a sub-array to loop if (elemMatchSubArr && elemMatchSubArr.length) { elemMatchSpliceArr = []; // Loop the sub-array and check for projection query matches for (k = 0; k < elemMatchSubArr.length; k++) { // Check if the current item in the sub-array matches the projection query if (self._match(elemMatchSubArr[k], options.$elemsMatch[i], options, '', {})) { // The item matches the projection query so add it to the final array elemMatchSpliceArr.push(elemMatchSubArr[k]); } } // Now set the final sub-array to the matched items elemMatchPathSolver.set(resultArr[j], i, elemMatchSpliceArr); } } } } op.time('projection-elemsMatch'); } } // Process aggregation if (options.$aggregate) { op.data('flag.aggregate', true); op.time('aggregate'); pathSolver = new Path(options.$aggregate); resultArr = pathSolver.value(resultArr); op.time('aggregate'); } op.stop(); resultArr.__fdbOp = op; resultArr.$cursor = cursor; return resultArr; }; Collection.prototype._resolveDynamicQuery = function (query, item) { var self = this, newQuery, propType, propVal, pathResult, i; if (typeof query === 'string') { // Check if the property name starts with a back-reference if (query.substr(0, 3) === '$$.') { // Fill the query with a back-referenced value pathResult = new Path(query.substr(3, query.length - 3)).value(item); } else { pathResult = new Path(query).value(item); } if (pathResult.length > 1) { return {$in: pathResult}; } else { return pathResult[0]; } } newQuery = {}; for (i in query) { if (query.hasOwnProperty(i)) { propType = typeof query[i]; propVal = query[i]; switch (propType) { case 'string': // Check if the property name starts with a back-reference if (propVal.substr(0, 3) === '$$.') { // Fill the query with a back-referenced value newQuery[i] = new Path(propVal.substr(3, propVal.length - 3)).value(item)[0]; } else { newQuery[i] = propVal; } break; case 'object': newQuery[i] = self._resolveDynamicQuery(propVal, item); break; default: newQuery[i] = propVal; break; } } } return newQuery; }; /** * Returns one document that satisfies the specified query criteria. If multiple * documents satisfy the query, this method returns the first document to match * the query. * @returns {*} */ Collection.prototype.findOne = function () { return (this.find.apply(this, arguments))[0]; }; /** * Gets the index in the collection data array of the first item matched by * the passed query object. * @param {Object} query The query to run to find the item to return the index of. * @param {Object=} options An options object. * @returns {Number} */ Collection.prototype.indexOf = function (query, options) { var item = this.find(query, {$decouple: false})[0], sortedData; if (item) { if (!options || options && !options.$orderBy) { // Basic lookup from order of insert return this._data.indexOf(item); } else { // Trying to locate index based on query with sort order options.$decouple = false; sortedData = this.find(query, options); return sortedData.indexOf(item); } } return -1; }; /** * Returns the index of the document identified by the passed item's primary key. * @param {*} itemLookup The document whose primary key should be used to lookup * or the id to lookup. * @param {Object=} options An options object. * @returns {Number} The index the item with the matching primary key is occupying. */ Collection.prototype.indexOfDocById = function (itemLookup, options) { var item, sortedData; if (typeof itemLookup !== 'object') { item = this._primaryIndex.get(itemLookup); } else { item = this._primaryIndex.get(itemLookup[this._primaryKey]); } if (item) { if (!options || options && !options.$orderBy) { // Basic lookup return this._data.indexOf(item); } else { // Sorted lookup options.$decouple = false; sortedData = this.find({}, options); return sortedData.indexOf(item); } } return -1; }; /** * Removes a document from the collection by it's index in the collection's * data array. * @param {Number} index The index of the document to remove. * @returns {Object} The document that has been removed or false if none was * removed. */ Collection.prototype.removeByIndex = function (index) { var doc, docId; doc = this._data[index]; if (doc !== undefined) { doc = this.decouple(doc); docId = doc[this.primaryKey()]; return this.removeById(docId); } return false; }; /** * Gets / sets the collection transform options. * @param {Object} obj A collection transform options object. * @returns {*} */ Collection.prototype.transform = function (obj) { if (obj !== undefined) { if (typeof obj === "object") { if (obj.enabled !== undefined) { this._transformEnabled = obj.enabled; } if (obj.dataIn !== undefined) { this._transformIn = obj.dataIn; } if (obj.dataOut !== undefined) { this._transformOut = obj.dataOut; } } else { this._transformEnabled = obj !== false; } return this; } return { enabled: this._transformEnabled, dataIn: this._transformIn, dataOut: this._transformOut }; }; /** * Transforms data using the set transformIn method. * @param {Object} data The data to transform. * @returns {*} */ Collection.prototype.transformIn = function (data) { if (this._transformEnabled && this._transformIn) { if (data instanceof Array) { var finalArr = [], i; for (i = 0; i < data.length; i++) { finalArr[i] = this._transformIn(data[i]); } return finalArr; } else { return this._transformIn(data); } } return data; }; /** * Transforms data using the set transformOut method. * @param {Object} data The data to transform. * @returns {*} */ Collection.prototype.transformOut = function (data) { if (this._transformEnabled && this._transformOut) { if (data instanceof Array) { var finalArr = [], i; for (i = 0; i < data.length; i++) { finalArr[i] = this._transformOut(data[i]); } return finalArr; } else { return this._transformOut(data); } } return data; }; /** * Sorts an array of documents by the given sort path. * @param {*} sortObj The keys and orders the array objects should be sorted by. * @param {Array} arr The array of documents to sort. * @returns {Array} */ Collection.prototype.sort = function (sortObj, arr) { // Make sure we have an array object arr = arr || []; var sortArr = [], sortKey, sortSingleObj; for (sortKey in sortObj) { if (sortObj.hasOwnProperty(sortKey)) { sortSingleObj = {}; sortSingleObj[sortKey] = sortObj[sortKey]; sortSingleObj.___fdbKey = String(sortKey); sortArr.push(sortSingleObj); } } if (sortArr.length < 2) { // There is only one sort criteria, do a simple sort and return it return this._sort(sortObj, arr); } else { return this._bucketSort(sortArr, arr); } }; /** * Takes array of sort paths and sorts them into buckets before returning final * array fully sorted by multi-keys. * @param keyArr * @param arr * @returns {*} * @private */ Collection.prototype._bucketSort = function (keyArr, arr) { var keyObj = keyArr.shift(), arrCopy, bucketData, bucketOrder, bucketKey, buckets, i, finalArr = []; if (keyArr.length > 0) { // Sort array by bucket key arr = this._sort(keyObj, arr); // Split items into buckets bucketData = this.bucket(keyObj.___fdbKey, arr); bucketOrder = bucketData.order; buckets = bucketData.buckets; // Loop buckets and sort contents for (i = 0; i < bucketOrder.length; i++) { bucketKey = bucketOrder[i]; arrCopy = [].concat(keyArr); finalArr = finalArr.concat(this._bucketSort(arrCopy, buckets[bucketKey])); } return finalArr; } else { return this._sort(keyObj, arr); } }; /** * Sorts array by individual sort path. * @param key * @param arr * @returns {Array|*} * @private */ Collection.prototype._sort = function (key, arr) { var self = this, sorterMethod, pathSolver = new Path(), dataPath = pathSolver.parse(key, true)[0]; pathSolver.path(dataPath.path); if (dataPath.value === 1) { // Sort ascending sorterMethod = function (a, b) { var valA = pathSolver.value(a)[0], valB = pathSolver.value(b)[0]; return self.sortAsc(valA, valB); }; } else if (dataPath.value === -1) { // Sort descending sorterMethod = function (a, b) { var valA = pathSolver.value(a)[0], valB = pathSolver.value(b)[0]; return self.sortDesc(valA, valB); }; } else { throw(this.logIdentifier() + ' $orderBy clause has invalid direction: ' + dataPath.value + ', accepted values are 1 or -1 for ascending or descending!'); } return arr.sort(sorterMethod); }; /** * Takes an array of objects and returns a new object with the array items * split into buckets by the passed key. * @param {String} key The key to split the array into buckets by. * @param {Array} arr An array of objects. * @returns {Object} */ Collection.prototype.bucket = function (key, arr) { var i, oldField, field, fieldArr = [], buckets = {}; for (i = 0; i < arr.length; i++) { field = String(arr[i][key]); if (oldField !== field) { fieldArr.push(field); oldField = field; } buckets[field] = buckets[field] || []; buckets[field].push(arr[i]); } return { buckets: buckets, order: fieldArr }; }; /** * Internal method that takes a search query and options and returns an object * containing details about the query which can be used to optimise the search. * * @param query * @param options * @param op * @returns {Object} * @private */ Collection.prototype._analyseQuery = function (query, options, op) { var analysis = { queriesOn: [this._name], indexMatch: [], hasJoin: false, queriesJoin: false, joinQueries: {}, query: query, options: options }, joinCollectionIndex, joinCollectionName, joinCollections = [], joinCollectionReferences = [], queryPath, index, indexMatchData, indexRef, indexRefName, indexLookup, pathSolver, queryKeyCount, i; // Check if the query is a primary key lookup op.time('checkIndexes'); pathSolver = new Path(); queryKeyCount = pathSolver.countKeys(query); if (queryKeyCount) { if (query[this._primaryKey] !== undefined) { // Return item via primary key possible op.time('checkIndexMatch: Primary Key'); analysis.indexMatch.push({ lookup: this._primaryIndex.lookup(query, options), keyData: { matchedKeys: [this._primaryKey], totalKeyCount: queryKeyCount, score: 1 }, index: this._primaryIndex }); op.time('checkIndexMatch: Primary Key'); } // Check if an index can speed up the query for (i in this._indexById) { if (this._indexById.hasOwnProperty(i)) { indexRef = this._indexById[i]; indexRefName = indexRef.name(); op.time('checkIndexMatch: ' + indexRefName); indexMatchData = indexRef.match(query, options); if (indexMatchData.score > 0) { // This index can be used, store it indexLookup = indexRef.lookup(query, options); analysis.indexMatch.push({ lookup: indexLookup, keyData: indexMatchData, index: indexRef }); } op.time('checkIndexMatch: ' + indexRefName); if (indexMatchData.score === queryKeyCount) { // Found an optimal index, do not check for any more break; } } } op.time('checkIndexes'); // Sort array descending on index key count (effectively a measure of relevance to the query) if (analysis.indexMatch.length > 1) { op.time('findOptimalIndex'); analysis.indexMatch.sort(function (a, b) { if (a.keyData.score > b.keyData.score) { // This index has a higher score than the other return -1; } if (a.keyData.score < b.keyData.score) { // This index has a lower score than the other return 1; } // The indexes have the same score but can still be compared by the number of records // they return from the query. The fewer records they return the better so order by // record count if (a.keyData.score === b.keyData.score) { return a.lookup.length - b.lookup.length; } }); op.time('findOptimalIndex'); } } // Check for join data if (options.$join) { analysis.hasJoin = true; // Loop all join operations for (joinCollectionIndex = 0; joinCollectionIndex < options.$join.length; joinCollectionIndex++) { // Loop the join collections and keep a reference to them for (joinCollectionName in options.$join[joinCollectionIndex]) { if (options.$join[joinCollectionIndex].hasOwnProperty(joinCollectionName)) { joinCollections.push(joinCollectionName); // Check if the join uses an $as operator if ('$as' in options.$join[joinCollectionIndex][joinCollectionName]) { joinCollectionReferences.push(options.$join[joinCollectionIndex][joinCollectionName].$as); } else { joinCollectionReferences.push(joinCollectionName); } } } } // Loop the join collection references and determine if the query references // any of the collections that are used in the join. If there no queries against // joined collections the find method can use a code path optimised for this. // Queries against joined collections requires the joined collections to be filtered // first and then joined so requires a little more work. for (index = 0; index < joinCollectionReferences.length; index++) { // Check if the query references any collection data that the join will create queryPath = this._queryReferencesCollection(query, joinCollectionReferences[index], ''); if (queryPath) { analysis.joinQueries[joinCollections[index]] = queryPath; analysis.queriesJoin = true; } } analysis.joinsOn = joinCollections; analysis.queriesOn = analysis.queriesOn.concat(joinCollections); } return analysis; }; /** * Checks if the passed query references this collection. * @param query * @param collection * @param path * @returns {*} * @private */ Collection.prototype._queryReferencesCollection = function (query, collection, path) { var i; for (i in query) { if (query.hasOwnProperty(i)) { // Check if this key is a reference match if (i === collection) { if (path) { path += '.'; } return path + i; } else { if (typeof(query[i]) === 'object') { // Recurse if (path) { path += '.'; } path += i; return this._queryReferencesCollection(query[i], collection, path); } } } } return false; }; /** * Returns the number of documents currently in the collection. * @returns {Number} */ Collection.prototype.count = function (query, options) { if (!query) { return this._data.length; } else { // Run query and return count return this.find(query, options).length; } }; /** * Finds sub-documents from the collection's documents. * @param {Object} match The query object to use when matching parent documents * from which the sub-documents are queried. * @param {String} path The path string used to identify the key in which * sub-documents are stored in parent documents. * @param {Object=} subDocQuery The query to use when matching which sub-documents * to return. * @param {Object=} subDocOptions The options object to use when querying for * sub-documents. * @returns {*} */ Collection.prototype.findSub = function (match, path, subDocQuery, subDocOptions) { var pathHandler = new Path(path), docArr = this.find(match), docCount = docArr.length, docIndex, subDocArr, subDocCollection = this._db.collection('__FDB_temp_' + this.objectId()), subDocResults, resultObj = { parents: docCount, subDocTotal: 0, subDocs: [], pathFound: false, err: '' }; subDocOptions = subDocOptions || {}; for (docIndex = 0; docIndex < docCount; docIndex++) { subDocArr = pathHandler.value(docArr[docIndex])[0]; if (subDocArr) { subDocCollection.setData(subDocArr); subDocResults = subDocCollection.find(subDocQuery, subDocOptions); if (subDocOptions.returnFirst && subDocResults.length) { return subDocResults[0]; } if (subDocOptions.$split) { resultObj.subDocs.push(subDocResults); } else { resultObj.subDocs = resultObj.subDocs.concat(subDocResults); } resultObj.subDocTotal += subDocResults.length; resultObj.pathFound = true; } } // Drop the sub-document collection subDocCollection.drop(); // Check if the call should not return stats, if so return only subDocs array if (subDocOptions.$stats) { return resultObj; } else { return resultObj.subDocs; } if (!resultObj.pathFound) { resultObj.err = 'No objects found in the parent documents with a matching path of: ' + path; } return resultObj; }; /** * Finds the first sub-document from the collection's documents that matches * the subDocQuery parameter. * @param {Object} match The query object to use when matching parent documents * from which the sub-documents are queried. * @param {String} path The path string used to identify the key in which * sub-documents are stored in parent documents. * @param {Object=} subDocQuery The query to use when matching which sub-documents * to return. * @param {Object=} subDocOptions The options object to use when querying for * sub-documents. * @returns {Object} */ Collection.prototype.findSubOne = function (match, path, subDocQuery, subDocOptions) { return this.findSub(match, path, subDocQuery, subDocOptions)[0]; }; /** * Checks that the passed document will not violate any index rules if * inserted into the collection. * @param {Object} doc The document to check indexes against. * @returns {Boolean} Either false (no violation occurred) or true if * a violation was detected. */ Collection.prototype.insertIndexViolation = function (doc) { var indexViolated, arr = this._indexByName, arrIndex, arrItem; // Check the item's primary key is not already in use if (this._primaryIndex.get(doc[this._primaryKey])) { indexViolated = this._primaryIndex; } else { // Check violations of other indexes for (arrIndex in arr) { if (arr.hasOwnProperty(arrIndex)) { arrItem = arr[arrIndex]; if (arrItem.unique()) { if (arrItem.violation(doc)) { indexViolated = arrItem; break; } } } } } return indexViolated ? indexViolated.name() : false; }; /** * Creates an index on the specified keys. * @param {Object} keys The object containing keys to index. * @param {Object} options An options object. * @returns {*} */ Collection.prototype.ensureIndex = function (keys, options) { if (this.isDropped()) { throw(this.logIdentifier() + ' Cannot operate in a dropped state!'); } this._indexByName = this._indexByName || {}; this._indexById = this._indexById || {}; var index, time = { start: new Date().getTime() }; if (options) { switch (options.type) { case 'hashed': index = new IndexHashMap(keys, options, this); break; case 'btree': index = new IndexBinaryTree(keys, options, this); break; default: // Default index = new IndexHashMap(keys, options, this); break; } } else { // Default index = new IndexHashMap(keys, options, this); } // Check the index does not already exist if (this._indexByName[index.name()]) { // Index already exists return { err: 'Index with that name already exists' }; } if (this._indexById[index.id()]) { // Index already exists return { err: 'Index with those keys already exists' }; } // Create the index index.rebuild(); // Add the index this._indexByName[index.name()] = index; this._indexById[index.id()] = index; time.end = new Date().getTime(); time.total = time.end - time.start; this._lastOp = { type: 'ensureIndex', stats: { time: time } }; return { index: index, id: index.id(), name: index.name(), state: index.state() }; }; /** * Gets an index by it's name. * @param {String} name The name of the index to retreive. * @returns {*} */ Collection.prototype.index = function (name) { if (this._indexByName) { return this._indexByName[name]; } }; /** * Gets the last reporting operation's details such as run time. * @returns {Object} */ Collection.prototype.lastOp = function () { return this._metrics.list(); }; /** * Generates a difference object that contains insert, update and remove arrays * representing the operations to execute to make this collection have the same * data as the one passed. * @param {Collection} collection The collection to diff against. * @returns {{}} */ Collection.prototype.diff = function (collection) { var diff = { insert: [], update: [], remove: [] }; var pm = this.primaryKey(), arr, arrIndex, arrItem, arrCount; // Check if the primary key index of each collection can be utilised if (pm !== collection.primaryKey()) { throw(this.logIdentifier() + ' Diffing requires that both collections have the same primary key!'); } // Use the collection primary key index to do the diff (super-fast) arr = collection._data; // Check if we have an array or another collection while (arr && !(arr instanceof Array)) { // We don't have an array, assign collection and get data collection = arr; arr = collection._data; } arrCount = arr.length; // Loop the collection's data array and check for matching items for (arrIndex = 0; arrIndex < arrCount; arrIndex++) { arrItem = arr[arrIndex]; // Check for a matching item in this collection if (this._primaryIndex.get(arrItem[pm])) { // Matching item exists, check if the data is the same if (this._primaryCrc.get(arrItem[pm]) !== collection._primaryCrc.get(arrItem[pm])) { // The documents exist in both collections but data differs, update required diff.update.push(arrItem); } } else { // The document is missing from this collection, insert required diff.insert.push(arrItem); } } // Now loop this collection's data and check for matching items arr = this._data; arrCount = arr.length; for (arrIndex = 0; arrIndex < arrCount; arrIndex++) { arrItem = arr[arrIndex]; if (!collection._primaryIndex.get(arrItem[pm])) { // The document does not exist in the other collection, remove required diff.remove.push(arrItem); } } return diff; }; Collection.prototype.collateAdd = new Overload({ /** * Adds a data source to collate data from and specifies the * key name to collate data to. * @func collateAdd * @memberof Collection * @param {Collection} collection The collection to collate data from. * @param {String=} keyName Optional name of the key to collate data to. * If none is provided the record CRUD is operated on the root collection * data. */ 'object, string': function (collection, keyName) { var self = this; self.collateAdd(collection, function (packet) { var obj1, obj2; switch (packet.type) { case 'insert': if (keyName) { obj1 = { $push: {} }; obj1.$push[keyName] = self.decouple(packet.data); self.update({}, obj1); } else { self.insert(packet.data); } break; case 'update': if (keyName) { obj1 = {}; obj2 = {}; obj1[keyName] = packet.data.query; obj2[keyName + '.$'] = packet.data.update; self.update(obj1, obj2); } else { self.update(packet.data.query, packet.data.update); } break; case 'remove': if (keyName) { obj1 = { $pull: {} }; obj1.$pull[keyName] = {}; obj1.$pull[keyName][self.primaryKey()] = packet.data.dataSet[0][collection.primaryKey()]; self.update({}, obj1); } else { self.remove(packet.data); } break; default: } }); }, /** * Adds a data source to collate data from and specifies a process * method that will handle the collation functionality (for custom * collation). * @func collateAdd * @memberof Collection * @param {Collection} collection The collection to collate data from. * @param {Function} process The process method. */ 'object, function': function (collection, process) { if (typeof collection === 'string') { // The collection passed is a name, not a reference so get // the reference from the name collection = this._db.collection(collection, { autoCreate: false, throwError: false }); } if (collection) { this._collate = this._collate || {}; this._collate[collection.name()] = new ReactorIO(collection, this, process); return this; } else { throw('Cannot collate from a non-existent collection!'); } } }); Collection.prototype.collateRemove = function (collection) { if (typeof collection === 'object') { // We need to have the name of the collection to remove it collection = collection.name(); } if (collection) { // Drop the reactor IO chain node this._collate[collection].drop(); // Remove the collection data from the collate object delete this._collate[collection]; return this; } else { throw('No collection name passed to collateRemove() or collection not found!'); } }; Db.prototype.collection = new Overload({ /** * Get a collection with no name (generates a random name). If the * collection does not already exist then one is created for that * name automatically. * @func collection * @memberof Db * @param {String} collectionName The name of the collection. * @returns {Collection} */ '': function () { return this.$main.call(this, { name: this.objectId() }); }, /** * Get a collection by name. If the collection does not already exist * then one is created for that name automatically. * @func collection * @memberof Db * @param {Object} data An options object or a collection instance. * @returns {Collection} */ 'object': function (data) { // Handle being passed an instance if (data instanceof Collection) { if (data.state() !== 'droppped') { return data; } else { return this.$main.call(this, { name: data.name() }); } } return this.$main.call(this, data); }, /** * Get a collection by name. If the collection does not already exist * then one is created for that name automatically. * @func collection * @memberof Db * @param {String} collectionName The name of the collection. * @returns {Collection} */ 'string': function (collectionName) { return this.$main.call(this, { name: collectionName }); }, /** * Get a collection by name. If the collection does not already exist * then one is created for that name automatically. * @func collection * @memberof Db * @param {String} collectionName The name of the collection. * @param {String} primaryKey Optional primary key to specify the primary key field on the collection * objects. Defaults to "_id". * @returns {Collection} */ 'string, string': function (collectionName, primaryKey) { return this.$main.call(this, { name: collectionName, primaryKey: primaryKey }); }, /** * Get a collection by name. If the collection does not already exist * then one is created for that name automatically. * @func collection * @memberof Db * @param {String} collectionName The name of the collection. * @param {Object} options An options object. * @returns {Collection} */ 'string, object': function (collectionName, options) { options.name = collectionName; return this.$main.call(this, options); }, /** * Get a collection by name. If the collection does not already exist * then one is created for that name automatically. * @func collection * @memberof Db * @param {String} collectionName The name of the collection. * @param {String} primaryKey Optional primary key to specify the primary key field on the collection * objects. Defaults to "_id". * @param {Object} options An options object. * @returns {Collection} */ 'string, string, object': function (collectionName, primaryKey, options) { options.name = collectionName; options.primaryKey = primaryKey; return this.$main.call(this, options); }, /** * The main handler method. This gets called by all the other variants and * handles the actual logic of the overloaded method. * @func collection * @memberof Db * @param {Object} options An options object. * @returns {*} */ '$main': function (options) { var name = options.name; if (name) { if (!this._collection[name]) { if (options && options.autoCreate === false) { if (options && options.throwError !== false) { throw(this.logIdentifier() + ' Cannot get collection ' + name + ' because it does not exist and auto-create has been disabled!'); } return undefined; } if (this.debug()) { console.log(this.logIdentifier() + ' Creating collection ' + name); } } this._collection[name] = this._collection[name] || new Collection(name, options).db(this); this._collection[name].mongoEmulation(this.mongoEmulation()); if (options.primaryKey !== undefined) { this._collection[name].primaryKey(options.primaryKey); } if (options.capped !== undefined) { // Check we have a size if (options.size !== undefined) { this._collection[name].capped(options.capped); this._collection[name].cappedSize(options.size); } else { throw(this.logIdentifier() + ' Cannot create a capped collection without specifying a size!'); } } return this._collection[name]; } else { if (!options || (options && options.throwError !== false)) { throw(this.logIdentifier() + ' Cannot get collection with undefined name!'); } } } }); /** * Determine if a collection with the passed name already exists. * @memberof Db * @param {String} viewName The name of the collection to check for. * @returns {boolean} */ Db.prototype.collectionExists = function (viewName) { return Boolean(this._collection[viewName]); }; /** * Returns an array of collections the DB currently has. * @memberof Db * @param {String|RegExp=} search The optional search string or regular expression to use * to match collection names against. * @returns {Array} An array of objects containing details of each collection * the database is currently managing. */ Db.prototype.collections = function (search) { var arr = [], collections = this._collection, collection, i; if (search) { if (!(search instanceof RegExp)) { // Turn the search into a regular expression search = new RegExp(search); } } for (i in collections) { if (collections.hasOwnProperty(i)) { collection = collections[i]; if (search) { if (search.exec(i)) { arr.push({ name: i, count: collection.count(), linked: collection.isLinked !== undefined ? collection.isLinked() : false }); } } else { arr.push({ name: i, count: collection.count(), linked: collection.isLinked !== undefined ? collection.isLinked() : false }); } } } arr.sort(function (a, b) { return a.name.localeCompare(b.name); }); return arr; }; Shared.finishModule('Collection'); module.exports = Collection; },{"./Crc":7,"./IndexBinaryTree":9,"./IndexHashMap":10,"./KeyValueStore":11,"./Metrics":12,"./Overload":24,"./Path":25,"./ReactorIO":29,"./Shared":31}],5:[function(_dereq_,module,exports){ "use strict"; // Import external names locally var Shared, Db, DbInit, Collection; Shared = _dereq_('./Shared'); /** * Creates a new collection group. Collection groups allow single operations to be * propagated to multiple collections at once. CRUD operations against a collection * group are in fed to the group's collections. Useful when separating out slightly * different data into multiple collections but querying as one collection. * @constructor */ var CollectionGroup = function () { this.init.apply(this, arguments); }; CollectionGroup.prototype.init = function (name) { var self = this; self._name = name; self._data = new Collection('__FDB__cg_data_' + self._name); self._collections = []; self._view = []; }; Shared.addModule('CollectionGroup', CollectionGroup); Shared.mixin(CollectionGroup.prototype, 'Mixin.Common'); Shared.mixin(CollectionGroup.prototype, 'Mixin.ChainReactor'); Shared.mixin(CollectionGroup.prototype, 'Mixin.Constants'); Shared.mixin(CollectionGroup.prototype, 'Mixin.Triggers'); Shared.mixin(CollectionGroup.prototype, 'Mixin.Tags'); Collection = _dereq_('./Collection'); Db = Shared.modules.Db; DbInit = Shared.modules.Db.prototype.init; CollectionGroup.prototype.on = function () { this._data.on.apply(this._data, arguments); }; CollectionGroup.prototype.off = function () { this._data.off.apply(this._data, arguments); }; CollectionGroup.prototype.emit = function () { this._data.emit.apply(this._data, arguments); }; /** * Gets / sets the primary key for this collection group. * @param {String=} keyName The name of the primary key. * @returns {*} */ CollectionGroup.prototype.primaryKey = function (keyName) { if (keyName !== undefined) { this._primaryKey = keyName; return this; } return this._primaryKey; }; /** * Gets / sets the current state. * @param {String=} val The name of the state to set. * @returns {*} */ Shared.synthesize(CollectionGroup.prototype, 'state'); /** * Gets / sets the db instance the collection group belongs to. * @param {Db=} db The db instance. * @returns {*} */ Shared.synthesize(CollectionGroup.prototype, 'db'); /** * Gets / sets the instance name. * @param {Name=} name The new name to set. * @returns {*} */ Shared.synthesize(CollectionGroup.prototype, 'name'); CollectionGroup.prototype.addCollection = function (collection) { if (collection) { if (this._collections.indexOf(collection) === -1) { //var self = this; // Check for compatible primary keys if (this._collections.length) { if (this._primaryKey !== collection.primaryKey()) { throw(this.logIdentifier() + ' All collections in a collection group must have the same primary key!'); } } else { // Set the primary key to the first collection added this.primaryKey(collection.primaryKey()); } // Add the collection this._collections.push(collection); collection._groups = collection._groups || []; collection._groups.push(this); collection.chain(this); // Hook the collection's drop event to destroy group data collection.on('drop', function () { // Remove collection from any group associations if (collection._groups && collection._groups.length) { var groupArr = [], i; // Copy the group array because if we call removeCollection on a group // it will alter the groups array of this collection mid-loop! for (i = 0; i < collection._groups.length; i++) { groupArr.push(collection._groups[i]); } // Loop any groups we are part of and remove ourselves from them for (i = 0; i < groupArr.length; i++) { collection._groups[i].removeCollection(collection); } } delete collection._groups; }); // Add collection's data this._data.insert(collection.find()); } } return this; }; CollectionGroup.prototype.removeCollection = function (collection) { if (collection) { var collectionIndex = this._collections.indexOf(collection), groupIndex; if (collectionIndex !== -1) { collection.unChain(this); this._collections.splice(collectionIndex, 1); collection._groups = collection._groups || []; groupIndex = collection._groups.indexOf(this); if (groupIndex !== -1) { collection._groups.splice(groupIndex, 1); } collection.off('drop'); } if (this._collections.length === 0) { // Wipe the primary key delete this._primaryKey; } } return this; }; CollectionGroup.prototype._chainHandler = function (chainPacket) { //sender = chainPacket.sender; switch (chainPacket.type) { case 'setData': // Decouple the data to ensure we are working with our own copy chainPacket.data = this.decouple(chainPacket.data); // Remove old data this._data.remove(chainPacket.options.oldData); // Add new data this._data.insert(chainPacket.data); break; case 'insert': // Decouple the data to ensure we are working with our own copy chainPacket.data = this.decouple(chainPacket.data); // Add new data this._data.insert(chainPacket.data); break; case 'update': // Update data this._data.update(chainPacket.data.query, chainPacket.data.update, chainPacket.options); break; case 'remove': this._data.remove(chainPacket.data.query, chainPacket.options); break; default: break; } }; CollectionGroup.prototype.insert = function () { this._collectionsRun('insert', arguments); }; CollectionGroup.prototype.update = function () { this._collectionsRun('update', arguments); }; CollectionGroup.prototype.updateById = function () { this._collectionsRun('updateById', arguments); }; CollectionGroup.prototype.remove = function () { this._collectionsRun('remove', arguments); }; CollectionGroup.prototype._collectionsRun = function (type, args) { for (var i = 0; i < this._collections.length; i++) { this._collections[i][type].apply(this._collections[i], args); } }; CollectionGroup.prototype.find = function (query, options) { return this._data.find(query, options); }; /** * Helper method that removes a document that matches the given id. * @param {String} id The id of the document to remove. */ CollectionGroup.prototype.removeById = function (id) { // Loop the collections in this group and apply the remove for (var i = 0; i < this._collections.length; i++) { this._collections[i].removeById(id); } }; /** * Uses the passed query to generate a new collection with results * matching the query parameters. * * @param query * @param options * @returns {*} */ CollectionGroup.prototype.subset = function (query, options) { var result = this.find(query, options); return new Collection() .subsetOf(this) .primaryKey(this._primaryKey) .setData(result); }; /** * Drops a collection group from the database. * @returns {boolean} True on success, false on failure. */ CollectionGroup.prototype.drop = function (callback) { if (!this.isDropped()) { var i, collArr, viewArr; if (this._debug) { console.log(this.logIdentifier() + ' Dropping'); } this._state = 'dropped'; if (this._collections && this._collections.length) { collArr = [].concat(this._collections); for (i = 0; i < collArr.length; i++) { this.removeCollection(collArr[i]); } } if (this._view && this._view.length) { viewArr = [].concat(this._view); for (i = 0; i < viewArr.length; i++) { this._removeView(viewArr[i]); } } this.emit('drop', this); if (callback) { callback(false, true); } } return true; }; // Extend DB to include collection groups Db.prototype.init = function () { this._collectionGroup = {}; DbInit.apply(this, arguments); }; Db.prototype.collectionGroup = function (collectionGroupName) { if (collectionGroupName) { // Handle being passed an instance if (collectionGroupName instanceof CollectionGroup) { return collectionGroupName; } this._collectionGroup[collectionGroupName] = this._collectionGroup[collectionGroupName] || new CollectionGroup(collectionGroupName).db(this); return this._collectionGroup[collectionGroupName]; } else { // Return an object of collection data return this._collectionGroup; } }; /** * Returns an array of collection groups the DB currently has. * @returns {Array} An array of objects containing details of each collection group * the database is currently managing. */ Db.prototype.collectionGroups = function () { var arr = [], i; for (i in this._collectionGroup) { if (this._collectionGroup.hasOwnProperty(i)) { arr.push({ name: i }); } } return arr; }; module.exports = CollectionGroup; },{"./Collection":4,"./Shared":31}],6:[function(_dereq_,module,exports){ /* License Copyright (c) 2015 Irrelon Software Limited http://www.irrelon.com http://www.forerunnerdb.com Please visit the license page to see latest license information: http://www.forerunnerdb.com/licensing.html */ "use strict"; var Shared, Db, Metrics, Overload, _instances = []; Shared = _dereq_('./Shared'); Overload = _dereq_('./Overload'); /** * Creates a new ForerunnerDB instance. Core instances handle the lifecycle of * multiple database instances. * @constructor */ var Core = function (name) { this.init.apply(this, arguments); }; Core.prototype.init = function (name) { this._db = {}; this._debug = {}; this._name = name || 'ForerunnerDB'; _instances.push(this); }; /** * Returns the number of instantiated ForerunnerDB objects. * @returns {Number} The number of instantiated instances. */ Core.prototype.instantiatedCount = function () { return _instances.length; }; /** * Get all instances as an array or a single ForerunnerDB instance * by it's array index. * @param {Number=} index Optional index of instance to get. * @returns {Array|Object} Array of instances or a single instance. */ Core.prototype.instances = function (index) { if (index !== undefined) { return _instances[index]; } return _instances; }; /** * Get all instances as an array of instance names or a single ForerunnerDB * instance by it's name. * @param {String=} name Optional name of instance to get. * @returns {Array|Object} Array of instance names or a single instance. */ Core.prototype.namedInstances = function (name) { var i, instArr; if (name !== undefined) { for (i = 0; i < _instances.length; i++) { if (_instances[i].name === name) { return _instances[i]; } } return undefined; } instArr = []; for (i = 0; i < _instances.length; i++) { instArr.push(_instances[i].name); } return instArr; }; Core.prototype.moduleLoaded = new Overload({ /** * Checks if a module has been loaded into the database. * @func moduleLoaded * @memberof Core * @param {String} moduleName The name of the module to check for. * @returns {Boolean} True if the module is loaded, false if not. */ 'string': function (moduleName) { if (moduleName !== undefined) { moduleName = moduleName.replace(/ /g, ''); var modules = moduleName.split(','), index; for (index = 0; index < modules.length; index++) { if (!Shared.modules[modules[index]]) { return false; } } return true; } return false; }, /** * Checks if a module is loaded and if so calls the passed * callback method. * @func moduleLoaded * @memberof Core * @param {String} moduleName The name of the module to check for. * @param {Function} callback The callback method to call if module is loaded. */ 'string, function': function (moduleName, callback) { if (moduleName !== undefined) { moduleName = moduleName.replace(/ /g, ''); var modules = moduleName.split(','), index; for (index = 0; index < modules.length; index++) { if (!Shared.modules[modules[index]]) { return false; } } if (callback) { callback(); } } }, /** * Checks if an array of named modules are loaded and if so * calls the passed callback method. * @func moduleLoaded * @memberof Core * @param {Array} moduleName The array of module names to check for. * @param {Function} callback The callback method to call if modules are loaded. */ 'array, function': function (moduleNameArr, callback) { var moduleName, i; for (i = 0; i < moduleNameArr.length; i++) { moduleName = moduleNameArr[i]; if (moduleName !== undefined) { moduleName = moduleName.replace(/ /g, ''); var modules = moduleName.split(','), index; for (index = 0; index < modules.length; index++) { if (!Shared.modules[modules[index]]) { return false; } } } } if (callback) { callback(); } }, /** * Checks if a module is loaded and if so calls the passed * success method, otherwise calls the failure method. * @func moduleLoaded * @memberof Core * @param {String} moduleName The name of the module to check for. * @param {Function} success The callback method to call if module is loaded. * @param {Function} failure The callback method to call if module not loaded. */ 'string, function, function': function (moduleName, success, failure) { if (moduleName !== undefined) { moduleName = moduleName.replace(/ /g, ''); var modules = moduleName.split(','), index; for (index = 0; index < modules.length; index++) { if (!Shared.modules[modules[index]]) { failure(); return false; } } success(); } } }); /** * Checks version against the string passed and if it matches (or partially matches) * then the callback is called. * @param {String} val The version to check against. * @param {Function} callback The callback to call if match is true. * @returns {Boolean} */ Core.prototype.version = function (val, callback) { if (val !== undefined) { if (Shared.version.indexOf(val) === 0) { if (callback) { callback(); } return true; } return false; } return Shared.version; }; // Expose moduleLoaded() method to non-instantiated object ForerunnerDB Core.moduleLoaded = Core.prototype.moduleLoaded; // Expose version() method to non-instantiated object ForerunnerDB Core.version = Core.prototype.version; // Expose instances() method to non-instantiated object ForerunnerDB Core.instances = Core.prototype.instances; // Expose instantiatedCount() method to non-instantiated object ForerunnerDB Core.instantiatedCount = Core.prototype.instantiatedCount; // Provide public access to the Shared object Core.shared = Shared; Core.prototype.shared = Shared; Shared.addModule('Core', Core); Shared.mixin(Core.prototype, 'Mixin.Common'); Shared.mixin(Core.prototype, 'Mixin.Constants'); Db = _dereq_('./Db.js'); Metrics = _dereq_('./Metrics.js'); /** * Gets / sets the name of the instance. This is primarily used for * name-spacing persistent storage. * @param {String=} val The name of the instance to set. * @returns {*} */ Shared.synthesize(Core.prototype, 'name'); /** * Gets / sets mongodb emulation mode. * @param {Boolean=} val True to enable, false to disable. * @returns {*} */ Shared.synthesize(Core.prototype, 'mongoEmulation'); // Set a flag to determine environment Core.prototype._isServer = false; /** * Returns true if ForerunnerDB is running on a client browser. * @returns {boolean} */ Core.prototype.isClient = function () { return !this._isServer; }; /** * Returns true if ForerunnerDB is running on a server. * @returns {boolean} */ Core.prototype.isServer = function () { return this._isServer; }; /** * Checks if the database is running on a client (browser) or * a server (node.js). * @returns {Boolean} Returns true if running on a browser. */ Core.prototype.isClient = function () { return !this._isServer; }; /** * Checks if the database is running on a client (browser) or * a server (node.js). * @returns {Boolean} Returns true if running on a server. */ Core.prototype.isServer = function () { return this._isServer; }; /** * Added to provide an error message for users who have not seen * the new instantiation breaking change warning and try to get * a collection directly from the core instance. */ Core.prototype.collection = function () { throw("ForerunnerDB's instantiation has changed since version 1.3.36 to support multiple database instances. Please see the readme.md file for the minor change you have to make to get your project back up and running, or see the issue related to this change at https://github.com/Irrelon/ForerunnerDB/issues/44"); }; module.exports = Core; },{"./Db.js":8,"./Metrics.js":12,"./Overload":24,"./Shared":31}],7:[function(_dereq_,module,exports){ "use strict"; /** * @mixin */ var crcTable = (function () { var crcTable = [], c, n, k; for (n = 0; n < 256; n++) { c = n; for (k = 0; k < 8; k++) { c = ((c & 1) ? (0xEDB88320 ^ (c >>> 1)) : (c >>> 1)); // jshint ignore:line } crcTable[n] = c; } return crcTable; }()); module.exports = function(str) { var crc = 0 ^ (-1), // jshint ignore:line i; for (i = 0; i < str.length; i++) { crc = (crc >>> 8) ^ crcTable[(crc ^ str.charCodeAt(i)) & 0xFF]; // jshint ignore:line } return (crc ^ (-1)) >>> 0; // jshint ignore:line }; },{}],8:[function(_dereq_,module,exports){ "use strict"; var Shared, Core, Collection, Metrics, Crc, Overload; Shared = _dereq_('./Shared'); Overload = _dereq_('./Overload'); /** * Creates a new ForerunnerDB database instance. * @constructor */ var Db = function (name, core) { this.init.apply(this, arguments); }; Db.prototype.init = function (name, core) { this.core(core); this._primaryKey = '_id'; this._name = name; this._collection = {}; this._debug = {}; }; Shared.addModule('Db', Db); Db.prototype.moduleLoaded = new Overload({ /** * Checks if a module has been loaded into the database. * @func moduleLoaded * @memberof Db * @param {String} moduleName The name of the module to check for. * @returns {Boolean} True if the module is loaded, false if not. */ 'string': function (moduleName) { if (moduleName !== undefined) { moduleName = moduleName.replace(/ /g, ''); var modules = moduleName.split(','), index; for (index = 0; index < modules.length; index++) { if (!Shared.modules[modules[index]]) { return false; } } return true; } return false; }, /** * Checks if a module is loaded and if so calls the passed * callback method. * @func moduleLoaded * @memberof Db * @param {String} moduleName The name of the module to check for. * @param {Function} callback The callback method to call if module is loaded. */ 'string, function': function (moduleName, callback) { if (moduleName !== undefined) { moduleName = moduleName.replace(/ /g, ''); var modules = moduleName.split(','), index; for (index = 0; index < modules.length; index++) { if (!Shared.modules[modules[index]]) { return false; } } if (callback) { callback(); } } }, /** * Checks if a module is loaded and if so calls the passed * success method, otherwise calls the failure method. * @func moduleLoaded * @memberof Db * @param {String} moduleName The name of the module to check for. * @param {Function} success The callback method to call if module is loaded. * @param {Function} failure The callback method to call if module not loaded. */ 'string, function, function': function (moduleName, success, failure) { if (moduleName !== undefined) { moduleName = moduleName.replace(/ /g, ''); var modules = moduleName.split(','), index; for (index = 0; index < modules.length; index++) { if (!Shared.modules[modules[index]]) { failure(); return false; } } success(); } } }); /** * Checks version against the string passed and if it matches (or partially matches) * then the callback is called. * @param {String} val The version to check against. * @param {Function} callback The callback to call if match is true. * @returns {Boolean} */ Db.prototype.version = function (val, callback) { if (val !== undefined) { if (Shared.version.indexOf(val) === 0) { if (callback) { callback(); } return true; } return false; } return Shared.version; }; // Expose moduleLoaded method to non-instantiated object ForerunnerDB Db.moduleLoaded = Db.prototype.moduleLoaded; // Expose version method to non-instantiated object ForerunnerDB Db.version = Db.prototype.version; // Provide public access to the Shared object Db.shared = Shared; Db.prototype.shared = Shared; Shared.addModule('Db', Db); Shared.mixin(Db.prototype, 'Mixin.Common'); Shared.mixin(Db.prototype, 'Mixin.ChainReactor'); Shared.mixin(Db.prototype, 'Mixin.Constants'); Shared.mixin(Db.prototype, 'Mixin.Tags'); Core = Shared.modules.Core; Collection = _dereq_('./Collection.js'); Metrics = _dereq_('./Metrics.js'); Crc = _dereq_('./Crc.js'); Db.prototype._isServer = false; /** * Gets / sets the core object this database belongs to. */ Shared.synthesize(Db.prototype, 'core'); /** * Gets / sets the default primary key for new collections. * @param {String=} val The name of the primary key to set. * @returns {*} */ Shared.synthesize(Db.prototype, 'primaryKey'); /** * Gets / sets the current state. * @param {String=} val The name of the state to set. * @returns {*} */ Shared.synthesize(Db.prototype, 'state'); /** * Gets / sets the name of the database. * @param {String=} val The name of the database to set. * @returns {*} */ Shared.synthesize(Db.prototype, 'name'); /** * Gets / sets mongodb emulation mode. * @param {Boolean=} val True to enable, false to disable. * @returns {*} */ Shared.synthesize(Db.prototype, 'mongoEmulation'); /** * Returns true if ForerunnerDB is running on a client browser. * @returns {boolean} */ Db.prototype.isClient = function () { return !this._isServer; }; /** * Returns true if ForerunnerDB is running on a server. * @returns {boolean} */ Db.prototype.isServer = function () { return this._isServer; }; /** * Returns a checksum of a string. * @param {String} string The string to checksum. * @return {String} The checksum generated. */ Db.prototype.crc = Crc; /** * Checks if the database is running on a client (browser) or * a server (node.js). * @returns {Boolean} Returns true if running on a browser. */ Db.prototype.isClient = function () { return !this._isServer; }; /** * Checks if the database is running on a client (browser) or * a server (node.js). * @returns {Boolean} Returns true if running on a server. */ Db.prototype.isServer = function () { return this._isServer; }; /** * Converts a normal javascript array of objects into a DB collection. * @param {Array} arr An array of objects. * @returns {Collection} A new collection instance with the data set to the * array passed. */ Db.prototype.arrayToCollection = function (arr) { return new Collection().setData(arr); }; /** * Registers an event listener against an event name. * @param {String} event The name of the event to listen for. * @param {Function} listener The listener method to call when * the event is fired. * @returns {*} */ Db.prototype.on = function(event, listener) { this._listeners = this._listeners || {}; this._listeners[event] = this._listeners[event] || []; this._listeners[event].push(listener); return this; }; /** * De-registers an event listener from an event name. * @param {String} event The name of the event to stop listening for. * @param {Function} listener The listener method passed to on() when * registering the event listener. * @returns {*} */ Db.prototype.off = function(event, listener) { if (event in this._listeners) { var arr = this._listeners[event], index = arr.indexOf(listener); if (index > -1) { arr.splice(index, 1); } } return this; }; /** * Emits an event by name with the given data. * @param {String} event The name of the event to emit. * @param {*=} data The data to emit with the event. * @returns {*} */ Db.prototype.emit = function(event, data) { this._listeners = this._listeners || {}; if (event in this._listeners) { var arr = this._listeners[event], arrCount = arr.length, arrIndex; for (arrIndex = 0; arrIndex < arrCount; arrIndex++) { arr[arrIndex].apply(this, Array.prototype.slice.call(arguments, 1)); } } return this; }; Db.prototype.peek = function (search) { var i, coll, arr = [], typeOfSearch = typeof search; // Loop collections for (i in this._collection) { if (this._collection.hasOwnProperty(i)) { coll = this._collection[i]; if (typeOfSearch === 'string') { arr = arr.concat(coll.peek(search)); } else { arr = arr.concat(coll.find(search)); } } } return arr; }; /** * Find all documents across all collections in the database that match the passed * string or search object. * @param search String or search object. * @returns {Array} */ Db.prototype.peek = function (search) { var i, coll, arr = [], typeOfSearch = typeof search; // Loop collections for (i in this._collection) { if (this._collection.hasOwnProperty(i)) { coll = this._collection[i]; if (typeOfSearch === 'string') { arr = arr.concat(coll.peek(search)); } else { arr = arr.concat(coll.find(search)); } } } return arr; }; /** * Find all documents across all collections in the database that match the passed * string or search object and return them in an object where each key is the name * of the collection that the document was matched in. * @param search String or search object. * @returns {object} */ Db.prototype.peekCat = function (search) { var i, coll, cat = {}, arr, typeOfSearch = typeof search; // Loop collections for (i in this._collection) { if (this._collection.hasOwnProperty(i)) { coll = this._collection[i]; if (typeOfSearch === 'string') { arr = coll.peek(search); if (arr && arr.length) { cat[coll.name()] = arr; } } else { arr = coll.find(search); if (arr && arr.length) { cat[coll.name()] = arr; } } } } return cat; }; Db.prototype.drop = new Overload({ /** * Drops the database. * @func drop * @memberof Db */ '': function () { if (!this.isDropped()) { var arr = this.collections(), arrCount = arr.length, arrIndex; this._state = 'dropped'; for (arrIndex = 0; arrIndex < arrCount; arrIndex++) { this.collection(arr[arrIndex].name).drop(); delete this._collection[arr[arrIndex].name]; } this.emit('drop', this); delete this._core._db[this._name]; } return true; }, /** * Drops the database with optional callback method. * @func drop * @memberof Db * @param {Function} callback Optional callback method. */ 'function': function (callback) { if (!this.isDropped()) { var arr = this.collections(), arrCount = arr.length, arrIndex, finishCount = 0, afterDrop = function () { finishCount++; if (finishCount === arrCount) { if (callback) { callback(); } } }; this._state = 'dropped'; for (arrIndex = 0; arrIndex < arrCount; arrIndex++) { this.collection(arr[arrIndex].name).drop(afterDrop); delete this._collection[arr[arrIndex].name]; } this.emit('drop', this); delete this._core._db[this._name]; } return true; }, /** * Drops the database with optional persistent storage drop. Persistent * storage is dropped by default if no preference is provided. * @func drop * @memberof Db * @param {Boolean} removePersist Drop persistent storage for this database. */ 'boolean': function (removePersist) { if (!this.isDropped()) { var arr = this.collections(), arrCount = arr.length, arrIndex; this._state = 'dropped'; for (arrIndex = 0; arrIndex < arrCount; arrIndex++) { this.collection(arr[arrIndex].name).drop(removePersist); delete this._collection[arr[arrIndex].name]; } this.emit('drop', this); delete this._core._db[this._name]; } return true; }, /** * Drops the database and optionally controls dropping persistent storage * and callback method. * @func drop * @memberof Db * @param {Boolean} removePersist Drop persistent storage for this database. * @param {Function} callback Optional callback method. */ 'boolean, function': function (removePersist, callback) { if (!this.isDropped()) { var arr = this.collections(), arrCount = arr.length, arrIndex, finishCount = 0, afterDrop = function () { finishCount++; if (finishCount === arrCount) { if (callback) { callback(); } } }; this._state = 'dropped'; for (arrIndex = 0; arrIndex < arrCount; arrIndex++) { this.collection(arr[arrIndex].name).drop(removePersist, afterDrop); delete this._collection[arr[arrIndex].name]; } this.emit('drop', this); delete this._core._db[this._name]; } return true; } }); /** * Gets a database instance by name. * @memberof Core * @param {String=} name Optional name of the database. If none is provided * a random name is assigned. * @returns {Db} */ Core.prototype.db = function (name) { // Handle being passed an instance if (name instanceof Db) { return name; } if (!name) { name = this.objectId(); } this._db[name] = this._db[name] || new Db(name, this); this._db[name].mongoEmulation(this.mongoEmulation()); return this._db[name]; }; /** * Returns an array of databases that ForerunnerDB currently has. * @memberof Core * @param {String|RegExp=} search The optional search string or regular expression to use * to match collection names against. * @returns {Array} An array of objects containing details of each database * that ForerunnerDB is currently managing and it's child entities. */ Core.prototype.databases = function (search) { var arr = [], tmpObj, addDb, i; if (search) { if (!(search instanceof RegExp)) { // Turn the search into a regular expression search = new RegExp(search); } } for (i in this._db) { if (this._db.hasOwnProperty(i)) { addDb = true; if (search) { if (!search.exec(i)) { addDb = false; } } if (addDb) { tmpObj = { name: i, children: [] }; if (this.shared.moduleExists('Collection')) { tmpObj.children.push({ module: 'collection', moduleName: 'Collections', count: this._db[i].collections().length }); } if (this.shared.moduleExists('CollectionGroup')) { tmpObj.children.push({ module: 'collectionGroup', moduleName: 'Collection Groups', count: this._db[i].collectionGroups().length }); } if (this.shared.moduleExists('Document')) { tmpObj.children.push({ module: 'document', moduleName: 'Documents', count: this._db[i].documents().length }); } if (this.shared.moduleExists('Grid')) { tmpObj.children.push({ module: 'grid', moduleName: 'Grids', count: this._db[i].grids().length }); } if (this.shared.moduleExists('Overview')) { tmpObj.children.push({ module: 'overview', moduleName: 'Overviews', count: this._db[i].overviews().length }); } if (this.shared.moduleExists('View')) { tmpObj.children.push({ module: 'view', moduleName: 'Views', count: this._db[i].views().length }); } arr.push(tmpObj); } } } arr.sort(function (a, b) { return a.name.localeCompare(b.name); }); return arr; }; Shared.finishModule('Db'); module.exports = Db; },{"./Collection.js":4,"./Crc.js":7,"./Metrics.js":12,"./Overload":24,"./Shared":31}],9:[function(_dereq_,module,exports){ "use strict"; /* name id rebuild state match lookup */ var Shared = _dereq_('./Shared'), Path = _dereq_('./Path'), BinaryTree = _dereq_('./BinaryTree'), treeInstance = new BinaryTree(), btree = function () {}; treeInstance.inOrder('hash'); /** * The index class used to instantiate hash map indexes that the database can * use to speed up queries on collections and views. * @constructor */ var IndexBinaryTree = function () { this.init.apply(this, arguments); }; IndexBinaryTree.prototype.init = function (keys, options, collection) { this._btree = new (btree.create(2, this.sortAsc))(); this._size = 0; this._id = this._itemKeyHash(keys, keys); this.unique(options && options.unique ? options.unique : false); if (keys !== undefined) { this.keys(keys); } if (collection !== undefined) { this.collection(collection); } this.name(options && options.name ? options.name : this._id); }; Shared.addModule('IndexBinaryTree', IndexBinaryTree); Shared.mixin(IndexBinaryTree.prototype, 'Mixin.ChainReactor'); Shared.mixin(IndexBinaryTree.prototype, 'Mixin.Sorting'); IndexBinaryTree.prototype.id = function () { return this._id; }; IndexBinaryTree.prototype.state = function () { return this._state; }; IndexBinaryTree.prototype.size = function () { return this._size; }; Shared.synthesize(IndexBinaryTree.prototype, 'data'); Shared.synthesize(IndexBinaryTree.prototype, 'name'); Shared.synthesize(IndexBinaryTree.prototype, 'collection'); Shared.synthesize(IndexBinaryTree.prototype, 'type'); Shared.synthesize(IndexBinaryTree.prototype, 'unique'); IndexBinaryTree.prototype.keys = function (val) { if (val !== undefined) { this._keys = val; // Count the keys this._keyCount = (new Path()).parse(this._keys).length; return this; } return this._keys; }; IndexBinaryTree.prototype.rebuild = function () { // Do we have a collection? if (this._collection) { // Get sorted data var collection = this._collection.subset({}, { $decouple: false, $orderBy: this._keys }), collectionData = collection.find(), dataIndex, dataCount = collectionData.length; // Clear the index data for the index this._btree = new (btree.create(2, this.sortAsc))(); if (this._unique) { this._uniqueLookup = {}; } // Loop the collection data for (dataIndex = 0; dataIndex < dataCount; dataIndex++) { this.insert(collectionData[dataIndex]); } } this._state = { name: this._name, keys: this._keys, indexSize: this._size, built: new Date(), updated: new Date(), ok: true }; }; IndexBinaryTree.prototype.insert = function (dataItem, options) { var uniqueFlag = this._unique, uniqueHash, dataItemHash = this._itemKeyHash(dataItem, this._keys), keyArr; if (uniqueFlag) { uniqueHash = this._itemHash(dataItem, this._keys); this._uniqueLookup[uniqueHash] = dataItem; } // We store multiple items that match a key inside an array // that is then stored against that key in the tree... // Check if item exists for this key already keyArr = this._btree.get(dataItemHash); // Check if the array exists if (keyArr === undefined) { // Generate an array for this key first keyArr = []; // Put the new array into the tree under the key this._btree.put(dataItemHash, keyArr); } // Push the item into the array keyArr.push(dataItem); this._size++; }; IndexBinaryTree.prototype.remove = function (dataItem, options) { var uniqueFlag = this._unique, uniqueHash, dataItemHash = this._itemKeyHash(dataItem, this._keys), keyArr, itemIndex; if (uniqueFlag) { uniqueHash = this._itemHash(dataItem, this._keys); delete this._uniqueLookup[uniqueHash]; } // Try and get the array for the item hash key keyArr = this._btree.get(dataItemHash); if (keyArr !== undefined) { // The key array exits, remove the item from the key array itemIndex = keyArr.indexOf(dataItem); if (itemIndex > -1) { // Check the length of the array if (keyArr.length === 1) { // This item is the last in the array, just kill the tree entry this._btree.del(dataItemHash); } else { // Remove the item keyArr.splice(itemIndex, 1); } this._size--; } } }; IndexBinaryTree.prototype.violation = function (dataItem) { // Generate item hash var uniqueHash = this._itemHash(dataItem, this._keys); // Check if the item breaks the unique constraint return Boolean(this._uniqueLookup[uniqueHash]); }; IndexBinaryTree.prototype.hashViolation = function (uniqueHash) { // Check if the item breaks the unique constraint return Boolean(this._uniqueLookup[uniqueHash]); }; IndexBinaryTree.prototype.lookup = function (query) { return this._data[this._itemHash(query, this._keys)] || []; }; IndexBinaryTree.prototype.match = function (query, options) { // Check if the passed query has data in the keys our index // operates on and if so, is the query sort matching our order var pathSolver = new Path(); var indexKeyArr = pathSolver.parseArr(this._keys), queryArr = pathSolver.parseArr(query), matchedKeys = [], matchedKeyCount = 0, i; // Loop the query array and check the order of keys against the // index key array to see if this index can be used for (i = 0; i < indexKeyArr.length; i++) { if (queryArr[i] === indexKeyArr[i]) { matchedKeyCount++; matchedKeys.push(queryArr[i]); } else { // Query match failed - this is a hash map index so partial key match won't work return { matchedKeys: [], totalKeyCount: queryArr.length, score: 0 }; } } return { matchedKeys: matchedKeys, totalKeyCount: queryArr.length, score: matchedKeyCount }; //return pathSolver.countObjectPaths(this._keys, query); }; IndexBinaryTree.prototype._itemHash = function (item, keys) { var path = new Path(), pathData, hash = '', k; pathData = path.parse(keys); for (k = 0; k < pathData.length; k++) { if (hash) { hash += '_'; } hash += path.value(item, pathData[k].path).join(':'); } return hash; }; IndexBinaryTree.prototype._itemKeyHash = function (item, keys) { var path = new Path(), pathData, hash = '', k; pathData = path.parse(keys); for (k = 0; k < pathData.length; k++) { if (hash) { hash += '_'; } hash += path.keyValue(item, pathData[k].path); } return hash; }; IndexBinaryTree.prototype._itemHashArr = function (item, keys) { var path = new Path(), pathData, //hash = '', hashArr = [], valArr, i, k, j; pathData = path.parse(keys); for (k = 0; k < pathData.length; k++) { valArr = path.value(item, pathData[k].path); for (i = 0; i < valArr.length; i++) { if (k === 0) { // Setup the initial hash array hashArr.push(valArr[i]); } else { // Loop the hash array and concat the value to it for (j = 0; j < hashArr.length; j++) { hashArr[j] = hashArr[j] + '_' + valArr[i]; } } } } return hashArr; }; Shared.finishModule('IndexBinaryTree'); module.exports = IndexBinaryTree; },{"./BinaryTree":3,"./Path":25,"./Shared":31}],10:[function(_dereq_,module,exports){ "use strict"; var Shared = _dereq_('./Shared'), Path = _dereq_('./Path'); /** * The index class used to instantiate hash map indexes that the database can * use to speed up queries on collections and views. * @constructor */ var IndexHashMap = function () { this.init.apply(this, arguments); }; IndexHashMap.prototype.init = function (keys, options, collection) { this._crossRef = {}; this._size = 0; this._id = this._itemKeyHash(keys, keys); this.data({}); this.unique(options && options.unique ? options.unique : false); if (keys !== undefined) { this.keys(keys); } if (collection !== undefined) { this.collection(collection); } this.name(options && options.name ? options.name : this._id); }; Shared.addModule('IndexHashMap', IndexHashMap); Shared.mixin(IndexHashMap.prototype, 'Mixin.ChainReactor'); IndexHashMap.prototype.id = function () { return this._id; }; IndexHashMap.prototype.state = function () { return this._state; }; IndexHashMap.prototype.size = function () { return this._size; }; Shared.synthesize(IndexHashMap.prototype, 'data'); Shared.synthesize(IndexHashMap.prototype, 'name'); Shared.synthesize(IndexHashMap.prototype, 'collection'); Shared.synthesize(IndexHashMap.prototype, 'type'); Shared.synthesize(IndexHashMap.prototype, 'unique'); IndexHashMap.prototype.keys = function (val) { if (val !== undefined) { this._keys = val; // Count the keys this._keyCount = (new Path()).parse(this._keys).length; return this; } return this._keys; }; IndexHashMap.prototype.rebuild = function () { // Do we have a collection? if (this._collection) { // Get sorted data var collection = this._collection.subset({}, { $decouple: false, $orderBy: this._keys }), collectionData = collection.find(), dataIndex, dataCount = collectionData.length; // Clear the index data for the index this._data = {}; if (this._unique) { this._uniqueLookup = {}; } // Loop the collection data for (dataIndex = 0; dataIndex < dataCount; dataIndex++) { this.insert(collectionData[dataIndex]); } } this._state = { name: this._name, keys: this._keys, indexSize: this._size, built: new Date(), updated: new Date(), ok: true }; }; IndexHashMap.prototype.insert = function (dataItem, options) { var uniqueFlag = this._unique, uniqueHash, itemHashArr, hashIndex; if (uniqueFlag) { uniqueHash = this._itemHash(dataItem, this._keys); this._uniqueLookup[uniqueHash] = dataItem; } // Generate item hash itemHashArr = this._itemHashArr(dataItem, this._keys); // Get the path search results and store them for (hashIndex = 0; hashIndex < itemHashArr.length; hashIndex++) { this.pushToPathValue(itemHashArr[hashIndex], dataItem); } }; IndexHashMap.prototype.update = function (dataItem, options) { // TODO: Write updates to work // 1: Get uniqueHash for the dataItem primary key value (may need to generate a store for this) // 2: Remove the uniqueHash as it currently stands // 3: Generate a new uniqueHash for dataItem // 4: Insert the new uniqueHash }; IndexHashMap.prototype.remove = function (dataItem, options) { var uniqueFlag = this._unique, uniqueHash, itemHashArr, hashIndex; if (uniqueFlag) { uniqueHash = this._itemHash(dataItem, this._keys); delete this._uniqueLookup[uniqueHash]; } // Generate item hash itemHashArr = this._itemHashArr(dataItem, this._keys); // Get the path search results and store them for (hashIndex = 0; hashIndex < itemHashArr.length; hashIndex++) { this.pullFromPathValue(itemHashArr[hashIndex], dataItem); } }; IndexHashMap.prototype.violation = function (dataItem) { // Generate item hash var uniqueHash = this._itemHash(dataItem, this._keys); // Check if the item breaks the unique constraint return Boolean(this._uniqueLookup[uniqueHash]); }; IndexHashMap.prototype.hashViolation = function (uniqueHash) { // Check if the item breaks the unique constraint return Boolean(this._uniqueLookup[uniqueHash]); }; IndexHashMap.prototype.pushToPathValue = function (hash, obj) { var pathValArr = this._data[hash] = this._data[hash] || []; // Make sure we have not already indexed this object at this path/value if (pathValArr.indexOf(obj) === -1) { // Index the object pathValArr.push(obj); // Record the reference to this object in our index size this._size++; // Cross-reference this association for later lookup this.pushToCrossRef(obj, pathValArr); } }; IndexHashMap.prototype.pullFromPathValue = function (hash, obj) { var pathValArr = this._data[hash], indexOfObject; // Make sure we have already indexed this object at this path/value indexOfObject = pathValArr.indexOf(obj); if (indexOfObject > -1) { // Un-index the object pathValArr.splice(indexOfObject, 1); // Record the reference to this object in our index size this._size--; // Remove object cross-reference this.pullFromCrossRef(obj, pathValArr); } // Check if we should remove the path value array if (!pathValArr.length) { // Remove the array delete this._data[hash]; } }; IndexHashMap.prototype.pull = function (obj) { // Get all places the object has been used and remove them var id = obj[this._collection.primaryKey()], crossRefArr = this._crossRef[id], arrIndex, arrCount = crossRefArr.length, arrItem; for (arrIndex = 0; arrIndex < arrCount; arrIndex++) { arrItem = crossRefArr[arrIndex]; // Remove item from this index lookup array this._pullFromArray(arrItem, obj); } // Record the reference to this object in our index size this._size--; // Now remove the cross-reference entry for this object delete this._crossRef[id]; }; IndexHashMap.prototype._pullFromArray = function (arr, obj) { var arrCount = arr.length; while (arrCount--) { if (arr[arrCount] === obj) { arr.splice(arrCount, 1); } } }; IndexHashMap.prototype.pushToCrossRef = function (obj, pathValArr) { var id = obj[this._collection.primaryKey()], crObj; this._crossRef[id] = this._crossRef[id] || []; // Check if the cross-reference to the pathVal array already exists crObj = this._crossRef[id]; if (crObj.indexOf(pathValArr) === -1) { // Add the cross-reference crObj.push(pathValArr); } }; IndexHashMap.prototype.pullFromCrossRef = function (obj, pathValArr) { var id = obj[this._collection.primaryKey()]; delete this._crossRef[id]; }; IndexHashMap.prototype.lookup = function (query) { return this._data[this._itemHash(query, this._keys)] || []; }; IndexHashMap.prototype.match = function (query, options) { // Check if the passed query has data in the keys our index // operates on and if so, is the query sort matching our order var pathSolver = new Path(); var indexKeyArr = pathSolver.parseArr(this._keys), queryArr = pathSolver.parseArr(query), matchedKeys = [], matchedKeyCount = 0, i; // Loop the query array and check the order of keys against the // index key array to see if this index can be used for (i = 0; i < indexKeyArr.length; i++) { if (queryArr[i] === indexKeyArr[i]) { matchedKeyCount++; matchedKeys.push(queryArr[i]); } else { // Query match failed - this is a hash map index so partial key match won't work return { matchedKeys: [], totalKeyCount: queryArr.length, score: 0 }; } } return { matchedKeys: matchedKeys, totalKeyCount: queryArr.length, score: matchedKeyCount }; //return pathSolver.countObjectPaths(this._keys, query); }; IndexHashMap.prototype._itemHash = function (item, keys) { var path = new Path(), pathData, hash = '', k; pathData = path.parse(keys); for (k = 0; k < pathData.length; k++) { if (hash) { hash += '_'; } hash += path.value(item, pathData[k].path).join(':'); } return hash; }; IndexHashMap.prototype._itemKeyHash = function (item, keys) { var path = new Path(), pathData, hash = '', k; pathData = path.parse(keys); for (k = 0; k < pathData.length; k++) { if (hash) { hash += '_'; } hash += path.keyValue(item, pathData[k].path); } return hash; }; IndexHashMap.prototype._itemHashArr = function (item, keys) { var path = new Path(), pathData, //hash = '', hashArr = [], valArr, i, k, j; pathData = path.parse(keys); for (k = 0; k < pathData.length; k++) { valArr = path.value(item, pathData[k].path); for (i = 0; i < valArr.length; i++) { if (k === 0) { // Setup the initial hash array hashArr.push(valArr[i]); } else { // Loop the hash array and concat the value to it for (j = 0; j < hashArr.length; j++) { hashArr[j] = hashArr[j] + '_' + valArr[i]; } } } } return hashArr; }; Shared.finishModule('IndexHashMap'); module.exports = IndexHashMap; },{"./Path":25,"./Shared":31}],11:[function(_dereq_,module,exports){ "use strict"; var Shared = _dereq_('./Shared'); /** * The key value store class used when storing basic in-memory KV data, * and can be queried for quick retrieval. Mostly used for collection * primary key indexes and lookups. * @param {String=} name Optional KV store name. * @constructor */ var KeyValueStore = function (name) { this.init.apply(this, arguments); }; KeyValueStore.prototype.init = function (name) { this._name = name; this._data = {}; this._primaryKey = '_id'; }; Shared.addModule('KeyValueStore', KeyValueStore); Shared.mixin(KeyValueStore.prototype, 'Mixin.ChainReactor'); /** * Get / set the name of the key/value store. * @param {String} val The name to set. * @returns {*} */ Shared.synthesize(KeyValueStore.prototype, 'name'); /** * Get / set the primary key. * @param {String} key The key to set. * @returns {*} */ KeyValueStore.prototype.primaryKey = function (key) { if (key !== undefined) { this._primaryKey = key; return this; } return this._primaryKey; }; /** * Removes all data from the store. * @returns {*} */ KeyValueStore.prototype.truncate = function () { this._data = {}; return this; }; /** * Sets data against a key in the store. * @param {String} key The key to set data for. * @param {*} value The value to assign to the key. * @returns {*} */ KeyValueStore.prototype.set = function (key, value) { this._data[key] = value ? value : true; return this; }; /** * Gets data stored for the passed key. * @param {String} key The key to get data for. * @returns {*} */ KeyValueStore.prototype.get = function (key) { return this._data[key]; }; /** * Get / set the primary key. * @param {*} obj A lookup query, can be a string key, an array of string keys, * an object with further query clauses or a regular expression that should be * run against all keys. * @returns {*} */ KeyValueStore.prototype.lookup = function (obj) { var pKeyVal = obj[this._primaryKey], arrIndex, arrCount, lookupItem, result; if (pKeyVal instanceof Array) { // An array of primary keys, find all matches arrCount = pKeyVal.length; result = []; for (arrIndex = 0; arrIndex < arrCount; arrIndex++) { lookupItem = this._data[pKeyVal[arrIndex]]; if (lookupItem) { result.push(lookupItem); } } return result; } else if (pKeyVal instanceof RegExp) { // Create new data result = []; for (arrIndex in this._data) { if (this._data.hasOwnProperty(arrIndex)) { if (pKeyVal.test(arrIndex)) { result.push(this._data[arrIndex]); } } } return result; } else if (typeof pKeyVal === 'object') { // The primary key clause is an object, now we have to do some // more extensive searching if (pKeyVal.$ne) { // Create new data result = []; for (arrIndex in this._data) { if (this._data.hasOwnProperty(arrIndex)) { if (arrIndex !== pKeyVal.$ne) { result.push(this._data[arrIndex]); } } } return result; } if (pKeyVal.$in && (pKeyVal.$in instanceof Array)) { // Create new data result = []; for (arrIndex in this._data) { if (this._data.hasOwnProperty(arrIndex)) { if (pKeyVal.$in.indexOf(arrIndex) > -1) { result.push(this._data[arrIndex]); } } } return result; } if (pKeyVal.$nin && (pKeyVal.$nin instanceof Array)) { // Create new data result = []; for (arrIndex in this._data) { if (this._data.hasOwnProperty(arrIndex)) { if (pKeyVal.$nin.indexOf(arrIndex) === -1) { result.push(this._data[arrIndex]); } } } return result; } if (pKeyVal.$or && (pKeyVal.$or instanceof Array)) { // Create new data result = []; for (arrIndex = 0; arrIndex < pKeyVal.$or.length; arrIndex++) { result = result.concat(this.lookup(pKeyVal.$or[arrIndex])); } return result; } } else { // Key is a basic lookup from string lookupItem = this._data[pKeyVal]; if (lookupItem !== undefined) { return [lookupItem]; } else { return []; } } }; /** * Removes data for the given key from the store. * @param {String} key The key to un-set. * @returns {*} */ KeyValueStore.prototype.unSet = function (key) { delete this._data[key]; return this; }; /** * Sets data for the give key in the store only where the given key * does not already have a value in the store. * @param {String} key The key to set data for. * @param {*} value The value to assign to the key. * @returns {Boolean} True if data was set or false if data already * exists for the key. */ KeyValueStore.prototype.uniqueSet = function (key, value) { if (this._data[key] === undefined) { this._data[key] = value; return true; } return false; }; Shared.finishModule('KeyValueStore'); module.exports = KeyValueStore; },{"./Shared":31}],12:[function(_dereq_,module,exports){ "use strict"; var Shared = _dereq_('./Shared'), Operation = _dereq_('./Operation'); /** * The metrics class used to store details about operations. * @constructor */ var Metrics = function () { this.init.apply(this, arguments); }; Metrics.prototype.init = function () { this._data = []; }; Shared.addModule('Metrics', Metrics); Shared.mixin(Metrics.prototype, 'Mixin.ChainReactor'); /** * Creates an operation within the metrics instance and if metrics * are currently enabled (by calling the start() method) the operation * is also stored in the metrics log. * @param {String} name The name of the operation. * @returns {Operation} */ Metrics.prototype.create = function (name) { var op = new Operation(name); if (this._enabled) { this._data.push(op); } return op; }; /** * Starts logging operations. * @returns {Metrics} */ Metrics.prototype.start = function () { this._enabled = true; return this; }; /** * Stops logging operations. * @returns {Metrics} */ Metrics.prototype.stop = function () { this._enabled = false; return this; }; /** * Clears all logged operations. * @returns {Metrics} */ Metrics.prototype.clear = function () { this._data = []; return this; }; /** * Returns an array of all logged operations. * @returns {Array} */ Metrics.prototype.list = function () { return this._data; }; Shared.finishModule('Metrics'); module.exports = Metrics; },{"./Operation":23,"./Shared":31}],13:[function(_dereq_,module,exports){ "use strict"; var CRUD = { preSetData: function () { }, postSetData: function () { } }; module.exports = CRUD; },{}],14:[function(_dereq_,module,exports){ "use strict"; /** * The chain reactor mixin, provides methods to the target object that allow chain * reaction events to propagate to the target and be handled, processed and passed * on down the chain. * @mixin */ var ChainReactor = { /** * * @param obj */ chain: function (obj) { if (this.debug && this.debug()) { if (obj._reactorIn && obj._reactorOut) { console.log(obj._reactorIn.logIdentifier() + ' Adding target "' + obj._reactorOut.instanceIdentifier() + '" to the chain reactor target list'); } else { console.log(this.logIdentifier() + ' Adding target "' + obj.instanceIdentifier() + '" to the chain reactor target list'); } } this._chain = this._chain || []; var index = this._chain.indexOf(obj); if (index === -1) { this._chain.push(obj); } }, unChain: function (obj) { if (this.debug && this.debug()) { if (obj._reactorIn && obj._reactorOut) { console.log(obj._reactorIn.logIdentifier() + ' Removing target "' + obj._reactorOut.instanceIdentifier() + '" from the chain reactor target list'); } else { console.log(this.logIdentifier() + ' Removing target "' + obj.instanceIdentifier() + '" from the chain reactor target list'); } } if (this._chain) { var index = this._chain.indexOf(obj); if (index > -1) { this._chain.splice(index, 1); } } }, chainSend: function (type, data, options) { if (this._chain) { var arr = this._chain, arrItem, count = arr.length, index; for (index = 0; index < count; index++) { arrItem = arr[index]; if (!arrItem._state || (arrItem._state && !arrItem.isDropped())) { if (this.debug && this.debug()) { if (arrItem._reactorIn && arrItem._reactorOut) { console.log(arrItem._reactorIn.logIdentifier() + ' Sending data down the chain reactor pipe to "' + arrItem._reactorOut.instanceIdentifier() + '"'); } else { console.log(this.logIdentifier() + ' Sending data down the chain reactor pipe to "' + arrItem.instanceIdentifier() + '"'); } } arrItem.chainReceive(this, type, data, options); } else { console.log('Reactor Data:', type, data, options); console.log('Reactor Node:', arrItem); throw('Chain reactor attempting to send data to target reactor node that is in a dropped state!'); } } } }, chainReceive: function (sender, type, data, options) { var chainPacket = { sender: sender, type: type, data: data, options: options }; if (this.debug && this.debug()) { console.log(this.logIdentifier() + 'Received data from parent reactor node'); } // Fire our internal handler if (!this._chainHandler || (this._chainHandler && !this._chainHandler(chainPacket))) { // Propagate the message down the chain this.chainSend(chainPacket.type, chainPacket.data, chainPacket.options); } } }; module.exports = ChainReactor; },{}],15:[function(_dereq_,module,exports){ "use strict"; var idCounter = 0, Overload = _dereq_('./Overload'), Serialiser = _dereq_('./Serialiser'), Common, serialiser = new Serialiser(); /** * Provides commonly used methods to most classes in ForerunnerDB. * @mixin */ Common = { // Expose the serialiser object so it can be extended with new data handlers. serialiser: serialiser, /** * Gets / sets data in the item store. The store can be used to set and * retrieve data against a key. Useful for adding arbitrary key/value data * to a collection / view etc and retrieving it later. * @param {String|*} key The key under which to store the passed value or * retrieve the existing stored value. * @param {*=} val Optional value. If passed will overwrite the existing value * stored against the specified key if one currently exists. * @returns {*} */ store: function (key, val) { if (key !== undefined) { if (val !== undefined) { // Store the data this._store = this._store || {}; this._store[key] = val; return this; } if (this._store) { return this._store[key]; } } return undefined; }, /** * Removes a previously stored key/value pair from the item store, set previously * by using the store() method. * @param {String|*} key The key of the key/value pair to remove; * @returns {Common} Returns this for chaining. */ unStore: function (key) { if (key !== undefined) { delete this._store[key]; } return this; }, /** * Returns a non-referenced version of the passed object / array. * @param {Object} data The object or array to return as a non-referenced version. * @param {Number=} copies Optional number of copies to produce. If specified, the return * value will be an array of decoupled objects, each distinct from the other. * @returns {*} */ decouple: function (data, copies) { if (data !== undefined) { if (!copies) { return this.jParse(this.jStringify(data)); } else { var i, json = this.jStringify(data), copyArr = []; for (i = 0; i < copies; i++) { copyArr.push(this.jParse(json)); } return copyArr; } } return undefined; }, /** * Parses and returns data from stringified version. * @param {String} data The stringified version of data to parse. * @returns {Object} The parsed JSON object from the data. */ jParse: function (data) { return serialiser.parse(data); //return JSON.parse(data); }, /** * Converts a JSON object into a stringified version. * @param {Object} data The data to stringify. * @returns {String} The stringified data. */ jStringify: function (data) { return serialiser.stringify(data); //return JSON.stringify(data); }, /** * Generates a new 16-character hexadecimal unique ID or * generates a new 16-character hexadecimal ID based on * the passed string. Will always generate the same ID * for the same string. * @param {String=} str A string to generate the ID from. * @return {String} */ objectId: function (str) { var id, pow = Math.pow(10, 17); if (!str) { idCounter++; id = (idCounter + ( Math.random() * pow + Math.random() * pow + Math.random() * pow + Math.random() * pow )).toString(16); } else { var val = 0, count = str.length, i; for (i = 0; i < count; i++) { val += str.charCodeAt(i) * pow; } id = val.toString(16); } return id; }, /** * Gets / sets debug flag that can enable debug message output to the * console if required. * @param {Boolean} val The value to set debug flag to. * @return {Boolean} True if enabled, false otherwise. */ /** * Sets debug flag for a particular type that can enable debug message * output to the console if required. * @param {String} type The name of the debug type to set flag for. * @param {Boolean} val The value to set debug flag to. * @return {Boolean} True if enabled, false otherwise. */ debug: new Overload([ function () { return this._debug && this._debug.all; }, function (val) { if (val !== undefined) { if (typeof val === 'boolean') { this._debug = this._debug || {}; this._debug.all = val; this.chainSend('debug', this._debug); return this; } else { return (this._debug && this._debug[val]) || (this._db && this._db._debug && this._db._debug[val]) || (this._debug && this._debug.all); } } return this._debug && this._debug.all; }, function (type, val) { if (type !== undefined) { if (val !== undefined) { this._debug = this._debug || {}; this._debug[type] = val; this.chainSend('debug', this._debug); return this; } return (this._debug && this._debug[val]) || (this._db && this._db._debug && this._db._debug[type]); } return this._debug && this._debug.all; } ]), /** * Returns a string describing the class this instance is derived from. * @returns {string} */ classIdentifier: function () { return 'ForerunnerDB.' + this.className; }, /** * Returns a string describing the instance by it's class name and instance * object name. * @returns {String} The instance identifier. */ instanceIdentifier: function () { return '[' + this.className + ']' + this.name(); }, /** * Returns a string used to denote a console log against this instance, * consisting of the class identifier and instance identifier. * @returns {string} The log identifier. */ logIdentifier: function () { return this.classIdentifier() + ': ' + this.instanceIdentifier(); }, /** * Converts a query object with MongoDB dot notation syntax * to Forerunner's object notation syntax. * @param {Object} obj The object to convert. */ convertToFdb: function (obj) { var varName, splitArr, objCopy, i; for (i in obj) { if (obj.hasOwnProperty(i)) { objCopy = obj; if (i.indexOf('.') > -1) { // Replace .$ with a placeholder before splitting by . char i = i.replace('.$', '[|$|]'); splitArr = i.split('.'); while ((varName = splitArr.shift())) { // Replace placeholder back to original .$ varName = varName.replace('[|$|]', '.$'); if (splitArr.length) { objCopy[varName] = {}; } else { objCopy[varName] = obj[i]; } objCopy = objCopy[varName]; } delete obj[i]; } } } }, /** * Checks if the state is dropped. * @returns {boolean} True when dropped, false otherwise. */ isDropped: function () { return this._state === 'dropped'; } }; module.exports = Common; },{"./Overload":24,"./Serialiser":30}],16:[function(_dereq_,module,exports){ "use strict"; /** * Provides some database constants. * @mixin */ var Constants = { TYPE_INSERT: 0, TYPE_UPDATE: 1, TYPE_REMOVE: 2, PHASE_BEFORE: 0, PHASE_AFTER: 1 }; module.exports = Constants; },{}],17:[function(_dereq_,module,exports){ "use strict"; var Overload = _dereq_('./Overload'); /** * Provides event emitter functionality including the methods: on, off, once, emit, deferEmit. * @mixin */ var Events = { on: new Overload({ /** * Attach an event listener to the passed event. * @param {String} event The name of the event to listen for. * @param {Function} listener The method to call when the event is fired. */ 'string, function': function (event, listener) { this._listeners = this._listeners || {}; this._listeners[event] = this._listeners[event] || {}; this._listeners[event]['*'] = this._listeners[event]['*'] || []; this._listeners[event]['*'].push(listener); return this; }, /** * Attach an event listener to the passed event only if the passed * id matches the document id for the event being fired. * @param {String} event The name of the event to listen for. * @param {*} id The document id to match against. * @param {Function} listener The method to call when the event is fired. */ 'string, *, function': function (event, id, listener) { this._listeners = this._listeners || {}; this._listeners[event] = this._listeners[event] || {}; this._listeners[event][id] = this._listeners[event][id] || []; this._listeners[event][id].push(listener); return this; } }), once: new Overload({ 'string, function': function (eventName, callback) { var self = this, internalCallback = function () { self.off(eventName, internalCallback); callback.apply(self, arguments); }; return this.on(eventName, internalCallback); }, 'string, *, function': function (eventName, id, callback) { var self = this, internalCallback = function () { self.off(eventName, id, internalCallback); callback.apply(self, arguments); }; return this.on(eventName, id, internalCallback); } }), off: new Overload({ 'string': function (event) { if (this._listeners && this._listeners[event] && event in this._listeners) { delete this._listeners[event]; } return this; }, 'string, function': function (event, listener) { var arr, index; if (typeof(listener) === 'string') { if (this._listeners && this._listeners[event] && this._listeners[event][listener]) { delete this._listeners[event][listener]; } } else { if (this._listeners && event in this._listeners) { arr = this._listeners[event]['*']; index = arr.indexOf(listener); if (index > -1) { arr.splice(index, 1); } } } return this; }, 'string, *, function': function (event, id, listener) { if (this._listeners && event in this._listeners && id in this.listeners[event]) { var arr = this._listeners[event][id], index = arr.indexOf(listener); if (index > -1) { arr.splice(index, 1); } } }, 'string, *': function (event, id) { if (this._listeners && event in this._listeners && id in this._listeners[event]) { // Kill all listeners for this event id delete this._listeners[event][id]; } } }), emit: function (event, data) { this._listeners = this._listeners || {}; if (event in this._listeners) { var arrIndex, arrCount, tmpFunc, arr, listenerIdArr, listenerIdCount, listenerIdIndex; // Handle global emit if (this._listeners[event]['*']) { arr = this._listeners[event]['*']; arrCount = arr.length; for (arrIndex = 0; arrIndex < arrCount; arrIndex++) { // Check we have a function to execute tmpFunc = arr[arrIndex]; if (typeof tmpFunc === 'function') { tmpFunc.apply(this, Array.prototype.slice.call(arguments, 1)); } } } // Handle individual emit if (data instanceof Array) { // Check if the array is an array of objects in the collection if (data[0] && data[0][this._primaryKey]) { // Loop the array and check for listeners against the primary key listenerIdArr = this._listeners[event]; arrCount = data.length; for (arrIndex = 0; arrIndex < arrCount; arrIndex++) { if (listenerIdArr[data[arrIndex][this._primaryKey]]) { // Emit for this id listenerIdCount = listenerIdArr[data[arrIndex][this._primaryKey]].length; for (listenerIdIndex = 0; listenerIdIndex < listenerIdCount; listenerIdIndex++) { tmpFunc = listenerIdArr[data[arrIndex][this._primaryKey]][listenerIdIndex]; if (typeof tmpFunc === 'function') { listenerIdArr[data[arrIndex][this._primaryKey]][listenerIdIndex].apply(this, Array.prototype.slice.call(arguments, 1)); } } } } } } } return this; }, /** * Queues an event to be fired. This has automatic de-bouncing so that any * events of the same type that occur within 100 milliseconds of a previous * one will all be wrapped into a single emit rather than emitting tons of * events for lots of chained inserts etc. Only the data from the last * de-bounced event will be emitted. * @param {String} eventName The name of the event to emit. * @param {*=} data Optional data to emit with the event. */ deferEmit: function (eventName, data) { var self = this, args; if (!this._noEmitDefer && (!this._db || (this._db && !this._db._noEmitDefer))) { args = arguments; // Check for an existing timeout this._deferTimeout = this._deferTimeout || {}; if (this._deferTimeout[eventName]) { clearTimeout(this._deferTimeout[eventName]); } // Set a timeout this._deferTimeout[eventName] = setTimeout(function () { if (self.debug()) { console.log(self.logIdentifier() + ' Emitting ' + args[0]); } self.emit.apply(self, args); }, 1); } else { this.emit.apply(this, arguments); } return this; } }; module.exports = Events; },{"./Overload":24}],18:[function(_dereq_,module,exports){ "use strict"; /** * Provides object matching algorithm methods. * @mixin */ var Matching = { /** * Internal method that checks a document against a test object. * @param {*} source The source object or value to test against. * @param {*} test The test object or value to test with. * @param {Object} queryOptions The options the query was passed with. * @param {String=} opToApply The special operation to apply to the test such * as 'and' or an 'or' operator. * @param {Object=} options An object containing options to apply to the * operation such as limiting the fields returned etc. * @returns {Boolean} True if the test was positive, false on negative. * @private */ _match: function (source, test, queryOptions, opToApply, options) { // TODO: This method is quite long, break into smaller pieces var operation, applyOp = opToApply, recurseVal, tmpIndex, sourceType = typeof source, testType = typeof test, matchedAll = true, opResult, substringCache, i; options = options || {}; queryOptions = queryOptions || {}; // Check if options currently holds a root query object if (!options.$rootQuery) { // Root query not assigned, hold the root query options.$rootQuery = test; } // Check if options currently holds a root source object if (!options.$rootSource) { // Root query not assigned, hold the root query options.$rootSource = source; } // Assign current query data options.$currentQuery = test; options.$rootData = options.$rootData || {}; // Check if the comparison data are both strings or numbers if ((sourceType === 'string' || sourceType === 'number') && (testType === 'string' || testType === 'number')) { // The source and test data are flat types that do not require recursive searches, // so just compare them and return the result if (sourceType === 'number') { // Number comparison if (source !== test) { matchedAll = false; } } else { // String comparison // TODO: We can probably use a queryOptions.$locale as a second parameter here // TODO: to satisfy https://github.com/Irrelon/ForerunnerDB/issues/35 if (source.localeCompare(test)) { matchedAll = false; } } } else if ((sourceType === 'string' || sourceType === 'number') && (testType === 'object' && test instanceof RegExp)) { if (!test.test(source)) { matchedAll = false; } } else { for (i in test) { if (test.hasOwnProperty(i)) { // Assign previous query data options.$previousQuery = options.$parent; // Assign parent query data options.$parent = { query: test[i], key: i, parent: options.$previousQuery }; // Reset operation flag operation = false; // Grab first two chars of the key name to check for $ substringCache = i.substr(0, 2); // Check if the property is a comment (ignorable) if (substringCache === '//') { // Skip this property continue; } // Check if the property starts with a dollar (function) if (substringCache.indexOf('$') === 0) { // Ask the _matchOp method to handle the operation opResult = this._matchOp(i, source, test[i], queryOptions, options); // Check the result of the matchOp operation // If the result is -1 then no operation took place, otherwise the result // will be a boolean denoting a match (true) or no match (false) if (opResult > -1) { if (opResult) { if (opToApply === 'or') { return true; } } else { // Set the matchedAll flag to the result of the operation // because the operation did not return true matchedAll = opResult; } // Record that an operation was handled operation = true; } } // Check for regex if (!operation && test[i] instanceof RegExp) { operation = true; if (sourceType === 'object' && source[i] !== undefined && test[i].test(source[i])) { if (opToApply === 'or') { return true; } } else { matchedAll = false; } } if (!operation) { // Check if our query is an object if (typeof(test[i]) === 'object') { // Because test[i] is an object, source must also be an object // Check if our source data we are checking the test query against // is an object or an array if (source[i] !== undefined) { if (source[i] instanceof Array && !(test[i] instanceof Array)) { // The source data is an array, so check each item until a // match is found recurseVal = false; for (tmpIndex = 0; tmpIndex < source[i].length; tmpIndex++) { recurseVal = this._match(source[i][tmpIndex], test[i], queryOptions, applyOp, options); if (recurseVal) { // One of the array items matched the query so we can // include this item in the results, so break now break; } } if (recurseVal) { if (opToApply === 'or') { return true; } } else { matchedAll = false; } } else if (!(source[i] instanceof Array) && test[i] instanceof Array) { // The test key data is an array and the source key data is not so check // each item in the test key data to see if the source item matches one // of them. This is effectively an $in search. recurseVal = false; for (tmpIndex = 0; tmpIndex < test[i].length; tmpIndex++) { recurseVal = this._match(source[i], test[i][tmpIndex], queryOptions, applyOp, options); if (recurseVal) { // One of the array items matched the query so we can // include this item in the results, so break now break; } } if (recurseVal) { if (opToApply === 'or') { return true; } } else { matchedAll = false; } } else if (typeof(source) === 'object') { // Recurse down the object tree recurseVal = this._match(source[i], test[i], queryOptions, applyOp, options); if (recurseVal) { if (opToApply === 'or') { return true; } } else { matchedAll = false; } } else { recurseVal = this._match(undefined, test[i], queryOptions, applyOp, options); if (recurseVal) { if (opToApply === 'or') { return true; } } else { matchedAll = false; } } } else { // First check if the test match is an $exists if (test[i] && test[i].$exists !== undefined) { // Push the item through another match recurse recurseVal = this._match(undefined, test[i], queryOptions, applyOp, options); if (recurseVal) { if (opToApply === 'or') { return true; } } else { matchedAll = false; } } else { matchedAll = false; } } } else { // Check if the prop matches our test value if (source && source[i] === test[i]) { if (opToApply === 'or') { return true; } } else if (source && source[i] && source[i] instanceof Array && test[i] && typeof(test[i]) !== "object") { // We are looking for a value inside an array // The source data is an array, so check each item until a // match is found recurseVal = false; for (tmpIndex = 0; tmpIndex < source[i].length; tmpIndex++) { recurseVal = this._match(source[i][tmpIndex], test[i], queryOptions, applyOp, options); if (recurseVal) { // One of the array items matched the query so we can // include this item in the results, so break now break; } } if (recurseVal) { if (opToApply === 'or') { return true; } } else { matchedAll = false; } } else { matchedAll = false; } } } if (opToApply === 'and' && !matchedAll) { return false; } } } } return matchedAll; }, /** * Internal method, performs a matching process against a query operator such as $gt or $nin. * @param {String} key The property name in the test that matches the operator to perform * matching against. * @param {*} source The source data to match the query against. * @param {*} test The query to match the source against. * @param {Object} queryOptions The options the query was passed with. * @param {Object=} options An options object. * @returns {*} * @private */ _matchOp: function (key, source, test, queryOptions, options) { // Check for commands switch (key) { case '$gt': // Greater than return source > test; case '$gte': // Greater than or equal return source >= test; case '$lt': // Less than return source < test; case '$lte': // Less than or equal return source <= test; case '$exists': // Property exists return (source === undefined) !== test; case '$eq': // Equals return source == test; // jshint ignore:line case '$eeq': // Equals equals return source === test; case '$ne': // Not equals return source != test; // jshint ignore:line case '$nee': // Not equals equals return source !== test; case '$or': // Match true on ANY check to pass for (var orIndex = 0; orIndex < test.length; orIndex++) { if (this._match(source, test[orIndex], queryOptions, 'and', options)) { return true; } } return false; case '$and': // Match true on ALL checks to pass for (var andIndex = 0; andIndex < test.length; andIndex++) { if (!this._match(source, test[andIndex], queryOptions, 'and', options)) { return false; } } return true; case '$in': // In // Check that the in test is an array if (test instanceof Array) { var inArr = test, inArrCount = inArr.length, inArrIndex; for (inArrIndex = 0; inArrIndex < inArrCount; inArrIndex++) { if (this._match(source, inArr[inArrIndex], queryOptions, 'and', options)) { return true; } } return false; } else if (typeof test === 'object') { return this._match(source, test, queryOptions, 'and', options); } else { throw(this.logIdentifier() + ' Cannot use an $in operator on a non-array key: ' + key); } break; case '$nin': // Not in // Check that the not-in test is an array if (test instanceof Array) { var notInArr = test, notInArrCount = notInArr.length, notInArrIndex; for (notInArrIndex = 0; notInArrIndex < notInArrCount; notInArrIndex++) { if (this._match(source, notInArr[notInArrIndex], queryOptions, 'and', options)) { return false; } } return true; } else if (typeof test === 'object') { return this._match(source, test, queryOptions, 'and', options); } else { throw(this.logIdentifier() + ' Cannot use a $nin operator on a non-array key: ' + key); } break; case '$distinct': // Ensure options holds a distinct lookup options.$rootData['//distinctLookup'] = options.$rootData['//distinctLookup'] || {}; for (var distinctProp in test) { if (test.hasOwnProperty(distinctProp)) { options.$rootData['//distinctLookup'][distinctProp] = options.$rootData['//distinctLookup'][distinctProp] || {}; // Check if the options distinct lookup has this field's value if (options.$rootData['//distinctLookup'][distinctProp][source[distinctProp]]) { // Value is already in use return false; } else { // Set the value in the lookup options.$rootData['//distinctLookup'][distinctProp][source[distinctProp]] = true; // Allow the item in the results return true; } } } break; case '$count': var countKey, countArr, countVal; // Iterate the count object's keys for (countKey in test) { if (test.hasOwnProperty(countKey)) { // Check the property exists and is an array. If the property being counted is not // an array (or doesn't exist) then use a value of zero in any further count logic countArr = source[countKey]; if (typeof countArr === 'object' && countArr instanceof Array) { countVal = countArr.length; } else { countVal = 0; } // Now recurse down the query chain further to satisfy the query for this key (countKey) if (!this._match(countVal, test[countKey], queryOptions, 'and', options)) { return false; } } } // Allow the item in the results return true; case '$find': case '$findOne': case '$findSub': var fromType = 'collection', findQuery, findOptions, subQuery, subOptions, subPath, result, operation = {}; // Check we have a database object to work from if (!this.db()) { throw('Cannot operate a ' + key + ' sub-query on an anonymous collection (one with no db set)!'); } // Check all parts of the $find operation exist if (!test.$from) { throw(key + ' missing $from property!'); } if (test.$fromType) { fromType = test.$fromType; // Check the fromType exists as a method if (!this.db()[fromType] || typeof this.db()[fromType] !== 'function') { throw(key + ' cannot operate against $fromType "' + fromType + '" because the database does not recognise this type of object!'); } } // Perform the find operation findQuery = test.$query || {}; findOptions = test.$options || {}; if (key === '$findSub') { if (!test.$path) { throw(key + ' missing $path property!'); } subPath = test.$path; subQuery = test.$subQuery || {}; subOptions = test.$subOptions || {}; result = this.db()[fromType](test.$from).findSub(findQuery, subPath, subQuery, subOptions); } else { result = this.db()[fromType](test.$from)[key.substr(1)](findQuery, findOptions); } operation[options.$parent.parent.key] = result; return this._match(source, operation, queryOptions, 'and', options); } return -1; } }; module.exports = Matching; },{}],19:[function(_dereq_,module,exports){ "use strict"; /** * Provides sorting methods. * @mixin */ var Sorting = { /** * Sorts the passed value a against the passed value b ascending. * @param {*} a The first value to compare. * @param {*} b The second value to compare. * @returns {*} 1 if a is sorted after b, -1 if a is sorted before b. */ sortAsc: function (a, b) { if (typeof(a) === 'string' && typeof(b) === 'string') { return a.localeCompare(b); } else { if (a > b) { return 1; } else if (a < b) { return -1; } } return 0; }, /** * Sorts the passed value a against the passed value b descending. * @param {*} a The first value to compare. * @param {*} b The second value to compare. * @returns {*} 1 if a is sorted after b, -1 if a is sorted before b. */ sortDesc: function (a, b) { if (typeof(a) === 'string' && typeof(b) === 'string') { return b.localeCompare(a); } else { if (a > b) { return -1; } else if (a < b) { return 1; } } return 0; } }; module.exports = Sorting; },{}],20:[function(_dereq_,module,exports){ "use strict"; var Tags, tagMap = {}; /** * Provides class instance tagging and tag operation methods. * @mixin */ Tags = { /** * Tags a class instance for later lookup. * @param {String} name The tag to add. * @returns {boolean} */ tagAdd: function (name) { var i, self = this, mapArr = tagMap[name] = tagMap[name] || []; for (i = 0; i < mapArr.length; i++) { if (mapArr[i] === self) { return true; } } mapArr.push(self); // Hook the drop event for this so we can react if (self.on) { self.on('drop', function () { // We've been dropped so remove ourselves from the tag map self.tagRemove(name); }); } return true; }, /** * Removes a tag from a class instance. * @param {String} name The tag to remove. * @returns {boolean} */ tagRemove: function (name) { var i, mapArr = tagMap[name]; if (mapArr) { for (i = 0; i < mapArr.length; i++) { if (mapArr[i] === this) { mapArr.splice(i, 1); return true; } } } return false; }, /** * Gets an array of all instances tagged with the passed tag name. * @param {String} name The tag to lookup. * @returns {Array} The array of instances that have the passed tag. */ tagLookup: function (name) { return tagMap[name] || []; }, /** * Drops all instances that are tagged with the passed tag name. * @param {String} name The tag to lookup. * @param {Function} callback Callback once dropping has completed * for all instances that match the passed tag name. * @returns {boolean} */ tagDrop: function (name, callback) { var arr = this.tagLookup(name), dropCb, dropCount, i; dropCb = function () { dropCount--; if (callback && dropCount === 0) { callback(false); } }; if (arr.length) { dropCount = arr.length; // Loop the array and drop all items for (i = arr.length - 1; i >= 0; i--) { arr[i].drop(dropCb); } } return true; } }; module.exports = Tags; },{}],21:[function(_dereq_,module,exports){ "use strict"; var Overload = _dereq_('./Overload'); /** * Provides trigger functionality methods. * @mixin */ var Triggers = { /** * Add a trigger by id. * @param {String} id The id of the trigger. This must be unique to the type and * phase of the trigger. Only one trigger may be added with this id per type and * phase. * @param {Number} type The type of operation to apply the trigger to. See * Mixin.Constants for constants to use. * @param {Number} phase The phase of an operation to fire the trigger on. See * Mixin.Constants for constants to use. * @param {Function} method The method to call when the trigger is fired. * @returns {boolean} True if the trigger was added successfully, false if not. */ addTrigger: function (id, type, phase, method) { var self = this, triggerIndex; // Check if the trigger already exists triggerIndex = self._triggerIndexOf(id, type, phase); if (triggerIndex === -1) { // The trigger does not exist, create it self._trigger = self._trigger || {}; self._trigger[type] = self._trigger[type] || {}; self._trigger[type][phase] = self._trigger[type][phase] || []; self._trigger[type][phase].push({ id: id, method: method, enabled: true }); return true; } return false; }, /** * * @param {String} id The id of the trigger to remove. * @param {Number} type The type of operation to remove the trigger from. See * Mixin.Constants for constants to use. * @param {Number} phase The phase of the operation to remove the trigger from. * See Mixin.Constants for constants to use. * @returns {boolean} True if removed successfully, false if not. */ removeTrigger: function (id, type, phase) { var self = this, triggerIndex; // Check if the trigger already exists triggerIndex = self._triggerIndexOf(id, type, phase); if (triggerIndex > -1) { // The trigger exists, remove it self._trigger[type][phase].splice(triggerIndex, 1); } return false; }, enableTrigger: new Overload({ 'string': function (id) { // Alter all triggers of this type var self = this, types = self._trigger, phases, triggers, result = false, i, k, j; if (types) { for (j in types) { if (types.hasOwnProperty(j)) { phases = types[j]; if (phases) { for (i in phases) { if (phases.hasOwnProperty(i)) { triggers = phases[i]; // Loop triggers and set enabled flag for (k = 0; k < triggers.length; k++) { if (triggers[k].id === id) { triggers[k].enabled = true; result = true; } } } } } } } } return result; }, 'number': function (type) { // Alter all triggers of this type var self = this, phases = self._trigger[type], triggers, result = false, i, k; if (phases) { for (i in phases) { if (phases.hasOwnProperty(i)) { triggers = phases[i]; // Loop triggers and set to enabled for (k = 0; k < triggers.length; k++) { triggers[k].enabled = true; result = true; } } } } return result; }, 'number, number': function (type, phase) { // Alter all triggers of this type and phase var self = this, phases = self._trigger[type], triggers, result = false, k; if (phases) { triggers = phases[phase]; if (triggers) { // Loop triggers and set to enabled for (k = 0; k < triggers.length; k++) { triggers[k].enabled = true; result = true; } } } return result; }, 'string, number, number': function (id, type, phase) { // Check if the trigger already exists var self = this, triggerIndex = self._triggerIndexOf(id, type, phase); if (triggerIndex > -1) { // Update the trigger self._trigger[type][phase][triggerIndex].enabled = true; return true; } return false; } }), disableTrigger: new Overload({ 'string': function (id) { // Alter all triggers of this type var self = this, types = self._trigger, phases, triggers, result = false, i, k, j; if (types) { for (j in types) { if (types.hasOwnProperty(j)) { phases = types[j]; if (phases) { for (i in phases) { if (phases.hasOwnProperty(i)) { triggers = phases[i]; // Loop triggers and set enabled flag for (k = 0; k < triggers.length; k++) { if (triggers[k].id === id) { triggers[k].enabled = false; result = true; } } } } } } } } return result; }, 'number': function (type) { // Alter all triggers of this type var self = this, phases = self._trigger[type], triggers, result = false, i, k; if (phases) { for (i in phases) { if (phases.hasOwnProperty(i)) { triggers = phases[i]; // Loop triggers and set to disabled for (k = 0; k < triggers.length; k++) { triggers[k].enabled = false; result = true; } } } } return result; }, 'number, number': function (type, phase) { // Alter all triggers of this type and phase var self = this, phases = self._trigger[type], triggers, result = false, k; if (phases) { triggers = phases[phase]; if (triggers) { // Loop triggers and set to disabled for (k = 0; k < triggers.length; k++) { triggers[k].enabled = false; result = true; } } } return result; }, 'string, number, number': function (id, type, phase) { // Check if the trigger already exists var self = this, triggerIndex = self._triggerIndexOf(id, type, phase); if (triggerIndex > -1) { // Update the trigger self._trigger[type][phase][triggerIndex].enabled = false; return true; } return false; } }), /** * Checks if a trigger will fire based on the type and phase provided. * @param {Number} type The type of operation. See Mixin.Constants for * constants to use. * @param {Number} phase The phase of the operation. See Mixin.Constants * for constants to use. * @returns {Boolean} True if the trigger will fire, false otherwise. */ willTrigger: function (type, phase) { if (this._trigger && this._trigger[type] && this._trigger[type][phase] && this._trigger[type][phase].length) { // Check if a trigger in this array is enabled var arr = this._trigger[type][phase], i; for (i = 0; i < arr.length; i++) { if (arr[i].enabled) { return true; } } } return false; }, /** * Processes trigger actions based on the operation, type and phase. * @param {Object} operation Operation data to pass to the trigger. * @param {Number} type The type of operation. See Mixin.Constants for * constants to use. * @param {Number} phase The phase of the operation. See Mixin.Constants * for constants to use. * @param {Object} oldDoc The document snapshot before operations are * carried out against the data. * @param {Object} newDoc The document snapshot after operations are * carried out against the data. * @returns {boolean} */ processTrigger: function (operation, type, phase, oldDoc, newDoc) { var self = this, triggerArr, triggerIndex, triggerCount, triggerItem, response; if (self._trigger && self._trigger[type] && self._trigger[type][phase]) { triggerArr = self._trigger[type][phase]; triggerCount = triggerArr.length; for (triggerIndex = 0; triggerIndex < triggerCount; triggerIndex++) { triggerItem = triggerArr[triggerIndex]; // Check if the trigger is enabled if (triggerItem.enabled) { if (this.debug()) { var typeName, phaseName; switch (type) { case this.TYPE_INSERT: typeName = 'insert'; break; case this.TYPE_UPDATE: typeName = 'update'; break; case this.TYPE_REMOVE: typeName = 'remove'; break; default: typeName = ''; break; } switch (phase) { case this.PHASE_BEFORE: phaseName = 'before'; break; case this.PHASE_AFTER: phaseName = 'after'; break; default: phaseName = ''; break; } //console.log('Triggers: Processing trigger "' + id + '" for ' + typeName + ' in phase "' + phaseName + '"'); } // Run the trigger's method and store the response response = triggerItem.method.call(self, operation, oldDoc, newDoc); // Check the response for a non-expected result (anything other than // undefined, true or false is considered a throwable error) if (response === false) { // The trigger wants us to cancel operations return false; } if (response !== undefined && response !== true && response !== false) { // Trigger responded with error, throw the error throw('ForerunnerDB.Mixin.Triggers: Trigger error: ' + response); } } } // Triggers all ran without issue, return a success (true) return true; } }, /** * Returns the index of a trigger by id based on type and phase. * @param {String} id The id of the trigger to find the index of. * @param {Number} type The type of operation. See Mixin.Constants for * constants to use. * @param {Number} phase The phase of the operation. See Mixin.Constants * for constants to use. * @returns {number} * @private */ _triggerIndexOf: function (id, type, phase) { var self = this, triggerArr, triggerCount, triggerIndex; if (self._trigger && self._trigger[type] && self._trigger[type][phase]) { triggerArr = self._trigger[type][phase]; triggerCount = triggerArr.length; for (triggerIndex = 0; triggerIndex < triggerCount; triggerIndex++) { if (triggerArr[triggerIndex].id === id) { return triggerIndex; } } } return -1; } }; module.exports = Triggers; },{"./Overload":24}],22:[function(_dereq_,module,exports){ "use strict"; /** * Provides methods to handle object update operations. * @mixin */ var Updating = { /** * Updates a property on an object. * @param {Object} doc The object whose property is to be updated. * @param {String} prop The property to update. * @param {*} val The new value of the property. * @private */ _updateProperty: function (doc, prop, val) { doc[prop] = val; if (this.debug()) { console.log(this.logIdentifier() + ' Setting non-data-bound document property "' + prop + '"'); } }, /** * Increments a value for a property on a document by the passed number. * @param {Object} doc The document to modify. * @param {String} prop The property to modify. * @param {Number} val The amount to increment by. * @private */ _updateIncrement: function (doc, prop, val) { doc[prop] += val; }, /** * Changes the index of an item in the passed array. * @param {Array} arr The array to modify. * @param {Number} indexFrom The index to move the item from. * @param {Number} indexTo The index to move the item to. * @private */ _updateSpliceMove: function (arr, indexFrom, indexTo) { arr.splice(indexTo, 0, arr.splice(indexFrom, 1)[0]); if (this.debug()) { console.log(this.logIdentifier() + ' Moving non-data-bound document array index from "' + indexFrom + '" to "' + indexTo + '"'); } }, /** * Inserts an item into the passed array at the specified index. * @param {Array} arr The array to insert into. * @param {Number} index The index to insert at. * @param {Object} doc The document to insert. * @private */ _updateSplicePush: function (arr, index, doc) { if (arr.length > index) { arr.splice(index, 0, doc); } else { arr.push(doc); } }, /** * Inserts an item at the end of an array. * @param {Array} arr The array to insert the item into. * @param {Object} doc The document to insert. * @private */ _updatePush: function (arr, doc) { arr.push(doc); }, /** * Removes an item from the passed array. * @param {Array} arr The array to modify. * @param {Number} index The index of the item in the array to remove. * @private */ _updatePull: function (arr, index) { arr.splice(index, 1); }, /** * Multiplies a value for a property on a document by the passed number. * @param {Object} doc The document to modify. * @param {String} prop The property to modify. * @param {Number} val The amount to multiply by. * @private */ _updateMultiply: function (doc, prop, val) { doc[prop] *= val; }, /** * Renames a property on a document to the passed property. * @param {Object} doc The document to modify. * @param {String} prop The property to rename. * @param {Number} val The new property name. * @private */ _updateRename: function (doc, prop, val) { doc[val] = doc[prop]; delete doc[prop]; }, /** * Sets a property on a document to the passed value. * @param {Object} doc The document to modify. * @param {String} prop The property to delete. * @param {*} val The new property value. * @private */ _updateOverwrite: function (doc, prop, val) { doc[prop] = val; }, /** * Deletes a property on a document. * @param {Object} doc The document to modify. * @param {String} prop The property to delete. * @private */ _updateUnset: function (doc, prop) { delete doc[prop]; }, /** * Removes all properties from an object without destroying * the object instance, thereby maintaining data-bound linking. * @param {Object} doc The parent object to modify. * @param {String} prop The name of the child object to clear. * @private */ _updateClear: function (doc, prop) { var obj = doc[prop], i; if (obj && typeof obj === 'object') { for (i in obj) { if (obj.hasOwnProperty(i)) { this._updateUnset(obj, i); } } } }, /** * Pops an item or items from the array stack. * @param {Object} doc The document to modify. * @param {Number} val If set to a positive integer, will pop the number specified * from the stack, if set to a negative integer will shift the number specified * from the stack. * @return {Boolean} * @private */ _updatePop: function (doc, val) { var updated = false, i; if (doc.length > 0) { if (val > 0) { for (i = 0; i < val; i++) { doc.pop(); } updated = true; } else if (val < 0) { for (i = 0; i > val; i--) { doc.shift(); } updated = true; } } return updated; } }; module.exports = Updating; },{}],23:[function(_dereq_,module,exports){ "use strict"; var Shared = _dereq_('./Shared'), Path = _dereq_('./Path'); /** * The operation class, used to store details about an operation being * performed by the database. * @param {String} name The name of the operation. * @constructor */ var Operation = function (name) { this.pathSolver = new Path(); this.counter = 0; this.init.apply(this, arguments); }; Operation.prototype.init = function (name) { this._data = { operation: name, // The name of the operation executed such as "find", "update" etc index: { potential: [], // Indexes that could have potentially been used used: false // The index that was picked to use }, steps: [], // The steps taken to generate the query results, time: { startMs: 0, stopMs: 0, totalMs: 0, process: {} }, flag: {}, // An object with flags that denote certain execution paths log: [] // Any extra data that might be useful such as warnings or helpful hints }; }; Shared.addModule('Operation', Operation); Shared.mixin(Operation.prototype, 'Mixin.ChainReactor'); /** * Starts the operation timer. */ Operation.prototype.start = function () { this._data.time.startMs = new Date().getTime(); }; /** * Adds an item to the operation log. * @param {String} event The item to log. * @returns {*} */ Operation.prototype.log = function (event) { if (event) { var lastLogTime = this._log.length > 0 ? this._data.log[this._data.log.length - 1].time : 0, logObj = { event: event, time: new Date().getTime(), delta: 0 }; this._data.log.push(logObj); if (lastLogTime) { logObj.delta = logObj.time - lastLogTime; } return this; } return this._data.log; }; /** * Called when starting and ending a timed operation, used to time * internal calls within an operation's execution. * @param {String} section An operation name. * @returns {*} */ Operation.prototype.time = function (section) { if (section !== undefined) { var process = this._data.time.process, processObj = process[section] = process[section] || {}; if (!processObj.startMs) { // Timer started processObj.startMs = new Date().getTime(); processObj.stepObj = { name: section }; this._data.steps.push(processObj.stepObj); } else { processObj.stopMs = new Date().getTime(); processObj.totalMs = processObj.stopMs - processObj.startMs; processObj.stepObj.totalMs = processObj.totalMs; delete processObj.stepObj; } return this; } return this._data.time; }; /** * Used to set key/value flags during operation execution. * @param {String} key * @param {String} val * @returns {*} */ Operation.prototype.flag = function (key, val) { if (key !== undefined && val !== undefined) { this._data.flag[key] = val; } else if (key !== undefined) { return this._data.flag[key]; } else { return this._data.flag; } }; Operation.prototype.data = function (path, val, noTime) { if (val !== undefined) { // Assign value to object path this.pathSolver.set(this._data, path, val); return this; } return this.pathSolver.get(this._data, path); }; Operation.prototype.pushData = function (path, val, noTime) { // Assign value to object path this.pathSolver.push(this._data, path, val); }; /** * Stops the operation timer. */ Operation.prototype.stop = function () { this._data.time.stopMs = new Date().getTime(); this._data.time.totalMs = this._data.time.stopMs - this._data.time.startMs; }; Shared.finishModule('Operation'); module.exports = Operation; },{"./Path":25,"./Shared":31}],24:[function(_dereq_,module,exports){ "use strict"; /** * Allows a method to accept overloaded calls with different parameters controlling * which passed overload function is called. * @param {Object} def * @returns {Function} * @constructor */ var Overload = function (def) { if (def) { var self = this, index, count, tmpDef, defNewKey, sigIndex, signatures; if (!(def instanceof Array)) { tmpDef = {}; // Def is an object, make sure all prop names are devoid of spaces for (index in def) { if (def.hasOwnProperty(index)) { defNewKey = index.replace(/ /g, ''); // Check if the definition array has a * string in it if (defNewKey.indexOf('*') === -1) { // No * found tmpDef[defNewKey] = def[index]; } else { // A * was found, generate the different signatures that this // definition could represent signatures = this.generateSignaturePermutations(defNewKey); for (sigIndex = 0; sigIndex < signatures.length; sigIndex++) { if (!tmpDef[signatures[sigIndex]]) { tmpDef[signatures[sigIndex]] = def[index]; } } } } } def = tmpDef; } return function () { var arr = [], lookup, type, name; // Check if we are being passed a key/function object or an array of functions if (def instanceof Array) { // We were passed an array of functions count = def.length; for (index = 0; index < count; index++) { if (def[index].length === arguments.length) { return self.callExtend(this, '$main', def, def[index], arguments); } } } else { // Generate lookup key from arguments // Copy arguments to an array for (index = 0; index < arguments.length; index++) { type = typeof arguments[index]; // Handle detecting arrays if (type === 'object' && arguments[index] instanceof Array) { type = 'array'; } // Handle been presented with a single undefined argument if (arguments.length === 1 && type === 'undefined') { break; } // Add the type to the argument types array arr.push(type); } lookup = arr.join(','); // Check for an exact lookup match if (def[lookup]) { return self.callExtend(this, '$main', def, def[lookup], arguments); } else { for (index = arr.length; index >= 0; index--) { // Get the closest match lookup = arr.slice(0, index).join(','); if (def[lookup + ',...']) { // Matched against arguments + "any other" return self.callExtend(this, '$main', def, def[lookup + ',...'], arguments); } } } } name = typeof this.name === 'function' ? this.name() : 'Unknown'; console.log('Overload: ', def); throw('ForerunnerDB.Overload "' + name + '": Overloaded method does not have a matching signature for the passed arguments: ' + this.jStringify(arr)); }; } return function () {}; }; /** * Generates an array of all the different definition signatures that can be * created from the passed string with a catch-all wildcard *. E.g. it will * convert the signature: string,*,string to all potentials: * string,string,string * string,number,string * string,object,string, * string,function,string, * string,undefined,string * * @param {String} str Signature string with a wildcard in it. * @returns {Array} An array of signature strings that are generated. */ Overload.prototype.generateSignaturePermutations = function (str) { var signatures = [], newSignature, types = ['string', 'object', 'number', 'function', 'undefined'], index; if (str.indexOf('*') > -1) { // There is at least one "any" type, break out into multiple keys // We could do this at query time with regular expressions but // would be significantly slower for (index = 0; index < types.length; index++) { newSignature = str.replace('*', types[index]); signatures = signatures.concat(this.generateSignaturePermutations(newSignature)); } } else { signatures.push(str); } return signatures; }; Overload.prototype.callExtend = function (context, prop, propContext, func, args) { var tmp, ret; if (context && propContext[prop]) { tmp = context[prop]; context[prop] = propContext[prop]; ret = func.apply(context, args); context[prop] = tmp; return ret; } else { return func.apply(context, args); } }; module.exports = Overload; },{}],25:[function(_dereq_,module,exports){ "use strict"; var Shared = _dereq_('./Shared'); /** * Path object used to resolve object paths and retrieve data from * objects by using paths. * @param {String=} path The path to assign. * @constructor */ var Path = function (path) { this.init.apply(this, arguments); }; Path.prototype.init = function (path) { if (path) { this.path(path); } }; Shared.addModule('Path', Path); Shared.mixin(Path.prototype, 'Mixin.Common'); Shared.mixin(Path.prototype, 'Mixin.ChainReactor'); /** * Gets / sets the given path for the Path instance. * @param {String=} path The path to assign. */ Path.prototype.path = function (path) { if (path !== undefined) { this._path = this.clean(path); this._pathParts = this._path.split('.'); return this; } return this._path; }; /** * Tests if the passed object has the paths that are specified and that * a value exists in those paths. * @param {Object} testKeys The object describing the paths to test for. * @param {Object} testObj The object to test paths against. * @returns {Boolean} True if the object paths exist. */ Path.prototype.hasObjectPaths = function (testKeys, testObj) { var result = true, i; for (i in testKeys) { if (testKeys.hasOwnProperty(i)) { if (testObj[i] === undefined) { return false; } if (typeof testKeys[i] === 'object') { // Recurse object result = this.hasObjectPaths(testKeys[i], testObj[i]); // Should we exit early? if (!result) { return false; } } } } return result; }; /** * Counts the total number of key endpoints in the passed object. * @param {Object} testObj The object to count key endpoints for. * @returns {Number} The number of endpoints. */ Path.prototype.countKeys = function (testObj) { var totalKeys = 0, i; for (i in testObj) { if (testObj.hasOwnProperty(i)) { if (testObj[i] !== undefined) { if (typeof testObj[i] !== 'object') { totalKeys++; } else { totalKeys += this.countKeys(testObj[i]); } } } } return totalKeys; }; /** * Tests if the passed object has the paths that are specified and that * a value exists in those paths and if so returns the number matched. * @param {Object} testKeys The object describing the paths to test for. * @param {Object} testObj The object to test paths against. * @returns {Object} Stats on the matched keys */ Path.prototype.countObjectPaths = function (testKeys, testObj) { var matchData, matchedKeys = {}, matchedKeyCount = 0, totalKeyCount = 0, i; for (i in testObj) { if (testObj.hasOwnProperty(i)) { if (typeof testObj[i] === 'object') { // The test / query object key is an object, recurse matchData = this.countObjectPaths(testKeys[i], testObj[i]); matchedKeys[i] = matchData.matchedKeys; totalKeyCount += matchData.totalKeyCount; matchedKeyCount += matchData.matchedKeyCount; } else { // The test / query object has a property that is not an object so add it as a key totalKeyCount++; // Check if the test keys also have this key and it is also not an object if (testKeys && testKeys[i] && typeof testKeys[i] !== 'object') { matchedKeys[i] = true; matchedKeyCount++; } else { matchedKeys[i] = false; } } } } return { matchedKeys: matchedKeys, matchedKeyCount: matchedKeyCount, totalKeyCount: totalKeyCount }; }; /** * Takes a non-recursive object and converts the object hierarchy into * a path string. * @param {Object} obj The object to parse. * @param {Boolean=} withValue If true will include a 'value' key in the returned * object that represents the value the object path points to. * @returns {Object} */ Path.prototype.parse = function (obj, withValue) { var paths = [], path = '', resultData, i, k; for (i in obj) { if (obj.hasOwnProperty(i)) { // Set the path to the key path = i; if (typeof(obj[i]) === 'object') { if (withValue) { resultData = this.parse(obj[i], withValue); for (k = 0; k < resultData.length; k++) { paths.push({ path: path + '.' + resultData[k].path, value: resultData[k].value }); } } else { resultData = this.parse(obj[i]); for (k = 0; k < resultData.length; k++) { paths.push({ path: path + '.' + resultData[k].path }); } } } else { if (withValue) { paths.push({ path: path, value: obj[i] }); } else { paths.push({ path: path }); } } } } return paths; }; /** * Takes a non-recursive object and converts the object hierarchy into * an array of path strings that allow you to target all possible paths * in an object. * * The options object accepts an "ignore" field with a regular expression * as the value. If any key matches the expression it is not included in * the results. * * The options object accepts a boolean "verbose" field. If set to true * the results will include all paths leading up to endpoints as well as * they endpoints themselves. * * @returns {Array} */ Path.prototype.parseArr = function (obj, options) { options = options || {}; return this._parseArr(obj, '', [], options); }; Path.prototype._parseArr = function (obj, path, paths, options) { var i, newPath = ''; path = path || ''; paths = paths || []; for (i in obj) { if (obj.hasOwnProperty(i)) { if (!options.ignore || (options.ignore && !options.ignore.test(i))) { if (path) { newPath = path + '.' + i; } else { newPath = i; } if (typeof(obj[i]) === 'object') { if (options.verbose) { paths.push(newPath); } this._parseArr(obj[i], newPath, paths, options); } else { paths.push(newPath); } } } } return paths; }; Path.prototype.valueOne = function (obj, path) { return this.value(obj, path)[0]; }; /** * Gets the value(s) that the object contains for the currently assigned path string. * @param {Object} obj The object to evaluate the path against. * @param {String=} path A path to use instead of the existing one passed in path(). * @param {Object=} options An optional options object. * @returns {Array} An array of values for the given path. */ Path.prototype.value = function (obj, path, options) { var pathParts, arr, arrCount, objPart, objPartParent, valuesArr, returnArr, i, k; if (obj !== undefined && typeof obj === 'object') { if (!options || options && !options.skipArrCheck) { // Check if we were passed an array of objects and if so, // iterate over the array and return the value from each // array item if (obj instanceof Array) { returnArr = []; for (i = 0; i < obj.length; i++) { returnArr.push(this.valueOne(obj[i], path)); } return returnArr; } } valuesArr = []; if (path !== undefined) { path = this.clean(path); pathParts = path.split('.'); } arr = pathParts || this._pathParts; arrCount = arr.length; objPart = obj; for (i = 0; i < arrCount; i++) { objPart = objPart[arr[i]]; if (objPartParent instanceof Array) { // Search inside the array for the next key for (k = 0; k < objPartParent.length; k++) { valuesArr = valuesArr.concat(this.value(objPartParent, k + '.' + arr[i], {skipArrCheck: true})); } return valuesArr; } else { if (!objPart || typeof(objPart) !== 'object') { break; } } objPartParent = objPart; } return [objPart]; } else { return []; } }; /** * Sets a value on an object for the specified path. * @param {Object} obj The object to update. * @param {String} path The path to update. * @param {*} val The value to set the object path to. * @returns {*} */ Path.prototype.set = function (obj, path, val) { if (obj !== undefined && path !== undefined) { var pathParts, part; path = this.clean(path); pathParts = path.split('.'); part = pathParts.shift(); if (pathParts.length) { // Generate the path part in the object if it does not already exist obj[part] = obj[part] || {}; // Recurse this.set(obj[part], pathParts.join('.'), val); } else { // Set the value obj[part] = val; } } return obj; }; Path.prototype.get = function (obj, path) { return this.value(obj, path)[0]; }; /** * Push a value to an array on an object for the specified path. * @param {Object} obj The object to update. * @param {String} path The path to the array to push to. * @param {*} val The value to push to the array at the object path. * @returns {*} */ Path.prototype.push = function (obj, path, val) { if (obj !== undefined && path !== undefined) { var pathParts, part; path = this.clean(path); pathParts = path.split('.'); part = pathParts.shift(); if (pathParts.length) { // Generate the path part in the object if it does not already exist obj[part] = obj[part] || {}; // Recurse this.set(obj[part], pathParts.join('.'), val); } else { // Set the value obj[part] = obj[part] || []; if (obj[part] instanceof Array) { obj[part].push(val); } else { throw('ForerunnerDB.Path: Cannot push to a path whose endpoint is not an array!'); } } } return obj; }; /** * Gets the value(s) that the object contains for the currently assigned path string * with their associated keys. * @param {Object} obj The object to evaluate the path against. * @param {String=} path A path to use instead of the existing one passed in path(). * @returns {Array} An array of values for the given path with the associated key. */ Path.prototype.keyValue = function (obj, path) { var pathParts, arr, arrCount, objPart, objPartParent, objPartHash, i; if (path !== undefined) { path = this.clean(path); pathParts = path.split('.'); } arr = pathParts || this._pathParts; arrCount = arr.length; objPart = obj; for (i = 0; i < arrCount; i++) { objPart = objPart[arr[i]]; if (!objPart || typeof(objPart) !== 'object') { objPartHash = arr[i] + ':' + objPart; break; } objPartParent = objPart; } return objPartHash; }; /** * Sets a value on an object for the specified path. * @param {Object} obj The object to update. * @param {String} path The path to update. * @param {*} val The value to set the object path to. * @returns {*} */ Path.prototype.set = function (obj, path, val) { if (obj !== undefined && path !== undefined) { var pathParts, part; path = this.clean(path); pathParts = path.split('.'); part = pathParts.shift(); if (pathParts.length) { // Generate the path part in the object if it does not already exist obj[part] = obj[part] || {}; // Recurse this.set(obj[part], pathParts.join('.'), val); } else { // Set the value obj[part] = val; } } return obj; }; /** * Removes leading period (.) from string and returns it. * @param {String} str The string to clean. * @returns {*} */ Path.prototype.clean = function (str) { if (str.substr(0, 1) === '.') { str = str.substr(1, str.length -1); } return str; }; Shared.finishModule('Path'); module.exports = Path; },{"./Shared":31}],26:[function(_dereq_,module,exports){ "use strict"; // Import external names locally var Shared = _dereq_('./Shared'), async = _dereq_('async'), localforage = _dereq_('localforage'), FdbCompress = _dereq_('./PersistCompress'),// jshint ignore:line FdbCrypto = _dereq_('./PersistCrypto'),// jshint ignore:line Db, Collection, CollectionDrop, CollectionGroup, CollectionInit, DbInit, DbDrop, Persist, Overload;//, //DataVersion = '2.0'; /** * The persistent storage class handles loading and saving data to browser * storage. * @constructor */ Persist = function () { this.init.apply(this, arguments); }; /** * The local forage library. */ Persist.prototype.localforage = localforage; /** * The init method that can be overridden or extended. * @param {Db} db The ForerunnerDB database instance. */ Persist.prototype.init = function (db) { var self = this; this._encodeSteps = [ function () { return self._encode.apply(self, arguments); } ]; this._decodeSteps = [ function () { return self._decode.apply(self, arguments); } ]; // Check environment if (db.isClient()) { if (window.Storage !== undefined) { this.mode('localforage'); localforage.config({ driver: [ localforage.INDEXEDDB, localforage.WEBSQL, localforage.LOCALSTORAGE ], name: String(db.core().name()), storeName: 'FDB' }); } } }; Shared.addModule('Persist', Persist); Shared.mixin(Persist.prototype, 'Mixin.ChainReactor'); Shared.mixin(Persist.prototype, 'Mixin.Common'); Db = Shared.modules.Db; Collection = _dereq_('./Collection'); CollectionDrop = Collection.prototype.drop; CollectionGroup = _dereq_('./CollectionGroup'); CollectionInit = Collection.prototype.init; DbInit = Db.prototype.init; DbDrop = Db.prototype.drop; Overload = Shared.overload; /** * Gets / sets the persistent storage mode (the library used * to persist data to the browser - defaults to localForage). * @param {String} type The library to use for storage. Defaults * to localForage. * @returns {*} */ Persist.prototype.mode = function (type) { if (type !== undefined) { this._mode = type; return this; } return this._mode; }; /** * Gets / sets the driver used when persisting data. * @param {String} val Specify the driver type (LOCALSTORAGE, * WEBSQL or INDEXEDDB) * @returns {*} */ Persist.prototype.driver = function (val) { if (val !== undefined) { switch (val.toUpperCase()) { case 'LOCALSTORAGE': localforage.setDriver(localforage.LOCALSTORAGE); break; case 'WEBSQL': localforage.setDriver(localforage.WEBSQL); break; case 'INDEXEDDB': localforage.setDriver(localforage.INDEXEDDB); break; default: throw('ForerunnerDB.Persist: The persistence driver you have specified is not found. Please use either IndexedDB, WebSQL or LocalStorage!'); } return this; } return localforage.driver(); }; /** * Starts a decode waterfall process. * @param {*} val The data to be decoded. * @param {Function} finished The callback to pass final data to. */ Persist.prototype.decode = function (val, finished) { async.waterfall([function (callback) { if (callback) { callback(false, val, {}); } }].concat(this._decodeSteps), finished); }; /** * Starts an encode waterfall process. * @param {*} val The data to be encoded. * @param {Function} finished The callback to pass final data to. */ Persist.prototype.encode = function (val, finished) { async.waterfall([function (callback) { if (callback) { callback(false, val, {}); } }].concat(this._encodeSteps), finished); }; Shared.synthesize(Persist.prototype, 'encodeSteps'); Shared.synthesize(Persist.prototype, 'decodeSteps'); /** * Adds an encode/decode step to the persistent storage system so * that you can add custom functionality. * @param {Function} encode The encode method called with the data from the * previous encode step. When your method is complete it MUST call the * callback method. If you provide anything other than false to the err * parameter the encoder will fail and throw an error. * @param {Function} decode The decode method called with the data from the * previous decode step. When your method is complete it MUST call the * callback method. If you provide anything other than false to the err * parameter the decoder will fail and throw an error. * @param {Number=} index Optional index to add the encoder step to. This * allows you to place a step before or after other existing steps. If not * provided your step is placed last in the list of steps. For instance if * you are providing an encryption step it makes sense to place this last * since all previous steps will then have their data encrypted by your * final step. */ Persist.prototype.addStep = new Overload({ 'object': function (obj) { this.$main.call(this, function objEncode () { obj.encode.apply(obj, arguments); }, function objDecode () { obj.decode.apply(obj, arguments); }, 0); }, 'function, function': function (encode, decode) { this.$main.call(this, encode, decode, 0); }, 'function, function, number': function (encode, decode, index) { this.$main.call(this, encode, decode, index); }, $main: function (encode, decode, index) { if (index === 0 || index === undefined) { this._encodeSteps.push(encode); this._decodeSteps.unshift(decode); } else { // Place encoder step at index then work out correct // index to place decoder step this._encodeSteps.splice(index, 0, encode); this._decodeSteps.splice(this._decodeSteps.length - index, 0, decode); } } }); Persist.prototype.unwrap = function (dataStr) { var parts = dataStr.split('::fdb::'), data; switch (parts[0]) { case 'json': data = this.jParse(parts[1]); break; case 'raw': data = parts[1]; break; default: break; } }; /** * Takes encoded data and decodes it for use as JS native objects and arrays. * @param {String} val The currently encoded string data. * @param {Object} meta Meta data object that can be used to pass back useful * supplementary data. * @param {Function} finished The callback method to call when decoding is * completed. * @private */ Persist.prototype._decode = function (val, meta, finished) { var parts, data; if (val) { parts = val.split('::fdb::'); switch (parts[0]) { case 'json': data = this.jParse(parts[1]); break; case 'raw': data = parts[1]; break; default: break; } if (data) { meta.foundData = true; meta.rowCount = data.length; } else { meta.foundData = false; } if (finished) { finished(false, data, meta); } } else { meta.foundData = false; meta.rowCount = 0; if (finished) { finished(false, val, meta); } } }; /** * Takes native JS data and encodes it for for storage as a string. * @param {Object} val The current un-encoded data. * @param {Object} meta Meta data object that can be used to pass back useful * supplementary data. * @param {Function} finished The callback method to call when encoding is * completed. * @private */ Persist.prototype._encode = function (val, meta, finished) { var data = val; if (typeof val === 'object') { val = 'json::fdb::' + this.jStringify(val); } else { val = 'raw::fdb::' + val; } if (data) { meta.foundData = true; meta.rowCount = data.length; } else { meta.foundData = false; } if (finished) { finished(false, val, meta); } }; /** * Encodes passed data and then stores it in the browser's persistent * storage layer. * @param {String} key The key to store the data under in the persistent * storage. * @param {Object} data The data to store under the key. * @param {Function=} callback The method to call when the save process * has completed. */ Persist.prototype.save = function (key, data, callback) { switch (this.mode()) { case 'localforage': this.encode(data, function (err, data, tableStats) { localforage.setItem(key, data).then(function (data) { if (callback) { callback(false, data, tableStats); } }, function (err) { if (callback) { callback(err); } }); }); break; default: if (callback) { callback('No data handler.'); } break; } }; /** * Loads and decodes data from the passed key. * @param {String} key The key to retrieve data from in the persistent * storage. * @param {Function=} callback The method to call when the load process * has completed. */ Persist.prototype.load = function (key, callback) { var self = this; switch (this.mode()) { case 'localforage': localforage.getItem(key).then(function (val) { self.decode(val, callback); }, function (err) { if (callback) { callback(err); } }); break; default: if (callback) { callback('No data handler or unrecognised data type.'); } break; } }; /** * Deletes data in persistent storage stored under the passed key. * @param {String} key The key to drop data for in the storage. * @param {Function=} callback The method to call when the data is dropped. */ Persist.prototype.drop = function (key, callback) { switch (this.mode()) { case 'localforage': localforage.removeItem(key).then(function () { if (callback) { callback(false); } }, function (err) { if (callback) { callback(err); } }); break; default: if (callback) { callback('No data handler or unrecognised data type.'); } break; } }; // Extend the Collection prototype with persist methods Collection.prototype.drop = new Overload({ /** * Drop collection and persistent storage. */ '': function () { if (!this.isDropped()) { this.drop(true); } }, /** * Drop collection and persistent storage with callback. * @param {Function} callback Callback method. */ 'function': function (callback) { if (!this.isDropped()) { this.drop(true, callback); } }, /** * Drop collection and optionally drop persistent storage. * @param {Boolean} removePersistent True to drop persistent storage, false to keep it. */ 'boolean': function (removePersistent) { if (!this.isDropped()) { // Remove persistent storage if (removePersistent) { if (this._name) { if (this._db) { // Drop the collection data from storage this._db.persist.drop(this._db._name + '-' + this._name); this._db.persist.drop(this._db._name + '-' + this._name + '-metaData'); } } else { throw('ForerunnerDB.Persist: Cannot drop a collection\'s persistent storage when no name assigned to collection!'); } } // Call the original method CollectionDrop.call(this); } }, /** * Drop collections and optionally drop persistent storage with callback. * @param {Boolean} removePersistent True to drop persistent storage, false to keep it. * @param {Function} callback Callback method. */ 'boolean, function': function (removePersistent, callback) { var self = this; if (!this.isDropped()) { // Remove persistent storage if (removePersistent) { if (this._name) { if (this._db) { // Drop the collection data from storage this._db.persist.drop(this._db._name + '-' + this._name, function () { self._db.persist.drop(self._db._name + '-' + self._name + '-metaData', callback); }); return CollectionDrop.call(this); } else { if (callback) { callback('Cannot drop a collection\'s persistent storage when the collection is not attached to a database!'); } } } else { if (callback) { callback('Cannot drop a collection\'s persistent storage when no name assigned to collection!'); } } } else { // Call the original method return CollectionDrop.call(this, callback); } } } }); /** * Saves an entire collection's data to persistent storage. * @param {Function=} callback The method to call when the save function * has completed. */ Collection.prototype.save = function (callback) { var self = this, processSave; if (self._name) { if (self._db) { processSave = function () { // Save the collection data self._db.persist.save(self._db._name + '-' + self._name, self._data, function (err, data, tableStats) { if (!err) { self._db.persist.save(self._db._name + '-' + self._name + '-metaData', self.metaData(), function (err, data, metaStats) { if (callback) { callback(err, data, tableStats, metaStats); } }); } else { if (callback) { callback(err); } } }); }; // Check for processing queues if (self.isProcessingQueue()) { // Hook queue complete to process save self.on('queuesComplete', function () { processSave(); }); } else { // Process save immediately processSave(); } } else { if (callback) { callback('Cannot save a collection that is not attached to a database!'); } } } else { if (callback) { callback('Cannot save a collection with no assigned name!'); } } }; /** * Loads an entire collection's data from persistent storage. * @param {Function=} callback The method to call when the load function * has completed. */ Collection.prototype.load = function (callback) { var self = this; if (self._name) { if (self._db) { // Load the collection data self._db.persist.load(self._db._name + '-' + self._name, function (err, data, tableStats) { if (!err) { if (data) { // Remove all previous data self.remove({}); self.insert(data); //self.setData(data); } // Now load the collection's metadata self._db.persist.load(self._db._name + '-' + self._name + '-metaData', function (err, data, metaStats) { if (!err) { if (data) { self.metaData(data); } } if (callback) { callback(err, tableStats, metaStats); } }); } else { if (callback) { callback(err); } } }); } else { if (callback) { callback('Cannot load a collection that is not attached to a database!'); } } } else { if (callback) { callback('Cannot load a collection with no assigned name!'); } } }; /** * Gets the data that represents this collection for easy storage using * a third-party method / plugin instead of using the standard persistent * storage system. * @param {Function} callback The method to call with the data response. */ Collection.prototype.saveCustom = function (callback) { var self = this, myData = {}, processSave; if (self._name) { if (self._db) { processSave = function () { self.encode(self._data, function (err, data, tableStats) { if (!err) { myData.data = { name: self._db._name + '-' + self._name, store: data, tableStats: tableStats }; self.encode(self._data, function (err, data, tableStats) { if (!err) { myData.metaData = { name: self._db._name + '-' + self._name + '-metaData', store: data, tableStats: tableStats }; callback(false, myData); } else { callback(err); } }); } else { callback(err); } }); }; // Check for processing queues if (self.isProcessingQueue()) { // Hook queue complete to process save self.on('queuesComplete', function () { processSave(); }); } else { // Process save immediately processSave(); } } else { if (callback) { callback('Cannot save a collection that is not attached to a database!'); } } } else { if (callback) { callback('Cannot save a collection with no assigned name!'); } } }; /** * Loads custom data loaded by a third-party plugin into the collection. * @param {Object} myData Data object previously saved by using saveCustom() * @param {Function} callback A callback method to receive notification when * data has loaded. */ Collection.prototype.loadCustom = function (myData, callback) { var self = this; if (self._name) { if (self._db) { if (myData.data && myData.data.store) { if (myData.metaData && myData.metaData.store) { self.decode(myData.data.store, function (err, data, tableStats) { if (!err) { if (data) { // Remove all previous data self.remove({}); self.insert(data); self.decode(myData.metaData.store, function (err, data, metaStats) { if (!err) { if (data) { self.metaData(data); if (callback) { callback(err, tableStats, metaStats); } } } else { callback(err); } }); } } else { callback(err); } }); } else { callback('No "metaData" key found in passed object!'); } } else { callback('No "data" key found in passed object!'); } } else { if (callback) { callback('Cannot load a collection that is not attached to a database!'); } } } else { if (callback) { callback('Cannot load a collection with no assigned name!'); } } }; // Override the DB init to instantiate the plugin Db.prototype.init = function () { DbInit.apply(this, arguments); this.persist = new Persist(this); }; Db.prototype.load = new Overload({ /** * Loads an entire database's data from persistent storage. * @param {Function=} callback The method to call when the load function * has completed. */ 'function': function (callback) { this.$main.call(this, {}, callback); }, 'object, function': function (myData, callback) { this.$main.call(this, myData, callback); }, '$main': function (myData, callback) { // Loop the collections in the database var obj = this._collection, keys = obj.keys(), keyCount = keys.length, loadCallback, index; loadCallback = function (err) { if (!err) { keyCount--; if (keyCount === 0) { if (callback) { callback(false); } } } else { if (callback) { callback(err); } } }; for (index in obj) { if (obj.hasOwnProperty(index)) { // Call the collection load method if (!myData) { obj[index].load(loadCallback); } else { obj[index].loadCustom(myData, loadCallback); } } } } }); Db.prototype.save = new Overload({ /** * Saves an entire database's data to persistent storage. * @param {Function=} callback The method to call when the save function * has completed. */ 'function': function (callback) { this.$main.call(this, {}, callback); }, 'object, function': function (options, callback) { this.$main.call(this, options, callback); }, '$main': function (options, callback) { // Loop the collections in the database var obj = this._collection, keys = obj.keys(), keyCount = keys.length, saveCallback, index; saveCallback = function (err) { if (!err) { keyCount--; if (keyCount === 0) { if (callback) { callback(false); } } } else { if (callback) { callback(err); } } }; for (index in obj) { if (obj.hasOwnProperty(index)) { // Call the collection save method if (!options.custom) { obj[index].save(saveCallback); } else { obj[index].saveCustom(saveCallback); } } } } }); Shared.finishModule('Persist'); module.exports = Persist; },{"./Collection":4,"./CollectionGroup":5,"./PersistCompress":27,"./PersistCrypto":28,"./Shared":31,"async":33,"localforage":69}],27:[function(_dereq_,module,exports){ "use strict"; var Shared = _dereq_('./Shared'), pako = _dereq_('pako'); var Plugin = function () { this.init.apply(this, arguments); }; Plugin.prototype.init = function (options) { }; Shared.mixin(Plugin.prototype, 'Mixin.Common'); Plugin.prototype.encode = function (val, meta, finished) { var wrapper = { data: val, type: 'fdbCompress', enabled: false }, before, after, compressedVal; // Compress the data before = val.length; compressedVal = pako.deflate(val, {to: 'string'}); after = compressedVal.length; // If the compressed version is smaller than the original, use it! if (after < before) { wrapper.data = compressedVal; wrapper.enabled = true; } meta.compression = { enabled: wrapper.enabled, compressedBytes: after, uncompressedBytes: before, effect: Math.round((100 / before) * after) + '%' }; finished(false, this.jStringify(wrapper), meta); }; Plugin.prototype.decode = function (wrapper, meta, finished) { var compressionEnabled = false, data; if (wrapper) { wrapper = this.jParse(wrapper); // Check if we need to decompress the string if (wrapper.enabled) { data = pako.inflate(wrapper.data, {to: 'string'}); compressionEnabled = true; } else { data = wrapper.data; compressionEnabled = false; } meta.compression = { enabled: compressionEnabled }; if (finished) { finished(false, data, meta); } } else { if (finished) { finished(false, data, meta); } } }; // Register this plugin with the persistent storage class Shared.plugins.FdbCompress = Plugin; module.exports = Plugin; },{"./Shared":31,"pako":70}],28:[function(_dereq_,module,exports){ "use strict"; var Shared = _dereq_('./Shared'), CryptoJS = _dereq_('crypto-js'); var Plugin = function () { this.init.apply(this, arguments); }; Plugin.prototype.init = function (options) { // Ensure at least a password is passed in options if (!options || !options.pass) { throw('Cannot initialise persistent storage encryption without a passphrase provided in the passed options object as the "pass" field.'); } this._algo = options.algo || 'AES'; this._pass = options.pass; }; Shared.mixin(Plugin.prototype, 'Mixin.Common'); /** * Gets / sets the current pass-phrase being used to encrypt / decrypt * data with the plugin. */ Shared.synthesize(Plugin.prototype, 'pass'); Plugin.prototype.stringify = function (cipherParams) { // create json object with ciphertext var jsonObj = { ct: cipherParams.ciphertext.toString(CryptoJS.enc.Base64) }; // optionally add iv and salt if (cipherParams.iv) { jsonObj.iv = cipherParams.iv.toString(); } if (cipherParams.salt) { jsonObj.s = cipherParams.salt.toString(); } // stringify json object return this.jStringify(jsonObj); }; Plugin.prototype.parse = function (jsonStr) { // parse json string var jsonObj = this.jParse(jsonStr); // extract ciphertext from json object, and create cipher params object var cipherParams = CryptoJS.lib.CipherParams.create({ ciphertext: CryptoJS.enc.Base64.parse(jsonObj.ct) }); // optionally extract iv and salt if (jsonObj.iv) { cipherParams.iv = CryptoJS.enc.Hex.parse(jsonObj.iv); } if (jsonObj.s) { cipherParams.salt = CryptoJS.enc.Hex.parse(jsonObj.s); } return cipherParams; }; Plugin.prototype.encode = function (val, meta, finished) { var self = this, wrapper = { type: 'fdbCrypto' }, encryptedVal; // Encrypt the data encryptedVal = CryptoJS[this._algo].encrypt(val, this._pass, { format: { stringify: function () { return self.stringify.apply(self, arguments); }, parse: function () { return self.parse.apply(self, arguments); } } }); wrapper.data = encryptedVal.toString(); wrapper.enabled = true; meta.encryption = { enabled: wrapper.enabled }; if (finished) { finished(false, this.jStringify(wrapper), meta); } }; Plugin.prototype.decode = function (wrapper, meta, finished) { var self = this, data; if (wrapper) { wrapper = this.jParse(wrapper); data = CryptoJS[this._algo].decrypt(wrapper.data, this._pass, { format: { stringify: function () { return self.stringify.apply(self, arguments); }, parse: function () { return self.parse.apply(self, arguments); } } }).toString(CryptoJS.enc.Utf8); if (finished) { finished(false, data, meta); } } else { if (finished) { finished(false, wrapper, meta); } } }; // Register this plugin with the persistent storage class Shared.plugins.FdbCrypto = Plugin; module.exports = Plugin; },{"./Shared":31,"crypto-js":42}],29:[function(_dereq_,module,exports){ "use strict"; var Shared = _dereq_('./Shared'); /** * Provides chain reactor node linking so that a chain reaction can propagate * down a node tree. Effectively creates a chain link between the reactorIn and * reactorOut objects where a chain reaction from the reactorIn is passed through * the reactorProcess before being passed to the reactorOut object. Reactor * packets are only passed through to the reactorOut if the reactor IO method * chainSend is used. * @param {*} reactorIn An object that has the Mixin.ChainReactor methods mixed * in to it. Chain reactions that occur inside this object will be passed through * to the reactorOut object. * @param {*} reactorOut An object that has the Mixin.ChainReactor methods mixed * in to it. Chain reactions that occur in the reactorIn object will be passed * through to this object. * @param {Function} reactorProcess The processing method to use when chain * reactions occur. * @constructor */ var ReactorIO = function (reactorIn, reactorOut, reactorProcess) { if (reactorIn && reactorOut && reactorProcess) { this._reactorIn = reactorIn; this._reactorOut = reactorOut; this._chainHandler = reactorProcess; if (!reactorIn.chain || !reactorOut.chainReceive) { throw('ForerunnerDB.ReactorIO: ReactorIO requires passed in and out objects to implement the ChainReactor mixin!'); } // Register the reactorIO with the input reactorIn.chain(this); // Register the output with the reactorIO this.chain(reactorOut); } else { throw('ForerunnerDB.ReactorIO: ReactorIO requires in, out and process arguments to instantiate!'); } }; Shared.addModule('ReactorIO', ReactorIO); /** * Drop a reactor IO object, breaking the reactor link between the in and out * reactor nodes. * @returns {boolean} */ ReactorIO.prototype.drop = function () { if (!this.isDropped()) { this._state = 'dropped'; // Remove links if (this._reactorIn) { this._reactorIn.unChain(this); } if (this._reactorOut) { this.unChain(this._reactorOut); } delete this._reactorIn; delete this._reactorOut; delete this._chainHandler; this.emit('drop', this); } return true; }; /** * Gets / sets the current state. * @param {String=} val The name of the state to set. * @returns {*} */ Shared.synthesize(ReactorIO.prototype, 'state'); Shared.mixin(ReactorIO.prototype, 'Mixin.Common'); Shared.mixin(ReactorIO.prototype, 'Mixin.ChainReactor'); Shared.mixin(ReactorIO.prototype, 'Mixin.Events'); Shared.finishModule('ReactorIO'); module.exports = ReactorIO; },{"./Shared":31}],30:[function(_dereq_,module,exports){ "use strict"; /** * Provides functionality to encode and decode JavaScript objects to strings * and back again. This differs from JSON.stringify and JSON.parse in that * special objects such as dates can be encoded to strings and back again * so that the reconstituted version of the string still contains a JavaScript * date object. * @constructor */ var Serialiser = function () { this.init.apply(this, arguments); }; Serialiser.prototype.init = function () { this._encoder = []; this._decoder = {}; // Register our handlers this.registerEncoder('$date', function (data) { if (data instanceof Date) { return data.toISOString(); } }); this.registerDecoder('$date', function (data) { return new Date(data); }); }; /** * Register an encoder that can handle encoding for a particular * object type. * @param {String} handles The name of the handler e.g. $date. * @param {Function} method The encoder method. */ Serialiser.prototype.registerEncoder = function (handles, method) { this._encoder.push(function (data) { var methodVal = method(data), returnObj; if (methodVal !== undefined) { returnObj = {}; returnObj[handles] = methodVal; } return returnObj; }); }; /** * Register a decoder that can handle decoding for a particular * object type. * @param {String} handles The name of the handler e.g. $date. When an object * has a field matching this handler name then this decode will be invoked * to provide a decoded version of the data that was previously encoded by * it's counterpart encoder method. * @param {Function} method The decoder method. */ Serialiser.prototype.registerDecoder = function (handles, method) { this._decoder[handles] = method; }; /** * Loops the encoders and asks each one if it wants to handle encoding for * the passed data object. If no value is returned (undefined) then the data * will be passed to the next encoder and so on. If a value is returned the * loop will break and the encoded data will be used. * @param {Object} data The data object to handle. * @returns {*} The encoded data. * @private */ Serialiser.prototype._encode = function (data) { // Loop the encoders and if a return value is given by an encoder // the loop will exit and return that value. var count = this._encoder.length, retVal; while (count-- && !retVal) { retVal = this._encoder[count](data); } return retVal; }; /** * Converts a previously encoded string back into an object. * @param {String} data The string to convert to an object. * @returns {Object} The reconstituted object. */ Serialiser.prototype.parse = function (data) { return this._parse(JSON.parse(data)); }; /** * Handles restoring an object with special data markers back into * it's original format. * @param {Object} data The object to recurse. * @param {Object=} target The target object to restore data to. * @returns {Object} The final restored object. * @private */ Serialiser.prototype._parse = function (data, target) { var i; if (typeof data === 'object' && data !== null) { if (data instanceof Array) { target = target || []; } else { target = target || {}; } // Iterate through the object's keys and handle // special object types and restore them for (i in data) { if (data.hasOwnProperty(i)) { if (i.substr(0, 1) === '$' && this._decoder[i]) { // This is a special object type and a handler // exists, restore it return this._decoder[i](data[i]); } // Not a special object or no handler, recurse as normal target[i] = this._parse(data[i], target[i]); } } } else { target = data; } // The data is a basic type return target; }; /** * Converts an object to a encoded string representation. * @param {Object} data The object to encode. */ Serialiser.prototype.stringify = function (data) { return JSON.stringify(this._stringify(data)); }; /** * Recurse down an object and encode special objects so they can be * stringified and later restored. * @param {Object} data The object to parse. * @param {Object=} target The target object to store converted data to. * @returns {Object} The converted object. * @private */ Serialiser.prototype._stringify = function (data, target) { var handledData, i; if (typeof data === 'object' && data !== null) { // Handle special object types so they can be encoded with // a special marker and later restored by a decoder counterpart handledData = this._encode(data); if (handledData) { // An encoder handled this object type so return it now return handledData; } if (data instanceof Array) { target = target || []; } else { target = target || {}; } // Iterate through the object's keys and serialise for (i in data) { if (data.hasOwnProperty(i)) { target[i] = this._stringify(data[i], target[i]); } } } else { target = data; } // The data is a basic type return target; }; module.exports = Serialiser; },{}],31:[function(_dereq_,module,exports){ "use strict"; var Overload = _dereq_('./Overload'); /** * A shared object that can be used to store arbitrary data between class * instances, and access helper methods. * @mixin */ var Shared = { version: '1.3.488', modules: {}, plugins: {}, _synth: {}, /** * Adds a module to ForerunnerDB. * @memberof Shared * @param {String} name The name of the module. * @param {Function} module The module class. */ addModule: function (name, module) { // Store the module in the module registry this.modules[name] = module; // Tell the universe we are loading this module this.emit('moduleLoad', [name, module]); }, /** * Called by the module once all processing has been completed. Used to determine * if the module is ready for use by other modules. * @memberof Shared * @param {String} name The name of the module. */ finishModule: function (name) { if (this.modules[name]) { // Set the finished loading flag to true this.modules[name]._fdbFinished = true; // Assign the module name to itself so it knows what it // is called if (this.modules[name].prototype) { this.modules[name].prototype.className = name; } else { this.modules[name].className = name; } this.emit('moduleFinished', [name, this.modules[name]]); } else { throw('ForerunnerDB.Shared: finishModule called on a module that has not been registered with addModule(): ' + name); } }, /** * Will call your callback method when the specified module has loaded. If the module * is already loaded the callback is called immediately. * @memberof Shared * @param {String} name The name of the module. * @param {Function} callback The callback method to call when the module is loaded. */ moduleFinished: function (name, callback) { if (this.modules[name] && this.modules[name]._fdbFinished) { if (callback) { callback(name, this.modules[name]); } } else { this.on('moduleFinished', callback); } }, /** * Determines if a module has been added to ForerunnerDB or not. * @memberof Shared * @param {String} name The name of the module. * @returns {Boolean} True if the module exists or false if not. */ moduleExists: function (name) { return Boolean(this.modules[name]); }, /** * Adds the properties and methods defined in the mixin to the passed object. * @memberof Shared * @param {Object} obj The target object to add mixin key/values to. * @param {String} mixinName The name of the mixin to add to the object. */ mixin: new Overload({ 'object, string': function (obj, mixinName) { var mixinObj; if (typeof mixinName === 'string') { mixinObj = this.mixins[mixinName]; if (!mixinObj) { throw('ForerunnerDB.Shared: Cannot find mixin named: ' + mixinName); } } return this.$main.call(this, obj, mixinObj); }, 'object, *': function (obj, mixinObj) { return this.$main.call(this, obj, mixinObj); }, '$main': function (obj, mixinObj) { if (mixinObj && typeof mixinObj === 'object') { for (var i in mixinObj) { if (mixinObj.hasOwnProperty(i)) { obj[i] = mixinObj[i]; } } } return obj; } }), /** * Generates a generic getter/setter method for the passed method name. * @memberof Shared * @param {Object} obj The object to add the getter/setter to. * @param {String} name The name of the getter/setter to generate. * @param {Function=} extend A method to call before executing the getter/setter. * The existing getter/setter can be accessed from the extend method via the * $super e.g. this.$super(); */ synthesize: function (obj, name, extend) { this._synth[name] = this._synth[name] || function (val) { if (val !== undefined) { this['_' + name] = val; return this; } return this['_' + name]; }; if (extend) { var self = this; obj[name] = function () { var tmp = this.$super, ret; this.$super = self._synth[name]; ret = extend.apply(this, arguments); this.$super = tmp; return ret; }; } else { obj[name] = this._synth[name]; } }, /** * Allows a method to be overloaded. * @memberof Shared * @param arr * @returns {Function} * @constructor */ overload: Overload, /** * Define the mixins that other modules can use as required. * @memberof Shared */ mixins: { 'Mixin.Common': _dereq_('./Mixin.Common'), 'Mixin.Events': _dereq_('./Mixin.Events'), 'Mixin.ChainReactor': _dereq_('./Mixin.ChainReactor'), 'Mixin.CRUD': _dereq_('./Mixin.CRUD'), 'Mixin.Constants': _dereq_('./Mixin.Constants'), 'Mixin.Triggers': _dereq_('./Mixin.Triggers'), 'Mixin.Sorting': _dereq_('./Mixin.Sorting'), 'Mixin.Matching': _dereq_('./Mixin.Matching'), 'Mixin.Updating': _dereq_('./Mixin.Updating'), 'Mixin.Tags': _dereq_('./Mixin.Tags') } }; // Add event handling to shared Shared.mixin(Shared, 'Mixin.Events'); module.exports = Shared; },{"./Mixin.CRUD":13,"./Mixin.ChainReactor":14,"./Mixin.Common":15,"./Mixin.Constants":16,"./Mixin.Events":17,"./Mixin.Matching":18,"./Mixin.Sorting":19,"./Mixin.Tags":20,"./Mixin.Triggers":21,"./Mixin.Updating":22,"./Overload":24}],32:[function(_dereq_,module,exports){ /* jshint strict:false */ if (!Array.prototype.filter) { Array.prototype.filter = function(fun/*, thisArg*/) { if (this === void 0 || this === null) { throw new TypeError(); } var t = Object(this); var len = t.length >>> 0; // jshint ignore:line if (typeof fun !== 'function') { throw new TypeError(); } var res = []; var thisArg = arguments.length >= 2 ? arguments[1] : void 0; for (var i = 0; i < len; i++) { if (i in t) { var val = t[i]; // NOTE: Technically this should Object.defineProperty at // the next index, as push can be affected by // properties on Object.prototype and Array.prototype. // But that method's new, and collisions should be // rare, so use the more-compatible alternative. if (fun.call(thisArg, val, i, t)) { res.push(val); } } } return res; }; } if (typeof Object.create !== 'function') { Object.create = (function() { var Temp = function() {}; return function (prototype) { if (arguments.length > 1) { throw Error('Second argument not supported'); } if (typeof prototype !== 'object') { throw TypeError('Argument must be an object'); } Temp.prototype = prototype; var result = new Temp(); Temp.prototype = null; return result; }; })(); } // Production steps of ECMA-262, Edition 5, 15.4.4.14 // Reference: http://es5.github.io/#x15.4.4.14e if (!Array.prototype.indexOf) { Array.prototype.indexOf = function(searchElement, fromIndex) { var k; // 1. Let O be the result of calling ToObject passing // the this value as the argument. if (this === null) { throw new TypeError('"this" is null or not defined'); } var O = Object(this); // 2. Let lenValue be the result of calling the Get // internal method of O with the argument "length". // 3. Let len be ToUint32(lenValue). var len = O.length >>> 0; // jshint ignore:line // 4. If len is 0, return -1. if (len === 0) { return -1; } // 5. If argument fromIndex was passed let n be // ToInteger(fromIndex); else let n be 0. var n = +fromIndex || 0; if (Math.abs(n) === Infinity) { n = 0; } // 6. If n >= len, return -1. if (n >= len) { return -1; } // 7. If n >= 0, then Let k be n. // 8. Else, n<0, Let k be len - abs(n). // If k is less than 0, then let k be 0. k = Math.max(n >= 0 ? n : len - Math.abs(n), 0); // 9. Repeat, while k < len while (k < len) { // a. Let Pk be ToString(k). // This is implicit for LHS operands of the in operator // b. Let kPresent be the result of calling the // HasProperty internal method of O with argument Pk. // This step can be combined with c // c. If kPresent is true, then // i. Let elementK be the result of calling the Get // internal method of O with the argument ToString(k). // ii. Let same be the result of applying the // Strict Equality Comparison Algorithm to // searchElement and elementK. // iii. If same is true, return k. if (k in O && O[k] === searchElement) { return k; } k++; } return -1; }; } module.exports = {}; },{}],33:[function(_dereq_,module,exports){ (function (process,global){ /*! * async * https://github.com/caolan/async * * Copyright 2010-2014 Caolan McMahon * Released under the MIT license */ (function () { var async = {}; function noop() {} function identity(v) { return v; } function toBool(v) { return !!v; } function notId(v) { return !v; } // global on the server, window in the browser var previous_async; // Establish the root object, `window` (`self`) in the browser, `global` // on the server, or `this` in some virtual machines. We use `self` // instead of `window` for `WebWorker` support. var root = typeof self === 'object' && self.self === self && self || typeof global === 'object' && global.global === global && global || this; if (root != null) { previous_async = root.async; } async.noConflict = function () { root.async = previous_async; return async; }; function only_once(fn) { return function() { if (fn === null) throw new Error("Callback was already called."); fn.apply(this, arguments); fn = null; }; } function _once(fn) { return function() { if (fn === null) return; fn.apply(this, arguments); fn = null; }; } //// cross-browser compatiblity functions //// var _toString = Object.prototype.toString; var _isArray = Array.isArray || function (obj) { return _toString.call(obj) === '[object Array]'; }; // Ported from underscore.js isObject var _isObject = function(obj) { var type = typeof obj; return type === 'function' || type === 'object' && !!obj; }; function _isArrayLike(arr) { return _isArray(arr) || ( // has a positive integer length property typeof arr.length === "number" && arr.length >= 0 && arr.length % 1 === 0 ); } function _arrayEach(arr, iterator) { var index = -1, length = arr.length; while (++index < length) { iterator(arr[index], index, arr); } } function _map(arr, iterator) { var index = -1, length = arr.length, result = Array(length); while (++index < length) { result[index] = iterator(arr[index], index, arr); } return result; } function _range(count) { return _map(Array(count), function (v, i) { return i; }); } function _reduce(arr, iterator, memo) { _arrayEach(arr, function (x, i, a) { memo = iterator(memo, x, i, a); }); return memo; } function _forEachOf(object, iterator) { _arrayEach(_keys(object), function (key) { iterator(object[key], key); }); } function _indexOf(arr, item) { for (var i = 0; i < arr.length; i++) { if (arr[i] === item) return i; } return -1; } var _keys = Object.keys || function (obj) { var keys = []; for (var k in obj) { if (obj.hasOwnProperty(k)) { keys.push(k); } } return keys; }; function _keyIterator(coll) { var i = -1; var len; var keys; if (_isArrayLike(coll)) { len = coll.length; return function next() { i++; return i < len ? i : null; }; } else { keys = _keys(coll); len = keys.length; return function next() { i++; return i < len ? keys[i] : null; }; } } // Similar to ES6's rest param (http://ariya.ofilabs.com/2013/03/es6-and-rest-parameter.html) // This accumulates the arguments passed into an array, after a given index. // From underscore.js (https://github.com/jashkenas/underscore/pull/2140). function _restParam(func, startIndex) { startIndex = startIndex == null ? func.length - 1 : +startIndex; return function() { var length = Math.max(arguments.length - startIndex, 0); var rest = Array(length); for (var index = 0; index < length; index++) { rest[index] = arguments[index + startIndex]; } switch (startIndex) { case 0: return func.call(this, rest); case 1: return func.call(this, arguments[0], rest); } // Currently unused but handle cases outside of the switch statement: // var args = Array(startIndex + 1); // for (index = 0; index < startIndex; index++) { // args[index] = arguments[index]; // } // args[startIndex] = rest; // return func.apply(this, args); }; } function _withoutIndex(iterator) { return function (value, index, callback) { return iterator(value, callback); }; } //// exported async module functions //// //// nextTick implementation with browser-compatible fallback //// // capture the global reference to guard against fakeTimer mocks var _setImmediate = typeof setImmediate === 'function' && setImmediate; var _delay = _setImmediate ? function(fn) { // not a direct alias for IE10 compatibility _setImmediate(fn); } : function(fn) { setTimeout(fn, 0); }; if (typeof process === 'object' && typeof process.nextTick === 'function') { async.nextTick = process.nextTick; } else { async.nextTick = _delay; } async.setImmediate = _setImmediate ? _delay : async.nextTick; async.forEach = async.each = function (arr, iterator, callback) { return async.eachOf(arr, _withoutIndex(iterator), callback); }; async.forEachSeries = async.eachSeries = function (arr, iterator, callback) { return async.eachOfSeries(arr, _withoutIndex(iterator), callback); }; async.forEachLimit = async.eachLimit = function (arr, limit, iterator, callback) { return _eachOfLimit(limit)(arr, _withoutIndex(iterator), callback); }; async.forEachOf = async.eachOf = function (object, iterator, callback) { callback = _once(callback || noop); object = object || []; var iter = _keyIterator(object); var key, completed = 0; while ((key = iter()) != null) { completed += 1; iterator(object[key], key, only_once(done)); } if (completed === 0) callback(null); function done(err) { completed--; if (err) { callback(err); } // Check key is null in case iterator isn't exhausted // and done resolved synchronously. else if (key === null && completed <= 0) { callback(null); } } }; async.forEachOfSeries = async.eachOfSeries = function (obj, iterator, callback) { callback = _once(callback || noop); obj = obj || []; var nextKey = _keyIterator(obj); var key = nextKey(); function iterate() { var sync = true; if (key === null) { return callback(null); } iterator(obj[key], key, only_once(function (err) { if (err) { callback(err); } else { key = nextKey(); if (key === null) { return callback(null); } else { if (sync) { async.setImmediate(iterate); } else { iterate(); } } } })); sync = false; } iterate(); }; async.forEachOfLimit = async.eachOfLimit = function (obj, limit, iterator, callback) { _eachOfLimit(limit)(obj, iterator, callback); }; function _eachOfLimit(limit) { return function (obj, iterator, callback) { callback = _once(callback || noop); obj = obj || []; var nextKey = _keyIterator(obj); if (limit <= 0) { return callback(null); } var done = false; var running = 0; var errored = false; (function replenish () { if (done && running <= 0) { return callback(null); } while (running < limit && !errored) { var key = nextKey(); if (key === null) { done = true; if (running <= 0) { callback(null); } return; } running += 1; iterator(obj[key], key, only_once(function (err) { running -= 1; if (err) { callback(err); errored = true; } else { replenish(); } })); } })(); }; } function doParallel(fn) { return function (obj, iterator, callback) { return fn(async.eachOf, obj, iterator, callback); }; } function doParallelLimit(fn) { return function (obj, limit, iterator, callback) { return fn(_eachOfLimit(limit), obj, iterator, callback); }; } function doSeries(fn) { return function (obj, iterator, callback) { return fn(async.eachOfSeries, obj, iterator, callback); }; } function _asyncMap(eachfn, arr, iterator, callback) { callback = _once(callback || noop); arr = arr || []; var results = _isArrayLike(arr) ? [] : {}; eachfn(arr, function (value, index, callback) { iterator(value, function (err, v) { results[index] = v; callback(err); }); }, function (err) { callback(err, results); }); } async.map = doParallel(_asyncMap); async.mapSeries = doSeries(_asyncMap); async.mapLimit = doParallelLimit(_asyncMap); // reduce only has a series version, as doing reduce in parallel won't // work in many situations. async.inject = async.foldl = async.reduce = function (arr, memo, iterator, callback) { async.eachOfSeries(arr, function (x, i, callback) { iterator(memo, x, function (err, v) { memo = v; callback(err); }); }, function (err) { callback(err, memo); }); }; async.foldr = async.reduceRight = function (arr, memo, iterator, callback) { var reversed = _map(arr, identity).reverse(); async.reduce(reversed, memo, iterator, callback); }; async.transform = function (arr, memo, iterator, callback) { if (arguments.length === 3) { callback = iterator; iterator = memo; memo = _isArray(arr) ? [] : {}; } async.eachOf(arr, function(v, k, cb) { iterator(memo, v, k, cb); }, function(err) { callback(err, memo); }); }; function _filter(eachfn, arr, iterator, callback) { var results = []; eachfn(arr, function (x, index, callback) { iterator(x, function (v) { if (v) { results.push({index: index, value: x}); } callback(); }); }, function () { callback(_map(results.sort(function (a, b) { return a.index - b.index; }), function (x) { return x.value; })); }); } async.select = async.filter = doParallel(_filter); async.selectLimit = async.filterLimit = doParallelLimit(_filter); async.selectSeries = async.filterSeries = doSeries(_filter); function _reject(eachfn, arr, iterator, callback) { _filter(eachfn, arr, function(value, cb) { iterator(value, function(v) { cb(!v); }); }, callback); } async.reject = doParallel(_reject); async.rejectLimit = doParallelLimit(_reject); async.rejectSeries = doSeries(_reject); function _createTester(eachfn, check, getResult) { return function(arr, limit, iterator, cb) { function done() { if (cb) cb(getResult(false, void 0)); } function iteratee(x, _, callback) { if (!cb) return callback(); iterator(x, function (v) { if (cb && check(v)) { cb(getResult(true, x)); cb = iterator = false; } callback(); }); } if (arguments.length > 3) { eachfn(arr, limit, iteratee, done); } else { cb = iterator; iterator = limit; eachfn(arr, iteratee, done); } }; } async.any = async.some = _createTester(async.eachOf, toBool, identity); async.someLimit = _createTester(async.eachOfLimit, toBool, identity); async.all = async.every = _createTester(async.eachOf, notId, notId); async.everyLimit = _createTester(async.eachOfLimit, notId, notId); function _findGetResult(v, x) { return x; } async.detect = _createTester(async.eachOf, identity, _findGetResult); async.detectSeries = _createTester(async.eachOfSeries, identity, _findGetResult); async.detectLimit = _createTester(async.eachOfLimit, identity, _findGetResult); async.sortBy = function (arr, iterator, callback) { async.map(arr, function (x, callback) { iterator(x, function (err, criteria) { if (err) { callback(err); } else { callback(null, {value: x, criteria: criteria}); } }); }, function (err, results) { if (err) { return callback(err); } else { callback(null, _map(results.sort(comparator), function (x) { return x.value; })); } }); function comparator(left, right) { var a = left.criteria, b = right.criteria; return a < b ? -1 : a > b ? 1 : 0; } }; async.auto = function (tasks, concurrency, callback) { if (!callback) { // concurrency is optional, shift the args. callback = concurrency; concurrency = null; } callback = _once(callback || noop); var keys = _keys(tasks); var remainingTasks = keys.length; if (!remainingTasks) { return callback(null); } if (!concurrency) { concurrency = remainingTasks; } var results = {}; var runningTasks = 0; var listeners = []; function addListener(fn) { listeners.unshift(fn); } function removeListener(fn) { var idx = _indexOf(listeners, fn); if (idx >= 0) listeners.splice(idx, 1); } function taskComplete() { remainingTasks--; _arrayEach(listeners.slice(0), function (fn) { fn(); }); } addListener(function () { if (!remainingTasks) { callback(null, results); } }); _arrayEach(keys, function (k) { var task = _isArray(tasks[k]) ? tasks[k]: [tasks[k]]; var taskCallback = _restParam(function(err, args) { runningTasks--; if (args.length <= 1) { args = args[0]; } if (err) { var safeResults = {}; _forEachOf(results, function(val, rkey) { safeResults[rkey] = val; }); safeResults[k] = args; callback(err, safeResults); } else { results[k] = args; async.setImmediate(taskComplete); } }); var requires = task.slice(0, task.length - 1); // prevent dead-locks var len = requires.length; var dep; while (len--) { if (!(dep = tasks[requires[len]])) { throw new Error('Has inexistant dependency'); } if (_isArray(dep) && _indexOf(dep, k) >= 0) { throw new Error('Has cyclic dependencies'); } } function ready() { return runningTasks < concurrency && _reduce(requires, function (a, x) { return (a && results.hasOwnProperty(x)); }, true) && !results.hasOwnProperty(k); } if (ready()) { runningTasks++; task[task.length - 1](taskCallback, results); } else { addListener(listener); } function listener() { if (ready()) { runningTasks++; removeListener(listener); task[task.length - 1](taskCallback, results); } } }); }; async.retry = function(times, task, callback) { var DEFAULT_TIMES = 5; var DEFAULT_INTERVAL = 0; var attempts = []; var opts = { times: DEFAULT_TIMES, interval: DEFAULT_INTERVAL }; function parseTimes(acc, t){ if(typeof t === 'number'){ acc.times = parseInt(t, 10) || DEFAULT_TIMES; } else if(typeof t === 'object'){ acc.times = parseInt(t.times, 10) || DEFAULT_TIMES; acc.interval = parseInt(t.interval, 10) || DEFAULT_INTERVAL; } else { throw new Error('Unsupported argument type for \'times\': ' + typeof t); } } var length = arguments.length; if (length < 1 || length > 3) { throw new Error('Invalid arguments - must be either (task), (task, callback), (times, task) or (times, task, callback)'); } else if (length <= 2 && typeof times === 'function') { callback = task; task = times; } if (typeof times !== 'function') { parseTimes(opts, times); } opts.callback = callback; opts.task = task; function wrappedTask(wrappedCallback, wrappedResults) { function retryAttempt(task, finalAttempt) { return function(seriesCallback) { task(function(err, result){ seriesCallback(!err || finalAttempt, {err: err, result: result}); }, wrappedResults); }; } function retryInterval(interval){ return function(seriesCallback){ setTimeout(function(){ seriesCallback(null); }, interval); }; } while (opts.times) { var finalAttempt = !(opts.times-=1); attempts.push(retryAttempt(opts.task, finalAttempt)); if(!finalAttempt && opts.interval > 0){ attempts.push(retryInterval(opts.interval)); } } async.series(attempts, function(done, data){ data = data[data.length - 1]; (wrappedCallback || opts.callback)(data.err, data.result); }); } // If a callback is passed, run this as a controll flow return opts.callback ? wrappedTask() : wrappedTask; }; async.waterfall = function (tasks, callback) { callback = _once(callback || noop); if (!_isArray(tasks)) { var err = new Error('First argument to waterfall must be an array of functions'); return callback(err); } if (!tasks.length) { return callback(); } function wrapIterator(iterator) { return _restParam(function (err, args) { if (err) { callback.apply(null, [err].concat(args)); } else { var next = iterator.next(); if (next) { args.push(wrapIterator(next)); } else { args.push(callback); } ensureAsync(iterator).apply(null, args); } }); } wrapIterator(async.iterator(tasks))(); }; function _parallel(eachfn, tasks, callback) { callback = callback || noop; var results = _isArrayLike(tasks) ? [] : {}; eachfn(tasks, function (task, key, callback) { task(_restParam(function (err, args) { if (args.length <= 1) { args = args[0]; } results[key] = args; callback(err); })); }, function (err) { callback(err, results); }); } async.parallel = function (tasks, callback) { _parallel(async.eachOf, tasks, callback); }; async.parallelLimit = function(tasks, limit, callback) { _parallel(_eachOfLimit(limit), tasks, callback); }; async.series = function(tasks, callback) { _parallel(async.eachOfSeries, tasks, callback); }; async.iterator = function (tasks) { function makeCallback(index) { function fn() { if (tasks.length) { tasks[index].apply(null, arguments); } return fn.next(); } fn.next = function () { return (index < tasks.length - 1) ? makeCallback(index + 1): null; }; return fn; } return makeCallback(0); }; async.apply = _restParam(function (fn, args) { return _restParam(function (callArgs) { return fn.apply( null, args.concat(callArgs) ); }); }); function _concat(eachfn, arr, fn, callback) { var result = []; eachfn(arr, function (x, index, cb) { fn(x, function (err, y) { result = result.concat(y || []); cb(err); }); }, function (err) { callback(err, result); }); } async.concat = doParallel(_concat); async.concatSeries = doSeries(_concat); async.whilst = function (test, iterator, callback) { callback = callback || noop; if (test()) { var next = _restParam(function(err, args) { if (err) { callback(err); } else if (test.apply(this, args)) { iterator(next); } else { callback(null); } }); iterator(next); } else { callback(null); } }; async.doWhilst = function (iterator, test, callback) { var calls = 0; return async.whilst(function() { return ++calls <= 1 || test.apply(this, arguments); }, iterator, callback); }; async.until = function (test, iterator, callback) { return async.whilst(function() { return !test.apply(this, arguments); }, iterator, callback); }; async.doUntil = function (iterator, test, callback) { return async.doWhilst(iterator, function() { return !test.apply(this, arguments); }, callback); }; async.during = function (test, iterator, callback) { callback = callback || noop; var next = _restParam(function(err, args) { if (err) { callback(err); } else { args.push(check); test.apply(this, args); } }); var check = function(err, truth) { if (err) { callback(err); } else if (truth) { iterator(next); } else { callback(null); } }; test(check); }; async.doDuring = function (iterator, test, callback) { var calls = 0; async.during(function(next) { if (calls++ < 1) { next(null, true); } else { test.apply(this, arguments); } }, iterator, callback); }; function _queue(worker, concurrency, payload) { if (concurrency == null) { concurrency = 1; } else if(concurrency === 0) { throw new Error('Concurrency must not be zero'); } function _insert(q, data, pos, callback) { if (callback != null && typeof callback !== "function") { throw new Error("task callback must be a function"); } q.started = true; if (!_isArray(data)) { data = [data]; } if(data.length === 0 && q.idle()) { // call drain immediately if there are no tasks return async.setImmediate(function() { q.drain(); }); } _arrayEach(data, function(task) { var item = { data: task, callback: callback || noop }; if (pos) { q.tasks.unshift(item); } else { q.tasks.push(item); } if (q.tasks.length === q.concurrency) { q.saturated(); } }); async.setImmediate(q.process); } function _next(q, tasks) { return function(){ workers -= 1; var removed = false; var args = arguments; _arrayEach(tasks, function (task) { _arrayEach(workersList, function (worker, index) { if (worker === task && !removed) { workersList.splice(index, 1); removed = true; } }); task.callback.apply(task, args); }); if (q.tasks.length + workers === 0) { q.drain(); } q.process(); }; } var workers = 0; var workersList = []; var q = { tasks: [], concurrency: concurrency, payload: payload, saturated: noop, empty: noop, drain: noop, started: false, paused: false, push: function (data, callback) { _insert(q, data, false, callback); }, kill: function () { q.drain = noop; q.tasks = []; }, unshift: function (data, callback) { _insert(q, data, true, callback); }, process: function () { if (!q.paused && workers < q.concurrency && q.tasks.length) { while(workers < q.concurrency && q.tasks.length){ var tasks = q.payload ? q.tasks.splice(0, q.payload) : q.tasks.splice(0, q.tasks.length); var data = _map(tasks, function (task) { return task.data; }); if (q.tasks.length === 0) { q.empty(); } workers += 1; workersList.push(tasks[0]); var cb = only_once(_next(q, tasks)); worker(data, cb); } } }, length: function () { return q.tasks.length; }, running: function () { return workers; }, workersList: function () { return workersList; }, idle: function() { return q.tasks.length + workers === 0; }, pause: function () { q.paused = true; }, resume: function () { if (q.paused === false) { return; } q.paused = false; var resumeCount = Math.min(q.concurrency, q.tasks.length); // Need to call q.process once per concurrent // worker to preserve full concurrency after pause for (var w = 1; w <= resumeCount; w++) { async.setImmediate(q.process); } } }; return q; } async.queue = function (worker, concurrency) { var q = _queue(function (items, cb) { worker(items[0], cb); }, concurrency, 1); return q; }; async.priorityQueue = function (worker, concurrency) { function _compareTasks(a, b){ return a.priority - b.priority; } function _binarySearch(sequence, item, compare) { var beg = -1, end = sequence.length - 1; while (beg < end) { var mid = beg + ((end - beg + 1) >>> 1); if (compare(item, sequence[mid]) >= 0) { beg = mid; } else { end = mid - 1; } } return beg; } function _insert(q, data, priority, callback) { if (callback != null && typeof callback !== "function") { throw new Error("task callback must be a function"); } q.started = true; if (!_isArray(data)) { data = [data]; } if(data.length === 0) { // call drain immediately if there are no tasks return async.setImmediate(function() { q.drain(); }); } _arrayEach(data, function(task) { var item = { data: task, priority: priority, callback: typeof callback === 'function' ? callback : noop }; q.tasks.splice(_binarySearch(q.tasks, item, _compareTasks) + 1, 0, item); if (q.tasks.length === q.concurrency) { q.saturated(); } async.setImmediate(q.process); }); } // Start with a normal queue var q = async.queue(worker, concurrency); // Override push to accept second parameter representing priority q.push = function (data, priority, callback) { _insert(q, data, priority, callback); }; // Remove unshift function delete q.unshift; return q; }; async.cargo = function (worker, payload) { return _queue(worker, 1, payload); }; function _console_fn(name) { return _restParam(function (fn, args) { fn.apply(null, args.concat([_restParam(function (err, args) { if (typeof console === 'object') { if (err) { if (console.error) { console.error(err); } } else if (console[name]) { _arrayEach(args, function (x) { console[name](x); }); } } })])); }); } async.log = _console_fn('log'); async.dir = _console_fn('dir'); /*async.info = _console_fn('info'); async.warn = _console_fn('warn'); async.error = _console_fn('error');*/ async.memoize = function (fn, hasher) { var memo = {}; var queues = {}; hasher = hasher || identity; var memoized = _restParam(function memoized(args) { var callback = args.pop(); var key = hasher.apply(null, args); if (key in memo) { async.setImmediate(function () { callback.apply(null, memo[key]); }); } else if (key in queues) { queues[key].push(callback); } else { queues[key] = [callback]; fn.apply(null, args.concat([_restParam(function (args) { memo[key] = args; var q = queues[key]; delete queues[key]; for (var i = 0, l = q.length; i < l; i++) { q[i].apply(null, args); } })])); } }); memoized.memo = memo; memoized.unmemoized = fn; return memoized; }; async.unmemoize = function (fn) { return function () { return (fn.unmemoized || fn).apply(null, arguments); }; }; function _times(mapper) { return function (count, iterator, callback) { mapper(_range(count), iterator, callback); }; } async.times = _times(async.map); async.timesSeries = _times(async.mapSeries); async.timesLimit = function (count, limit, iterator, callback) { return async.mapLimit(_range(count), limit, iterator, callback); }; async.seq = function (/* functions... */) { var fns = arguments; return _restParam(function (args) { var that = this; var callback = args[args.length - 1]; if (typeof callback == 'function') { args.pop(); } else { callback = noop; } async.reduce(fns, args, function (newargs, fn, cb) { fn.apply(that, newargs.concat([_restParam(function (err, nextargs) { cb(err, nextargs); })])); }, function (err, results) { callback.apply(that, [err].concat(results)); }); }); }; async.compose = function (/* functions... */) { return async.seq.apply(null, Array.prototype.reverse.call(arguments)); }; function _applyEach(eachfn) { return _restParam(function(fns, args) { var go = _restParam(function(args) { var that = this; var callback = args.pop(); return eachfn(fns, function (fn, _, cb) { fn.apply(that, args.concat([cb])); }, callback); }); if (args.length) { return go.apply(this, args); } else { return go; } }); } async.applyEach = _applyEach(async.eachOf); async.applyEachSeries = _applyEach(async.eachOfSeries); async.forever = function (fn, callback) { var done = only_once(callback || noop); var task = ensureAsync(fn); function next(err) { if (err) { return done(err); } task(next); } next(); }; function ensureAsync(fn) { return _restParam(function (args) { var callback = args.pop(); args.push(function () { var innerArgs = arguments; if (sync) { async.setImmediate(function () { callback.apply(null, innerArgs); }); } else { callback.apply(null, innerArgs); } }); var sync = true; fn.apply(this, args); sync = false; }); } async.ensureAsync = ensureAsync; async.constant = _restParam(function(values) { var args = [null].concat(values); return function (callback) { return callback.apply(this, args); }; }); async.wrapSync = async.asyncify = function asyncify(func) { return _restParam(function (args) { var callback = args.pop(); var result; try { result = func.apply(this, args); } catch (e) { return callback(e); } // if result is Promise object if (_isObject(result) && typeof result.then === "function") { result.then(function(value) { callback(null, value); })["catch"](function(err) { callback(err.message ? err : new Error(err)); }); } else { callback(null, result); } }); }; // Node.js if (typeof module === 'object' && module.exports) { module.exports = async; } // AMD / RequireJS else if (typeof define === 'function' && define.amd) { define([], function () { return async; }); } // included directly via <script> tag else { root.async = async; } }()); }).call(this,_dereq_('_process'),typeof global !== "undefined" ? global : typeof self !== "undefined" ? self : typeof window !== "undefined" ? window : {}) },{"_process":68}],34:[function(_dereq_,module,exports){ ;(function (root, factory, undef) { if (typeof exports === "object") { // CommonJS module.exports = exports = factory(_dereq_("./core"), _dereq_("./enc-base64"), _dereq_("./md5"), _dereq_("./evpkdf"), _dereq_("./cipher-core")); } else if (typeof define === "function" && define.amd) { // AMD define(["./core", "./enc-base64", "./md5", "./evpkdf", "./cipher-core"], factory); } else { // Global (browser) factory(root.CryptoJS); } }(this, function (CryptoJS) { (function () { // Shortcuts var C = CryptoJS; var C_lib = C.lib; var BlockCipher = C_lib.BlockCipher; var C_algo = C.algo; // Lookup tables var SBOX = []; var INV_SBOX = []; var SUB_MIX_0 = []; var SUB_MIX_1 = []; var SUB_MIX_2 = []; var SUB_MIX_3 = []; var INV_SUB_MIX_0 = []; var INV_SUB_MIX_1 = []; var INV_SUB_MIX_2 = []; var INV_SUB_MIX_3 = []; // Compute lookup tables (function () { // Compute double table var d = []; for (var i = 0; i < 256; i++) { if (i < 128) { d[i] = i << 1; } else { d[i] = (i << 1) ^ 0x11b; } } // Walk GF(2^8) var x = 0; var xi = 0; for (var i = 0; i < 256; i++) { // Compute sbox var sx = xi ^ (xi << 1) ^ (xi << 2) ^ (xi << 3) ^ (xi << 4); sx = (sx >>> 8) ^ (sx & 0xff) ^ 0x63; SBOX[x] = sx; INV_SBOX[sx] = x; // Compute multiplication var x2 = d[x]; var x4 = d[x2]; var x8 = d[x4]; // Compute sub bytes, mix columns tables var t = (d[sx] * 0x101) ^ (sx * 0x1010100); SUB_MIX_0[x] = (t << 24) | (t >>> 8); SUB_MIX_1[x] = (t << 16) | (t >>> 16); SUB_MIX_2[x] = (t << 8) | (t >>> 24); SUB_MIX_3[x] = t; // Compute inv sub bytes, inv mix columns tables var t = (x8 * 0x1010101) ^ (x4 * 0x10001) ^ (x2 * 0x101) ^ (x * 0x1010100); INV_SUB_MIX_0[sx] = (t << 24) | (t >>> 8); INV_SUB_MIX_1[sx] = (t << 16) | (t >>> 16); INV_SUB_MIX_2[sx] = (t << 8) | (t >>> 24); INV_SUB_MIX_3[sx] = t; // Compute next counter if (!x) { x = xi = 1; } else { x = x2 ^ d[d[d[x8 ^ x2]]]; xi ^= d[d[xi]]; } } }()); // Precomputed Rcon lookup var RCON = [0x00, 0x01, 0x02, 0x04, 0x08, 0x10, 0x20, 0x40, 0x80, 0x1b, 0x36]; /** * AES block cipher algorithm. */ var AES = C_algo.AES = BlockCipher.extend({ _doReset: function () { // Shortcuts var key = this._key; var keyWords = key.words; var keySize = key.sigBytes / 4; // Compute number of rounds var nRounds = this._nRounds = keySize + 6 // Compute number of key schedule rows var ksRows = (nRounds + 1) * 4; // Compute key schedule var keySchedule = this._keySchedule = []; for (var ksRow = 0; ksRow < ksRows; ksRow++) { if (ksRow < keySize) { keySchedule[ksRow] = keyWords[ksRow]; } else { var t = keySchedule[ksRow - 1]; if (!(ksRow % keySize)) { // Rot word t = (t << 8) | (t >>> 24); // Sub word t = (SBOX[t >>> 24] << 24) | (SBOX[(t >>> 16) & 0xff] << 16) | (SBOX[(t >>> 8) & 0xff] << 8) | SBOX[t & 0xff]; // Mix Rcon t ^= RCON[(ksRow / keySize) | 0] << 24; } else if (keySize > 6 && ksRow % keySize == 4) { // Sub word t = (SBOX[t >>> 24] << 24) | (SBOX[(t >>> 16) & 0xff] << 16) | (SBOX[(t >>> 8) & 0xff] << 8) | SBOX[t & 0xff]; } keySchedule[ksRow] = keySchedule[ksRow - keySize] ^ t; } } // Compute inv key schedule var invKeySchedule = this._invKeySchedule = []; for (var invKsRow = 0; invKsRow < ksRows; invKsRow++) { var ksRow = ksRows - invKsRow; if (invKsRow % 4) { var t = keySchedule[ksRow]; } else { var t = keySchedule[ksRow - 4]; } if (invKsRow < 4 || ksRow <= 4) { invKeySchedule[invKsRow] = t; } else { invKeySchedule[invKsRow] = INV_SUB_MIX_0[SBOX[t >>> 24]] ^ INV_SUB_MIX_1[SBOX[(t >>> 16) & 0xff]] ^ INV_SUB_MIX_2[SBOX[(t >>> 8) & 0xff]] ^ INV_SUB_MIX_3[SBOX[t & 0xff]]; } } }, encryptBlock: function (M, offset) { this._doCryptBlock(M, offset, this._keySchedule, SUB_MIX_0, SUB_MIX_1, SUB_MIX_2, SUB_MIX_3, SBOX); }, decryptBlock: function (M, offset) { // Swap 2nd and 4th rows var t = M[offset + 1]; M[offset + 1] = M[offset + 3]; M[offset + 3] = t; this._doCryptBlock(M, offset, this._invKeySchedule, INV_SUB_MIX_0, INV_SUB_MIX_1, INV_SUB_MIX_2, INV_SUB_MIX_3, INV_SBOX); // Inv swap 2nd and 4th rows var t = M[offset + 1]; M[offset + 1] = M[offset + 3]; M[offset + 3] = t; }, _doCryptBlock: function (M, offset, keySchedule, SUB_MIX_0, SUB_MIX_1, SUB_MIX_2, SUB_MIX_3, SBOX) { // Shortcut var nRounds = this._nRounds; // Get input, add round key var s0 = M[offset] ^ keySchedule[0]; var s1 = M[offset + 1] ^ keySchedule[1]; var s2 = M[offset + 2] ^ keySchedule[2]; var s3 = M[offset + 3] ^ keySchedule[3]; // Key schedule row counter var ksRow = 4; // Rounds for (var round = 1; round < nRounds; round++) { // Shift rows, sub bytes, mix columns, add round key var t0 = SUB_MIX_0[s0 >>> 24] ^ SUB_MIX_1[(s1 >>> 16) & 0xff] ^ SUB_MIX_2[(s2 >>> 8) & 0xff] ^ SUB_MIX_3[s3 & 0xff] ^ keySchedule[ksRow++]; var t1 = SUB_MIX_0[s1 >>> 24] ^ SUB_MIX_1[(s2 >>> 16) & 0xff] ^ SUB_MIX_2[(s3 >>> 8) & 0xff] ^ SUB_MIX_3[s0 & 0xff] ^ keySchedule[ksRow++]; var t2 = SUB_MIX_0[s2 >>> 24] ^ SUB_MIX_1[(s3 >>> 16) & 0xff] ^ SUB_MIX_2[(s0 >>> 8) & 0xff] ^ SUB_MIX_3[s1 & 0xff] ^ keySchedule[ksRow++]; var t3 = SUB_MIX_0[s3 >>> 24] ^ SUB_MIX_1[(s0 >>> 16) & 0xff] ^ SUB_MIX_2[(s1 >>> 8) & 0xff] ^ SUB_MIX_3[s2 & 0xff] ^ keySchedule[ksRow++]; // Update state s0 = t0; s1 = t1; s2 = t2; s3 = t3; } // Shift rows, sub bytes, add round key var t0 = ((SBOX[s0 >>> 24] << 24) | (SBOX[(s1 >>> 16) & 0xff] << 16) | (SBOX[(s2 >>> 8) & 0xff] << 8) | SBOX[s3 & 0xff]) ^ keySchedule[ksRow++]; var t1 = ((SBOX[s1 >>> 24] << 24) | (SBOX[(s2 >>> 16) & 0xff] << 16) | (SBOX[(s3 >>> 8) & 0xff] << 8) | SBOX[s0 & 0xff]) ^ keySchedule[ksRow++]; var t2 = ((SBOX[s2 >>> 24] << 24) | (SBOX[(s3 >>> 16) & 0xff] << 16) | (SBOX[(s0 >>> 8) & 0xff] << 8) | SBOX[s1 & 0xff]) ^ keySchedule[ksRow++]; var t3 = ((SBOX[s3 >>> 24] << 24) | (SBOX[(s0 >>> 16) & 0xff] << 16) | (SBOX[(s1 >>> 8) & 0xff] << 8) | SBOX[s2 & 0xff]) ^ keySchedule[ksRow++]; // Set output M[offset] = t0; M[offset + 1] = t1; M[offset + 2] = t2; M[offset + 3] = t3; }, keySize: 256/32 }); /** * Shortcut functions to the cipher's object interface. * * @example * * var ciphertext = CryptoJS.AES.encrypt(message, key, cfg); * var plaintext = CryptoJS.AES.decrypt(ciphertext, key, cfg); */ C.AES = BlockCipher._createHelper(AES); }()); return CryptoJS.AES; })); },{"./cipher-core":35,"./core":36,"./enc-base64":37,"./evpkdf":39,"./md5":44}],35:[function(_dereq_,module,exports){ ;(function (root, factory) { if (typeof exports === "object") { // CommonJS module.exports = exports = factory(_dereq_("./core")); } else if (typeof define === "function" && define.amd) { // AMD define(["./core"], factory); } else { // Global (browser) factory(root.CryptoJS); } }(this, function (CryptoJS) { /** * Cipher core components. */ CryptoJS.lib.Cipher || (function (undefined) { // Shortcuts var C = CryptoJS; var C_lib = C.lib; var Base = C_lib.Base; var WordArray = C_lib.WordArray; var BufferedBlockAlgorithm = C_lib.BufferedBlockAlgorithm; var C_enc = C.enc; var Utf8 = C_enc.Utf8; var Base64 = C_enc.Base64; var C_algo = C.algo; var EvpKDF = C_algo.EvpKDF; /** * Abstract base cipher template. * * @property {number} keySize This cipher's key size. Default: 4 (128 bits) * @property {number} ivSize This cipher's IV size. Default: 4 (128 bits) * @property {number} _ENC_XFORM_MODE A constant representing encryption mode. * @property {number} _DEC_XFORM_MODE A constant representing decryption mode. */ var Cipher = C_lib.Cipher = BufferedBlockAlgorithm.extend({ /** * Configuration options. * * @property {WordArray} iv The IV to use for this operation. */ cfg: Base.extend(), /** * Creates this cipher in encryption mode. * * @param {WordArray} key The key. * @param {Object} cfg (Optional) The configuration options to use for this operation. * * @return {Cipher} A cipher instance. * * @static * * @example * * var cipher = CryptoJS.algo.AES.createEncryptor(keyWordArray, { iv: ivWordArray }); */ createEncryptor: function (key, cfg) { return this.create(this._ENC_XFORM_MODE, key, cfg); }, /** * Creates this cipher in decryption mode. * * @param {WordArray} key The key. * @param {Object} cfg (Optional) The configuration options to use for this operation. * * @return {Cipher} A cipher instance. * * @static * * @example * * var cipher = CryptoJS.algo.AES.createDecryptor(keyWordArray, { iv: ivWordArray }); */ createDecryptor: function (key, cfg) { return this.create(this._DEC_XFORM_MODE, key, cfg); }, /** * Initializes a newly created cipher. * * @param {number} xformMode Either the encryption or decryption transormation mode constant. * @param {WordArray} key The key. * @param {Object} cfg (Optional) The configuration options to use for this operation. * * @example * * var cipher = CryptoJS.algo.AES.create(CryptoJS.algo.AES._ENC_XFORM_MODE, keyWordArray, { iv: ivWordArray }); */ init: function (xformMode, key, cfg) { // Apply config defaults this.cfg = this.cfg.extend(cfg); // Store transform mode and key this._xformMode = xformMode; this._key = key; // Set initial values this.reset(); }, /** * Resets this cipher to its initial state. * * @example * * cipher.reset(); */ reset: function () { // Reset data buffer BufferedBlockAlgorithm.reset.call(this); // Perform concrete-cipher logic this._doReset(); }, /** * Adds data to be encrypted or decrypted. * * @param {WordArray|string} dataUpdate The data to encrypt or decrypt. * * @return {WordArray} The data after processing. * * @example * * var encrypted = cipher.process('data'); * var encrypted = cipher.process(wordArray); */ process: function (dataUpdate) { // Append this._append(dataUpdate); // Process available blocks return this._process(); }, /** * Finalizes the encryption or decryption process. * Note that the finalize operation is effectively a destructive, read-once operation. * * @param {WordArray|string} dataUpdate The final data to encrypt or decrypt. * * @return {WordArray} The data after final processing. * * @example * * var encrypted = cipher.finalize(); * var encrypted = cipher.finalize('data'); * var encrypted = cipher.finalize(wordArray); */ finalize: function (dataUpdate) { // Final data update if (dataUpdate) { this._append(dataUpdate); } // Perform concrete-cipher logic var finalProcessedData = this._doFinalize(); return finalProcessedData; }, keySize: 128/32, ivSize: 128/32, _ENC_XFORM_MODE: 1, _DEC_XFORM_MODE: 2, /** * Creates shortcut functions to a cipher's object interface. * * @param {Cipher} cipher The cipher to create a helper for. * * @return {Object} An object with encrypt and decrypt shortcut functions. * * @static * * @example * * var AES = CryptoJS.lib.Cipher._createHelper(CryptoJS.algo.AES); */ _createHelper: (function () { function selectCipherStrategy(key) { if (typeof key == 'string') { return PasswordBasedCipher; } else { return SerializableCipher; } } return function (cipher) { return { encrypt: function (message, key, cfg) { return selectCipherStrategy(key).encrypt(cipher, message, key, cfg); }, decrypt: function (ciphertext, key, cfg) { return selectCipherStrategy(key).decrypt(cipher, ciphertext, key, cfg); } }; }; }()) }); /** * Abstract base stream cipher template. * * @property {number} blockSize The number of 32-bit words this cipher operates on. Default: 1 (32 bits) */ var StreamCipher = C_lib.StreamCipher = Cipher.extend({ _doFinalize: function () { // Process partial blocks var finalProcessedBlocks = this._process(!!'flush'); return finalProcessedBlocks; }, blockSize: 1 }); /** * Mode namespace. */ var C_mode = C.mode = {}; /** * Abstract base block cipher mode template. */ var BlockCipherMode = C_lib.BlockCipherMode = Base.extend({ /** * Creates this mode for encryption. * * @param {Cipher} cipher A block cipher instance. * @param {Array} iv The IV words. * * @static * * @example * * var mode = CryptoJS.mode.CBC.createEncryptor(cipher, iv.words); */ createEncryptor: function (cipher, iv) { return this.Encryptor.create(cipher, iv); }, /** * Creates this mode for decryption. * * @param {Cipher} cipher A block cipher instance. * @param {Array} iv The IV words. * * @static * * @example * * var mode = CryptoJS.mode.CBC.createDecryptor(cipher, iv.words); */ createDecryptor: function (cipher, iv) { return this.Decryptor.create(cipher, iv); }, /** * Initializes a newly created mode. * * @param {Cipher} cipher A block cipher instance. * @param {Array} iv The IV words. * * @example * * var mode = CryptoJS.mode.CBC.Encryptor.create(cipher, iv.words); */ init: function (cipher, iv) { this._cipher = cipher; this._iv = iv; } }); /** * Cipher Block Chaining mode. */ var CBC = C_mode.CBC = (function () { /** * Abstract base CBC mode. */ var CBC = BlockCipherMode.extend(); /** * CBC encryptor. */ CBC.Encryptor = CBC.extend({ /** * Processes the data block at offset. * * @param {Array} words The data words to operate on. * @param {number} offset The offset where the block starts. * * @example * * mode.processBlock(data.words, offset); */ processBlock: function (words, offset) { // Shortcuts var cipher = this._cipher; var blockSize = cipher.blockSize; // XOR and encrypt xorBlock.call(this, words, offset, blockSize); cipher.encryptBlock(words, offset); // Remember this block to use with next block this._prevBlock = words.slice(offset, offset + blockSize); } }); /** * CBC decryptor. */ CBC.Decryptor = CBC.extend({ /** * Processes the data block at offset. * * @param {Array} words The data words to operate on. * @param {number} offset The offset where the block starts. * * @example * * mode.processBlock(data.words, offset); */ processBlock: function (words, offset) { // Shortcuts var cipher = this._cipher; var blockSize = cipher.blockSize; // Remember this block to use with next block var thisBlock = words.slice(offset, offset + blockSize); // Decrypt and XOR cipher.decryptBlock(words, offset); xorBlock.call(this, words, offset, blockSize); // This block becomes the previous block this._prevBlock = thisBlock; } }); function xorBlock(words, offset, blockSize) { // Shortcut var iv = this._iv; // Choose mixing block if (iv) { var block = iv; // Remove IV for subsequent blocks this._iv = undefined; } else { var block = this._prevBlock; } // XOR blocks for (var i = 0; i < blockSize; i++) { words[offset + i] ^= block[i]; } } return CBC; }()); /** * Padding namespace. */ var C_pad = C.pad = {}; /** * PKCS #5/7 padding strategy. */ var Pkcs7 = C_pad.Pkcs7 = { /** * Pads data using the algorithm defined in PKCS #5/7. * * @param {WordArray} data The data to pad. * @param {number} blockSize The multiple that the data should be padded to. * * @static * * @example * * CryptoJS.pad.Pkcs7.pad(wordArray, 4); */ pad: function (data, blockSize) { // Shortcut var blockSizeBytes = blockSize * 4; // Count padding bytes var nPaddingBytes = blockSizeBytes - data.sigBytes % blockSizeBytes; // Create padding word var paddingWord = (nPaddingBytes << 24) | (nPaddingBytes << 16) | (nPaddingBytes << 8) | nPaddingBytes; // Create padding var paddingWords = []; for (var i = 0; i < nPaddingBytes; i += 4) { paddingWords.push(paddingWord); } var padding = WordArray.create(paddingWords, nPaddingBytes); // Add padding data.concat(padding); }, /** * Unpads data that had been padded using the algorithm defined in PKCS #5/7. * * @param {WordArray} data The data to unpad. * * @static * * @example * * CryptoJS.pad.Pkcs7.unpad(wordArray); */ unpad: function (data) { // Get number of padding bytes from last byte var nPaddingBytes = data.words[(data.sigBytes - 1) >>> 2] & 0xff; // Remove padding data.sigBytes -= nPaddingBytes; } }; /** * Abstract base block cipher template. * * @property {number} blockSize The number of 32-bit words this cipher operates on. Default: 4 (128 bits) */ var BlockCipher = C_lib.BlockCipher = Cipher.extend({ /** * Configuration options. * * @property {Mode} mode The block mode to use. Default: CBC * @property {Padding} padding The padding strategy to use. Default: Pkcs7 */ cfg: Cipher.cfg.extend({ mode: CBC, padding: Pkcs7 }), reset: function () { // Reset cipher Cipher.reset.call(this); // Shortcuts var cfg = this.cfg; var iv = cfg.iv; var mode = cfg.mode; // Reset block mode if (this._xformMode == this._ENC_XFORM_MODE) { var modeCreator = mode.createEncryptor; } else /* if (this._xformMode == this._DEC_XFORM_MODE) */ { var modeCreator = mode.createDecryptor; // Keep at least one block in the buffer for unpadding this._minBufferSize = 1; } this._mode = modeCreator.call(mode, this, iv && iv.words); }, _doProcessBlock: function (words, offset) { this._mode.processBlock(words, offset); }, _doFinalize: function () { // Shortcut var padding = this.cfg.padding; // Finalize if (this._xformMode == this._ENC_XFORM_MODE) { // Pad data padding.pad(this._data, this.blockSize); // Process final blocks var finalProcessedBlocks = this._process(!!'flush'); } else /* if (this._xformMode == this._DEC_XFORM_MODE) */ { // Process final blocks var finalProcessedBlocks = this._process(!!'flush'); // Unpad data padding.unpad(finalProcessedBlocks); } return finalProcessedBlocks; }, blockSize: 128/32 }); /** * A collection of cipher parameters. * * @property {WordArray} ciphertext The raw ciphertext. * @property {WordArray} key The key to this ciphertext. * @property {WordArray} iv The IV used in the ciphering operation. * @property {WordArray} salt The salt used with a key derivation function. * @property {Cipher} algorithm The cipher algorithm. * @property {Mode} mode The block mode used in the ciphering operation. * @property {Padding} padding The padding scheme used in the ciphering operation. * @property {number} blockSize The block size of the cipher. * @property {Format} formatter The default formatting strategy to convert this cipher params object to a string. */ var CipherParams = C_lib.CipherParams = Base.extend({ /** * Initializes a newly created cipher params object. * * @param {Object} cipherParams An object with any of the possible cipher parameters. * * @example * * var cipherParams = CryptoJS.lib.CipherParams.create({ * ciphertext: ciphertextWordArray, * key: keyWordArray, * iv: ivWordArray, * salt: saltWordArray, * algorithm: CryptoJS.algo.AES, * mode: CryptoJS.mode.CBC, * padding: CryptoJS.pad.PKCS7, * blockSize: 4, * formatter: CryptoJS.format.OpenSSL * }); */ init: function (cipherParams) { this.mixIn(cipherParams); }, /** * Converts this cipher params object to a string. * * @param {Format} formatter (Optional) The formatting strategy to use. * * @return {string} The stringified cipher params. * * @throws Error If neither the formatter nor the default formatter is set. * * @example * * var string = cipherParams + ''; * var string = cipherParams.toString(); * var string = cipherParams.toString(CryptoJS.format.OpenSSL); */ toString: function (formatter) { return (formatter || this.formatter).stringify(this); } }); /** * Format namespace. */ var C_format = C.format = {}; /** * OpenSSL formatting strategy. */ var OpenSSLFormatter = C_format.OpenSSL = { /** * Converts a cipher params object to an OpenSSL-compatible string. * * @param {CipherParams} cipherParams The cipher params object. * * @return {string} The OpenSSL-compatible string. * * @static * * @example * * var openSSLString = CryptoJS.format.OpenSSL.stringify(cipherParams); */ stringify: function (cipherParams) { // Shortcuts var ciphertext = cipherParams.ciphertext; var salt = cipherParams.salt; // Format if (salt) { var wordArray = WordArray.create([0x53616c74, 0x65645f5f]).concat(salt).concat(ciphertext); } else { var wordArray = ciphertext; } return wordArray.toString(Base64); }, /** * Converts an OpenSSL-compatible string to a cipher params object. * * @param {string} openSSLStr The OpenSSL-compatible string. * * @return {CipherParams} The cipher params object. * * @static * * @example * * var cipherParams = CryptoJS.format.OpenSSL.parse(openSSLString); */ parse: function (openSSLStr) { // Parse base64 var ciphertext = Base64.parse(openSSLStr); // Shortcut var ciphertextWords = ciphertext.words; // Test for salt if (ciphertextWords[0] == 0x53616c74 && ciphertextWords[1] == 0x65645f5f) { // Extract salt var salt = WordArray.create(ciphertextWords.slice(2, 4)); // Remove salt from ciphertext ciphertextWords.splice(0, 4); ciphertext.sigBytes -= 16; } return CipherParams.create({ ciphertext: ciphertext, salt: salt }); } }; /** * A cipher wrapper that returns ciphertext as a serializable cipher params object. */ var SerializableCipher = C_lib.SerializableCipher = Base.extend({ /** * Configuration options. * * @property {Formatter} format The formatting strategy to convert cipher param objects to and from a string. Default: OpenSSL */ cfg: Base.extend({ format: OpenSSLFormatter }), /** * Encrypts a message. * * @param {Cipher} cipher The cipher algorithm to use. * @param {WordArray|string} message The message to encrypt. * @param {WordArray} key The key. * @param {Object} cfg (Optional) The configuration options to use for this operation. * * @return {CipherParams} A cipher params object. * * @static * * @example * * var ciphertextParams = CryptoJS.lib.SerializableCipher.encrypt(CryptoJS.algo.AES, message, key); * var ciphertextParams = CryptoJS.lib.SerializableCipher.encrypt(CryptoJS.algo.AES, message, key, { iv: iv }); * var ciphertextParams = CryptoJS.lib.SerializableCipher.encrypt(CryptoJS.algo.AES, message, key, { iv: iv, format: CryptoJS.format.OpenSSL }); */ encrypt: function (cipher, message, key, cfg) { // Apply config defaults cfg = this.cfg.extend(cfg); // Encrypt var encryptor = cipher.createEncryptor(key, cfg); var ciphertext = encryptor.finalize(message); // Shortcut var cipherCfg = encryptor.cfg; // Create and return serializable cipher params return CipherParams.create({ ciphertext: ciphertext, key: key, iv: cipherCfg.iv, algorithm: cipher, mode: cipherCfg.mode, padding: cipherCfg.padding, blockSize: cipher.blockSize, formatter: cfg.format }); }, /** * Decrypts serialized ciphertext. * * @param {Cipher} cipher The cipher algorithm to use. * @param {CipherParams|string} ciphertext The ciphertext to decrypt. * @param {WordArray} key The key. * @param {Object} cfg (Optional) The configuration options to use for this operation. * * @return {WordArray} The plaintext. * * @static * * @example * * var plaintext = CryptoJS.lib.SerializableCipher.decrypt(CryptoJS.algo.AES, formattedCiphertext, key, { iv: iv, format: CryptoJS.format.OpenSSL }); * var plaintext = CryptoJS.lib.SerializableCipher.decrypt(CryptoJS.algo.AES, ciphertextParams, key, { iv: iv, format: CryptoJS.format.OpenSSL }); */ decrypt: function (cipher, ciphertext, key, cfg) { // Apply config defaults cfg = this.cfg.extend(cfg); // Convert string to CipherParams ciphertext = this._parse(ciphertext, cfg.format); // Decrypt var plaintext = cipher.createDecryptor(key, cfg).finalize(ciphertext.ciphertext); return plaintext; }, /** * Converts serialized ciphertext to CipherParams, * else assumed CipherParams already and returns ciphertext unchanged. * * @param {CipherParams|string} ciphertext The ciphertext. * @param {Formatter} format The formatting strategy to use to parse serialized ciphertext. * * @return {CipherParams} The unserialized ciphertext. * * @static * * @example * * var ciphertextParams = CryptoJS.lib.SerializableCipher._parse(ciphertextStringOrParams, format); */ _parse: function (ciphertext, format) { if (typeof ciphertext == 'string') { return format.parse(ciphertext, this); } else { return ciphertext; } } }); /** * Key derivation function namespace. */ var C_kdf = C.kdf = {}; /** * OpenSSL key derivation function. */ var OpenSSLKdf = C_kdf.OpenSSL = { /** * Derives a key and IV from a password. * * @param {string} password The password to derive from. * @param {number} keySize The size in words of the key to generate. * @param {number} ivSize The size in words of the IV to generate. * @param {WordArray|string} salt (Optional) A 64-bit salt to use. If omitted, a salt will be generated randomly. * * @return {CipherParams} A cipher params object with the key, IV, and salt. * * @static * * @example * * var derivedParams = CryptoJS.kdf.OpenSSL.execute('Password', 256/32, 128/32); * var derivedParams = CryptoJS.kdf.OpenSSL.execute('Password', 256/32, 128/32, 'saltsalt'); */ execute: function (password, keySize, ivSize, salt) { // Generate random salt if (!salt) { salt = WordArray.random(64/8); } // Derive key and IV var key = EvpKDF.create({ keySize: keySize + ivSize }).compute(password, salt); // Separate key and IV var iv = WordArray.create(key.words.slice(keySize), ivSize * 4); key.sigBytes = keySize * 4; // Return params return CipherParams.create({ key: key, iv: iv, salt: salt }); } }; /** * A serializable cipher wrapper that derives the key from a password, * and returns ciphertext as a serializable cipher params object. */ var PasswordBasedCipher = C_lib.PasswordBasedCipher = SerializableCipher.extend({ /** * Configuration options. * * @property {KDF} kdf The key derivation function to use to generate a key and IV from a password. Default: OpenSSL */ cfg: SerializableCipher.cfg.extend({ kdf: OpenSSLKdf }), /** * Encrypts a message using a password. * * @param {Cipher} cipher The cipher algorithm to use. * @param {WordArray|string} message The message to encrypt. * @param {string} password The password. * @param {Object} cfg (Optional) The configuration options to use for this operation. * * @return {CipherParams} A cipher params object. * * @static * * @example * * var ciphertextParams = CryptoJS.lib.PasswordBasedCipher.encrypt(CryptoJS.algo.AES, message, 'password'); * var ciphertextParams = CryptoJS.lib.PasswordBasedCipher.encrypt(CryptoJS.algo.AES, message, 'password', { format: CryptoJS.format.OpenSSL }); */ encrypt: function (cipher, message, password, cfg) { // Apply config defaults cfg = this.cfg.extend(cfg); // Derive key and other params var derivedParams = cfg.kdf.execute(password, cipher.keySize, cipher.ivSize); // Add IV to config cfg.iv = derivedParams.iv; // Encrypt var ciphertext = SerializableCipher.encrypt.call(this, cipher, message, derivedParams.key, cfg); // Mix in derived params ciphertext.mixIn(derivedParams); return ciphertext; }, /** * Decrypts serialized ciphertext using a password. * * @param {Cipher} cipher The cipher algorithm to use. * @param {CipherParams|string} ciphertext The ciphertext to decrypt. * @param {string} password The password. * @param {Object} cfg (Optional) The configuration options to use for this operation. * * @return {WordArray} The plaintext. * * @static * * @example * * var plaintext = CryptoJS.lib.PasswordBasedCipher.decrypt(CryptoJS.algo.AES, formattedCiphertext, 'password', { format: CryptoJS.format.OpenSSL }); * var plaintext = CryptoJS.lib.PasswordBasedCipher.decrypt(CryptoJS.algo.AES, ciphertextParams, 'password', { format: CryptoJS.format.OpenSSL }); */ decrypt: function (cipher, ciphertext, password, cfg) { // Apply config defaults cfg = this.cfg.extend(cfg); // Convert string to CipherParams ciphertext = this._parse(ciphertext, cfg.format); // Derive key and other params var derivedParams = cfg.kdf.execute(password, cipher.keySize, cipher.ivSize, ciphertext.salt); // Add IV to config cfg.iv = derivedParams.iv; // Decrypt var plaintext = SerializableCipher.decrypt.call(this, cipher, ciphertext, derivedParams.key, cfg); return plaintext; } }); }()); })); },{"./core":36}],36:[function(_dereq_,module,exports){ ;(function (root, factory) { if (typeof exports === "object") { // CommonJS module.exports = exports = factory(); } else if (typeof define === "function" && define.amd) { // AMD define([], factory); } else { // Global (browser) root.CryptoJS = factory(); } }(this, function () { /** * CryptoJS core components. */ var CryptoJS = CryptoJS || (function (Math, undefined) { /** * CryptoJS namespace. */ var C = {}; /** * Library namespace. */ var C_lib = C.lib = {}; /** * Base object for prototypal inheritance. */ var Base = C_lib.Base = (function () { function F() {} return { /** * Creates a new object that inherits from this object. * * @param {Object} overrides Properties to copy into the new object. * * @return {Object} The new object. * * @static * * @example * * var MyType = CryptoJS.lib.Base.extend({ * field: 'value', * * method: function () { * } * }); */ extend: function (overrides) { // Spawn F.prototype = this; var subtype = new F(); // Augment if (overrides) { subtype.mixIn(overrides); } // Create default initializer if (!subtype.hasOwnProperty('init')) { subtype.init = function () { subtype.$super.init.apply(this, arguments); }; } // Initializer's prototype is the subtype object subtype.init.prototype = subtype; // Reference supertype subtype.$super = this; return subtype; }, /** * Extends this object and runs the init method. * Arguments to create() will be passed to init(). * * @return {Object} The new object. * * @static * * @example * * var instance = MyType.create(); */ create: function () { var instance = this.extend(); instance.init.apply(instance, arguments); return instance; }, /** * Initializes a newly created object. * Override this method to add some logic when your objects are created. * * @example * * var MyType = CryptoJS.lib.Base.extend({ * init: function () { * // ... * } * }); */ init: function () { }, /** * Copies properties into this object. * * @param {Object} properties The properties to mix in. * * @example * * MyType.mixIn({ * field: 'value' * }); */ mixIn: function (properties) { for (var propertyName in properties) { if (properties.hasOwnProperty(propertyName)) { this[propertyName] = properties[propertyName]; } } // IE won't copy toString using the loop above if (properties.hasOwnProperty('toString')) { this.toString = properties.toString; } }, /** * Creates a copy of this object. * * @return {Object} The clone. * * @example * * var clone = instance.clone(); */ clone: function () { return this.init.prototype.extend(this); } }; }()); /** * An array of 32-bit words. * * @property {Array} words The array of 32-bit words. * @property {number} sigBytes The number of significant bytes in this word array. */ var WordArray = C_lib.WordArray = Base.extend({ /** * Initializes a newly created word array. * * @param {Array} words (Optional) An array of 32-bit words. * @param {number} sigBytes (Optional) The number of significant bytes in the words. * * @example * * var wordArray = CryptoJS.lib.WordArray.create(); * var wordArray = CryptoJS.lib.WordArray.create([0x00010203, 0x04050607]); * var wordArray = CryptoJS.lib.WordArray.create([0x00010203, 0x04050607], 6); */ init: function (words, sigBytes) { words = this.words = words || []; if (sigBytes != undefined) { this.sigBytes = sigBytes; } else { this.sigBytes = words.length * 4; } }, /** * Converts this word array to a string. * * @param {Encoder} encoder (Optional) The encoding strategy to use. Default: CryptoJS.enc.Hex * * @return {string} The stringified word array. * * @example * * var string = wordArray + ''; * var string = wordArray.toString(); * var string = wordArray.toString(CryptoJS.enc.Utf8); */ toString: function (encoder) { return (encoder || Hex).stringify(this); }, /** * Concatenates a word array to this word array. * * @param {WordArray} wordArray The word array to append. * * @return {WordArray} This word array. * * @example * * wordArray1.concat(wordArray2); */ concat: function (wordArray) { // Shortcuts var thisWords = this.words; var thatWords = wordArray.words; var thisSigBytes = this.sigBytes; var thatSigBytes = wordArray.sigBytes; // Clamp excess bits this.clamp(); // Concat if (thisSigBytes % 4) { // Copy one byte at a time for (var i = 0; i < thatSigBytes; i++) { var thatByte = (thatWords[i >>> 2] >>> (24 - (i % 4) * 8)) & 0xff; thisWords[(thisSigBytes + i) >>> 2] |= thatByte << (24 - ((thisSigBytes + i) % 4) * 8); } } else { // Copy one word at a time for (var i = 0; i < thatSigBytes; i += 4) { thisWords[(thisSigBytes + i) >>> 2] = thatWords[i >>> 2]; } } this.sigBytes += thatSigBytes; // Chainable return this; }, /** * Removes insignificant bits. * * @example * * wordArray.clamp(); */ clamp: function () { // Shortcuts var words = this.words; var sigBytes = this.sigBytes; // Clamp words[sigBytes >>> 2] &= 0xffffffff << (32 - (sigBytes % 4) * 8); words.length = Math.ceil(sigBytes / 4); }, /** * Creates a copy of this word array. * * @return {WordArray} The clone. * * @example * * var clone = wordArray.clone(); */ clone: function () { var clone = Base.clone.call(this); clone.words = this.words.slice(0); return clone; }, /** * Creates a word array filled with random bytes. * * @param {number} nBytes The number of random bytes to generate. * * @return {WordArray} The random word array. * * @static * * @example * * var wordArray = CryptoJS.lib.WordArray.random(16); */ random: function (nBytes) { var words = []; var r = (function (m_w) { var m_w = m_w; var m_z = 0x3ade68b1; var mask = 0xffffffff; return function () { m_z = (0x9069 * (m_z & 0xFFFF) + (m_z >> 0x10)) & mask; m_w = (0x4650 * (m_w & 0xFFFF) + (m_w >> 0x10)) & mask; var result = ((m_z << 0x10) + m_w) & mask; result /= 0x100000000; result += 0.5; return result * (Math.random() > .5 ? 1 : -1); } }); for (var i = 0, rcache; i < nBytes; i += 4) { var _r = r((rcache || Math.random()) * 0x100000000); rcache = _r() * 0x3ade67b7; words.push((_r() * 0x100000000) | 0); } return new WordArray.init(words, nBytes); } }); /** * Encoder namespace. */ var C_enc = C.enc = {}; /** * Hex encoding strategy. */ var Hex = C_enc.Hex = { /** * Converts a word array to a hex string. * * @param {WordArray} wordArray The word array. * * @return {string} The hex string. * * @static * * @example * * var hexString = CryptoJS.enc.Hex.stringify(wordArray); */ stringify: function (wordArray) { // Shortcuts var words = wordArray.words; var sigBytes = wordArray.sigBytes; // Convert var hexChars = []; for (var i = 0; i < sigBytes; i++) { var bite = (words[i >>> 2] >>> (24 - (i % 4) * 8)) & 0xff; hexChars.push((bite >>> 4).toString(16)); hexChars.push((bite & 0x0f).toString(16)); } return hexChars.join(''); }, /** * Converts a hex string to a word array. * * @param {string} hexStr The hex string. * * @return {WordArray} The word array. * * @static * * @example * * var wordArray = CryptoJS.enc.Hex.parse(hexString); */ parse: function (hexStr) { // Shortcut var hexStrLength = hexStr.length; // Convert var words = []; for (var i = 0; i < hexStrLength; i += 2) { words[i >>> 3] |= parseInt(hexStr.substr(i, 2), 16) << (24 - (i % 8) * 4); } return new WordArray.init(words, hexStrLength / 2); } }; /** * Latin1 encoding strategy. */ var Latin1 = C_enc.Latin1 = { /** * Converts a word array to a Latin1 string. * * @param {WordArray} wordArray The word array. * * @return {string} The Latin1 string. * * @static * * @example * * var latin1String = CryptoJS.enc.Latin1.stringify(wordArray); */ stringify: function (wordArray) { // Shortcuts var words = wordArray.words; var sigBytes = wordArray.sigBytes; // Convert var latin1Chars = []; for (var i = 0; i < sigBytes; i++) { var bite = (words[i >>> 2] >>> (24 - (i % 4) * 8)) & 0xff; latin1Chars.push(String.fromCharCode(bite)); } return latin1Chars.join(''); }, /** * Converts a Latin1 string to a word array. * * @param {string} latin1Str The Latin1 string. * * @return {WordArray} The word array. * * @static * * @example * * var wordArray = CryptoJS.enc.Latin1.parse(latin1String); */ parse: function (latin1Str) { // Shortcut var latin1StrLength = latin1Str.length; // Convert var words = []; for (var i = 0; i < latin1StrLength; i++) { words[i >>> 2] |= (latin1Str.charCodeAt(i) & 0xff) << (24 - (i % 4) * 8); } return new WordArray.init(words, latin1StrLength); } }; /** * UTF-8 encoding strategy. */ var Utf8 = C_enc.Utf8 = { /** * Converts a word array to a UTF-8 string. * * @param {WordArray} wordArray The word array. * * @return {string} The UTF-8 string. * * @static * * @example * * var utf8String = CryptoJS.enc.Utf8.stringify(wordArray); */ stringify: function (wordArray) { try { return decodeURIComponent(escape(Latin1.stringify(wordArray))); } catch (e) { throw new Error('Malformed UTF-8 data'); } }, /** * Converts a UTF-8 string to a word array. * * @param {string} utf8Str The UTF-8 string. * * @return {WordArray} The word array. * * @static * * @example * * var wordArray = CryptoJS.enc.Utf8.parse(utf8String); */ parse: function (utf8Str) { return Latin1.parse(unescape(encodeURIComponent(utf8Str))); } }; /** * Abstract buffered block algorithm template. * * The property blockSize must be implemented in a concrete subtype. * * @property {number} _minBufferSize The number of blocks that should be kept unprocessed in the buffer. Default: 0 */ var BufferedBlockAlgorithm = C_lib.BufferedBlockAlgorithm = Base.extend({ /** * Resets this block algorithm's data buffer to its initial state. * * @example * * bufferedBlockAlgorithm.reset(); */ reset: function () { // Initial values this._data = new WordArray.init(); this._nDataBytes = 0; }, /** * Adds new data to this block algorithm's buffer. * * @param {WordArray|string} data The data to append. Strings are converted to a WordArray using UTF-8. * * @example * * bufferedBlockAlgorithm._append('data'); * bufferedBlockAlgorithm._append(wordArray); */ _append: function (data) { // Convert string to WordArray, else assume WordArray already if (typeof data == 'string') { data = Utf8.parse(data); } // Append this._data.concat(data); this._nDataBytes += data.sigBytes; }, /** * Processes available data blocks. * * This method invokes _doProcessBlock(offset), which must be implemented by a concrete subtype. * * @param {boolean} doFlush Whether all blocks and partial blocks should be processed. * * @return {WordArray} The processed data. * * @example * * var processedData = bufferedBlockAlgorithm._process(); * var processedData = bufferedBlockAlgorithm._process(!!'flush'); */ _process: function (doFlush) { // Shortcuts var data = this._data; var dataWords = data.words; var dataSigBytes = data.sigBytes; var blockSize = this.blockSize; var blockSizeBytes = blockSize * 4; // Count blocks ready var nBlocksReady = dataSigBytes / blockSizeBytes; if (doFlush) { // Round up to include partial blocks nBlocksReady = Math.ceil(nBlocksReady); } else { // Round down to include only full blocks, // less the number of blocks that must remain in the buffer nBlocksReady = Math.max((nBlocksReady | 0) - this._minBufferSize, 0); } // Count words ready var nWordsReady = nBlocksReady * blockSize; // Count bytes ready var nBytesReady = Math.min(nWordsReady * 4, dataSigBytes); // Process blocks if (nWordsReady) { for (var offset = 0; offset < nWordsReady; offset += blockSize) { // Perform concrete-algorithm logic this._doProcessBlock(dataWords, offset); } // Remove processed words var processedWords = dataWords.splice(0, nWordsReady); data.sigBytes -= nBytesReady; } // Return processed words return new WordArray.init(processedWords, nBytesReady); }, /** * Creates a copy of this object. * * @return {Object} The clone. * * @example * * var clone = bufferedBlockAlgorithm.clone(); */ clone: function () { var clone = Base.clone.call(this); clone._data = this._data.clone(); return clone; }, _minBufferSize: 0 }); /** * Abstract hasher template. * * @property {number} blockSize The number of 32-bit words this hasher operates on. Default: 16 (512 bits) */ var Hasher = C_lib.Hasher = BufferedBlockAlgorithm.extend({ /** * Configuration options. */ cfg: Base.extend(), /** * Initializes a newly created hasher. * * @param {Object} cfg (Optional) The configuration options to use for this hash computation. * * @example * * var hasher = CryptoJS.algo.SHA256.create(); */ init: function (cfg) { // Apply config defaults this.cfg = this.cfg.extend(cfg); // Set initial values this.reset(); }, /** * Resets this hasher to its initial state. * * @example * * hasher.reset(); */ reset: function () { // Reset data buffer BufferedBlockAlgorithm.reset.call(this); // Perform concrete-hasher logic this._doReset(); }, /** * Updates this hasher with a message. * * @param {WordArray|string} messageUpdate The message to append. * * @return {Hasher} This hasher. * * @example * * hasher.update('message'); * hasher.update(wordArray); */ update: function (messageUpdate) { // Append this._append(messageUpdate); // Update the hash this._process(); // Chainable return this; }, /** * Finalizes the hash computation. * Note that the finalize operation is effectively a destructive, read-once operation. * * @param {WordArray|string} messageUpdate (Optional) A final message update. * * @return {WordArray} The hash. * * @example * * var hash = hasher.finalize(); * var hash = hasher.finalize('message'); * var hash = hasher.finalize(wordArray); */ finalize: function (messageUpdate) { // Final message update if (messageUpdate) { this._append(messageUpdate); } // Perform concrete-hasher logic var hash = this._doFinalize(); return hash; }, blockSize: 512/32, /** * Creates a shortcut function to a hasher's object interface. * * @param {Hasher} hasher The hasher to create a helper for. * * @return {Function} The shortcut function. * * @static * * @example * * var SHA256 = CryptoJS.lib.Hasher._createHelper(CryptoJS.algo.SHA256); */ _createHelper: function (hasher) { return function (message, cfg) { return new hasher.init(cfg).finalize(message); }; }, /** * Creates a shortcut function to the HMAC's object interface. * * @param {Hasher} hasher The hasher to use in this HMAC helper. * * @return {Function} The shortcut function. * * @static * * @example * * var HmacSHA256 = CryptoJS.lib.Hasher._createHmacHelper(CryptoJS.algo.SHA256); */ _createHmacHelper: function (hasher) { return function (message, key) { return new C_algo.HMAC.init(hasher, key).finalize(message); }; } }); /** * Algorithm namespace. */ var C_algo = C.algo = {}; return C; }(Math)); return CryptoJS; })); },{}],37:[function(_dereq_,module,exports){ ;(function (root, factory) { if (typeof exports === "object") { // CommonJS module.exports = exports = factory(_dereq_("./core")); } else if (typeof define === "function" && define.amd) { // AMD define(["./core"], factory); } else { // Global (browser) factory(root.CryptoJS); } }(this, function (CryptoJS) { (function () { // Shortcuts var C = CryptoJS; var C_lib = C.lib; var WordArray = C_lib.WordArray; var C_enc = C.enc; /** * Base64 encoding strategy. */ var Base64 = C_enc.Base64 = { /** * Converts a word array to a Base64 string. * * @param {WordArray} wordArray The word array. * * @return {string} The Base64 string. * * @static * * @example * * var base64String = CryptoJS.enc.Base64.stringify(wordArray); */ stringify: function (wordArray) { // Shortcuts var words = wordArray.words; var sigBytes = wordArray.sigBytes; var map = this._map; // Clamp excess bits wordArray.clamp(); // Convert var base64Chars = []; for (var i = 0; i < sigBytes; i += 3) { var byte1 = (words[i >>> 2] >>> (24 - (i % 4) * 8)) & 0xff; var byte2 = (words[(i + 1) >>> 2] >>> (24 - ((i + 1) % 4) * 8)) & 0xff; var byte3 = (words[(i + 2) >>> 2] >>> (24 - ((i + 2) % 4) * 8)) & 0xff; var triplet = (byte1 << 16) | (byte2 << 8) | byte3; for (var j = 0; (j < 4) && (i + j * 0.75 < sigBytes); j++) { base64Chars.push(map.charAt((triplet >>> (6 * (3 - j))) & 0x3f)); } } // Add padding var paddingChar = map.charAt(64); if (paddingChar) { while (base64Chars.length % 4) { base64Chars.push(paddingChar); } } return base64Chars.join(''); }, /** * Converts a Base64 string to a word array. * * @param {string} base64Str The Base64 string. * * @return {WordArray} The word array. * * @static * * @example * * var wordArray = CryptoJS.enc.Base64.parse(base64String); */ parse: function (base64Str) { // Shortcuts var base64StrLength = base64Str.length; var map = this._map; // Ignore padding var paddingChar = map.charAt(64); if (paddingChar) { var paddingIndex = base64Str.indexOf(paddingChar); if (paddingIndex != -1) { base64StrLength = paddingIndex; } } // Convert var words = []; var nBytes = 0; for (var i = 0; i < base64StrLength; i++) { if (i % 4) { var bits1 = map.indexOf(base64Str.charAt(i - 1)) << ((i % 4) * 2); var bits2 = map.indexOf(base64Str.charAt(i)) >>> (6 - (i % 4) * 2); words[nBytes >>> 2] |= (bits1 | bits2) << (24 - (nBytes % 4) * 8); nBytes++; } } return WordArray.create(words, nBytes); }, _map: 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/=' }; }()); return CryptoJS.enc.Base64; })); },{"./core":36}],38:[function(_dereq_,module,exports){ ;(function (root, factory) { if (typeof exports === "object") { // CommonJS module.exports = exports = factory(_dereq_("./core")); } else if (typeof define === "function" && define.amd) { // AMD define(["./core"], factory); } else { // Global (browser) factory(root.CryptoJS); } }(this, function (CryptoJS) { (function () { // Shortcuts var C = CryptoJS; var C_lib = C.lib; var WordArray = C_lib.WordArray; var C_enc = C.enc; /** * UTF-16 BE encoding strategy. */ var Utf16BE = C_enc.Utf16 = C_enc.Utf16BE = { /** * Converts a word array to a UTF-16 BE string. * * @param {WordArray} wordArray The word array. * * @return {string} The UTF-16 BE string. * * @static * * @example * * var utf16String = CryptoJS.enc.Utf16.stringify(wordArray); */ stringify: function (wordArray) { // Shortcuts var words = wordArray.words; var sigBytes = wordArray.sigBytes; // Convert var utf16Chars = []; for (var i = 0; i < sigBytes; i += 2) { var codePoint = (words[i >>> 2] >>> (16 - (i % 4) * 8)) & 0xffff; utf16Chars.push(String.fromCharCode(codePoint)); } return utf16Chars.join(''); }, /** * Converts a UTF-16 BE string to a word array. * * @param {string} utf16Str The UTF-16 BE string. * * @return {WordArray} The word array. * * @static * * @example * * var wordArray = CryptoJS.enc.Utf16.parse(utf16String); */ parse: function (utf16Str) { // Shortcut var utf16StrLength = utf16Str.length; // Convert var words = []; for (var i = 0; i < utf16StrLength; i++) { words[i >>> 1] |= utf16Str.charCodeAt(i) << (16 - (i % 2) * 16); } return WordArray.create(words, utf16StrLength * 2); } }; /** * UTF-16 LE encoding strategy. */ C_enc.Utf16LE = { /** * Converts a word array to a UTF-16 LE string. * * @param {WordArray} wordArray The word array. * * @return {string} The UTF-16 LE string. * * @static * * @example * * var utf16Str = CryptoJS.enc.Utf16LE.stringify(wordArray); */ stringify: function (wordArray) { // Shortcuts var words = wordArray.words; var sigBytes = wordArray.sigBytes; // Convert var utf16Chars = []; for (var i = 0; i < sigBytes; i += 2) { var codePoint = swapEndian((words[i >>> 2] >>> (16 - (i % 4) * 8)) & 0xffff); utf16Chars.push(String.fromCharCode(codePoint)); } return utf16Chars.join(''); }, /** * Converts a UTF-16 LE string to a word array. * * @param {string} utf16Str The UTF-16 LE string. * * @return {WordArray} The word array. * * @static * * @example * * var wordArray = CryptoJS.enc.Utf16LE.parse(utf16Str); */ parse: function (utf16Str) { // Shortcut var utf16StrLength = utf16Str.length; // Convert var words = []; for (var i = 0; i < utf16StrLength; i++) { words[i >>> 1] |= swapEndian(utf16Str.charCodeAt(i) << (16 - (i % 2) * 16)); } return WordArray.create(words, utf16StrLength * 2); } }; function swapEndian(word) { return ((word << 8) & 0xff00ff00) | ((word >>> 8) & 0x00ff00ff); } }()); return CryptoJS.enc.Utf16; })); },{"./core":36}],39:[function(_dereq_,module,exports){ ;(function (root, factory, undef) { if (typeof exports === "object") { // CommonJS module.exports = exports = factory(_dereq_("./core"), _dereq_("./sha1"), _dereq_("./hmac")); } else if (typeof define === "function" && define.amd) { // AMD define(["./core", "./sha1", "./hmac"], factory); } else { // Global (browser) factory(root.CryptoJS); } }(this, function (CryptoJS) { (function () { // Shortcuts var C = CryptoJS; var C_lib = C.lib; var Base = C_lib.Base; var WordArray = C_lib.WordArray; var C_algo = C.algo; var MD5 = C_algo.MD5; /** * This key derivation function is meant to conform with EVP_BytesToKey. * www.openssl.org/docs/crypto/EVP_BytesToKey.html */ var EvpKDF = C_algo.EvpKDF = Base.extend({ /** * Configuration options. * * @property {number} keySize The key size in words to generate. Default: 4 (128 bits) * @property {Hasher} hasher The hash algorithm to use. Default: MD5 * @property {number} iterations The number of iterations to perform. Default: 1 */ cfg: Base.extend({ keySize: 128/32, hasher: MD5, iterations: 1 }), /** * Initializes a newly created key derivation function. * * @param {Object} cfg (Optional) The configuration options to use for the derivation. * * @example * * var kdf = CryptoJS.algo.EvpKDF.create(); * var kdf = CryptoJS.algo.EvpKDF.create({ keySize: 8 }); * var kdf = CryptoJS.algo.EvpKDF.create({ keySize: 8, iterations: 1000 }); */ init: function (cfg) { this.cfg = this.cfg.extend(cfg); }, /** * Derives a key from a password. * * @param {WordArray|string} password The password. * @param {WordArray|string} salt A salt. * * @return {WordArray} The derived key. * * @example * * var key = kdf.compute(password, salt); */ compute: function (password, salt) { // Shortcut var cfg = this.cfg; // Init hasher var hasher = cfg.hasher.create(); // Initial values var derivedKey = WordArray.create(); // Shortcuts var derivedKeyWords = derivedKey.words; var keySize = cfg.keySize; var iterations = cfg.iterations; // Generate key while (derivedKeyWords.length < keySize) { if (block) { hasher.update(block); } var block = hasher.update(password).finalize(salt); hasher.reset(); // Iterations for (var i = 1; i < iterations; i++) { block = hasher.finalize(block); hasher.reset(); } derivedKey.concat(block); } derivedKey.sigBytes = keySize * 4; return derivedKey; } }); /** * Derives a key from a password. * * @param {WordArray|string} password The password. * @param {WordArray|string} salt A salt. * @param {Object} cfg (Optional) The configuration options to use for this computation. * * @return {WordArray} The derived key. * * @static * * @example * * var key = CryptoJS.EvpKDF(password, salt); * var key = CryptoJS.EvpKDF(password, salt, { keySize: 8 }); * var key = CryptoJS.EvpKDF(password, salt, { keySize: 8, iterations: 1000 }); */ C.EvpKDF = function (password, salt, cfg) { return EvpKDF.create(cfg).compute(password, salt); }; }()); return CryptoJS.EvpKDF; })); },{"./core":36,"./hmac":41,"./sha1":60}],40:[function(_dereq_,module,exports){ ;(function (root, factory, undef) { if (typeof exports === "object") { // CommonJS module.exports = exports = factory(_dereq_("./core"), _dereq_("./cipher-core")); } else if (typeof define === "function" && define.amd) { // AMD define(["./core", "./cipher-core"], factory); } else { // Global (browser) factory(root.CryptoJS); } }(this, function (CryptoJS) { (function (undefined) { // Shortcuts var C = CryptoJS; var C_lib = C.lib; var CipherParams = C_lib.CipherParams; var C_enc = C.enc; var Hex = C_enc.Hex; var C_format = C.format; var HexFormatter = C_format.Hex = { /** * Converts the ciphertext of a cipher params object to a hexadecimally encoded string. * * @param {CipherParams} cipherParams The cipher params object. * * @return {string} The hexadecimally encoded string. * * @static * * @example * * var hexString = CryptoJS.format.Hex.stringify(cipherParams); */ stringify: function (cipherParams) { return cipherParams.ciphertext.toString(Hex); }, /** * Converts a hexadecimally encoded ciphertext string to a cipher params object. * * @param {string} input The hexadecimally encoded string. * * @return {CipherParams} The cipher params object. * * @static * * @example * * var cipherParams = CryptoJS.format.Hex.parse(hexString); */ parse: function (input) { var ciphertext = Hex.parse(input); return CipherParams.create({ ciphertext: ciphertext }); } }; }()); return CryptoJS.format.Hex; })); },{"./cipher-core":35,"./core":36}],41:[function(_dereq_,module,exports){ ;(function (root, factory) { if (typeof exports === "object") { // CommonJS module.exports = exports = factory(_dereq_("./core")); } else if (typeof define === "function" && define.amd) { // AMD define(["./core"], factory); } else { // Global (browser) factory(root.CryptoJS); } }(this, function (CryptoJS) { (function () { // Shortcuts var C = CryptoJS; var C_lib = C.lib; var Base = C_lib.Base; var C_enc = C.enc; var Utf8 = C_enc.Utf8; var C_algo = C.algo; /** * HMAC algorithm. */ var HMAC = C_algo.HMAC = Base.extend({ /** * Initializes a newly created HMAC. * * @param {Hasher} hasher The hash algorithm to use. * @param {WordArray|string} key The secret key. * * @example * * var hmacHasher = CryptoJS.algo.HMAC.create(CryptoJS.algo.SHA256, key); */ init: function (hasher, key) { // Init hasher hasher = this._hasher = new hasher.init(); // Convert string to WordArray, else assume WordArray already if (typeof key == 'string') { key = Utf8.parse(key); } // Shortcuts var hasherBlockSize = hasher.blockSize; var hasherBlockSizeBytes = hasherBlockSize * 4; // Allow arbitrary length keys if (key.sigBytes > hasherBlockSizeBytes) { key = hasher.finalize(key); } // Clamp excess bits key.clamp(); // Clone key for inner and outer pads var oKey = this._oKey = key.clone(); var iKey = this._iKey = key.clone(); // Shortcuts var oKeyWords = oKey.words; var iKeyWords = iKey.words; // XOR keys with pad constants for (var i = 0; i < hasherBlockSize; i++) { oKeyWords[i] ^= 0x5c5c5c5c; iKeyWords[i] ^= 0x36363636; } oKey.sigBytes = iKey.sigBytes = hasherBlockSizeBytes; // Set initial values this.reset(); }, /** * Resets this HMAC to its initial state. * * @example * * hmacHasher.reset(); */ reset: function () { // Shortcut var hasher = this._hasher; // Reset hasher.reset(); hasher.update(this._iKey); }, /** * Updates this HMAC with a message. * * @param {WordArray|string} messageUpdate The message to append. * * @return {HMAC} This HMAC instance. * * @example * * hmacHasher.update('message'); * hmacHasher.update(wordArray); */ update: function (messageUpdate) { this._hasher.update(messageUpdate); // Chainable return this; }, /** * Finalizes the HMAC computation. * Note that the finalize operation is effectively a destructive, read-once operation. * * @param {WordArray|string} messageUpdate (Optional) A final message update. * * @return {WordArray} The HMAC. * * @example * * var hmac = hmacHasher.finalize(); * var hmac = hmacHasher.finalize('message'); * var hmac = hmacHasher.finalize(wordArray); */ finalize: function (messageUpdate) { // Shortcut var hasher = this._hasher; // Compute HMAC var innerHash = hasher.finalize(messageUpdate); hasher.reset(); var hmac = hasher.finalize(this._oKey.clone().concat(innerHash)); return hmac; } }); }()); })); },{"./core":36}],42:[function(_dereq_,module,exports){ ;(function (root, factory, undef) { if (typeof exports === "object") { // CommonJS module.exports = exports = factory(_dereq_("./core"), _dereq_("./x64-core"), _dereq_("./lib-typedarrays"), _dereq_("./enc-utf16"), _dereq_("./enc-base64"), _dereq_("./md5"), _dereq_("./sha1"), _dereq_("./sha256"), _dereq_("./sha224"), _dereq_("./sha512"), _dereq_("./sha384"), _dereq_("./sha3"), _dereq_("./ripemd160"), _dereq_("./hmac"), _dereq_("./pbkdf2"), _dereq_("./evpkdf"), _dereq_("./cipher-core"), _dereq_("./mode-cfb"), _dereq_("./mode-ctr"), _dereq_("./mode-ctr-gladman"), _dereq_("./mode-ofb"), _dereq_("./mode-ecb"), _dereq_("./pad-ansix923"), _dereq_("./pad-iso10126"), _dereq_("./pad-iso97971"), _dereq_("./pad-zeropadding"), _dereq_("./pad-nopadding"), _dereq_("./format-hex"), _dereq_("./aes"), _dereq_("./tripledes"), _dereq_("./rc4"), _dereq_("./rabbit"), _dereq_("./rabbit-legacy")); } else if (typeof define === "function" && define.amd) { // AMD define(["./core", "./x64-core", "./lib-typedarrays", "./enc-utf16", "./enc-base64", "./md5", "./sha1", "./sha256", "./sha224", "./sha512", "./sha384", "./sha3", "./ripemd160", "./hmac", "./pbkdf2", "./evpkdf", "./cipher-core", "./mode-cfb", "./mode-ctr", "./mode-ctr-gladman", "./mode-ofb", "./mode-ecb", "./pad-ansix923", "./pad-iso10126", "./pad-iso97971", "./pad-zeropadding", "./pad-nopadding", "./format-hex", "./aes", "./tripledes", "./rc4", "./rabbit", "./rabbit-legacy"], factory); } else { // Global (browser) root.CryptoJS = factory(root.CryptoJS); } }(this, function (CryptoJS) { return CryptoJS; })); },{"./aes":34,"./cipher-core":35,"./core":36,"./enc-base64":37,"./enc-utf16":38,"./evpkdf":39,"./format-hex":40,"./hmac":41,"./lib-typedarrays":43,"./md5":44,"./mode-cfb":45,"./mode-ctr":47,"./mode-ctr-gladman":46,"./mode-ecb":48,"./mode-ofb":49,"./pad-ansix923":50,"./pad-iso10126":51,"./pad-iso97971":52,"./pad-nopadding":53,"./pad-zeropadding":54,"./pbkdf2":55,"./rabbit":57,"./rabbit-legacy":56,"./rc4":58,"./ripemd160":59,"./sha1":60,"./sha224":61,"./sha256":62,"./sha3":63,"./sha384":64,"./sha512":65,"./tripledes":66,"./x64-core":67}],43:[function(_dereq_,module,exports){ ;(function (root, factory) { if (typeof exports === "object") { // CommonJS module.exports = exports = factory(_dereq_("./core")); } else if (typeof define === "function" && define.amd) { // AMD define(["./core"], factory); } else { // Global (browser) factory(root.CryptoJS); } }(this, function (CryptoJS) { (function () { // Check if typed arrays are supported if (typeof ArrayBuffer != 'function') { return; } // Shortcuts var C = CryptoJS; var C_lib = C.lib; var WordArray = C_lib.WordArray; // Reference original init var superInit = WordArray.init; // Augment WordArray.init to handle typed arrays var subInit = WordArray.init = function (typedArray) { // Convert buffers to uint8 if (typedArray instanceof ArrayBuffer) { typedArray = new Uint8Array(typedArray); } // Convert other array views to uint8 if ( typedArray instanceof Int8Array || (typeof Uint8ClampedArray !== "undefined" && typedArray instanceof Uint8ClampedArray) || typedArray instanceof Int16Array || typedArray instanceof Uint16Array || typedArray instanceof Int32Array || typedArray instanceof Uint32Array || typedArray instanceof Float32Array || typedArray instanceof Float64Array ) { typedArray = new Uint8Array(typedArray.buffer, typedArray.byteOffset, typedArray.byteLength); } // Handle Uint8Array if (typedArray instanceof Uint8Array) { // Shortcut var typedArrayByteLength = typedArray.byteLength; // Extract bytes var words = []; for (var i = 0; i < typedArrayByteLength; i++) { words[i >>> 2] |= typedArray[i] << (24 - (i % 4) * 8); } // Initialize this word array superInit.call(this, words, typedArrayByteLength); } else { // Else call normal init superInit.apply(this, arguments); } }; subInit.prototype = WordArray; }()); return CryptoJS.lib.WordArray; })); },{"./core":36}],44:[function(_dereq_,module,exports){ ;(function (root, factory) { if (typeof exports === "object") { // CommonJS module.exports = exports = factory(_dereq_("./core")); } else if (typeof define === "function" && define.amd) { // AMD define(["./core"], factory); } else { // Global (browser) factory(root.CryptoJS); } }(this, function (CryptoJS) { (function (Math) { // Shortcuts var C = CryptoJS; var C_lib = C.lib; var WordArray = C_lib.WordArray; var Hasher = C_lib.Hasher; var C_algo = C.algo; // Constants table var T = []; // Compute constants (function () { for (var i = 0; i < 64; i++) { T[i] = (Math.abs(Math.sin(i + 1)) * 0x100000000) | 0; } }()); /** * MD5 hash algorithm. */ var MD5 = C_algo.MD5 = Hasher.extend({ _doReset: function () { this._hash = new WordArray.init([ 0x67452301, 0xefcdab89, 0x98badcfe, 0x10325476 ]); }, _doProcessBlock: function (M, offset) { // Swap endian for (var i = 0; i < 16; i++) { // Shortcuts var offset_i = offset + i; var M_offset_i = M[offset_i]; M[offset_i] = ( (((M_offset_i << 8) | (M_offset_i >>> 24)) & 0x00ff00ff) | (((M_offset_i << 24) | (M_offset_i >>> 8)) & 0xff00ff00) ); } // Shortcuts var H = this._hash.words; var M_offset_0 = M[offset + 0]; var M_offset_1 = M[offset + 1]; var M_offset_2 = M[offset + 2]; var M_offset_3 = M[offset + 3]; var M_offset_4 = M[offset + 4]; var M_offset_5 = M[offset + 5]; var M_offset_6 = M[offset + 6]; var M_offset_7 = M[offset + 7]; var M_offset_8 = M[offset + 8]; var M_offset_9 = M[offset + 9]; var M_offset_10 = M[offset + 10]; var M_offset_11 = M[offset + 11]; var M_offset_12 = M[offset + 12]; var M_offset_13 = M[offset + 13]; var M_offset_14 = M[offset + 14]; var M_offset_15 = M[offset + 15]; // Working varialbes var a = H[0]; var b = H[1]; var c = H[2]; var d = H[3]; // Computation a = FF(a, b, c, d, M_offset_0, 7, T[0]); d = FF(d, a, b, c, M_offset_1, 12, T[1]); c = FF(c, d, a, b, M_offset_2, 17, T[2]); b = FF(b, c, d, a, M_offset_3, 22, T[3]); a = FF(a, b, c, d, M_offset_4, 7, T[4]); d = FF(d, a, b, c, M_offset_5, 12, T[5]); c = FF(c, d, a, b, M_offset_6, 17, T[6]); b = FF(b, c, d, a, M_offset_7, 22, T[7]); a = FF(a, b, c, d, M_offset_8, 7, T[8]); d = FF(d, a, b, c, M_offset_9, 12, T[9]); c = FF(c, d, a, b, M_offset_10, 17, T[10]); b = FF(b, c, d, a, M_offset_11, 22, T[11]); a = FF(a, b, c, d, M_offset_12, 7, T[12]); d = FF(d, a, b, c, M_offset_13, 12, T[13]); c = FF(c, d, a, b, M_offset_14, 17, T[14]); b = FF(b, c, d, a, M_offset_15, 22, T[15]); a = GG(a, b, c, d, M_offset_1, 5, T[16]); d = GG(d, a, b, c, M_offset_6, 9, T[17]); c = GG(c, d, a, b, M_offset_11, 14, T[18]); b = GG(b, c, d, a, M_offset_0, 20, T[19]); a = GG(a, b, c, d, M_offset_5, 5, T[20]); d = GG(d, a, b, c, M_offset_10, 9, T[21]); c = GG(c, d, a, b, M_offset_15, 14, T[22]); b = GG(b, c, d, a, M_offset_4, 20, T[23]); a = GG(a, b, c, d, M_offset_9, 5, T[24]); d = GG(d, a, b, c, M_offset_14, 9, T[25]); c = GG(c, d, a, b, M_offset_3, 14, T[26]); b = GG(b, c, d, a, M_offset_8, 20, T[27]); a = GG(a, b, c, d, M_offset_13, 5, T[28]); d = GG(d, a, b, c, M_offset_2, 9, T[29]); c = GG(c, d, a, b, M_offset_7, 14, T[30]); b = GG(b, c, d, a, M_offset_12, 20, T[31]); a = HH(a, b, c, d, M_offset_5, 4, T[32]); d = HH(d, a, b, c, M_offset_8, 11, T[33]); c = HH(c, d, a, b, M_offset_11, 16, T[34]); b = HH(b, c, d, a, M_offset_14, 23, T[35]); a = HH(a, b, c, d, M_offset_1, 4, T[36]); d = HH(d, a, b, c, M_offset_4, 11, T[37]); c = HH(c, d, a, b, M_offset_7, 16, T[38]); b = HH(b, c, d, a, M_offset_10, 23, T[39]); a = HH(a, b, c, d, M_offset_13, 4, T[40]); d = HH(d, a, b, c, M_offset_0, 11, T[41]); c = HH(c, d, a, b, M_offset_3, 16, T[42]); b = HH(b, c, d, a, M_offset_6, 23, T[43]); a = HH(a, b, c, d, M_offset_9, 4, T[44]); d = HH(d, a, b, c, M_offset_12, 11, T[45]); c = HH(c, d, a, b, M_offset_15, 16, T[46]); b = HH(b, c, d, a, M_offset_2, 23, T[47]); a = II(a, b, c, d, M_offset_0, 6, T[48]); d = II(d, a, b, c, M_offset_7, 10, T[49]); c = II(c, d, a, b, M_offset_14, 15, T[50]); b = II(b, c, d, a, M_offset_5, 21, T[51]); a = II(a, b, c, d, M_offset_12, 6, T[52]); d = II(d, a, b, c, M_offset_3, 10, T[53]); c = II(c, d, a, b, M_offset_10, 15, T[54]); b = II(b, c, d, a, M_offset_1, 21, T[55]); a = II(a, b, c, d, M_offset_8, 6, T[56]); d = II(d, a, b, c, M_offset_15, 10, T[57]); c = II(c, d, a, b, M_offset_6, 15, T[58]); b = II(b, c, d, a, M_offset_13, 21, T[59]); a = II(a, b, c, d, M_offset_4, 6, T[60]); d = II(d, a, b, c, M_offset_11, 10, T[61]); c = II(c, d, a, b, M_offset_2, 15, T[62]); b = II(b, c, d, a, M_offset_9, 21, T[63]); // Intermediate hash value H[0] = (H[0] + a) | 0; H[1] = (H[1] + b) | 0; H[2] = (H[2] + c) | 0; H[3] = (H[3] + d) | 0; }, _doFinalize: function () { // Shortcuts var data = this._data; var dataWords = data.words; var nBitsTotal = this._nDataBytes * 8; var nBitsLeft = data.sigBytes * 8; // Add padding dataWords[nBitsLeft >>> 5] |= 0x80 << (24 - nBitsLeft % 32); var nBitsTotalH = Math.floor(nBitsTotal / 0x100000000); var nBitsTotalL = nBitsTotal; dataWords[(((nBitsLeft + 64) >>> 9) << 4) + 15] = ( (((nBitsTotalH << 8) | (nBitsTotalH >>> 24)) & 0x00ff00ff) | (((nBitsTotalH << 24) | (nBitsTotalH >>> 8)) & 0xff00ff00) ); dataWords[(((nBitsLeft + 64) >>> 9) << 4) + 14] = ( (((nBitsTotalL << 8) | (nBitsTotalL >>> 24)) & 0x00ff00ff) | (((nBitsTotalL << 24) | (nBitsTotalL >>> 8)) & 0xff00ff00) ); data.sigBytes = (dataWords.length + 1) * 4; // Hash final blocks this._process(); // Shortcuts var hash = this._hash; var H = hash.words; // Swap endian for (var i = 0; i < 4; i++) { // Shortcut var H_i = H[i]; H[i] = (((H_i << 8) | (H_i >>> 24)) & 0x00ff00ff) | (((H_i << 24) | (H_i >>> 8)) & 0xff00ff00); } // Return final computed hash return hash; }, clone: function () { var clone = Hasher.clone.call(this); clone._hash = this._hash.clone(); return clone; } }); function FF(a, b, c, d, x, s, t) { var n = a + ((b & c) | (~b & d)) + x + t; return ((n << s) | (n >>> (32 - s))) + b; } function GG(a, b, c, d, x, s, t) { var n = a + ((b & d) | (c & ~d)) + x + t; return ((n << s) | (n >>> (32 - s))) + b; } function HH(a, b, c, d, x, s, t) { var n = a + (b ^ c ^ d) + x + t; return ((n << s) | (n >>> (32 - s))) + b; } function II(a, b, c, d, x, s, t) { var n = a + (c ^ (b | ~d)) + x + t; return ((n << s) | (n >>> (32 - s))) + b; } /** * Shortcut function to the hasher's object interface. * * @param {WordArray|string} message The message to hash. * * @return {WordArray} The hash. * * @static * * @example * * var hash = CryptoJS.MD5('message'); * var hash = CryptoJS.MD5(wordArray); */ C.MD5 = Hasher._createHelper(MD5); /** * Shortcut function to the HMAC's object interface. * * @param {WordArray|string} message The message to hash. * @param {WordArray|string} key The secret key. * * @return {WordArray} The HMAC. * * @static * * @example * * var hmac = CryptoJS.HmacMD5(message, key); */ C.HmacMD5 = Hasher._createHmacHelper(MD5); }(Math)); return CryptoJS.MD5; })); },{"./core":36}],45:[function(_dereq_,module,exports){ ;(function (root, factory, undef) { if (typeof exports === "object") { // CommonJS module.exports = exports = factory(_dereq_("./core"), _dereq_("./cipher-core")); } else if (typeof define === "function" && define.amd) { // AMD define(["./core", "./cipher-core"], factory); } else { // Global (browser) factory(root.CryptoJS); } }(this, function (CryptoJS) { /** * Cipher Feedback block mode. */ CryptoJS.mode.CFB = (function () { var CFB = CryptoJS.lib.BlockCipherMode.extend(); CFB.Encryptor = CFB.extend({ processBlock: function (words, offset) { // Shortcuts var cipher = this._cipher; var blockSize = cipher.blockSize; generateKeystreamAndEncrypt.call(this, words, offset, blockSize, cipher); // Remember this block to use with next block this._prevBlock = words.slice(offset, offset + blockSize); } }); CFB.Decryptor = CFB.extend({ processBlock: function (words, offset) { // Shortcuts var cipher = this._cipher; var blockSize = cipher.blockSize; // Remember this block to use with next block var thisBlock = words.slice(offset, offset + blockSize); generateKeystreamAndEncrypt.call(this, words, offset, blockSize, cipher); // This block becomes the previous block this._prevBlock = thisBlock; } }); function generateKeystreamAndEncrypt(words, offset, blockSize, cipher) { // Shortcut var iv = this._iv; // Generate keystream if (iv) { var keystream = iv.slice(0); // Remove IV for subsequent blocks this._iv = undefined; } else { var keystream = this._prevBlock; } cipher.encryptBlock(keystream, 0); // Encrypt for (var i = 0; i < blockSize; i++) { words[offset + i] ^= keystream[i]; } } return CFB; }()); return CryptoJS.mode.CFB; })); },{"./cipher-core":35,"./core":36}],46:[function(_dereq_,module,exports){ ;(function (root, factory, undef) { if (typeof exports === "object") { // CommonJS module.exports = exports = factory(_dereq_("./core"), _dereq_("./cipher-core")); } else if (typeof define === "function" && define.amd) { // AMD define(["./core", "./cipher-core"], factory); } else { // Global (browser) factory(root.CryptoJS); } }(this, function (CryptoJS) { /** @preserve * Counter block mode compatible with Dr Brian Gladman fileenc.c * derived from CryptoJS.mode.CTR * Jan Hruby [email protected] */ CryptoJS.mode.CTRGladman = (function () { var CTRGladman = CryptoJS.lib.BlockCipherMode.extend(); function incWord(word) { if (((word >> 24) & 0xff) === 0xff) { //overflow var b1 = (word >> 16)&0xff; var b2 = (word >> 8)&0xff; var b3 = word & 0xff; if (b1 === 0xff) // overflow b1 { b1 = 0; if (b2 === 0xff) { b2 = 0; if (b3 === 0xff) { b3 = 0; } else { ++b3; } } else { ++b2; } } else { ++b1; } word = 0; word += (b1 << 16); word += (b2 << 8); word += b3; } else { word += (0x01 << 24); } return word; } function incCounter(counter) { if ((counter[0] = incWord(counter[0])) === 0) { // encr_data in fileenc.c from Dr Brian Gladman's counts only with DWORD j < 8 counter[1] = incWord(counter[1]); } return counter; } var Encryptor = CTRGladman.Encryptor = CTRGladman.extend({ processBlock: function (words, offset) { // Shortcuts var cipher = this._cipher var blockSize = cipher.blockSize; var iv = this._iv; var counter = this._counter; // Generate keystream if (iv) { counter = this._counter = iv.slice(0); // Remove IV for subsequent blocks this._iv = undefined; } incCounter(counter); var keystream = counter.slice(0); cipher.encryptBlock(keystream, 0); // Encrypt for (var i = 0; i < blockSize; i++) { words[offset + i] ^= keystream[i]; } } }); CTRGladman.Decryptor = Encryptor; return CTRGladman; }()); return CryptoJS.mode.CTRGladman; })); },{"./cipher-core":35,"./core":36}],47:[function(_dereq_,module,exports){ ;(function (root, factory, undef) { if (typeof exports === "object") { // CommonJS module.exports = exports = factory(_dereq_("./core"), _dereq_("./cipher-core")); } else if (typeof define === "function" && define.amd) { // AMD define(["./core", "./cipher-core"], factory); } else { // Global (browser) factory(root.CryptoJS); } }(this, function (CryptoJS) { /** * Counter block mode. */ CryptoJS.mode.CTR = (function () { var CTR = CryptoJS.lib.BlockCipherMode.extend(); var Encryptor = CTR.Encryptor = CTR.extend({ processBlock: function (words, offset) { // Shortcuts var cipher = this._cipher var blockSize = cipher.blockSize; var iv = this._iv; var counter = this._counter; // Generate keystream if (iv) { counter = this._counter = iv.slice(0); // Remove IV for subsequent blocks this._iv = undefined; } var keystream = counter.slice(0); cipher.encryptBlock(keystream, 0); // Increment counter counter[blockSize - 1] = (counter[blockSize - 1] + 1) | 0 // Encrypt for (var i = 0; i < blockSize; i++) { words[offset + i] ^= keystream[i]; } } }); CTR.Decryptor = Encryptor; return CTR; }()); return CryptoJS.mode.CTR; })); },{"./cipher-core":35,"./core":36}],48:[function(_dereq_,module,exports){ ;(function (root, factory, undef) { if (typeof exports === "object") { // CommonJS module.exports = exports = factory(_dereq_("./core"), _dereq_("./cipher-core")); } else if (typeof define === "function" && define.amd) { // AMD define(["./core", "./cipher-core"], factory); } else { // Global (browser) factory(root.CryptoJS); } }(this, function (CryptoJS) { /** * Electronic Codebook block mode. */ CryptoJS.mode.ECB = (function () { var ECB = CryptoJS.lib.BlockCipherMode.extend(); ECB.Encryptor = ECB.extend({ processBlock: function (words, offset) { this._cipher.encryptBlock(words, offset); } }); ECB.Decryptor = ECB.extend({ processBlock: function (words, offset) { this._cipher.decryptBlock(words, offset); } }); return ECB; }()); return CryptoJS.mode.ECB; })); },{"./cipher-core":35,"./core":36}],49:[function(_dereq_,module,exports){ ;(function (root, factory, undef) { if (typeof exports === "object") { // CommonJS module.exports = exports = factory(_dereq_("./core"), _dereq_("./cipher-core")); } else if (typeof define === "function" && define.amd) { // AMD define(["./core", "./cipher-core"], factory); } else { // Global (browser) factory(root.CryptoJS); } }(this, function (CryptoJS) { /** * Output Feedback block mode. */ CryptoJS.mode.OFB = (function () { var OFB = CryptoJS.lib.BlockCipherMode.extend(); var Encryptor = OFB.Encryptor = OFB.extend({ processBlock: function (words, offset) { // Shortcuts var cipher = this._cipher var blockSize = cipher.blockSize; var iv = this._iv; var keystream = this._keystream; // Generate keystream if (iv) { keystream = this._keystream = iv.slice(0); // Remove IV for subsequent blocks this._iv = undefined; } cipher.encryptBlock(keystream, 0); // Encrypt for (var i = 0; i < blockSize; i++) { words[offset + i] ^= keystream[i]; } } }); OFB.Decryptor = Encryptor; return OFB; }()); return CryptoJS.mode.OFB; })); },{"./cipher-core":35,"./core":36}],50:[function(_dereq_,module,exports){ ;(function (root, factory, undef) { if (typeof exports === "object") { // CommonJS module.exports = exports = factory(_dereq_("./core"), _dereq_("./cipher-core")); } else if (typeof define === "function" && define.amd) { // AMD define(["./core", "./cipher-core"], factory); } else { // Global (browser) factory(root.CryptoJS); } }(this, function (CryptoJS) { /** * ANSI X.923 padding strategy. */ CryptoJS.pad.AnsiX923 = { pad: function (data, blockSize) { // Shortcuts var dataSigBytes = data.sigBytes; var blockSizeBytes = blockSize * 4; // Count padding bytes var nPaddingBytes = blockSizeBytes - dataSigBytes % blockSizeBytes; // Compute last byte position var lastBytePos = dataSigBytes + nPaddingBytes - 1; // Pad data.clamp(); data.words[lastBytePos >>> 2] |= nPaddingBytes << (24 - (lastBytePos % 4) * 8); data.sigBytes += nPaddingBytes; }, unpad: function (data) { // Get number of padding bytes from last byte var nPaddingBytes = data.words[(data.sigBytes - 1) >>> 2] & 0xff; // Remove padding data.sigBytes -= nPaddingBytes; } }; return CryptoJS.pad.Ansix923; })); },{"./cipher-core":35,"./core":36}],51:[function(_dereq_,module,exports){ ;(function (root, factory, undef) { if (typeof exports === "object") { // CommonJS module.exports = exports = factory(_dereq_("./core"), _dereq_("./cipher-core")); } else if (typeof define === "function" && define.amd) { // AMD define(["./core", "./cipher-core"], factory); } else { // Global (browser) factory(root.CryptoJS); } }(this, function (CryptoJS) { /** * ISO 10126 padding strategy. */ CryptoJS.pad.Iso10126 = { pad: function (data, blockSize) { // Shortcut var blockSizeBytes = blockSize * 4; // Count padding bytes var nPaddingBytes = blockSizeBytes - data.sigBytes % blockSizeBytes; // Pad data.concat(CryptoJS.lib.WordArray.random(nPaddingBytes - 1)). concat(CryptoJS.lib.WordArray.create([nPaddingBytes << 24], 1)); }, unpad: function (data) { // Get number of padding bytes from last byte var nPaddingBytes = data.words[(data.sigBytes - 1) >>> 2] & 0xff; // Remove padding data.sigBytes -= nPaddingBytes; } }; return CryptoJS.pad.Iso10126; })); },{"./cipher-core":35,"./core":36}],52:[function(_dereq_,module,exports){ ;(function (root, factory, undef) { if (typeof exports === "object") { // CommonJS module.exports = exports = factory(_dereq_("./core"), _dereq_("./cipher-core")); } else if (typeof define === "function" && define.amd) { // AMD define(["./core", "./cipher-core"], factory); } else { // Global (browser) factory(root.CryptoJS); } }(this, function (CryptoJS) { /** * ISO/IEC 9797-1 Padding Method 2. */ CryptoJS.pad.Iso97971 = { pad: function (data, blockSize) { // Add 0x80 byte data.concat(CryptoJS.lib.WordArray.create([0x80000000], 1)); // Zero pad the rest CryptoJS.pad.ZeroPadding.pad(data, blockSize); }, unpad: function (data) { // Remove zero padding CryptoJS.pad.ZeroPadding.unpad(data); // Remove one more byte -- the 0x80 byte data.sigBytes--; } }; return CryptoJS.pad.Iso97971; })); },{"./cipher-core":35,"./core":36}],53:[function(_dereq_,module,exports){ ;(function (root, factory, undef) { if (typeof exports === "object") { // CommonJS module.exports = exports = factory(_dereq_("./core"), _dereq_("./cipher-core")); } else if (typeof define === "function" && define.amd) { // AMD define(["./core", "./cipher-core"], factory); } else { // Global (browser) factory(root.CryptoJS); } }(this, function (CryptoJS) { /** * A noop padding strategy. */ CryptoJS.pad.NoPadding = { pad: function () { }, unpad: function () { } }; return CryptoJS.pad.NoPadding; })); },{"./cipher-core":35,"./core":36}],54:[function(_dereq_,module,exports){ ;(function (root, factory, undef) { if (typeof exports === "object") { // CommonJS module.exports = exports = factory(_dereq_("./core"), _dereq_("./cipher-core")); } else if (typeof define === "function" && define.amd) { // AMD define(["./core", "./cipher-core"], factory); } else { // Global (browser) factory(root.CryptoJS); } }(this, function (CryptoJS) { /** * Zero padding strategy. */ CryptoJS.pad.ZeroPadding = { pad: function (data, blockSize) { // Shortcut var blockSizeBytes = blockSize * 4; // Pad data.clamp(); data.sigBytes += blockSizeBytes - ((data.sigBytes % blockSizeBytes) || blockSizeBytes); }, unpad: function (data) { // Shortcut var dataWords = data.words; // Unpad var i = data.sigBytes - 1; while (!((dataWords[i >>> 2] >>> (24 - (i % 4) * 8)) & 0xff)) { i--; } data.sigBytes = i + 1; } }; return CryptoJS.pad.ZeroPadding; })); },{"./cipher-core":35,"./core":36}],55:[function(_dereq_,module,exports){ ;(function (root, factory, undef) { if (typeof exports === "object") { // CommonJS module.exports = exports = factory(_dereq_("./core"), _dereq_("./sha1"), _dereq_("./hmac")); } else if (typeof define === "function" && define.amd) { // AMD define(["./core", "./sha1", "./hmac"], factory); } else { // Global (browser) factory(root.CryptoJS); } }(this, function (CryptoJS) { (function () { // Shortcuts var C = CryptoJS; var C_lib = C.lib; var Base = C_lib.Base; var WordArray = C_lib.WordArray; var C_algo = C.algo; var SHA1 = C_algo.SHA1; var HMAC = C_algo.HMAC; /** * Password-Based Key Derivation Function 2 algorithm. */ var PBKDF2 = C_algo.PBKDF2 = Base.extend({ /** * Configuration options. * * @property {number} keySize The key size in words to generate. Default: 4 (128 bits) * @property {Hasher} hasher The hasher to use. Default: SHA1 * @property {number} iterations The number of iterations to perform. Default: 1 */ cfg: Base.extend({ keySize: 128/32, hasher: SHA1, iterations: 1 }), /** * Initializes a newly created key derivation function. * * @param {Object} cfg (Optional) The configuration options to use for the derivation. * * @example * * var kdf = CryptoJS.algo.PBKDF2.create(); * var kdf = CryptoJS.algo.PBKDF2.create({ keySize: 8 }); * var kdf = CryptoJS.algo.PBKDF2.create({ keySize: 8, iterations: 1000 }); */ init: function (cfg) { this.cfg = this.cfg.extend(cfg); }, /** * Computes the Password-Based Key Derivation Function 2. * * @param {WordArray|string} password The password. * @param {WordArray|string} salt A salt. * * @return {WordArray} The derived key. * * @example * * var key = kdf.compute(password, salt); */ compute: function (password, salt) { // Shortcut var cfg = this.cfg; // Init HMAC var hmac = HMAC.create(cfg.hasher, password); // Initial values var derivedKey = WordArray.create(); var blockIndex = WordArray.create([0x00000001]); // Shortcuts var derivedKeyWords = derivedKey.words; var blockIndexWords = blockIndex.words; var keySize = cfg.keySize; var iterations = cfg.iterations; // Generate key while (derivedKeyWords.length < keySize) { var block = hmac.update(salt).finalize(blockIndex); hmac.reset(); // Shortcuts var blockWords = block.words; var blockWordsLength = blockWords.length; // Iterations var intermediate = block; for (var i = 1; i < iterations; i++) { intermediate = hmac.finalize(intermediate); hmac.reset(); // Shortcut var intermediateWords = intermediate.words; // XOR intermediate with block for (var j = 0; j < blockWordsLength; j++) { blockWords[j] ^= intermediateWords[j]; } } derivedKey.concat(block); blockIndexWords[0]++; } derivedKey.sigBytes = keySize * 4; return derivedKey; } }); /** * Computes the Password-Based Key Derivation Function 2. * * @param {WordArray|string} password The password. * @param {WordArray|string} salt A salt. * @param {Object} cfg (Optional) The configuration options to use for this computation. * * @return {WordArray} The derived key. * * @static * * @example * * var key = CryptoJS.PBKDF2(password, salt); * var key = CryptoJS.PBKDF2(password, salt, { keySize: 8 }); * var key = CryptoJS.PBKDF2(password, salt, { keySize: 8, iterations: 1000 }); */ C.PBKDF2 = function (password, salt, cfg) { return PBKDF2.create(cfg).compute(password, salt); }; }()); return CryptoJS.PBKDF2; })); },{"./core":36,"./hmac":41,"./sha1":60}],56:[function(_dereq_,module,exports){ ;(function (root, factory, undef) { if (typeof exports === "object") { // CommonJS module.exports = exports = factory(_dereq_("./core"), _dereq_("./enc-base64"), _dereq_("./md5"), _dereq_("./evpkdf"), _dereq_("./cipher-core")); } else if (typeof define === "function" && define.amd) { // AMD define(["./core", "./enc-base64", "./md5", "./evpkdf", "./cipher-core"], factory); } else { // Global (browser) factory(root.CryptoJS); } }(this, function (CryptoJS) { (function () { // Shortcuts var C = CryptoJS; var C_lib = C.lib; var StreamCipher = C_lib.StreamCipher; var C_algo = C.algo; // Reusable objects var S = []; var C_ = []; var G = []; /** * Rabbit stream cipher algorithm. * * This is a legacy version that neglected to convert the key to little-endian. * This error doesn't affect the cipher's security, * but it does affect its compatibility with other implementations. */ var RabbitLegacy = C_algo.RabbitLegacy = StreamCipher.extend({ _doReset: function () { // Shortcuts var K = this._key.words; var iv = this.cfg.iv; // Generate initial state values var X = this._X = [ K[0], (K[3] << 16) | (K[2] >>> 16), K[1], (K[0] << 16) | (K[3] >>> 16), K[2], (K[1] << 16) | (K[0] >>> 16), K[3], (K[2] << 16) | (K[1] >>> 16) ]; // Generate initial counter values var C = this._C = [ (K[2] << 16) | (K[2] >>> 16), (K[0] & 0xffff0000) | (K[1] & 0x0000ffff), (K[3] << 16) | (K[3] >>> 16), (K[1] & 0xffff0000) | (K[2] & 0x0000ffff), (K[0] << 16) | (K[0] >>> 16), (K[2] & 0xffff0000) | (K[3] & 0x0000ffff), (K[1] << 16) | (K[1] >>> 16), (K[3] & 0xffff0000) | (K[0] & 0x0000ffff) ]; // Carry bit this._b = 0; // Iterate the system four times for (var i = 0; i < 4; i++) { nextState.call(this); } // Modify the counters for (var i = 0; i < 8; i++) { C[i] ^= X[(i + 4) & 7]; } // IV setup if (iv) { // Shortcuts var IV = iv.words; var IV_0 = IV[0]; var IV_1 = IV[1]; // Generate four subvectors var i0 = (((IV_0 << 8) | (IV_0 >>> 24)) & 0x00ff00ff) | (((IV_0 << 24) | (IV_0 >>> 8)) & 0xff00ff00); var i2 = (((IV_1 << 8) | (IV_1 >>> 24)) & 0x00ff00ff) | (((IV_1 << 24) | (IV_1 >>> 8)) & 0xff00ff00); var i1 = (i0 >>> 16) | (i2 & 0xffff0000); var i3 = (i2 << 16) | (i0 & 0x0000ffff); // Modify counter values C[0] ^= i0; C[1] ^= i1; C[2] ^= i2; C[3] ^= i3; C[4] ^= i0; C[5] ^= i1; C[6] ^= i2; C[7] ^= i3; // Iterate the system four times for (var i = 0; i < 4; i++) { nextState.call(this); } } }, _doProcessBlock: function (M, offset) { // Shortcut var X = this._X; // Iterate the system nextState.call(this); // Generate four keystream words S[0] = X[0] ^ (X[5] >>> 16) ^ (X[3] << 16); S[1] = X[2] ^ (X[7] >>> 16) ^ (X[5] << 16); S[2] = X[4] ^ (X[1] >>> 16) ^ (X[7] << 16); S[3] = X[6] ^ (X[3] >>> 16) ^ (X[1] << 16); for (var i = 0; i < 4; i++) { // Swap endian S[i] = (((S[i] << 8) | (S[i] >>> 24)) & 0x00ff00ff) | (((S[i] << 24) | (S[i] >>> 8)) & 0xff00ff00); // Encrypt M[offset + i] ^= S[i]; } }, blockSize: 128/32, ivSize: 64/32 }); function nextState() { // Shortcuts var X = this._X; var C = this._C; // Save old counter values for (var i = 0; i < 8; i++) { C_[i] = C[i]; } // Calculate new counter values C[0] = (C[0] + 0x4d34d34d + this._b) | 0; C[1] = (C[1] + 0xd34d34d3 + ((C[0] >>> 0) < (C_[0] >>> 0) ? 1 : 0)) | 0; C[2] = (C[2] + 0x34d34d34 + ((C[1] >>> 0) < (C_[1] >>> 0) ? 1 : 0)) | 0; C[3] = (C[3] + 0x4d34d34d + ((C[2] >>> 0) < (C_[2] >>> 0) ? 1 : 0)) | 0; C[4] = (C[4] + 0xd34d34d3 + ((C[3] >>> 0) < (C_[3] >>> 0) ? 1 : 0)) | 0; C[5] = (C[5] + 0x34d34d34 + ((C[4] >>> 0) < (C_[4] >>> 0) ? 1 : 0)) | 0; C[6] = (C[6] + 0x4d34d34d + ((C[5] >>> 0) < (C_[5] >>> 0) ? 1 : 0)) | 0; C[7] = (C[7] + 0xd34d34d3 + ((C[6] >>> 0) < (C_[6] >>> 0) ? 1 : 0)) | 0; this._b = (C[7] >>> 0) < (C_[7] >>> 0) ? 1 : 0; // Calculate the g-values for (var i = 0; i < 8; i++) { var gx = X[i] + C[i]; // Construct high and low argument for squaring var ga = gx & 0xffff; var gb = gx >>> 16; // Calculate high and low result of squaring var gh = ((((ga * ga) >>> 17) + ga * gb) >>> 15) + gb * gb; var gl = (((gx & 0xffff0000) * gx) | 0) + (((gx & 0x0000ffff) * gx) | 0); // High XOR low G[i] = gh ^ gl; } // Calculate new state values X[0] = (G[0] + ((G[7] << 16) | (G[7] >>> 16)) + ((G[6] << 16) | (G[6] >>> 16))) | 0; X[1] = (G[1] + ((G[0] << 8) | (G[0] >>> 24)) + G[7]) | 0; X[2] = (G[2] + ((G[1] << 16) | (G[1] >>> 16)) + ((G[0] << 16) | (G[0] >>> 16))) | 0; X[3] = (G[3] + ((G[2] << 8) | (G[2] >>> 24)) + G[1]) | 0; X[4] = (G[4] + ((G[3] << 16) | (G[3] >>> 16)) + ((G[2] << 16) | (G[2] >>> 16))) | 0; X[5] = (G[5] + ((G[4] << 8) | (G[4] >>> 24)) + G[3]) | 0; X[6] = (G[6] + ((G[5] << 16) | (G[5] >>> 16)) + ((G[4] << 16) | (G[4] >>> 16))) | 0; X[7] = (G[7] + ((G[6] << 8) | (G[6] >>> 24)) + G[5]) | 0; } /** * Shortcut functions to the cipher's object interface. * * @example * * var ciphertext = CryptoJS.RabbitLegacy.encrypt(message, key, cfg); * var plaintext = CryptoJS.RabbitLegacy.decrypt(ciphertext, key, cfg); */ C.RabbitLegacy = StreamCipher._createHelper(RabbitLegacy); }()); return CryptoJS.RabbitLegacy; })); },{"./cipher-core":35,"./core":36,"./enc-base64":37,"./evpkdf":39,"./md5":44}],57:[function(_dereq_,module,exports){ ;(function (root, factory, undef) { if (typeof exports === "object") { // CommonJS module.exports = exports = factory(_dereq_("./core"), _dereq_("./enc-base64"), _dereq_("./md5"), _dereq_("./evpkdf"), _dereq_("./cipher-core")); } else if (typeof define === "function" && define.amd) { // AMD define(["./core", "./enc-base64", "./md5", "./evpkdf", "./cipher-core"], factory); } else { // Global (browser) factory(root.CryptoJS); } }(this, function (CryptoJS) { (function () { // Shortcuts var C = CryptoJS; var C_lib = C.lib; var StreamCipher = C_lib.StreamCipher; var C_algo = C.algo; // Reusable objects var S = []; var C_ = []; var G = []; /** * Rabbit stream cipher algorithm */ var Rabbit = C_algo.Rabbit = StreamCipher.extend({ _doReset: function () { // Shortcuts var K = this._key.words; var iv = this.cfg.iv; // Swap endian for (var i = 0; i < 4; i++) { K[i] = (((K[i] << 8) | (K[i] >>> 24)) & 0x00ff00ff) | (((K[i] << 24) | (K[i] >>> 8)) & 0xff00ff00); } // Generate initial state values var X = this._X = [ K[0], (K[3] << 16) | (K[2] >>> 16), K[1], (K[0] << 16) | (K[3] >>> 16), K[2], (K[1] << 16) | (K[0] >>> 16), K[3], (K[2] << 16) | (K[1] >>> 16) ]; // Generate initial counter values var C = this._C = [ (K[2] << 16) | (K[2] >>> 16), (K[0] & 0xffff0000) | (K[1] & 0x0000ffff), (K[3] << 16) | (K[3] >>> 16), (K[1] & 0xffff0000) | (K[2] & 0x0000ffff), (K[0] << 16) | (K[0] >>> 16), (K[2] & 0xffff0000) | (K[3] & 0x0000ffff), (K[1] << 16) | (K[1] >>> 16), (K[3] & 0xffff0000) | (K[0] & 0x0000ffff) ]; // Carry bit this._b = 0; // Iterate the system four times for (var i = 0; i < 4; i++) { nextState.call(this); } // Modify the counters for (var i = 0; i < 8; i++) { C[i] ^= X[(i + 4) & 7]; } // IV setup if (iv) { // Shortcuts var IV = iv.words; var IV_0 = IV[0]; var IV_1 = IV[1]; // Generate four subvectors var i0 = (((IV_0 << 8) | (IV_0 >>> 24)) & 0x00ff00ff) | (((IV_0 << 24) | (IV_0 >>> 8)) & 0xff00ff00); var i2 = (((IV_1 << 8) | (IV_1 >>> 24)) & 0x00ff00ff) | (((IV_1 << 24) | (IV_1 >>> 8)) & 0xff00ff00); var i1 = (i0 >>> 16) | (i2 & 0xffff0000); var i3 = (i2 << 16) | (i0 & 0x0000ffff); // Modify counter values C[0] ^= i0; C[1] ^= i1; C[2] ^= i2; C[3] ^= i3; C[4] ^= i0; C[5] ^= i1; C[6] ^= i2; C[7] ^= i3; // Iterate the system four times for (var i = 0; i < 4; i++) { nextState.call(this); } } }, _doProcessBlock: function (M, offset) { // Shortcut var X = this._X; // Iterate the system nextState.call(this); // Generate four keystream words S[0] = X[0] ^ (X[5] >>> 16) ^ (X[3] << 16); S[1] = X[2] ^ (X[7] >>> 16) ^ (X[5] << 16); S[2] = X[4] ^ (X[1] >>> 16) ^ (X[7] << 16); S[3] = X[6] ^ (X[3] >>> 16) ^ (X[1] << 16); for (var i = 0; i < 4; i++) { // Swap endian S[i] = (((S[i] << 8) | (S[i] >>> 24)) & 0x00ff00ff) | (((S[i] << 24) | (S[i] >>> 8)) & 0xff00ff00); // Encrypt M[offset + i] ^= S[i]; } }, blockSize: 128/32, ivSize: 64/32 }); function nextState() { // Shortcuts var X = this._X; var C = this._C; // Save old counter values for (var i = 0; i < 8; i++) { C_[i] = C[i]; } // Calculate new counter values C[0] = (C[0] + 0x4d34d34d + this._b) | 0; C[1] = (C[1] + 0xd34d34d3 + ((C[0] >>> 0) < (C_[0] >>> 0) ? 1 : 0)) | 0; C[2] = (C[2] + 0x34d34d34 + ((C[1] >>> 0) < (C_[1] >>> 0) ? 1 : 0)) | 0; C[3] = (C[3] + 0x4d34d34d + ((C[2] >>> 0) < (C_[2] >>> 0) ? 1 : 0)) | 0; C[4] = (C[4] + 0xd34d34d3 + ((C[3] >>> 0) < (C_[3] >>> 0) ? 1 : 0)) | 0; C[5] = (C[5] + 0x34d34d34 + ((C[4] >>> 0) < (C_[4] >>> 0) ? 1 : 0)) | 0; C[6] = (C[6] + 0x4d34d34d + ((C[5] >>> 0) < (C_[5] >>> 0) ? 1 : 0)) | 0; C[7] = (C[7] + 0xd34d34d3 + ((C[6] >>> 0) < (C_[6] >>> 0) ? 1 : 0)) | 0; this._b = (C[7] >>> 0) < (C_[7] >>> 0) ? 1 : 0; // Calculate the g-values for (var i = 0; i < 8; i++) { var gx = X[i] + C[i]; // Construct high and low argument for squaring var ga = gx & 0xffff; var gb = gx >>> 16; // Calculate high and low result of squaring var gh = ((((ga * ga) >>> 17) + ga * gb) >>> 15) + gb * gb; var gl = (((gx & 0xffff0000) * gx) | 0) + (((gx & 0x0000ffff) * gx) | 0); // High XOR low G[i] = gh ^ gl; } // Calculate new state values X[0] = (G[0] + ((G[7] << 16) | (G[7] >>> 16)) + ((G[6] << 16) | (G[6] >>> 16))) | 0; X[1] = (G[1] + ((G[0] << 8) | (G[0] >>> 24)) + G[7]) | 0; X[2] = (G[2] + ((G[1] << 16) | (G[1] >>> 16)) + ((G[0] << 16) | (G[0] >>> 16))) | 0; X[3] = (G[3] + ((G[2] << 8) | (G[2] >>> 24)) + G[1]) | 0; X[4] = (G[4] + ((G[3] << 16) | (G[3] >>> 16)) + ((G[2] << 16) | (G[2] >>> 16))) | 0; X[5] = (G[5] + ((G[4] << 8) | (G[4] >>> 24)) + G[3]) | 0; X[6] = (G[6] + ((G[5] << 16) | (G[5] >>> 16)) + ((G[4] << 16) | (G[4] >>> 16))) | 0; X[7] = (G[7] + ((G[6] << 8) | (G[6] >>> 24)) + G[5]) | 0; } /** * Shortcut functions to the cipher's object interface. * * @example * * var ciphertext = CryptoJS.Rabbit.encrypt(message, key, cfg); * var plaintext = CryptoJS.Rabbit.decrypt(ciphertext, key, cfg); */ C.Rabbit = StreamCipher._createHelper(Rabbit); }()); return CryptoJS.Rabbit; })); },{"./cipher-core":35,"./core":36,"./enc-base64":37,"./evpkdf":39,"./md5":44}],58:[function(_dereq_,module,exports){ ;(function (root, factory, undef) { if (typeof exports === "object") { // CommonJS module.exports = exports = factory(_dereq_("./core"), _dereq_("./enc-base64"), _dereq_("./md5"), _dereq_("./evpkdf"), _dereq_("./cipher-core")); } else if (typeof define === "function" && define.amd) { // AMD define(["./core", "./enc-base64", "./md5", "./evpkdf", "./cipher-core"], factory); } else { // Global (browser) factory(root.CryptoJS); } }(this, function (CryptoJS) { (function () { // Shortcuts var C = CryptoJS; var C_lib = C.lib; var StreamCipher = C_lib.StreamCipher; var C_algo = C.algo; /** * RC4 stream cipher algorithm. */ var RC4 = C_algo.RC4 = StreamCipher.extend({ _doReset: function () { // Shortcuts var key = this._key; var keyWords = key.words; var keySigBytes = key.sigBytes; // Init sbox var S = this._S = []; for (var i = 0; i < 256; i++) { S[i] = i; } // Key setup for (var i = 0, j = 0; i < 256; i++) { var keyByteIndex = i % keySigBytes; var keyByte = (keyWords[keyByteIndex >>> 2] >>> (24 - (keyByteIndex % 4) * 8)) & 0xff; j = (j + S[i] + keyByte) % 256; // Swap var t = S[i]; S[i] = S[j]; S[j] = t; } // Counters this._i = this._j = 0; }, _doProcessBlock: function (M, offset) { M[offset] ^= generateKeystreamWord.call(this); }, keySize: 256/32, ivSize: 0 }); function generateKeystreamWord() { // Shortcuts var S = this._S; var i = this._i; var j = this._j; // Generate keystream word var keystreamWord = 0; for (var n = 0; n < 4; n++) { i = (i + 1) % 256; j = (j + S[i]) % 256; // Swap var t = S[i]; S[i] = S[j]; S[j] = t; keystreamWord |= S[(S[i] + S[j]) % 256] << (24 - n * 8); } // Update counters this._i = i; this._j = j; return keystreamWord; } /** * Shortcut functions to the cipher's object interface. * * @example * * var ciphertext = CryptoJS.RC4.encrypt(message, key, cfg); * var plaintext = CryptoJS.RC4.decrypt(ciphertext, key, cfg); */ C.RC4 = StreamCipher._createHelper(RC4); /** * Modified RC4 stream cipher algorithm. */ var RC4Drop = C_algo.RC4Drop = RC4.extend({ /** * Configuration options. * * @property {number} drop The number of keystream words to drop. Default 192 */ cfg: RC4.cfg.extend({ drop: 192 }), _doReset: function () { RC4._doReset.call(this); // Drop for (var i = this.cfg.drop; i > 0; i--) { generateKeystreamWord.call(this); } } }); /** * Shortcut functions to the cipher's object interface. * * @example * * var ciphertext = CryptoJS.RC4Drop.encrypt(message, key, cfg); * var plaintext = CryptoJS.RC4Drop.decrypt(ciphertext, key, cfg); */ C.RC4Drop = StreamCipher._createHelper(RC4Drop); }()); return CryptoJS.RC4; })); },{"./cipher-core":35,"./core":36,"./enc-base64":37,"./evpkdf":39,"./md5":44}],59:[function(_dereq_,module,exports){ ;(function (root, factory) { if (typeof exports === "object") { // CommonJS module.exports = exports = factory(_dereq_("./core")); } else if (typeof define === "function" && define.amd) { // AMD define(["./core"], factory); } else { // Global (browser) factory(root.CryptoJS); } }(this, function (CryptoJS) { /** @preserve (c) 2012 by Cédric Mesnil. All rights reserved. Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met: - Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer. - Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution. THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ (function (Math) { // Shortcuts var C = CryptoJS; var C_lib = C.lib; var WordArray = C_lib.WordArray; var Hasher = C_lib.Hasher; var C_algo = C.algo; // Constants table var _zl = WordArray.create([ 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 7, 4, 13, 1, 10, 6, 15, 3, 12, 0, 9, 5, 2, 14, 11, 8, 3, 10, 14, 4, 9, 15, 8, 1, 2, 7, 0, 6, 13, 11, 5, 12, 1, 9, 11, 10, 0, 8, 12, 4, 13, 3, 7, 15, 14, 5, 6, 2, 4, 0, 5, 9, 7, 12, 2, 10, 14, 1, 3, 8, 11, 6, 15, 13]); var _zr = WordArray.create([ 5, 14, 7, 0, 9, 2, 11, 4, 13, 6, 15, 8, 1, 10, 3, 12, 6, 11, 3, 7, 0, 13, 5, 10, 14, 15, 8, 12, 4, 9, 1, 2, 15, 5, 1, 3, 7, 14, 6, 9, 11, 8, 12, 2, 10, 0, 4, 13, 8, 6, 4, 1, 3, 11, 15, 0, 5, 12, 2, 13, 9, 7, 10, 14, 12, 15, 10, 4, 1, 5, 8, 7, 6, 2, 13, 14, 0, 3, 9, 11]); var _sl = WordArray.create([ 11, 14, 15, 12, 5, 8, 7, 9, 11, 13, 14, 15, 6, 7, 9, 8, 7, 6, 8, 13, 11, 9, 7, 15, 7, 12, 15, 9, 11, 7, 13, 12, 11, 13, 6, 7, 14, 9, 13, 15, 14, 8, 13, 6, 5, 12, 7, 5, 11, 12, 14, 15, 14, 15, 9, 8, 9, 14, 5, 6, 8, 6, 5, 12, 9, 15, 5, 11, 6, 8, 13, 12, 5, 12, 13, 14, 11, 8, 5, 6 ]); var _sr = WordArray.create([ 8, 9, 9, 11, 13, 15, 15, 5, 7, 7, 8, 11, 14, 14, 12, 6, 9, 13, 15, 7, 12, 8, 9, 11, 7, 7, 12, 7, 6, 15, 13, 11, 9, 7, 15, 11, 8, 6, 6, 14, 12, 13, 5, 14, 13, 13, 7, 5, 15, 5, 8, 11, 14, 14, 6, 14, 6, 9, 12, 9, 12, 5, 15, 8, 8, 5, 12, 9, 12, 5, 14, 6, 8, 13, 6, 5, 15, 13, 11, 11 ]); var _hl = WordArray.create([ 0x00000000, 0x5A827999, 0x6ED9EBA1, 0x8F1BBCDC, 0xA953FD4E]); var _hr = WordArray.create([ 0x50A28BE6, 0x5C4DD124, 0x6D703EF3, 0x7A6D76E9, 0x00000000]); /** * RIPEMD160 hash algorithm. */ var RIPEMD160 = C_algo.RIPEMD160 = Hasher.extend({ _doReset: function () { this._hash = WordArray.create([0x67452301, 0xEFCDAB89, 0x98BADCFE, 0x10325476, 0xC3D2E1F0]); }, _doProcessBlock: function (M, offset) { // Swap endian for (var i = 0; i < 16; i++) { // Shortcuts var offset_i = offset + i; var M_offset_i = M[offset_i]; // Swap M[offset_i] = ( (((M_offset_i << 8) | (M_offset_i >>> 24)) & 0x00ff00ff) | (((M_offset_i << 24) | (M_offset_i >>> 8)) & 0xff00ff00) ); } // Shortcut var H = this._hash.words; var hl = _hl.words; var hr = _hr.words; var zl = _zl.words; var zr = _zr.words; var sl = _sl.words; var sr = _sr.words; // Working variables var al, bl, cl, dl, el; var ar, br, cr, dr, er; ar = al = H[0]; br = bl = H[1]; cr = cl = H[2]; dr = dl = H[3]; er = el = H[4]; // Computation var t; for (var i = 0; i < 80; i += 1) { t = (al + M[offset+zl[i]])|0; if (i<16){ t += f1(bl,cl,dl) + hl[0]; } else if (i<32) { t += f2(bl,cl,dl) + hl[1]; } else if (i<48) { t += f3(bl,cl,dl) + hl[2]; } else if (i<64) { t += f4(bl,cl,dl) + hl[3]; } else {// if (i<80) { t += f5(bl,cl,dl) + hl[4]; } t = t|0; t = rotl(t,sl[i]); t = (t+el)|0; al = el; el = dl; dl = rotl(cl, 10); cl = bl; bl = t; t = (ar + M[offset+zr[i]])|0; if (i<16){ t += f5(br,cr,dr) + hr[0]; } else if (i<32) { t += f4(br,cr,dr) + hr[1]; } else if (i<48) { t += f3(br,cr,dr) + hr[2]; } else if (i<64) { t += f2(br,cr,dr) + hr[3]; } else {// if (i<80) { t += f1(br,cr,dr) + hr[4]; } t = t|0; t = rotl(t,sr[i]) ; t = (t+er)|0; ar = er; er = dr; dr = rotl(cr, 10); cr = br; br = t; } // Intermediate hash value t = (H[1] + cl + dr)|0; H[1] = (H[2] + dl + er)|0; H[2] = (H[3] + el + ar)|0; H[3] = (H[4] + al + br)|0; H[4] = (H[0] + bl + cr)|0; H[0] = t; }, _doFinalize: function () { // Shortcuts var data = this._data; var dataWords = data.words; var nBitsTotal = this._nDataBytes * 8; var nBitsLeft = data.sigBytes * 8; // Add padding dataWords[nBitsLeft >>> 5] |= 0x80 << (24 - nBitsLeft % 32); dataWords[(((nBitsLeft + 64) >>> 9) << 4) + 14] = ( (((nBitsTotal << 8) | (nBitsTotal >>> 24)) & 0x00ff00ff) | (((nBitsTotal << 24) | (nBitsTotal >>> 8)) & 0xff00ff00) ); data.sigBytes = (dataWords.length + 1) * 4; // Hash final blocks this._process(); // Shortcuts var hash = this._hash; var H = hash.words; // Swap endian for (var i = 0; i < 5; i++) { // Shortcut var H_i = H[i]; // Swap H[i] = (((H_i << 8) | (H_i >>> 24)) & 0x00ff00ff) | (((H_i << 24) | (H_i >>> 8)) & 0xff00ff00); } // Return final computed hash return hash; }, clone: function () { var clone = Hasher.clone.call(this); clone._hash = this._hash.clone(); return clone; } }); function f1(x, y, z) { return ((x) ^ (y) ^ (z)); } function f2(x, y, z) { return (((x)&(y)) | ((~x)&(z))); } function f3(x, y, z) { return (((x) | (~(y))) ^ (z)); } function f4(x, y, z) { return (((x) & (z)) | ((y)&(~(z)))); } function f5(x, y, z) { return ((x) ^ ((y) |(~(z)))); } function rotl(x,n) { return (x<<n) | (x>>>(32-n)); } /** * Shortcut function to the hasher's object interface. * * @param {WordArray|string} message The message to hash. * * @return {WordArray} The hash. * * @static * * @example * * var hash = CryptoJS.RIPEMD160('message'); * var hash = CryptoJS.RIPEMD160(wordArray); */ C.RIPEMD160 = Hasher._createHelper(RIPEMD160); /** * Shortcut function to the HMAC's object interface. * * @param {WordArray|string} message The message to hash. * @param {WordArray|string} key The secret key. * * @return {WordArray} The HMAC. * * @static * * @example * * var hmac = CryptoJS.HmacRIPEMD160(message, key); */ C.HmacRIPEMD160 = Hasher._createHmacHelper(RIPEMD160); }(Math)); return CryptoJS.RIPEMD160; })); },{"./core":36}],60:[function(_dereq_,module,exports){ ;(function (root, factory) { if (typeof exports === "object") { // CommonJS module.exports = exports = factory(_dereq_("./core")); } else if (typeof define === "function" && define.amd) { // AMD define(["./core"], factory); } else { // Global (browser) factory(root.CryptoJS); } }(this, function (CryptoJS) { (function () { // Shortcuts var C = CryptoJS; var C_lib = C.lib; var WordArray = C_lib.WordArray; var Hasher = C_lib.Hasher; var C_algo = C.algo; // Reusable object var W = []; /** * SHA-1 hash algorithm. */ var SHA1 = C_algo.SHA1 = Hasher.extend({ _doReset: function () { this._hash = new WordArray.init([ 0x67452301, 0xefcdab89, 0x98badcfe, 0x10325476, 0xc3d2e1f0 ]); }, _doProcessBlock: function (M, offset) { // Shortcut var H = this._hash.words; // Working variables var a = H[0]; var b = H[1]; var c = H[2]; var d = H[3]; var e = H[4]; // Computation for (var i = 0; i < 80; i++) { if (i < 16) { W[i] = M[offset + i] | 0; } else { var n = W[i - 3] ^ W[i - 8] ^ W[i - 14] ^ W[i - 16]; W[i] = (n << 1) | (n >>> 31); } var t = ((a << 5) | (a >>> 27)) + e + W[i]; if (i < 20) { t += ((b & c) | (~b & d)) + 0x5a827999; } else if (i < 40) { t += (b ^ c ^ d) + 0x6ed9eba1; } else if (i < 60) { t += ((b & c) | (b & d) | (c & d)) - 0x70e44324; } else /* if (i < 80) */ { t += (b ^ c ^ d) - 0x359d3e2a; } e = d; d = c; c = (b << 30) | (b >>> 2); b = a; a = t; } // Intermediate hash value H[0] = (H[0] + a) | 0; H[1] = (H[1] + b) | 0; H[2] = (H[2] + c) | 0; H[3] = (H[3] + d) | 0; H[4] = (H[4] + e) | 0; }, _doFinalize: function () { // Shortcuts var data = this._data; var dataWords = data.words; var nBitsTotal = this._nDataBytes * 8; var nBitsLeft = data.sigBytes * 8; // Add padding dataWords[nBitsLeft >>> 5] |= 0x80 << (24 - nBitsLeft % 32); dataWords[(((nBitsLeft + 64) >>> 9) << 4) + 14] = Math.floor(nBitsTotal / 0x100000000); dataWords[(((nBitsLeft + 64) >>> 9) << 4) + 15] = nBitsTotal; data.sigBytes = dataWords.length * 4; // Hash final blocks this._process(); // Return final computed hash return this._hash; }, clone: function () { var clone = Hasher.clone.call(this); clone._hash = this._hash.clone(); return clone; } }); /** * Shortcut function to the hasher's object interface. * * @param {WordArray|string} message The message to hash. * * @return {WordArray} The hash. * * @static * * @example * * var hash = CryptoJS.SHA1('message'); * var hash = CryptoJS.SHA1(wordArray); */ C.SHA1 = Hasher._createHelper(SHA1); /** * Shortcut function to the HMAC's object interface. * * @param {WordArray|string} message The message to hash. * @param {WordArray|string} key The secret key. * * @return {WordArray} The HMAC. * * @static * * @example * * var hmac = CryptoJS.HmacSHA1(message, key); */ C.HmacSHA1 = Hasher._createHmacHelper(SHA1); }()); return CryptoJS.SHA1; })); },{"./core":36}],61:[function(_dereq_,module,exports){ ;(function (root, factory, undef) { if (typeof exports === "object") { // CommonJS module.exports = exports = factory(_dereq_("./core"), _dereq_("./sha256")); } else if (typeof define === "function" && define.amd) { // AMD define(["./core", "./sha256"], factory); } else { // Global (browser) factory(root.CryptoJS); } }(this, function (CryptoJS) { (function () { // Shortcuts var C = CryptoJS; var C_lib = C.lib; var WordArray = C_lib.WordArray; var C_algo = C.algo; var SHA256 = C_algo.SHA256; /** * SHA-224 hash algorithm. */ var SHA224 = C_algo.SHA224 = SHA256.extend({ _doReset: function () { this._hash = new WordArray.init([ 0xc1059ed8, 0x367cd507, 0x3070dd17, 0xf70e5939, 0xffc00b31, 0x68581511, 0x64f98fa7, 0xbefa4fa4 ]); }, _doFinalize: function () { var hash = SHA256._doFinalize.call(this); hash.sigBytes -= 4; return hash; } }); /** * Shortcut function to the hasher's object interface. * * @param {WordArray|string} message The message to hash. * * @return {WordArray} The hash. * * @static * * @example * * var hash = CryptoJS.SHA224('message'); * var hash = CryptoJS.SHA224(wordArray); */ C.SHA224 = SHA256._createHelper(SHA224); /** * Shortcut function to the HMAC's object interface. * * @param {WordArray|string} message The message to hash. * @param {WordArray|string} key The secret key. * * @return {WordArray} The HMAC. * * @static * * @example * * var hmac = CryptoJS.HmacSHA224(message, key); */ C.HmacSHA224 = SHA256._createHmacHelper(SHA224); }()); return CryptoJS.SHA224; })); },{"./core":36,"./sha256":62}],62:[function(_dereq_,module,exports){ ;(function (root, factory) { if (typeof exports === "object") { // CommonJS module.exports = exports = factory(_dereq_("./core")); } else if (typeof define === "function" && define.amd) { // AMD define(["./core"], factory); } else { // Global (browser) factory(root.CryptoJS); } }(this, function (CryptoJS) { (function (Math) { // Shortcuts var C = CryptoJS; var C_lib = C.lib; var WordArray = C_lib.WordArray; var Hasher = C_lib.Hasher; var C_algo = C.algo; // Initialization and round constants tables var H = []; var K = []; // Compute constants (function () { function isPrime(n) { var sqrtN = Math.sqrt(n); for (var factor = 2; factor <= sqrtN; factor++) { if (!(n % factor)) { return false; } } return true; } function getFractionalBits(n) { return ((n - (n | 0)) * 0x100000000) | 0; } var n = 2; var nPrime = 0; while (nPrime < 64) { if (isPrime(n)) { if (nPrime < 8) { H[nPrime] = getFractionalBits(Math.pow(n, 1 / 2)); } K[nPrime] = getFractionalBits(Math.pow(n, 1 / 3)); nPrime++; } n++; } }()); // Reusable object var W = []; /** * SHA-256 hash algorithm. */ var SHA256 = C_algo.SHA256 = Hasher.extend({ _doReset: function () { this._hash = new WordArray.init(H.slice(0)); }, _doProcessBlock: function (M, offset) { // Shortcut var H = this._hash.words; // Working variables var a = H[0]; var b = H[1]; var c = H[2]; var d = H[3]; var e = H[4]; var f = H[5]; var g = H[6]; var h = H[7]; // Computation for (var i = 0; i < 64; i++) { if (i < 16) { W[i] = M[offset + i] | 0; } else { var gamma0x = W[i - 15]; var gamma0 = ((gamma0x << 25) | (gamma0x >>> 7)) ^ ((gamma0x << 14) | (gamma0x >>> 18)) ^ (gamma0x >>> 3); var gamma1x = W[i - 2]; var gamma1 = ((gamma1x << 15) | (gamma1x >>> 17)) ^ ((gamma1x << 13) | (gamma1x >>> 19)) ^ (gamma1x >>> 10); W[i] = gamma0 + W[i - 7] + gamma1 + W[i - 16]; } var ch = (e & f) ^ (~e & g); var maj = (a & b) ^ (a & c) ^ (b & c); var sigma0 = ((a << 30) | (a >>> 2)) ^ ((a << 19) | (a >>> 13)) ^ ((a << 10) | (a >>> 22)); var sigma1 = ((e << 26) | (e >>> 6)) ^ ((e << 21) | (e >>> 11)) ^ ((e << 7) | (e >>> 25)); var t1 = h + sigma1 + ch + K[i] + W[i]; var t2 = sigma0 + maj; h = g; g = f; f = e; e = (d + t1) | 0; d = c; c = b; b = a; a = (t1 + t2) | 0; } // Intermediate hash value H[0] = (H[0] + a) | 0; H[1] = (H[1] + b) | 0; H[2] = (H[2] + c) | 0; H[3] = (H[3] + d) | 0; H[4] = (H[4] + e) | 0; H[5] = (H[5] + f) | 0; H[6] = (H[6] + g) | 0; H[7] = (H[7] + h) | 0; }, _doFinalize: function () { // Shortcuts var data = this._data; var dataWords = data.words; var nBitsTotal = this._nDataBytes * 8; var nBitsLeft = data.sigBytes * 8; // Add padding dataWords[nBitsLeft >>> 5] |= 0x80 << (24 - nBitsLeft % 32); dataWords[(((nBitsLeft + 64) >>> 9) << 4) + 14] = Math.floor(nBitsTotal / 0x100000000); dataWords[(((nBitsLeft + 64) >>> 9) << 4) + 15] = nBitsTotal; data.sigBytes = dataWords.length * 4; // Hash final blocks this._process(); // Return final computed hash return this._hash; }, clone: function () { var clone = Hasher.clone.call(this); clone._hash = this._hash.clone(); return clone; } }); /** * Shortcut function to the hasher's object interface. * * @param {WordArray|string} message The message to hash. * * @return {WordArray} The hash. * * @static * * @example * * var hash = CryptoJS.SHA256('message'); * var hash = CryptoJS.SHA256(wordArray); */ C.SHA256 = Hasher._createHelper(SHA256); /** * Shortcut function to the HMAC's object interface. * * @param {WordArray|string} message The message to hash. * @param {WordArray|string} key The secret key. * * @return {WordArray} The HMAC. * * @static * * @example * * var hmac = CryptoJS.HmacSHA256(message, key); */ C.HmacSHA256 = Hasher._createHmacHelper(SHA256); }(Math)); return CryptoJS.SHA256; })); },{"./core":36}],63:[function(_dereq_,module,exports){ ;(function (root, factory, undef) { if (typeof exports === "object") { // CommonJS module.exports = exports = factory(_dereq_("./core"), _dereq_("./x64-core")); } else if (typeof define === "function" && define.amd) { // AMD define(["./core", "./x64-core"], factory); } else { // Global (browser) factory(root.CryptoJS); } }(this, function (CryptoJS) { (function (Math) { // Shortcuts var C = CryptoJS; var C_lib = C.lib; var WordArray = C_lib.WordArray; var Hasher = C_lib.Hasher; var C_x64 = C.x64; var X64Word = C_x64.Word; var C_algo = C.algo; // Constants tables var RHO_OFFSETS = []; var PI_INDEXES = []; var ROUND_CONSTANTS = []; // Compute Constants (function () { // Compute rho offset constants var x = 1, y = 0; for (var t = 0; t < 24; t++) { RHO_OFFSETS[x + 5 * y] = ((t + 1) * (t + 2) / 2) % 64; var newX = y % 5; var newY = (2 * x + 3 * y) % 5; x = newX; y = newY; } // Compute pi index constants for (var x = 0; x < 5; x++) { for (var y = 0; y < 5; y++) { PI_INDEXES[x + 5 * y] = y + ((2 * x + 3 * y) % 5) * 5; } } // Compute round constants var LFSR = 0x01; for (var i = 0; i < 24; i++) { var roundConstantMsw = 0; var roundConstantLsw = 0; for (var j = 0; j < 7; j++) { if (LFSR & 0x01) { var bitPosition = (1 << j) - 1; if (bitPosition < 32) { roundConstantLsw ^= 1 << bitPosition; } else /* if (bitPosition >= 32) */ { roundConstantMsw ^= 1 << (bitPosition - 32); } } // Compute next LFSR if (LFSR & 0x80) { // Primitive polynomial over GF(2): x^8 + x^6 + x^5 + x^4 + 1 LFSR = (LFSR << 1) ^ 0x71; } else { LFSR <<= 1; } } ROUND_CONSTANTS[i] = X64Word.create(roundConstantMsw, roundConstantLsw); } }()); // Reusable objects for temporary values var T = []; (function () { for (var i = 0; i < 25; i++) { T[i] = X64Word.create(); } }()); /** * SHA-3 hash algorithm. */ var SHA3 = C_algo.SHA3 = Hasher.extend({ /** * Configuration options. * * @property {number} outputLength * The desired number of bits in the output hash. * Only values permitted are: 224, 256, 384, 512. * Default: 512 */ cfg: Hasher.cfg.extend({ outputLength: 512 }), _doReset: function () { var state = this._state = [] for (var i = 0; i < 25; i++) { state[i] = new X64Word.init(); } this.blockSize = (1600 - 2 * this.cfg.outputLength) / 32; }, _doProcessBlock: function (M, offset) { // Shortcuts var state = this._state; var nBlockSizeLanes = this.blockSize / 2; // Absorb for (var i = 0; i < nBlockSizeLanes; i++) { // Shortcuts var M2i = M[offset + 2 * i]; var M2i1 = M[offset + 2 * i + 1]; // Swap endian M2i = ( (((M2i << 8) | (M2i >>> 24)) & 0x00ff00ff) | (((M2i << 24) | (M2i >>> 8)) & 0xff00ff00) ); M2i1 = ( (((M2i1 << 8) | (M2i1 >>> 24)) & 0x00ff00ff) | (((M2i1 << 24) | (M2i1 >>> 8)) & 0xff00ff00) ); // Absorb message into state var lane = state[i]; lane.high ^= M2i1; lane.low ^= M2i; } // Rounds for (var round = 0; round < 24; round++) { // Theta for (var x = 0; x < 5; x++) { // Mix column lanes var tMsw = 0, tLsw = 0; for (var y = 0; y < 5; y++) { var lane = state[x + 5 * y]; tMsw ^= lane.high; tLsw ^= lane.low; } // Temporary values var Tx = T[x]; Tx.high = tMsw; Tx.low = tLsw; } for (var x = 0; x < 5; x++) { // Shortcuts var Tx4 = T[(x + 4) % 5]; var Tx1 = T[(x + 1) % 5]; var Tx1Msw = Tx1.high; var Tx1Lsw = Tx1.low; // Mix surrounding columns var tMsw = Tx4.high ^ ((Tx1Msw << 1) | (Tx1Lsw >>> 31)); var tLsw = Tx4.low ^ ((Tx1Lsw << 1) | (Tx1Msw >>> 31)); for (var y = 0; y < 5; y++) { var lane = state[x + 5 * y]; lane.high ^= tMsw; lane.low ^= tLsw; } } // Rho Pi for (var laneIndex = 1; laneIndex < 25; laneIndex++) { // Shortcuts var lane = state[laneIndex]; var laneMsw = lane.high; var laneLsw = lane.low; var rhoOffset = RHO_OFFSETS[laneIndex]; // Rotate lanes if (rhoOffset < 32) { var tMsw = (laneMsw << rhoOffset) | (laneLsw >>> (32 - rhoOffset)); var tLsw = (laneLsw << rhoOffset) | (laneMsw >>> (32 - rhoOffset)); } else /* if (rhoOffset >= 32) */ { var tMsw = (laneLsw << (rhoOffset - 32)) | (laneMsw >>> (64 - rhoOffset)); var tLsw = (laneMsw << (rhoOffset - 32)) | (laneLsw >>> (64 - rhoOffset)); } // Transpose lanes var TPiLane = T[PI_INDEXES[laneIndex]]; TPiLane.high = tMsw; TPiLane.low = tLsw; } // Rho pi at x = y = 0 var T0 = T[0]; var state0 = state[0]; T0.high = state0.high; T0.low = state0.low; // Chi for (var x = 0; x < 5; x++) { for (var y = 0; y < 5; y++) { // Shortcuts var laneIndex = x + 5 * y; var lane = state[laneIndex]; var TLane = T[laneIndex]; var Tx1Lane = T[((x + 1) % 5) + 5 * y]; var Tx2Lane = T[((x + 2) % 5) + 5 * y]; // Mix rows lane.high = TLane.high ^ (~Tx1Lane.high & Tx2Lane.high); lane.low = TLane.low ^ (~Tx1Lane.low & Tx2Lane.low); } } // Iota var lane = state[0]; var roundConstant = ROUND_CONSTANTS[round]; lane.high ^= roundConstant.high; lane.low ^= roundConstant.low;; } }, _doFinalize: function () { // Shortcuts var data = this._data; var dataWords = data.words; var nBitsTotal = this._nDataBytes * 8; var nBitsLeft = data.sigBytes * 8; var blockSizeBits = this.blockSize * 32; // Add padding dataWords[nBitsLeft >>> 5] |= 0x1 << (24 - nBitsLeft % 32); dataWords[((Math.ceil((nBitsLeft + 1) / blockSizeBits) * blockSizeBits) >>> 5) - 1] |= 0x80; data.sigBytes = dataWords.length * 4; // Hash final blocks this._process(); // Shortcuts var state = this._state; var outputLengthBytes = this.cfg.outputLength / 8; var outputLengthLanes = outputLengthBytes / 8; // Squeeze var hashWords = []; for (var i = 0; i < outputLengthLanes; i++) { // Shortcuts var lane = state[i]; var laneMsw = lane.high; var laneLsw = lane.low; // Swap endian laneMsw = ( (((laneMsw << 8) | (laneMsw >>> 24)) & 0x00ff00ff) | (((laneMsw << 24) | (laneMsw >>> 8)) & 0xff00ff00) ); laneLsw = ( (((laneLsw << 8) | (laneLsw >>> 24)) & 0x00ff00ff) | (((laneLsw << 24) | (laneLsw >>> 8)) & 0xff00ff00) ); // Squeeze state to retrieve hash hashWords.push(laneLsw); hashWords.push(laneMsw); } // Return final computed hash return new WordArray.init(hashWords, outputLengthBytes); }, clone: function () { var clone = Hasher.clone.call(this); var state = clone._state = this._state.slice(0); for (var i = 0; i < 25; i++) { state[i] = state[i].clone(); } return clone; } }); /** * Shortcut function to the hasher's object interface. * * @param {WordArray|string} message The message to hash. * * @return {WordArray} The hash. * * @static * * @example * * var hash = CryptoJS.SHA3('message'); * var hash = CryptoJS.SHA3(wordArray); */ C.SHA3 = Hasher._createHelper(SHA3); /** * Shortcut function to the HMAC's object interface. * * @param {WordArray|string} message The message to hash. * @param {WordArray|string} key The secret key. * * @return {WordArray} The HMAC. * * @static * * @example * * var hmac = CryptoJS.HmacSHA3(message, key); */ C.HmacSHA3 = Hasher._createHmacHelper(SHA3); }(Math)); return CryptoJS.SHA3; })); },{"./core":36,"./x64-core":67}],64:[function(_dereq_,module,exports){ ;(function (root, factory, undef) { if (typeof exports === "object") { // CommonJS module.exports = exports = factory(_dereq_("./core"), _dereq_("./x64-core"), _dereq_("./sha512")); } else if (typeof define === "function" && define.amd) { // AMD define(["./core", "./x64-core", "./sha512"], factory); } else { // Global (browser) factory(root.CryptoJS); } }(this, function (CryptoJS) { (function () { // Shortcuts var C = CryptoJS; var C_x64 = C.x64; var X64Word = C_x64.Word; var X64WordArray = C_x64.WordArray; var C_algo = C.algo; var SHA512 = C_algo.SHA512; /** * SHA-384 hash algorithm. */ var SHA384 = C_algo.SHA384 = SHA512.extend({ _doReset: function () { this._hash = new X64WordArray.init([ new X64Word.init(0xcbbb9d5d, 0xc1059ed8), new X64Word.init(0x629a292a, 0x367cd507), new X64Word.init(0x9159015a, 0x3070dd17), new X64Word.init(0x152fecd8, 0xf70e5939), new X64Word.init(0x67332667, 0xffc00b31), new X64Word.init(0x8eb44a87, 0x68581511), new X64Word.init(0xdb0c2e0d, 0x64f98fa7), new X64Word.init(0x47b5481d, 0xbefa4fa4) ]); }, _doFinalize: function () { var hash = SHA512._doFinalize.call(this); hash.sigBytes -= 16; return hash; } }); /** * Shortcut function to the hasher's object interface. * * @param {WordArray|string} message The message to hash. * * @return {WordArray} The hash. * * @static * * @example * * var hash = CryptoJS.SHA384('message'); * var hash = CryptoJS.SHA384(wordArray); */ C.SHA384 = SHA512._createHelper(SHA384); /** * Shortcut function to the HMAC's object interface. * * @param {WordArray|string} message The message to hash. * @param {WordArray|string} key The secret key. * * @return {WordArray} The HMAC. * * @static * * @example * * var hmac = CryptoJS.HmacSHA384(message, key); */ C.HmacSHA384 = SHA512._createHmacHelper(SHA384); }()); return CryptoJS.SHA384; })); },{"./core":36,"./sha512":65,"./x64-core":67}],65:[function(_dereq_,module,exports){ ;(function (root, factory, undef) { if (typeof exports === "object") { // CommonJS module.exports = exports = factory(_dereq_("./core"), _dereq_("./x64-core")); } else if (typeof define === "function" && define.amd) { // AMD define(["./core", "./x64-core"], factory); } else { // Global (browser) factory(root.CryptoJS); } }(this, function (CryptoJS) { (function () { // Shortcuts var C = CryptoJS; var C_lib = C.lib; var Hasher = C_lib.Hasher; var C_x64 = C.x64; var X64Word = C_x64.Word; var X64WordArray = C_x64.WordArray; var C_algo = C.algo; function X64Word_create() { return X64Word.create.apply(X64Word, arguments); } // Constants var K = [ X64Word_create(0x428a2f98, 0xd728ae22), X64Word_create(0x71374491, 0x23ef65cd), X64Word_create(0xb5c0fbcf, 0xec4d3b2f), X64Word_create(0xe9b5dba5, 0x8189dbbc), X64Word_create(0x3956c25b, 0xf348b538), X64Word_create(0x59f111f1, 0xb605d019), X64Word_create(0x923f82a4, 0xaf194f9b), X64Word_create(0xab1c5ed5, 0xda6d8118), X64Word_create(0xd807aa98, 0xa3030242), X64Word_create(0x12835b01, 0x45706fbe), X64Word_create(0x243185be, 0x4ee4b28c), X64Word_create(0x550c7dc3, 0xd5ffb4e2), X64Word_create(0x72be5d74, 0xf27b896f), X64Word_create(0x80deb1fe, 0x3b1696b1), X64Word_create(0x9bdc06a7, 0x25c71235), X64Word_create(0xc19bf174, 0xcf692694), X64Word_create(0xe49b69c1, 0x9ef14ad2), X64Word_create(0xefbe4786, 0x384f25e3), X64Word_create(0x0fc19dc6, 0x8b8cd5b5), X64Word_create(0x240ca1cc, 0x77ac9c65), X64Word_create(0x2de92c6f, 0x592b0275), X64Word_create(0x4a7484aa, 0x6ea6e483), X64Word_create(0x5cb0a9dc, 0xbd41fbd4), X64Word_create(0x76f988da, 0x831153b5), X64Word_create(0x983e5152, 0xee66dfab), X64Word_create(0xa831c66d, 0x2db43210), X64Word_create(0xb00327c8, 0x98fb213f), X64Word_create(0xbf597fc7, 0xbeef0ee4), X64Word_create(0xc6e00bf3, 0x3da88fc2), X64Word_create(0xd5a79147, 0x930aa725), X64Word_create(0x06ca6351, 0xe003826f), X64Word_create(0x14292967, 0x0a0e6e70), X64Word_create(0x27b70a85, 0x46d22ffc), X64Word_create(0x2e1b2138, 0x5c26c926), X64Word_create(0x4d2c6dfc, 0x5ac42aed), X64Word_create(0x53380d13, 0x9d95b3df), X64Word_create(0x650a7354, 0x8baf63de), X64Word_create(0x766a0abb, 0x3c77b2a8), X64Word_create(0x81c2c92e, 0x47edaee6), X64Word_create(0x92722c85, 0x1482353b), X64Word_create(0xa2bfe8a1, 0x4cf10364), X64Word_create(0xa81a664b, 0xbc423001), X64Word_create(0xc24b8b70, 0xd0f89791), X64Word_create(0xc76c51a3, 0x0654be30), X64Word_create(0xd192e819, 0xd6ef5218), X64Word_create(0xd6990624, 0x5565a910), X64Word_create(0xf40e3585, 0x5771202a), X64Word_create(0x106aa070, 0x32bbd1b8), X64Word_create(0x19a4c116, 0xb8d2d0c8), X64Word_create(0x1e376c08, 0x5141ab53), X64Word_create(0x2748774c, 0xdf8eeb99), X64Word_create(0x34b0bcb5, 0xe19b48a8), X64Word_create(0x391c0cb3, 0xc5c95a63), X64Word_create(0x4ed8aa4a, 0xe3418acb), X64Word_create(0x5b9cca4f, 0x7763e373), X64Word_create(0x682e6ff3, 0xd6b2b8a3), X64Word_create(0x748f82ee, 0x5defb2fc), X64Word_create(0x78a5636f, 0x43172f60), X64Word_create(0x84c87814, 0xa1f0ab72), X64Word_create(0x8cc70208, 0x1a6439ec), X64Word_create(0x90befffa, 0x23631e28), X64Word_create(0xa4506ceb, 0xde82bde9), X64Word_create(0xbef9a3f7, 0xb2c67915), X64Word_create(0xc67178f2, 0xe372532b), X64Word_create(0xca273ece, 0xea26619c), X64Word_create(0xd186b8c7, 0x21c0c207), X64Word_create(0xeada7dd6, 0xcde0eb1e), X64Word_create(0xf57d4f7f, 0xee6ed178), X64Word_create(0x06f067aa, 0x72176fba), X64Word_create(0x0a637dc5, 0xa2c898a6), X64Word_create(0x113f9804, 0xbef90dae), X64Word_create(0x1b710b35, 0x131c471b), X64Word_create(0x28db77f5, 0x23047d84), X64Word_create(0x32caab7b, 0x40c72493), X64Word_create(0x3c9ebe0a, 0x15c9bebc), X64Word_create(0x431d67c4, 0x9c100d4c), X64Word_create(0x4cc5d4be, 0xcb3e42b6), X64Word_create(0x597f299c, 0xfc657e2a), X64Word_create(0x5fcb6fab, 0x3ad6faec), X64Word_create(0x6c44198c, 0x4a475817) ]; // Reusable objects var W = []; (function () { for (var i = 0; i < 80; i++) { W[i] = X64Word_create(); } }()); /** * SHA-512 hash algorithm. */ var SHA512 = C_algo.SHA512 = Hasher.extend({ _doReset: function () { this._hash = new X64WordArray.init([ new X64Word.init(0x6a09e667, 0xf3bcc908), new X64Word.init(0xbb67ae85, 0x84caa73b), new X64Word.init(0x3c6ef372, 0xfe94f82b), new X64Word.init(0xa54ff53a, 0x5f1d36f1), new X64Word.init(0x510e527f, 0xade682d1), new X64Word.init(0x9b05688c, 0x2b3e6c1f), new X64Word.init(0x1f83d9ab, 0xfb41bd6b), new X64Word.init(0x5be0cd19, 0x137e2179) ]); }, _doProcessBlock: function (M, offset) { // Shortcuts var H = this._hash.words; var H0 = H[0]; var H1 = H[1]; var H2 = H[2]; var H3 = H[3]; var H4 = H[4]; var H5 = H[5]; var H6 = H[6]; var H7 = H[7]; var H0h = H0.high; var H0l = H0.low; var H1h = H1.high; var H1l = H1.low; var H2h = H2.high; var H2l = H2.low; var H3h = H3.high; var H3l = H3.low; var H4h = H4.high; var H4l = H4.low; var H5h = H5.high; var H5l = H5.low; var H6h = H6.high; var H6l = H6.low; var H7h = H7.high; var H7l = H7.low; // Working variables var ah = H0h; var al = H0l; var bh = H1h; var bl = H1l; var ch = H2h; var cl = H2l; var dh = H3h; var dl = H3l; var eh = H4h; var el = H4l; var fh = H5h; var fl = H5l; var gh = H6h; var gl = H6l; var hh = H7h; var hl = H7l; // Rounds for (var i = 0; i < 80; i++) { // Shortcut var Wi = W[i]; // Extend message if (i < 16) { var Wih = Wi.high = M[offset + i * 2] | 0; var Wil = Wi.low = M[offset + i * 2 + 1] | 0; } else { // Gamma0 var gamma0x = W[i - 15]; var gamma0xh = gamma0x.high; var gamma0xl = gamma0x.low; var gamma0h = ((gamma0xh >>> 1) | (gamma0xl << 31)) ^ ((gamma0xh >>> 8) | (gamma0xl << 24)) ^ (gamma0xh >>> 7); var gamma0l = ((gamma0xl >>> 1) | (gamma0xh << 31)) ^ ((gamma0xl >>> 8) | (gamma0xh << 24)) ^ ((gamma0xl >>> 7) | (gamma0xh << 25)); // Gamma1 var gamma1x = W[i - 2]; var gamma1xh = gamma1x.high; var gamma1xl = gamma1x.low; var gamma1h = ((gamma1xh >>> 19) | (gamma1xl << 13)) ^ ((gamma1xh << 3) | (gamma1xl >>> 29)) ^ (gamma1xh >>> 6); var gamma1l = ((gamma1xl >>> 19) | (gamma1xh << 13)) ^ ((gamma1xl << 3) | (gamma1xh >>> 29)) ^ ((gamma1xl >>> 6) | (gamma1xh << 26)); // W[i] = gamma0 + W[i - 7] + gamma1 + W[i - 16] var Wi7 = W[i - 7]; var Wi7h = Wi7.high; var Wi7l = Wi7.low; var Wi16 = W[i - 16]; var Wi16h = Wi16.high; var Wi16l = Wi16.low; var Wil = gamma0l + Wi7l; var Wih = gamma0h + Wi7h + ((Wil >>> 0) < (gamma0l >>> 0) ? 1 : 0); var Wil = Wil + gamma1l; var Wih = Wih + gamma1h + ((Wil >>> 0) < (gamma1l >>> 0) ? 1 : 0); var Wil = Wil + Wi16l; var Wih = Wih + Wi16h + ((Wil >>> 0) < (Wi16l >>> 0) ? 1 : 0); Wi.high = Wih; Wi.low = Wil; } var chh = (eh & fh) ^ (~eh & gh); var chl = (el & fl) ^ (~el & gl); var majh = (ah & bh) ^ (ah & ch) ^ (bh & ch); var majl = (al & bl) ^ (al & cl) ^ (bl & cl); var sigma0h = ((ah >>> 28) | (al << 4)) ^ ((ah << 30) | (al >>> 2)) ^ ((ah << 25) | (al >>> 7)); var sigma0l = ((al >>> 28) | (ah << 4)) ^ ((al << 30) | (ah >>> 2)) ^ ((al << 25) | (ah >>> 7)); var sigma1h = ((eh >>> 14) | (el << 18)) ^ ((eh >>> 18) | (el << 14)) ^ ((eh << 23) | (el >>> 9)); var sigma1l = ((el >>> 14) | (eh << 18)) ^ ((el >>> 18) | (eh << 14)) ^ ((el << 23) | (eh >>> 9)); // t1 = h + sigma1 + ch + K[i] + W[i] var Ki = K[i]; var Kih = Ki.high; var Kil = Ki.low; var t1l = hl + sigma1l; var t1h = hh + sigma1h + ((t1l >>> 0) < (hl >>> 0) ? 1 : 0); var t1l = t1l + chl; var t1h = t1h + chh + ((t1l >>> 0) < (chl >>> 0) ? 1 : 0); var t1l = t1l + Kil; var t1h = t1h + Kih + ((t1l >>> 0) < (Kil >>> 0) ? 1 : 0); var t1l = t1l + Wil; var t1h = t1h + Wih + ((t1l >>> 0) < (Wil >>> 0) ? 1 : 0); // t2 = sigma0 + maj var t2l = sigma0l + majl; var t2h = sigma0h + majh + ((t2l >>> 0) < (sigma0l >>> 0) ? 1 : 0); // Update working variables hh = gh; hl = gl; gh = fh; gl = fl; fh = eh; fl = el; el = (dl + t1l) | 0; eh = (dh + t1h + ((el >>> 0) < (dl >>> 0) ? 1 : 0)) | 0; dh = ch; dl = cl; ch = bh; cl = bl; bh = ah; bl = al; al = (t1l + t2l) | 0; ah = (t1h + t2h + ((al >>> 0) < (t1l >>> 0) ? 1 : 0)) | 0; } // Intermediate hash value H0l = H0.low = (H0l + al); H0.high = (H0h + ah + ((H0l >>> 0) < (al >>> 0) ? 1 : 0)); H1l = H1.low = (H1l + bl); H1.high = (H1h + bh + ((H1l >>> 0) < (bl >>> 0) ? 1 : 0)); H2l = H2.low = (H2l + cl); H2.high = (H2h + ch + ((H2l >>> 0) < (cl >>> 0) ? 1 : 0)); H3l = H3.low = (H3l + dl); H3.high = (H3h + dh + ((H3l >>> 0) < (dl >>> 0) ? 1 : 0)); H4l = H4.low = (H4l + el); H4.high = (H4h + eh + ((H4l >>> 0) < (el >>> 0) ? 1 : 0)); H5l = H5.low = (H5l + fl); H5.high = (H5h + fh + ((H5l >>> 0) < (fl >>> 0) ? 1 : 0)); H6l = H6.low = (H6l + gl); H6.high = (H6h + gh + ((H6l >>> 0) < (gl >>> 0) ? 1 : 0)); H7l = H7.low = (H7l + hl); H7.high = (H7h + hh + ((H7l >>> 0) < (hl >>> 0) ? 1 : 0)); }, _doFinalize: function () { // Shortcuts var data = this._data; var dataWords = data.words; var nBitsTotal = this._nDataBytes * 8; var nBitsLeft = data.sigBytes * 8; // Add padding dataWords[nBitsLeft >>> 5] |= 0x80 << (24 - nBitsLeft % 32); dataWords[(((nBitsLeft + 128) >>> 10) << 5) + 30] = Math.floor(nBitsTotal / 0x100000000); dataWords[(((nBitsLeft + 128) >>> 10) << 5) + 31] = nBitsTotal; data.sigBytes = dataWords.length * 4; // Hash final blocks this._process(); // Convert hash to 32-bit word array before returning var hash = this._hash.toX32(); // Return final computed hash return hash; }, clone: function () { var clone = Hasher.clone.call(this); clone._hash = this._hash.clone(); return clone; }, blockSize: 1024/32 }); /** * Shortcut function to the hasher's object interface. * * @param {WordArray|string} message The message to hash. * * @return {WordArray} The hash. * * @static * * @example * * var hash = CryptoJS.SHA512('message'); * var hash = CryptoJS.SHA512(wordArray); */ C.SHA512 = Hasher._createHelper(SHA512); /** * Shortcut function to the HMAC's object interface. * * @param {WordArray|string} message The message to hash. * @param {WordArray|string} key The secret key. * * @return {WordArray} The HMAC. * * @static * * @example * * var hmac = CryptoJS.HmacSHA512(message, key); */ C.HmacSHA512 = Hasher._createHmacHelper(SHA512); }()); return CryptoJS.SHA512; })); },{"./core":36,"./x64-core":67}],66:[function(_dereq_,module,exports){ ;(function (root, factory, undef) { if (typeof exports === "object") { // CommonJS module.exports = exports = factory(_dereq_("./core"), _dereq_("./enc-base64"), _dereq_("./md5"), _dereq_("./evpkdf"), _dereq_("./cipher-core")); } else if (typeof define === "function" && define.amd) { // AMD define(["./core", "./enc-base64", "./md5", "./evpkdf", "./cipher-core"], factory); } else { // Global (browser) factory(root.CryptoJS); } }(this, function (CryptoJS) { (function () { // Shortcuts var C = CryptoJS; var C_lib = C.lib; var WordArray = C_lib.WordArray; var BlockCipher = C_lib.BlockCipher; var C_algo = C.algo; // Permuted Choice 1 constants var PC1 = [ 57, 49, 41, 33, 25, 17, 9, 1, 58, 50, 42, 34, 26, 18, 10, 2, 59, 51, 43, 35, 27, 19, 11, 3, 60, 52, 44, 36, 63, 55, 47, 39, 31, 23, 15, 7, 62, 54, 46, 38, 30, 22, 14, 6, 61, 53, 45, 37, 29, 21, 13, 5, 28, 20, 12, 4 ]; // Permuted Choice 2 constants var PC2 = [ 14, 17, 11, 24, 1, 5, 3, 28, 15, 6, 21, 10, 23, 19, 12, 4, 26, 8, 16, 7, 27, 20, 13, 2, 41, 52, 31, 37, 47, 55, 30, 40, 51, 45, 33, 48, 44, 49, 39, 56, 34, 53, 46, 42, 50, 36, 29, 32 ]; // Cumulative bit shift constants var BIT_SHIFTS = [1, 2, 4, 6, 8, 10, 12, 14, 15, 17, 19, 21, 23, 25, 27, 28]; // SBOXes and round permutation constants var SBOX_P = [ { 0x0: 0x808200, 0x10000000: 0x8000, 0x20000000: 0x808002, 0x30000000: 0x2, 0x40000000: 0x200, 0x50000000: 0x808202, 0x60000000: 0x800202, 0x70000000: 0x800000, 0x80000000: 0x202, 0x90000000: 0x800200, 0xa0000000: 0x8200, 0xb0000000: 0x808000, 0xc0000000: 0x8002, 0xd0000000: 0x800002, 0xe0000000: 0x0, 0xf0000000: 0x8202, 0x8000000: 0x0, 0x18000000: 0x808202, 0x28000000: 0x8202, 0x38000000: 0x8000, 0x48000000: 0x808200, 0x58000000: 0x200, 0x68000000: 0x808002, 0x78000000: 0x2, 0x88000000: 0x800200, 0x98000000: 0x8200, 0xa8000000: 0x808000, 0xb8000000: 0x800202, 0xc8000000: 0x800002, 0xd8000000: 0x8002, 0xe8000000: 0x202, 0xf8000000: 0x800000, 0x1: 0x8000, 0x10000001: 0x2, 0x20000001: 0x808200, 0x30000001: 0x800000, 0x40000001: 0x808002, 0x50000001: 0x8200, 0x60000001: 0x200, 0x70000001: 0x800202, 0x80000001: 0x808202, 0x90000001: 0x808000, 0xa0000001: 0x800002, 0xb0000001: 0x8202, 0xc0000001: 0x202, 0xd0000001: 0x800200, 0xe0000001: 0x8002, 0xf0000001: 0x0, 0x8000001: 0x808202, 0x18000001: 0x808000, 0x28000001: 0x800000, 0x38000001: 0x200, 0x48000001: 0x8000, 0x58000001: 0x800002, 0x68000001: 0x2, 0x78000001: 0x8202, 0x88000001: 0x8002, 0x98000001: 0x800202, 0xa8000001: 0x202, 0xb8000001: 0x808200, 0xc8000001: 0x800200, 0xd8000001: 0x0, 0xe8000001: 0x8200, 0xf8000001: 0x808002 }, { 0x0: 0x40084010, 0x1000000: 0x4000, 0x2000000: 0x80000, 0x3000000: 0x40080010, 0x4000000: 0x40000010, 0x5000000: 0x40084000, 0x6000000: 0x40004000, 0x7000000: 0x10, 0x8000000: 0x84000, 0x9000000: 0x40004010, 0xa000000: 0x40000000, 0xb000000: 0x84010, 0xc000000: 0x80010, 0xd000000: 0x0, 0xe000000: 0x4010, 0xf000000: 0x40080000, 0x800000: 0x40004000, 0x1800000: 0x84010, 0x2800000: 0x10, 0x3800000: 0x40004010, 0x4800000: 0x40084010, 0x5800000: 0x40000000, 0x6800000: 0x80000, 0x7800000: 0x40080010, 0x8800000: 0x80010, 0x9800000: 0x0, 0xa800000: 0x4000, 0xb800000: 0x40080000, 0xc800000: 0x40000010, 0xd800000: 0x84000, 0xe800000: 0x40084000, 0xf800000: 0x4010, 0x10000000: 0x0, 0x11000000: 0x40080010, 0x12000000: 0x40004010, 0x13000000: 0x40084000, 0x14000000: 0x40080000, 0x15000000: 0x10, 0x16000000: 0x84010, 0x17000000: 0x4000, 0x18000000: 0x4010, 0x19000000: 0x80000, 0x1a000000: 0x80010, 0x1b000000: 0x40000010, 0x1c000000: 0x84000, 0x1d000000: 0x40004000, 0x1e000000: 0x40000000, 0x1f000000: 0x40084010, 0x10800000: 0x84010, 0x11800000: 0x80000, 0x12800000: 0x40080000, 0x13800000: 0x4000, 0x14800000: 0x40004000, 0x15800000: 0x40084010, 0x16800000: 0x10, 0x17800000: 0x40000000, 0x18800000: 0x40084000, 0x19800000: 0x40000010, 0x1a800000: 0x40004010, 0x1b800000: 0x80010, 0x1c800000: 0x0, 0x1d800000: 0x4010, 0x1e800000: 0x40080010, 0x1f800000: 0x84000 }, { 0x0: 0x104, 0x100000: 0x0, 0x200000: 0x4000100, 0x300000: 0x10104, 0x400000: 0x10004, 0x500000: 0x4000004, 0x600000: 0x4010104, 0x700000: 0x4010000, 0x800000: 0x4000000, 0x900000: 0x4010100, 0xa00000: 0x10100, 0xb00000: 0x4010004, 0xc00000: 0x4000104, 0xd00000: 0x10000, 0xe00000: 0x4, 0xf00000: 0x100, 0x80000: 0x4010100, 0x180000: 0x4010004, 0x280000: 0x0, 0x380000: 0x4000100, 0x480000: 0x4000004, 0x580000: 0x10000, 0x680000: 0x10004, 0x780000: 0x104, 0x880000: 0x4, 0x980000: 0x100, 0xa80000: 0x4010000, 0xb80000: 0x10104, 0xc80000: 0x10100, 0xd80000: 0x4000104, 0xe80000: 0x4010104, 0xf80000: 0x4000000, 0x1000000: 0x4010100, 0x1100000: 0x10004, 0x1200000: 0x10000, 0x1300000: 0x4000100, 0x1400000: 0x100, 0x1500000: 0x4010104, 0x1600000: 0x4000004, 0x1700000: 0x0, 0x1800000: 0x4000104, 0x1900000: 0x4000000, 0x1a00000: 0x4, 0x1b00000: 0x10100, 0x1c00000: 0x4010000, 0x1d00000: 0x104, 0x1e00000: 0x10104, 0x1f00000: 0x4010004, 0x1080000: 0x4000000, 0x1180000: 0x104, 0x1280000: 0x4010100, 0x1380000: 0x0, 0x1480000: 0x10004, 0x1580000: 0x4000100, 0x1680000: 0x100, 0x1780000: 0x4010004, 0x1880000: 0x10000, 0x1980000: 0x4010104, 0x1a80000: 0x10104, 0x1b80000: 0x4000004, 0x1c80000: 0x4000104, 0x1d80000: 0x4010000, 0x1e80000: 0x4, 0x1f80000: 0x10100 }, { 0x0: 0x80401000, 0x10000: 0x80001040, 0x20000: 0x401040, 0x30000: 0x80400000, 0x40000: 0x0, 0x50000: 0x401000, 0x60000: 0x80000040, 0x70000: 0x400040, 0x80000: 0x80000000, 0x90000: 0x400000, 0xa0000: 0x40, 0xb0000: 0x80001000, 0xc0000: 0x80400040, 0xd0000: 0x1040, 0xe0000: 0x1000, 0xf0000: 0x80401040, 0x8000: 0x80001040, 0x18000: 0x40, 0x28000: 0x80400040, 0x38000: 0x80001000, 0x48000: 0x401000, 0x58000: 0x80401040, 0x68000: 0x0, 0x78000: 0x80400000, 0x88000: 0x1000, 0x98000: 0x80401000, 0xa8000: 0x400000, 0xb8000: 0x1040, 0xc8000: 0x80000000, 0xd8000: 0x400040, 0xe8000: 0x401040, 0xf8000: 0x80000040, 0x100000: 0x400040, 0x110000: 0x401000, 0x120000: 0x80000040, 0x130000: 0x0, 0x140000: 0x1040, 0x150000: 0x80400040, 0x160000: 0x80401000, 0x170000: 0x80001040, 0x180000: 0x80401040, 0x190000: 0x80000000, 0x1a0000: 0x80400000, 0x1b0000: 0x401040, 0x1c0000: 0x80001000, 0x1d0000: 0x400000, 0x1e0000: 0x40, 0x1f0000: 0x1000, 0x108000: 0x80400000, 0x118000: 0x80401040, 0x128000: 0x0, 0x138000: 0x401000, 0x148000: 0x400040, 0x158000: 0x80000000, 0x168000: 0x80001040, 0x178000: 0x40, 0x188000: 0x80000040, 0x198000: 0x1000, 0x1a8000: 0x80001000, 0x1b8000: 0x80400040, 0x1c8000: 0x1040, 0x1d8000: 0x80401000, 0x1e8000: 0x400000, 0x1f8000: 0x401040 }, { 0x0: 0x80, 0x1000: 0x1040000, 0x2000: 0x40000, 0x3000: 0x20000000, 0x4000: 0x20040080, 0x5000: 0x1000080, 0x6000: 0x21000080, 0x7000: 0x40080, 0x8000: 0x1000000, 0x9000: 0x20040000, 0xa000: 0x20000080, 0xb000: 0x21040080, 0xc000: 0x21040000, 0xd000: 0x0, 0xe000: 0x1040080, 0xf000: 0x21000000, 0x800: 0x1040080, 0x1800: 0x21000080, 0x2800: 0x80, 0x3800: 0x1040000, 0x4800: 0x40000, 0x5800: 0x20040080, 0x6800: 0x21040000, 0x7800: 0x20000000, 0x8800: 0x20040000, 0x9800: 0x0, 0xa800: 0x21040080, 0xb800: 0x1000080, 0xc800: 0x20000080, 0xd800: 0x21000000, 0xe800: 0x1000000, 0xf800: 0x40080, 0x10000: 0x40000, 0x11000: 0x80, 0x12000: 0x20000000, 0x13000: 0x21000080, 0x14000: 0x1000080, 0x15000: 0x21040000, 0x16000: 0x20040080, 0x17000: 0x1000000, 0x18000: 0x21040080, 0x19000: 0x21000000, 0x1a000: 0x1040000, 0x1b000: 0x20040000, 0x1c000: 0x40080, 0x1d000: 0x20000080, 0x1e000: 0x0, 0x1f000: 0x1040080, 0x10800: 0x21000080, 0x11800: 0x1000000, 0x12800: 0x1040000, 0x13800: 0x20040080, 0x14800: 0x20000000, 0x15800: 0x1040080, 0x16800: 0x80, 0x17800: 0x21040000, 0x18800: 0x40080, 0x19800: 0x21040080, 0x1a800: 0x0, 0x1b800: 0x21000000, 0x1c800: 0x1000080, 0x1d800: 0x40000, 0x1e800: 0x20040000, 0x1f800: 0x20000080 }, { 0x0: 0x10000008, 0x100: 0x2000, 0x200: 0x10200000, 0x300: 0x10202008, 0x400: 0x10002000, 0x500: 0x200000, 0x600: 0x200008, 0x700: 0x10000000, 0x800: 0x0, 0x900: 0x10002008, 0xa00: 0x202000, 0xb00: 0x8, 0xc00: 0x10200008, 0xd00: 0x202008, 0xe00: 0x2008, 0xf00: 0x10202000, 0x80: 0x10200000, 0x180: 0x10202008, 0x280: 0x8, 0x380: 0x200000, 0x480: 0x202008, 0x580: 0x10000008, 0x680: 0x10002000, 0x780: 0x2008, 0x880: 0x200008, 0x980: 0x2000, 0xa80: 0x10002008, 0xb80: 0x10200008, 0xc80: 0x0, 0xd80: 0x10202000, 0xe80: 0x202000, 0xf80: 0x10000000, 0x1000: 0x10002000, 0x1100: 0x10200008, 0x1200: 0x10202008, 0x1300: 0x2008, 0x1400: 0x200000, 0x1500: 0x10000000, 0x1600: 0x10000008, 0x1700: 0x202000, 0x1800: 0x202008, 0x1900: 0x0, 0x1a00: 0x8, 0x1b00: 0x10200000, 0x1c00: 0x2000, 0x1d00: 0x10002008, 0x1e00: 0x10202000, 0x1f00: 0x200008, 0x1080: 0x8, 0x1180: 0x202000, 0x1280: 0x200000, 0x1380: 0x10000008, 0x1480: 0x10002000, 0x1580: 0x2008, 0x1680: 0x10202008, 0x1780: 0x10200000, 0x1880: 0x10202000, 0x1980: 0x10200008, 0x1a80: 0x2000, 0x1b80: 0x202008, 0x1c80: 0x200008, 0x1d80: 0x0, 0x1e80: 0x10000000, 0x1f80: 0x10002008 }, { 0x0: 0x100000, 0x10: 0x2000401, 0x20: 0x400, 0x30: 0x100401, 0x40: 0x2100401, 0x50: 0x0, 0x60: 0x1, 0x70: 0x2100001, 0x80: 0x2000400, 0x90: 0x100001, 0xa0: 0x2000001, 0xb0: 0x2100400, 0xc0: 0x2100000, 0xd0: 0x401, 0xe0: 0x100400, 0xf0: 0x2000000, 0x8: 0x2100001, 0x18: 0x0, 0x28: 0x2000401, 0x38: 0x2100400, 0x48: 0x100000, 0x58: 0x2000001, 0x68: 0x2000000, 0x78: 0x401, 0x88: 0x100401, 0x98: 0x2000400, 0xa8: 0x2100000, 0xb8: 0x100001, 0xc8: 0x400, 0xd8: 0x2100401, 0xe8: 0x1, 0xf8: 0x100400, 0x100: 0x2000000, 0x110: 0x100000, 0x120: 0x2000401, 0x130: 0x2100001, 0x140: 0x100001, 0x150: 0x2000400, 0x160: 0x2100400, 0x170: 0x100401, 0x180: 0x401, 0x190: 0x2100401, 0x1a0: 0x100400, 0x1b0: 0x1, 0x1c0: 0x0, 0x1d0: 0x2100000, 0x1e0: 0x2000001, 0x1f0: 0x400, 0x108: 0x100400, 0x118: 0x2000401, 0x128: 0x2100001, 0x138: 0x1, 0x148: 0x2000000, 0x158: 0x100000, 0x168: 0x401, 0x178: 0x2100400, 0x188: 0x2000001, 0x198: 0x2100000, 0x1a8: 0x0, 0x1b8: 0x2100401, 0x1c8: 0x100401, 0x1d8: 0x400, 0x1e8: 0x2000400, 0x1f8: 0x100001 }, { 0x0: 0x8000820, 0x1: 0x20000, 0x2: 0x8000000, 0x3: 0x20, 0x4: 0x20020, 0x5: 0x8020820, 0x6: 0x8020800, 0x7: 0x800, 0x8: 0x8020000, 0x9: 0x8000800, 0xa: 0x20800, 0xb: 0x8020020, 0xc: 0x820, 0xd: 0x0, 0xe: 0x8000020, 0xf: 0x20820, 0x80000000: 0x800, 0x80000001: 0x8020820, 0x80000002: 0x8000820, 0x80000003: 0x8000000, 0x80000004: 0x8020000, 0x80000005: 0x20800, 0x80000006: 0x20820, 0x80000007: 0x20, 0x80000008: 0x8000020, 0x80000009: 0x820, 0x8000000a: 0x20020, 0x8000000b: 0x8020800, 0x8000000c: 0x0, 0x8000000d: 0x8020020, 0x8000000e: 0x8000800, 0x8000000f: 0x20000, 0x10: 0x20820, 0x11: 0x8020800, 0x12: 0x20, 0x13: 0x800, 0x14: 0x8000800, 0x15: 0x8000020, 0x16: 0x8020020, 0x17: 0x20000, 0x18: 0x0, 0x19: 0x20020, 0x1a: 0x8020000, 0x1b: 0x8000820, 0x1c: 0x8020820, 0x1d: 0x20800, 0x1e: 0x820, 0x1f: 0x8000000, 0x80000010: 0x20000, 0x80000011: 0x800, 0x80000012: 0x8020020, 0x80000013: 0x20820, 0x80000014: 0x20, 0x80000015: 0x8020000, 0x80000016: 0x8000000, 0x80000017: 0x8000820, 0x80000018: 0x8020820, 0x80000019: 0x8000020, 0x8000001a: 0x8000800, 0x8000001b: 0x0, 0x8000001c: 0x20800, 0x8000001d: 0x820, 0x8000001e: 0x20020, 0x8000001f: 0x8020800 } ]; // Masks that select the SBOX input var SBOX_MASK = [ 0xf8000001, 0x1f800000, 0x01f80000, 0x001f8000, 0x0001f800, 0x00001f80, 0x000001f8, 0x8000001f ]; /** * DES block cipher algorithm. */ var DES = C_algo.DES = BlockCipher.extend({ _doReset: function () { // Shortcuts var key = this._key; var keyWords = key.words; // Select 56 bits according to PC1 var keyBits = []; for (var i = 0; i < 56; i++) { var keyBitPos = PC1[i] - 1; keyBits[i] = (keyWords[keyBitPos >>> 5] >>> (31 - keyBitPos % 32)) & 1; } // Assemble 16 subkeys var subKeys = this._subKeys = []; for (var nSubKey = 0; nSubKey < 16; nSubKey++) { // Create subkey var subKey = subKeys[nSubKey] = []; // Shortcut var bitShift = BIT_SHIFTS[nSubKey]; // Select 48 bits according to PC2 for (var i = 0; i < 24; i++) { // Select from the left 28 key bits subKey[(i / 6) | 0] |= keyBits[((PC2[i] - 1) + bitShift) % 28] << (31 - i % 6); // Select from the right 28 key bits subKey[4 + ((i / 6) | 0)] |= keyBits[28 + (((PC2[i + 24] - 1) + bitShift) % 28)] << (31 - i % 6); } // Since each subkey is applied to an expanded 32-bit input, // the subkey can be broken into 8 values scaled to 32-bits, // which allows the key to be used without expansion subKey[0] = (subKey[0] << 1) | (subKey[0] >>> 31); for (var i = 1; i < 7; i++) { subKey[i] = subKey[i] >>> ((i - 1) * 4 + 3); } subKey[7] = (subKey[7] << 5) | (subKey[7] >>> 27); } // Compute inverse subkeys var invSubKeys = this._invSubKeys = []; for (var i = 0; i < 16; i++) { invSubKeys[i] = subKeys[15 - i]; } }, encryptBlock: function (M, offset) { this._doCryptBlock(M, offset, this._subKeys); }, decryptBlock: function (M, offset) { this._doCryptBlock(M, offset, this._invSubKeys); }, _doCryptBlock: function (M, offset, subKeys) { // Get input this._lBlock = M[offset]; this._rBlock = M[offset + 1]; // Initial permutation exchangeLR.call(this, 4, 0x0f0f0f0f); exchangeLR.call(this, 16, 0x0000ffff); exchangeRL.call(this, 2, 0x33333333); exchangeRL.call(this, 8, 0x00ff00ff); exchangeLR.call(this, 1, 0x55555555); // Rounds for (var round = 0; round < 16; round++) { // Shortcuts var subKey = subKeys[round]; var lBlock = this._lBlock; var rBlock = this._rBlock; // Feistel function var f = 0; for (var i = 0; i < 8; i++) { f |= SBOX_P[i][((rBlock ^ subKey[i]) & SBOX_MASK[i]) >>> 0]; } this._lBlock = rBlock; this._rBlock = lBlock ^ f; } // Undo swap from last round var t = this._lBlock; this._lBlock = this._rBlock; this._rBlock = t; // Final permutation exchangeLR.call(this, 1, 0x55555555); exchangeRL.call(this, 8, 0x00ff00ff); exchangeRL.call(this, 2, 0x33333333); exchangeLR.call(this, 16, 0x0000ffff); exchangeLR.call(this, 4, 0x0f0f0f0f); // Set output M[offset] = this._lBlock; M[offset + 1] = this._rBlock; }, keySize: 64/32, ivSize: 64/32, blockSize: 64/32 }); // Swap bits across the left and right words function exchangeLR(offset, mask) { var t = ((this._lBlock >>> offset) ^ this._rBlock) & mask; this._rBlock ^= t; this._lBlock ^= t << offset; } function exchangeRL(offset, mask) { var t = ((this._rBlock >>> offset) ^ this._lBlock) & mask; this._lBlock ^= t; this._rBlock ^= t << offset; } /** * Shortcut functions to the cipher's object interface. * * @example * * var ciphertext = CryptoJS.DES.encrypt(message, key, cfg); * var plaintext = CryptoJS.DES.decrypt(ciphertext, key, cfg); */ C.DES = BlockCipher._createHelper(DES); /** * Triple-DES block cipher algorithm. */ var TripleDES = C_algo.TripleDES = BlockCipher.extend({ _doReset: function () { // Shortcuts var key = this._key; var keyWords = key.words; // Create DES instances this._des1 = DES.createEncryptor(WordArray.create(keyWords.slice(0, 2))); this._des2 = DES.createEncryptor(WordArray.create(keyWords.slice(2, 4))); this._des3 = DES.createEncryptor(WordArray.create(keyWords.slice(4, 6))); }, encryptBlock: function (M, offset) { this._des1.encryptBlock(M, offset); this._des2.decryptBlock(M, offset); this._des3.encryptBlock(M, offset); }, decryptBlock: function (M, offset) { this._des3.decryptBlock(M, offset); this._des2.encryptBlock(M, offset); this._des1.decryptBlock(M, offset); }, keySize: 192/32, ivSize: 64/32, blockSize: 64/32 }); /** * Shortcut functions to the cipher's object interface. * * @example * * var ciphertext = CryptoJS.TripleDES.encrypt(message, key, cfg); * var plaintext = CryptoJS.TripleDES.decrypt(ciphertext, key, cfg); */ C.TripleDES = BlockCipher._createHelper(TripleDES); }()); return CryptoJS.TripleDES; })); },{"./cipher-core":35,"./core":36,"./enc-base64":37,"./evpkdf":39,"./md5":44}],67:[function(_dereq_,module,exports){ ;(function (root, factory) { if (typeof exports === "object") { // CommonJS module.exports = exports = factory(_dereq_("./core")); } else if (typeof define === "function" && define.amd) { // AMD define(["./core"], factory); } else { // Global (browser) factory(root.CryptoJS); } }(this, function (CryptoJS) { (function (undefined) { // Shortcuts var C = CryptoJS; var C_lib = C.lib; var Base = C_lib.Base; var X32WordArray = C_lib.WordArray; /** * x64 namespace. */ var C_x64 = C.x64 = {}; /** * A 64-bit word. */ var X64Word = C_x64.Word = Base.extend({ /** * Initializes a newly created 64-bit word. * * @param {number} high The high 32 bits. * @param {number} low The low 32 bits. * * @example * * var x64Word = CryptoJS.x64.Word.create(0x00010203, 0x04050607); */ init: function (high, low) { this.high = high; this.low = low; } /** * Bitwise NOTs this word. * * @return {X64Word} A new x64-Word object after negating. * * @example * * var negated = x64Word.not(); */ // not: function () { // var high = ~this.high; // var low = ~this.low; // return X64Word.create(high, low); // }, /** * Bitwise ANDs this word with the passed word. * * @param {X64Word} word The x64-Word to AND with this word. * * @return {X64Word} A new x64-Word object after ANDing. * * @example * * var anded = x64Word.and(anotherX64Word); */ // and: function (word) { // var high = this.high & word.high; // var low = this.low & word.low; // return X64Word.create(high, low); // }, /** * Bitwise ORs this word with the passed word. * * @param {X64Word} word The x64-Word to OR with this word. * * @return {X64Word} A new x64-Word object after ORing. * * @example * * var ored = x64Word.or(anotherX64Word); */ // or: function (word) { // var high = this.high | word.high; // var low = this.low | word.low; // return X64Word.create(high, low); // }, /** * Bitwise XORs this word with the passed word. * * @param {X64Word} word The x64-Word to XOR with this word. * * @return {X64Word} A new x64-Word object after XORing. * * @example * * var xored = x64Word.xor(anotherX64Word); */ // xor: function (word) { // var high = this.high ^ word.high; // var low = this.low ^ word.low; // return X64Word.create(high, low); // }, /** * Shifts this word n bits to the left. * * @param {number} n The number of bits to shift. * * @return {X64Word} A new x64-Word object after shifting. * * @example * * var shifted = x64Word.shiftL(25); */ // shiftL: function (n) { // if (n < 32) { // var high = (this.high << n) | (this.low >>> (32 - n)); // var low = this.low << n; // } else { // var high = this.low << (n - 32); // var low = 0; // } // return X64Word.create(high, low); // }, /** * Shifts this word n bits to the right. * * @param {number} n The number of bits to shift. * * @return {X64Word} A new x64-Word object after shifting. * * @example * * var shifted = x64Word.shiftR(7); */ // shiftR: function (n) { // if (n < 32) { // var low = (this.low >>> n) | (this.high << (32 - n)); // var high = this.high >>> n; // } else { // var low = this.high >>> (n - 32); // var high = 0; // } // return X64Word.create(high, low); // }, /** * Rotates this word n bits to the left. * * @param {number} n The number of bits to rotate. * * @return {X64Word} A new x64-Word object after rotating. * * @example * * var rotated = x64Word.rotL(25); */ // rotL: function (n) { // return this.shiftL(n).or(this.shiftR(64 - n)); // }, /** * Rotates this word n bits to the right. * * @param {number} n The number of bits to rotate. * * @return {X64Word} A new x64-Word object after rotating. * * @example * * var rotated = x64Word.rotR(7); */ // rotR: function (n) { // return this.shiftR(n).or(this.shiftL(64 - n)); // }, /** * Adds this word with the passed word. * * @param {X64Word} word The x64-Word to add with this word. * * @return {X64Word} A new x64-Word object after adding. * * @example * * var added = x64Word.add(anotherX64Word); */ // add: function (word) { // var low = (this.low + word.low) | 0; // var carry = (low >>> 0) < (this.low >>> 0) ? 1 : 0; // var high = (this.high + word.high + carry) | 0; // return X64Word.create(high, low); // } }); /** * An array of 64-bit words. * * @property {Array} words The array of CryptoJS.x64.Word objects. * @property {number} sigBytes The number of significant bytes in this word array. */ var X64WordArray = C_x64.WordArray = Base.extend({ /** * Initializes a newly created word array. * * @param {Array} words (Optional) An array of CryptoJS.x64.Word objects. * @param {number} sigBytes (Optional) The number of significant bytes in the words. * * @example * * var wordArray = CryptoJS.x64.WordArray.create(); * * var wordArray = CryptoJS.x64.WordArray.create([ * CryptoJS.x64.Word.create(0x00010203, 0x04050607), * CryptoJS.x64.Word.create(0x18191a1b, 0x1c1d1e1f) * ]); * * var wordArray = CryptoJS.x64.WordArray.create([ * CryptoJS.x64.Word.create(0x00010203, 0x04050607), * CryptoJS.x64.Word.create(0x18191a1b, 0x1c1d1e1f) * ], 10); */ init: function (words, sigBytes) { words = this.words = words || []; if (sigBytes != undefined) { this.sigBytes = sigBytes; } else { this.sigBytes = words.length * 8; } }, /** * Converts this 64-bit word array to a 32-bit word array. * * @return {CryptoJS.lib.WordArray} This word array's data as a 32-bit word array. * * @example * * var x32WordArray = x64WordArray.toX32(); */ toX32: function () { // Shortcuts var x64Words = this.words; var x64WordsLength = x64Words.length; // Convert var x32Words = []; for (var i = 0; i < x64WordsLength; i++) { var x64Word = x64Words[i]; x32Words.push(x64Word.high); x32Words.push(x64Word.low); } return X32WordArray.create(x32Words, this.sigBytes); }, /** * Creates a copy of this word array. * * @return {X64WordArray} The clone. * * @example * * var clone = x64WordArray.clone(); */ clone: function () { var clone = Base.clone.call(this); // Clone "words" array var words = clone.words = this.words.slice(0); // Clone each X64Word object var wordsLength = words.length; for (var i = 0; i < wordsLength; i++) { words[i] = words[i].clone(); } return clone; } }); }()); return CryptoJS; })); },{"./core":36}],68:[function(_dereq_,module,exports){ // shim for using process in browser var process = module.exports = {}; var queue = []; var draining = false; var currentQueue; var queueIndex = -1; function cleanUpNextTick() { 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; }; },{}],69:[function(_dereq_,module,exports){ (function (process,global){ /*! localForage -- Offline Storage, Improved Version 1.3.0 https://mozilla.github.io/localForage (c) 2013-2015 Mozilla, Apache License 2.0 */ (function() { var define, requireModule, _dereq_, requirejs; (function() { var registry = {}, seen = {}; define = function(name, deps, callback) { registry[name] = { deps: deps, callback: callback }; }; requirejs = _dereq_ = requireModule = function(name) { requirejs._eak_seen = registry; if (seen[name]) { return seen[name]; } seen[name] = {}; if (!registry[name]) { throw new Error("Could not find module " + name); } var mod = registry[name], deps = mod.deps, callback = mod.callback, reified = [], exports; for (var i=0, l=deps.length; i<l; i++) { if (deps[i] === 'exports') { reified.push(exports = {}); } else { reified.push(requireModule(resolve(deps[i]))); } } var value = callback.apply(this, reified); return seen[name] = exports || value; function resolve(child) { if (child.charAt(0) !== '.') { return child; } var parts = child.split("/"); var parentBase = name.split("/").slice(0, -1); for (var i=0, l=parts.length; i<l; i++) { var part = parts[i]; if (part === '..') { parentBase.pop(); } else if (part === '.') { continue; } else { parentBase.push(part); } } return parentBase.join("/"); } }; })(); define("promise/all", ["./utils","exports"], function(__dependency1__, __exports__) { "use strict"; /* global toString */ var isArray = __dependency1__.isArray; var isFunction = __dependency1__.isFunction; /** Returns a promise that is fulfilled when all the given promises have been fulfilled, or rejected if any of them become rejected. The return promise is fulfilled with an array that gives all the values in the order they were passed in the `promises` array argument. Example: ```javascript var promise1 = RSVP.resolve(1); var promise2 = RSVP.resolve(2); var promise3 = RSVP.resolve(3); var promises = [ promise1, promise2, promise3 ]; RSVP.all(promises).then(function(array){ // The array here would be [ 1, 2, 3 ]; }); ``` If any of the `promises` given to `RSVP.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 var promise1 = RSVP.resolve(1); var promise2 = RSVP.reject(new Error("2")); var promise3 = RSVP.reject(new Error("3")); var promises = [ promise1, promise2, promise3 ]; RSVP.all(promises).then(function(array){ // Code here never runs because there are rejected promises! }, function(error) { // error.message === "2" }); ``` @method all @for RSVP @param {Array} promises @param {String} label @return {Promise} promise that is fulfilled when all `promises` have been fulfilled, or rejected if any of them become rejected. */ function all(promises) { /*jshint validthis:true */ var Promise = this; if (!isArray(promises)) { throw new TypeError('You must pass an array to all.'); } return new Promise(function(resolve, reject) { var results = [], remaining = promises.length, promise; if (remaining === 0) { resolve([]); } function resolver(index) { return function(value) { resolveAll(index, value); }; } function resolveAll(index, value) { results[index] = value; if (--remaining === 0) { resolve(results); } } for (var i = 0; i < promises.length; i++) { promise = promises[i]; if (promise && isFunction(promise.then)) { promise.then(resolver(i), reject); } else { resolveAll(i, promise); } } }); } __exports__.all = all; }); define("promise/asap", ["exports"], function(__exports__) { "use strict"; var browserGlobal = (typeof window !== 'undefined') ? window : {}; var BrowserMutationObserver = browserGlobal.MutationObserver || browserGlobal.WebKitMutationObserver; var local = (typeof global !== 'undefined') ? global : (this === undefined? window:this); // node function useNextTick() { return function() { process.nextTick(flush); }; } 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); }; } function useSetTimeout() { return function() { local.setTimeout(flush, 1); }; } var queue = []; function flush() { for (var i = 0; i < queue.length; i++) { var tuple = queue[i]; var callback = tuple[0], arg = tuple[1]; callback(arg); } queue = []; } var scheduleFlush; // Decide what async method to use to triggering processing of queued callbacks: if (typeof process !== 'undefined' && {}.toString.call(process) === '[object process]') { scheduleFlush = useNextTick(); } else if (BrowserMutationObserver) { scheduleFlush = useMutationObserver(); } else { scheduleFlush = useSetTimeout(); } function asap(callback, arg) { var length = queue.push([callback, arg]); if (length === 1) { // If length is 1, 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. scheduleFlush(); } } __exports__.asap = asap; }); define("promise/config", ["exports"], function(__exports__) { "use strict"; var config = { instrument: false }; function configure(name, value) { if (arguments.length === 2) { config[name] = value; } else { return config[name]; } } __exports__.config = config; __exports__.configure = configure; }); define("promise/polyfill", ["./promise","./utils","exports"], function(__dependency1__, __dependency2__, __exports__) { "use strict"; /*global self*/ var RSVPPromise = __dependency1__.Promise; var isFunction = __dependency2__.isFunction; function polyfill() { var local; if (typeof global !== 'undefined') { local = global; } else if (typeof window !== 'undefined' && window.document) { local = window; } else { local = self; } var es6PromiseSupport = "Promise" in local && // Some of these methods are missing from // Firefox/Chrome experimental implementations "resolve" in local.Promise && "reject" in local.Promise && "all" in local.Promise && "race" in local.Promise && // Older version of the spec had a resolver object // as the arg rather than a function (function() { var resolve; new local.Promise(function(r) { resolve = r; }); return isFunction(resolve); }()); if (!es6PromiseSupport) { local.Promise = RSVPPromise; } } __exports__.polyfill = polyfill; }); define("promise/promise", ["./config","./utils","./all","./race","./resolve","./reject","./asap","exports"], function(__dependency1__, __dependency2__, __dependency3__, __dependency4__, __dependency5__, __dependency6__, __dependency7__, __exports__) { "use strict"; var config = __dependency1__.config; var configure = __dependency1__.configure; var objectOrFunction = __dependency2__.objectOrFunction; var isFunction = __dependency2__.isFunction; var now = __dependency2__.now; var all = __dependency3__.all; var race = __dependency4__.race; var staticResolve = __dependency5__.resolve; var staticReject = __dependency6__.reject; var asap = __dependency7__.asap; var counter = 0; config.async = asap; // default async is asap; function Promise(resolver) { if (!isFunction(resolver)) { throw new TypeError('You must pass a resolver function as the first argument to the promise constructor'); } if (!(this instanceof Promise)) { throw new TypeError("Failed to construct 'Promise': Please use the 'new' operator, this object constructor cannot be called as a function."); } this._subscribers = []; invokeResolver(resolver, this); } function invokeResolver(resolver, promise) { function resolvePromise(value) { resolve(promise, value); } function rejectPromise(reason) { reject(promise, reason); } try { resolver(resolvePromise, rejectPromise); } catch(e) { rejectPromise(e); } } function invokeCallback(settled, promise, callback, detail) { var hasCallback = isFunction(callback), value, error, succeeded, failed; if (hasCallback) { try { value = callback(detail); succeeded = true; } catch(e) { failed = true; error = e; } } else { value = detail; succeeded = true; } if (handleThenable(promise, value)) { return; } else if (hasCallback && succeeded) { resolve(promise, value); } else if (failed) { reject(promise, error); } else if (settled === FULFILLED) { resolve(promise, value); } else if (settled === REJECTED) { reject(promise, value); } } var PENDING = void 0; var SEALED = 0; var FULFILLED = 1; var REJECTED = 2; function subscribe(parent, child, onFulfillment, onRejection) { var subscribers = parent._subscribers; var length = subscribers.length; subscribers[length] = child; subscribers[length + FULFILLED] = onFulfillment; subscribers[length + REJECTED] = onRejection; } function publish(promise, settled) { var child, callback, subscribers = promise._subscribers, detail = promise._detail; for (var i = 0; i < subscribers.length; i += 3) { child = subscribers[i]; callback = subscribers[i + settled]; invokeCallback(settled, child, callback, detail); } promise._subscribers = null; } Promise.prototype = { constructor: Promise, _state: undefined, _detail: undefined, _subscribers: undefined, then: function(onFulfillment, onRejection) { var promise = this; var thenPromise = new this.constructor(function() {}); if (this._state) { var callbacks = arguments; config.async(function invokePromiseCallback() { invokeCallback(promise._state, thenPromise, callbacks[promise._state - 1], promise._detail); }); } else { subscribe(this, thenPromise, onFulfillment, onRejection); } return thenPromise; }, 'catch': function(onRejection) { return this.then(null, onRejection); } }; Promise.all = all; Promise.race = race; Promise.resolve = staticResolve; Promise.reject = staticReject; function handleThenable(promise, value) { var then = null, resolved; try { if (promise === value) { throw new TypeError("A promises callback cannot return that same promise."); } if (objectOrFunction(value)) { then = value.then; if (isFunction(then)) { then.call(value, function(val) { if (resolved) { return true; } resolved = true; if (value !== val) { resolve(promise, val); } else { fulfill(promise, val); } }, function(val) { if (resolved) { return true; } resolved = true; reject(promise, val); }); return true; } } } catch (error) { if (resolved) { return true; } reject(promise, error); return true; } return false; } function resolve(promise, value) { if (promise === value) { fulfill(promise, value); } else if (!handleThenable(promise, value)) { fulfill(promise, value); } } function fulfill(promise, value) { if (promise._state !== PENDING) { return; } promise._state = SEALED; promise._detail = value; config.async(publishFulfillment, promise); } function reject(promise, reason) { if (promise._state !== PENDING) { return; } promise._state = SEALED; promise._detail = reason; config.async(publishRejection, promise); } function publishFulfillment(promise) { publish(promise, promise._state = FULFILLED); } function publishRejection(promise) { publish(promise, promise._state = REJECTED); } __exports__.Promise = Promise; }); define("promise/race", ["./utils","exports"], function(__dependency1__, __exports__) { "use strict"; /* global toString */ var isArray = __dependency1__.isArray; /** `RSVP.race` allows you to watch a series of promises and act as soon as the first promise given to the `promises` argument fulfills or rejects. Example: ```javascript var promise1 = new RSVP.Promise(function(resolve, reject){ setTimeout(function(){ resolve("promise 1"); }, 200); }); var promise2 = new RSVP.Promise(function(resolve, reject){ setTimeout(function(){ resolve("promise 2"); }, 100); }); RSVP.race([promise1, promise2]).then(function(result){ // result === "promise 2" because it was resolved before promise1 // was resolved. }); ``` `RSVP.race` is deterministic in that only the state of the first completed promise matters. For example, even if other promises given to the `promises` array argument are resolved, but the first completed promise has become rejected before the other promises became fulfilled, the returned promise will become rejected: ```javascript var promise1 = new RSVP.Promise(function(resolve, reject){ setTimeout(function(){ resolve("promise 1"); }, 200); }); var promise2 = new RSVP.Promise(function(resolve, reject){ setTimeout(function(){ reject(new Error("promise 2")); }, 100); }); RSVP.race([promise1, promise2]).then(function(result){ // Code here never runs because there are rejected promises! }, function(reason){ // reason.message === "promise2" because promise 2 became rejected before // promise 1 became fulfilled }); ``` @method race @for RSVP @param {Array} promises array of promises to observe @param {String} label optional string for describing the promise returned. Useful for tooling. @return {Promise} a promise that becomes fulfilled with the value the first completed promises is resolved with if the first completed promise was fulfilled, or rejected with the reason that the first completed promise was rejected with. */ function race(promises) { /*jshint validthis:true */ var Promise = this; if (!isArray(promises)) { throw new TypeError('You must pass an array to race.'); } return new Promise(function(resolve, reject) { var results = [], promise; for (var i = 0; i < promises.length; i++) { promise = promises[i]; if (promise && typeof promise.then === 'function') { promise.then(resolve, reject); } else { resolve(promise); } } }); } __exports__.race = race; }); define("promise/reject", ["exports"], function(__exports__) { "use strict"; /** `RSVP.reject` returns a promise that will become rejected with the passed `reason`. `RSVP.reject` is essentially shorthand for the following: ```javascript var promise = new RSVP.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 var promise = RSVP.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 @for RSVP @param {Any} reason value that the returned promise will be rejected with. @param {String} label optional string for identifying the returned promise. Useful for tooling. @return {Promise} a promise that will become rejected with the given `reason`. */ function reject(reason) { /*jshint validthis:true */ var Promise = this; return new Promise(function (resolve, reject) { reject(reason); }); } __exports__.reject = reject; }); define("promise/resolve", ["exports"], function(__exports__) { "use strict"; function resolve(value) { /*jshint validthis:true */ if (value && typeof value === 'object' && value.constructor === this) { return value; } var Promise = this; return new Promise(function(resolve) { resolve(value); }); } __exports__.resolve = resolve; }); define("promise/utils", ["exports"], function(__exports__) { "use strict"; function objectOrFunction(x) { return isFunction(x) || (typeof x === "object" && x !== null); } function isFunction(x) { return typeof x === "function"; } function isArray(x) { return Object.prototype.toString.call(x) === "[object Array]"; } // Date.now is not available in browsers < IE9 // https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Date/now#Compatibility var now = Date.now || function() { return new Date().getTime(); }; __exports__.objectOrFunction = objectOrFunction; __exports__.isFunction = isFunction; __exports__.isArray = isArray; __exports__.now = now; }); requireModule('promise/polyfill').polyfill(); }());(function webpackUniversalModuleDefinition(root, factory) { if(typeof exports === 'object' && typeof module === 'object') module.exports = factory(); else if(typeof define === 'function' && define.amd) define([], factory); else if(typeof exports === 'object') exports["localforage"] = factory(); else root["localforage"] = factory(); })(this, function() { return /******/ (function(modules) { // webpackBootstrap /******/ // The module cache /******/ var installedModules = {}; /******/ // The require function /******/ function __webpack_require__(moduleId) { /******/ // Check if module is in cache /******/ if(installedModules[moduleId]) /******/ return installedModules[moduleId].exports; /******/ // Create a new module (and put it into the cache) /******/ var module = installedModules[moduleId] = { /******/ exports: {}, /******/ id: moduleId, /******/ loaded: false /******/ }; /******/ // Execute the module function /******/ modules[moduleId].call(module.exports, module, module.exports, __webpack_require__); /******/ // Flag the module as loaded /******/ module.loaded = true; /******/ // Return the exports of the module /******/ return module.exports; /******/ } /******/ // expose the modules object (__webpack_modules__) /******/ __webpack_require__.m = modules; /******/ // expose the module cache /******/ __webpack_require__.c = installedModules; /******/ // __webpack_public_path__ /******/ __webpack_require__.p = ""; /******/ // Load entry module and return exports /******/ return __webpack_require__(0); /******/ }) /************************************************************************/ /******/ ([ /* 0 */ /***/ function(module, exports, __webpack_require__) { 'use strict'; exports.__esModule = true; function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError('Cannot call a class as a function'); } } (function () { 'use strict'; // Custom drivers are stored here when `defineDriver()` is called. // They are shared across all instances of localForage. var CustomDrivers = {}; var DriverType = { INDEXEDDB: 'asyncStorage', LOCALSTORAGE: 'localStorageWrapper', WEBSQL: 'webSQLStorage' }; var DefaultDriverOrder = [DriverType.INDEXEDDB, DriverType.WEBSQL, DriverType.LOCALSTORAGE]; var LibraryMethods = ['clear', 'getItem', 'iterate', 'key', 'keys', 'length', 'removeItem', 'setItem']; var DefaultConfig = { description: '', driver: DefaultDriverOrder.slice(), name: 'localforage', // Default DB size is _JUST UNDER_ 5MB, as it's the highest size // we can use without a prompt. size: 4980736, storeName: 'keyvaluepairs', version: 1.0 }; // Check to see if IndexedDB is available and if it is the latest // implementation; it's our preferred backend library. We use "_spec_test" // as the name of the database because it's not the one we'll operate on, // but it's useful to make sure its using the right spec. // See: https://github.com/mozilla/localForage/issues/128 var driverSupport = (function (self) { // Initialize IndexedDB; fall back to vendor-prefixed versions // if needed. var indexedDB = indexedDB || self.indexedDB || self.webkitIndexedDB || self.mozIndexedDB || self.OIndexedDB || self.msIndexedDB; var result = {}; result[DriverType.WEBSQL] = !!self.openDatabase; result[DriverType.INDEXEDDB] = !!(function () { // We mimic PouchDB here; just UA test for Safari (which, as of // iOS 8/Yosemite, doesn't properly support IndexedDB). // IndexedDB support is broken and different from Blink's. // This is faster than the test case (and it's sync), so we just // do this. *SIGH* // http://bl.ocks.org/nolanlawson/raw/c83e9039edf2278047e9/ // // We test for openDatabase because IE Mobile identifies itself // as Safari. Oh the lulz... if (typeof self.openDatabase !== 'undefined' && self.navigator && self.navigator.userAgent && /Safari/.test(self.navigator.userAgent) && !/Chrome/.test(self.navigator.userAgent)) { return false; } try { return indexedDB && typeof indexedDB.open === 'function' && // Some Samsung/HTC Android 4.0-4.3 devices // have older IndexedDB specs; if this isn't available // their IndexedDB is too old for us to use. // (Replaces the onupgradeneeded test.) typeof self.IDBKeyRange !== 'undefined'; } catch (e) { return false; } })(); result[DriverType.LOCALSTORAGE] = !!(function () { try { return self.localStorage && 'setItem' in self.localStorage && self.localStorage.setItem; } catch (e) { return false; } })(); return result; })(this); var isArray = Array.isArray || function (arg) { return Object.prototype.toString.call(arg) === '[object Array]'; }; function callWhenReady(localForageInstance, libraryMethod) { localForageInstance[libraryMethod] = function () { var _args = arguments; return localForageInstance.ready().then(function () { return localForageInstance[libraryMethod].apply(localForageInstance, _args); }); }; } function extend() { for (var i = 1; i < arguments.length; i++) { var arg = arguments[i]; if (arg) { for (var key in arg) { if (arg.hasOwnProperty(key)) { if (isArray(arg[key])) { arguments[0][key] = arg[key].slice(); } else { arguments[0][key] = arg[key]; } } } } } return arguments[0]; } function isLibraryDriver(driverName) { for (var driver in DriverType) { if (DriverType.hasOwnProperty(driver) && DriverType[driver] === driverName) { return true; } } return false; } var LocalForage = (function () { function LocalForage(options) { _classCallCheck(this, LocalForage); this.INDEXEDDB = DriverType.INDEXEDDB; this.LOCALSTORAGE = DriverType.LOCALSTORAGE; this.WEBSQL = DriverType.WEBSQL; this._defaultConfig = extend({}, DefaultConfig); this._config = extend({}, this._defaultConfig, options); this._driverSet = null; this._initDriver = null; this._ready = false; this._dbInfo = null; this._wrapLibraryMethodsWithReady(); this.setDriver(this._config.driver); } // The actual localForage object that we expose as a module or via a // global. It's extended by pulling in one of our other libraries. // Set any config values for localForage; can be called anytime before // the first API call (e.g. `getItem`, `setItem`). // We loop through options so we don't overwrite existing config // values. LocalForage.prototype.config = function config(options) { // If the options argument is an object, we use it to set values. // Otherwise, we return either a specified config value or all // config values. if (typeof options === 'object') { // If localforage is ready and fully initialized, we can't set // any new configuration values. Instead, we return an error. if (this._ready) { return new Error("Can't call config() after localforage " + 'has been used.'); } for (var i in options) { if (i === 'storeName') { options[i] = options[i].replace(/\W/g, '_'); } this._config[i] = options[i]; } // after all config options are set and // the driver option is used, try setting it if ('driver' in options && options.driver) { this.setDriver(this._config.driver); } return true; } else if (typeof options === 'string') { return this._config[options]; } else { return this._config; } }; // Used to define a custom driver, shared across all instances of // localForage. LocalForage.prototype.defineDriver = function defineDriver(driverObject, callback, errorCallback) { var promise = new Promise(function (resolve, reject) { try { var driverName = driverObject._driver; var complianceError = new Error('Custom driver not compliant; see ' + 'https://mozilla.github.io/localForage/#definedriver'); var namingError = new Error('Custom driver name already in use: ' + driverObject._driver); // A driver name should be defined and not overlap with the // library-defined, default drivers. if (!driverObject._driver) { reject(complianceError); return; } if (isLibraryDriver(driverObject._driver)) { reject(namingError); return; } var customDriverMethods = LibraryMethods.concat('_initStorage'); for (var i = 0; i < customDriverMethods.length; i++) { var customDriverMethod = customDriverMethods[i]; if (!customDriverMethod || !driverObject[customDriverMethod] || typeof driverObject[customDriverMethod] !== 'function') { reject(complianceError); return; } } var supportPromise = Promise.resolve(true); if ('_support' in driverObject) { if (driverObject._support && typeof driverObject._support === 'function') { supportPromise = driverObject._support(); } else { supportPromise = Promise.resolve(!!driverObject._support); } } supportPromise.then(function (supportResult) { driverSupport[driverName] = supportResult; CustomDrivers[driverName] = driverObject; resolve(); }, reject); } catch (e) { reject(e); } }); promise.then(callback, errorCallback); return promise; }; LocalForage.prototype.driver = function driver() { return this._driver || null; }; LocalForage.prototype.getDriver = function getDriver(driverName, callback, errorCallback) { var self = this; var getDriverPromise = (function () { if (isLibraryDriver(driverName)) { switch (driverName) { case self.INDEXEDDB: return new Promise(function (resolve, reject) { resolve(__webpack_require__(1)); }); case self.LOCALSTORAGE: return new Promise(function (resolve, reject) { resolve(__webpack_require__(2)); }); case self.WEBSQL: return new Promise(function (resolve, reject) { resolve(__webpack_require__(4)); }); } } else if (CustomDrivers[driverName]) { return Promise.resolve(CustomDrivers[driverName]); } return Promise.reject(new Error('Driver not found.')); })(); getDriverPromise.then(callback, errorCallback); return getDriverPromise; }; LocalForage.prototype.getSerializer = function getSerializer(callback) { var serializerPromise = new Promise(function (resolve, reject) { resolve(__webpack_require__(3)); }); if (callback && typeof callback === 'function') { serializerPromise.then(function (result) { callback(result); }); } return serializerPromise; }; LocalForage.prototype.ready = function ready(callback) { var self = this; var promise = self._driverSet.then(function () { if (self._ready === null) { self._ready = self._initDriver(); } return self._ready; }); promise.then(callback, callback); return promise; }; LocalForage.prototype.setDriver = function setDriver(drivers, callback, errorCallback) { var self = this; if (!isArray(drivers)) { drivers = [drivers]; } var supportedDrivers = this._getSupportedDrivers(drivers); function setDriverToConfig() { self._config.driver = self.driver(); } function initDriver(supportedDrivers) { return function () { var currentDriverIndex = 0; function driverPromiseLoop() { while (currentDriverIndex < supportedDrivers.length) { var driverName = supportedDrivers[currentDriverIndex]; currentDriverIndex++; self._dbInfo = null; self._ready = null; return self.getDriver(driverName).then(function (driver) { self._extend(driver); setDriverToConfig(); self._ready = self._initStorage(self._config); return self._ready; })['catch'](driverPromiseLoop); } setDriverToConfig(); var error = new Error('No available storage method found.'); self._driverSet = Promise.reject(error); return self._driverSet; } return driverPromiseLoop(); }; } // There might be a driver initialization in progress // so wait for it to finish in order to avoid a possible // race condition to set _dbInfo var oldDriverSetDone = this._driverSet !== null ? this._driverSet['catch'](function () { return Promise.resolve(); }) : Promise.resolve(); this._driverSet = oldDriverSetDone.then(function () { var driverName = supportedDrivers[0]; self._dbInfo = null; self._ready = null; return self.getDriver(driverName).then(function (driver) { self._driver = driver._driver; setDriverToConfig(); self._wrapLibraryMethodsWithReady(); self._initDriver = initDriver(supportedDrivers); }); })['catch'](function () { setDriverToConfig(); var error = new Error('No available storage method found.'); self._driverSet = Promise.reject(error); return self._driverSet; }); this._driverSet.then(callback, errorCallback); return this._driverSet; }; LocalForage.prototype.supports = function supports(driverName) { return !!driverSupport[driverName]; }; LocalForage.prototype._extend = function _extend(libraryMethodsAndProperties) { extend(this, libraryMethodsAndProperties); }; LocalForage.prototype._getSupportedDrivers = function _getSupportedDrivers(drivers) { var supportedDrivers = []; for (var i = 0, len = drivers.length; i < len; i++) { var driverName = drivers[i]; if (this.supports(driverName)) { supportedDrivers.push(driverName); } } return supportedDrivers; }; LocalForage.prototype._wrapLibraryMethodsWithReady = function _wrapLibraryMethodsWithReady() { // Add a stub for each driver API method that delays the call to the // corresponding driver method until localForage is ready. These stubs // will be replaced by the driver methods as soon as the driver is // loaded, so there is no performance impact. for (var i = 0; i < LibraryMethods.length; i++) { callWhenReady(this, LibraryMethods[i]); } }; LocalForage.prototype.createInstance = function createInstance(options) { return new LocalForage(options); }; return LocalForage; })(); var localForage = new LocalForage(); exports['default'] = localForage; }).call(typeof window !== 'undefined' ? window : self); module.exports = exports['default']; /***/ }, /* 1 */ /***/ function(module, exports) { // Some code originally from async_storage.js in // [Gaia](https://github.com/mozilla-b2g/gaia). 'use strict'; exports.__esModule = true; (function () { 'use strict'; var globalObject = this; // Initialize IndexedDB; fall back to vendor-prefixed versions if needed. var indexedDB = indexedDB || this.indexedDB || this.webkitIndexedDB || this.mozIndexedDB || this.OIndexedDB || this.msIndexedDB; // If IndexedDB isn't available, we get outta here! if (!indexedDB) { return; } var DETECT_BLOB_SUPPORT_STORE = 'local-forage-detect-blob-support'; var supportsBlobs; var dbContexts; // Abstracts constructing a Blob object, so it also works in older // browsers that don't support the native Blob constructor. (i.e. // old QtWebKit versions, at least). function _createBlob(parts, properties) { parts = parts || []; properties = properties || {}; try { return new Blob(parts, properties); } catch (e) { if (e.name !== 'TypeError') { throw e; } var BlobBuilder = globalObject.BlobBuilder || globalObject.MSBlobBuilder || globalObject.MozBlobBuilder || globalObject.WebKitBlobBuilder; var builder = new BlobBuilder(); for (var i = 0; i < parts.length; i += 1) { builder.append(parts[i]); } return builder.getBlob(properties.type); } } // Transform a binary string to an array buffer, because otherwise // weird stuff happens when you try to work with the binary string directly. // It is known. // From http://stackoverflow.com/questions/14967647/ (continues on next line) // encode-decode-image-with-base64-breaks-image (2013-04-21) function _binStringToArrayBuffer(bin) { var length = bin.length; var buf = new ArrayBuffer(length); var arr = new Uint8Array(buf); for (var i = 0; i < length; i++) { arr[i] = bin.charCodeAt(i); } return buf; } // Fetch a blob using ajax. This reveals bugs in Chrome < 43. // For details on all this junk: // https://github.com/nolanlawson/state-of-binary-data-in-the-browser#readme function _blobAjax(url) { return new Promise(function (resolve, reject) { var xhr = new XMLHttpRequest(); xhr.open('GET', url); xhr.withCredentials = true; xhr.responseType = 'arraybuffer'; xhr.onreadystatechange = function () { if (xhr.readyState !== 4) { return; } if (xhr.status === 200) { return resolve({ response: xhr.response, type: xhr.getResponseHeader('Content-Type') }); } reject({ status: xhr.status, response: xhr.response }); }; xhr.send(); }); } // // Detect blob support. Chrome didn't support it until version 38. // In version 37 they had a broken version where PNGs (and possibly // other binary types) aren't stored correctly, because when you fetch // them, the content type is always null. // // Furthermore, they have some outstanding bugs where blobs occasionally // are read by FileReader as null, or by ajax as 404s. // // Sadly we use the 404 bug to detect the FileReader bug, so if they // get fixed independently and released in different versions of Chrome, // then the bug could come back. So it's worthwhile to watch these issues: // 404 bug: https://code.google.com/p/chromium/issues/detail?id=447916 // FileReader bug: https://code.google.com/p/chromium/issues/detail?id=447836 // function _checkBlobSupportWithoutCaching(idb) { return new Promise(function (resolve, reject) { var blob = _createBlob([''], { type: 'image/png' }); var txn = idb.transaction([DETECT_BLOB_SUPPORT_STORE], 'readwrite'); txn.objectStore(DETECT_BLOB_SUPPORT_STORE).put(blob, 'key'); txn.oncomplete = function () { // have to do it in a separate transaction, else the correct // content type is always returned var blobTxn = idb.transaction([DETECT_BLOB_SUPPORT_STORE], 'readwrite'); var getBlobReq = blobTxn.objectStore(DETECT_BLOB_SUPPORT_STORE).get('key'); getBlobReq.onerror = reject; getBlobReq.onsuccess = function (e) { var storedBlob = e.target.result; var url = URL.createObjectURL(storedBlob); _blobAjax(url).then(function (res) { resolve(!!(res && res.type === 'image/png')); }, function () { resolve(false); }).then(function () { URL.revokeObjectURL(url); }); }; }; })['catch'](function () { return false; // error, so assume unsupported }); } function _checkBlobSupport(idb) { if (typeof supportsBlobs === 'boolean') { return Promise.resolve(supportsBlobs); } return _checkBlobSupportWithoutCaching(idb).then(function (value) { supportsBlobs = value; return supportsBlobs; }); } // encode a blob for indexeddb engines that don't support blobs function _encodeBlob(blob) { return new Promise(function (resolve, reject) { var reader = new FileReader(); reader.onerror = reject; reader.onloadend = function (e) { var base64 = btoa(e.target.result || ''); resolve({ __local_forage_encoded_blob: true, data: base64, type: blob.type }); }; reader.readAsBinaryString(blob); }); } // decode an encoded blob function _decodeBlob(encodedBlob) { var arrayBuff = _binStringToArrayBuffer(atob(encodedBlob.data)); return _createBlob([arrayBuff], { type: encodedBlob.type }); } // is this one of our fancy encoded blobs? function _isEncodedBlob(value) { return value && value.__local_forage_encoded_blob; } // Open the IndexedDB database (automatically creates one if one didn't // previously exist), using any options set in the config. function _initStorage(options) { var self = this; var dbInfo = { db: null }; if (options) { for (var i in options) { dbInfo[i] = options[i]; } } // Initialize a singleton container for all running localForages. if (!dbContexts) { dbContexts = {}; } // Get the current context of the database; var dbContext = dbContexts[dbInfo.name]; // ...or create a new context. if (!dbContext) { dbContext = { // Running localForages sharing a database. forages: [], // Shared database. db: null }; // Register the new context in the global container. dbContexts[dbInfo.name] = dbContext; } // Register itself as a running localForage in the current context. dbContext.forages.push(this); // Create an array of readiness of the related localForages. var readyPromises = []; function ignoreErrors() { // Don't handle errors here, // just makes sure related localForages aren't pending. return Promise.resolve(); } for (var j = 0; j < dbContext.forages.length; j++) { var forage = dbContext.forages[j]; if (forage !== this) { // Don't wait for itself... readyPromises.push(forage.ready()['catch'](ignoreErrors)); } } // Take a snapshot of the related localForages. var forages = dbContext.forages.slice(0); // Initialize the connection process only when // all the related localForages aren't pending. return Promise.all(readyPromises).then(function () { dbInfo.db = dbContext.db; // Get the connection or open a new one without upgrade. return _getOriginalConnection(dbInfo); }).then(function (db) { dbInfo.db = db; if (_isUpgradeNeeded(dbInfo, self._defaultConfig.version)) { // Reopen the database for upgrading. return _getUpgradedConnection(dbInfo); } return db; }).then(function (db) { dbInfo.db = dbContext.db = db; self._dbInfo = dbInfo; // Share the final connection amongst related localForages. for (var k in forages) { var forage = forages[k]; if (forage !== self) { // Self is already up-to-date. forage._dbInfo.db = dbInfo.db; forage._dbInfo.version = dbInfo.version; } } }); } function _getOriginalConnection(dbInfo) { return _getConnection(dbInfo, false); } function _getUpgradedConnection(dbInfo) { return _getConnection(dbInfo, true); } function _getConnection(dbInfo, upgradeNeeded) { return new Promise(function (resolve, reject) { if (dbInfo.db) { if (upgradeNeeded) { dbInfo.db.close(); } else { return resolve(dbInfo.db); } } var dbArgs = [dbInfo.name]; if (upgradeNeeded) { dbArgs.push(dbInfo.version); } var openreq = indexedDB.open.apply(indexedDB, dbArgs); if (upgradeNeeded) { openreq.onupgradeneeded = function (e) { var db = openreq.result; try { db.createObjectStore(dbInfo.storeName); if (e.oldVersion <= 1) { // Added when support for blob shims was added db.createObjectStore(DETECT_BLOB_SUPPORT_STORE); } } catch (ex) { if (ex.name === 'ConstraintError') { globalObject.console.warn('The database "' + dbInfo.name + '"' + ' has been upgraded from version ' + e.oldVersion + ' to version ' + e.newVersion + ', but the storage "' + dbInfo.storeName + '" already exists.'); } else { throw ex; } } }; } openreq.onerror = function () { reject(openreq.error); }; openreq.onsuccess = function () { resolve(openreq.result); }; }); } function _isUpgradeNeeded(dbInfo, defaultVersion) { if (!dbInfo.db) { return true; } var isNewStore = !dbInfo.db.objectStoreNames.contains(dbInfo.storeName); var isDowngrade = dbInfo.version < dbInfo.db.version; var isUpgrade = dbInfo.version > dbInfo.db.version; if (isDowngrade) { // If the version is not the default one // then warn for impossible downgrade. if (dbInfo.version !== defaultVersion) { globalObject.console.warn('The database "' + dbInfo.name + '"' + ' can\'t be downgraded from version ' + dbInfo.db.version + ' to version ' + dbInfo.version + '.'); } // Align the versions to prevent errors. dbInfo.version = dbInfo.db.version; } if (isUpgrade || isNewStore) { // If the store is new then increment the version (if needed). // This will trigger an "upgradeneeded" event which is required // for creating a store. if (isNewStore) { var incVersion = dbInfo.db.version + 1; if (incVersion > dbInfo.version) { dbInfo.version = incVersion; } } return true; } return false; } function getItem(key, callback) { var self = this; // Cast the key to a string, as that's all we can set as a key. if (typeof key !== 'string') { globalObject.console.warn(key + ' used as a key, but it is not a string.'); key = String(key); } var promise = new Promise(function (resolve, reject) { self.ready().then(function () { var dbInfo = self._dbInfo; var store = dbInfo.db.transaction(dbInfo.storeName, 'readonly').objectStore(dbInfo.storeName); var req = store.get(key); req.onsuccess = function () { var value = req.result; if (value === undefined) { value = null; } if (_isEncodedBlob(value)) { value = _decodeBlob(value); } resolve(value); }; req.onerror = function () { reject(req.error); }; })['catch'](reject); }); executeCallback(promise, callback); return promise; } // Iterate over all items stored in database. function iterate(iterator, callback) { var self = this; var promise = new Promise(function (resolve, reject) { self.ready().then(function () { var dbInfo = self._dbInfo; var store = dbInfo.db.transaction(dbInfo.storeName, 'readonly').objectStore(dbInfo.storeName); var req = store.openCursor(); var iterationNumber = 1; req.onsuccess = function () { var cursor = req.result; if (cursor) { var value = cursor.value; if (_isEncodedBlob(value)) { value = _decodeBlob(value); } var result = iterator(value, cursor.key, iterationNumber++); if (result !== void 0) { resolve(result); } else { cursor['continue'](); } } else { resolve(); } }; req.onerror = function () { reject(req.error); }; })['catch'](reject); }); executeCallback(promise, callback); return promise; } function setItem(key, value, callback) { var self = this; // Cast the key to a string, as that's all we can set as a key. if (typeof key !== 'string') { globalObject.console.warn(key + ' used as a key, but it is not a string.'); key = String(key); } var promise = new Promise(function (resolve, reject) { var dbInfo; self.ready().then(function () { dbInfo = self._dbInfo; return _checkBlobSupport(dbInfo.db); }).then(function (blobSupport) { if (!blobSupport && value instanceof Blob) { return _encodeBlob(value); } return value; }).then(function (value) { var transaction = dbInfo.db.transaction(dbInfo.storeName, 'readwrite'); var store = transaction.objectStore(dbInfo.storeName); // The reason we don't _save_ null is because IE 10 does // not support saving the `null` type in IndexedDB. How // ironic, given the bug below! // See: https://github.com/mozilla/localForage/issues/161 if (value === null) { value = undefined; } var req = store.put(value, key); transaction.oncomplete = function () { // Cast to undefined so the value passed to // callback/promise is the same as what one would get out // of `getItem()` later. This leads to some weirdness // (setItem('foo', undefined) will return `null`), but // it's not my fault localStorage is our baseline and that // it's weird. if (value === undefined) { value = null; } resolve(value); }; transaction.onabort = transaction.onerror = function () { var err = req.error ? req.error : req.transaction.error; reject(err); }; })['catch'](reject); }); executeCallback(promise, callback); return promise; } function removeItem(key, callback) { var self = this; // Cast the key to a string, as that's all we can set as a key. if (typeof key !== 'string') { globalObject.console.warn(key + ' used as a key, but it is not a string.'); key = String(key); } var promise = new Promise(function (resolve, reject) { self.ready().then(function () { var dbInfo = self._dbInfo; var transaction = dbInfo.db.transaction(dbInfo.storeName, 'readwrite'); var store = transaction.objectStore(dbInfo.storeName); // We use a Grunt task to make this safe for IE and some // versions of Android (including those used by Cordova). // Normally IE won't like `['delete']()` and will insist on // using `['delete']()`, but we have a build step that // fixes this for us now. var req = store['delete'](key); transaction.oncomplete = function () { resolve(); }; transaction.onerror = function () { reject(req.error); }; // The request will be also be aborted if we've exceeded our storage // space. transaction.onabort = function () { var err = req.error ? req.error : req.transaction.error; reject(err); }; })['catch'](reject); }); executeCallback(promise, callback); return promise; } function clear(callback) { var self = this; var promise = new Promise(function (resolve, reject) { self.ready().then(function () { var dbInfo = self._dbInfo; var transaction = dbInfo.db.transaction(dbInfo.storeName, 'readwrite'); var store = transaction.objectStore(dbInfo.storeName); var req = store.clear(); transaction.oncomplete = function () { resolve(); }; transaction.onabort = transaction.onerror = function () { var err = req.error ? req.error : req.transaction.error; reject(err); }; })['catch'](reject); }); executeCallback(promise, callback); return promise; } function length(callback) { var self = this; var promise = new Promise(function (resolve, reject) { self.ready().then(function () { var dbInfo = self._dbInfo; var store = dbInfo.db.transaction(dbInfo.storeName, 'readonly').objectStore(dbInfo.storeName); var req = store.count(); req.onsuccess = function () { resolve(req.result); }; req.onerror = function () { reject(req.error); }; })['catch'](reject); }); executeCallback(promise, callback); return promise; } function key(n, callback) { var self = this; var promise = new Promise(function (resolve, reject) { if (n < 0) { resolve(null); return; } self.ready().then(function () { var dbInfo = self._dbInfo; var store = dbInfo.db.transaction(dbInfo.storeName, 'readonly').objectStore(dbInfo.storeName); var advanced = false; var req = store.openCursor(); req.onsuccess = function () { var cursor = req.result; if (!cursor) { // this means there weren't enough keys resolve(null); return; } if (n === 0) { // We have the first key, return it if that's what they // wanted. resolve(cursor.key); } else { if (!advanced) { // Otherwise, ask the cursor to skip ahead n // records. advanced = true; cursor.advance(n); } else { // When we get here, we've got the nth key. resolve(cursor.key); } } }; req.onerror = function () { reject(req.error); }; })['catch'](reject); }); executeCallback(promise, callback); return promise; } function keys(callback) { var self = this; var promise = new Promise(function (resolve, reject) { self.ready().then(function () { var dbInfo = self._dbInfo; var store = dbInfo.db.transaction(dbInfo.storeName, 'readonly').objectStore(dbInfo.storeName); var req = store.openCursor(); var keys = []; req.onsuccess = function () { var cursor = req.result; if (!cursor) { resolve(keys); return; } keys.push(cursor.key); cursor['continue'](); }; req.onerror = function () { reject(req.error); }; })['catch'](reject); }); executeCallback(promise, callback); return promise; } function executeCallback(promise, callback) { if (callback) { promise.then(function (result) { callback(null, result); }, function (error) { callback(error); }); } } var asyncStorage = { _driver: 'asyncStorage', _initStorage: _initStorage, iterate: iterate, getItem: getItem, setItem: setItem, removeItem: removeItem, clear: clear, length: length, key: key, keys: keys }; exports['default'] = asyncStorage; }).call(typeof window !== 'undefined' ? window : self); module.exports = exports['default']; /***/ }, /* 2 */ /***/ function(module, exports, __webpack_require__) { // If IndexedDB isn't available, we'll fall back to localStorage. // Note that this will have considerable performance and storage // side-effects (all data will be serialized on save and only data that // can be converted to a string via `JSON.stringify()` will be saved). 'use strict'; exports.__esModule = true; (function () { 'use strict'; var globalObject = this; var localStorage = null; // If the app is running inside a Google Chrome packaged webapp, or some // other context where localStorage isn't available, we don't use // localStorage. This feature detection is preferred over the old // `if (window.chrome && window.chrome.runtime)` code. // See: https://github.com/mozilla/localForage/issues/68 try { // If localStorage isn't available, we get outta here! // This should be inside a try catch if (!this.localStorage || !('setItem' in this.localStorage)) { return; } // Initialize localStorage and create a variable to use throughout // the code. localStorage = this.localStorage; } catch (e) { return; } // Config the localStorage backend, using options set in the config. function _initStorage(options) { var self = this; var dbInfo = {}; if (options) { for (var i in options) { dbInfo[i] = options[i]; } } dbInfo.keyPrefix = dbInfo.name + '/'; if (dbInfo.storeName !== self._defaultConfig.storeName) { dbInfo.keyPrefix += dbInfo.storeName + '/'; } self._dbInfo = dbInfo; return new Promise(function (resolve, reject) { resolve(__webpack_require__(3)); }).then(function (lib) { dbInfo.serializer = lib; return Promise.resolve(); }); } // Remove all keys from the datastore, effectively destroying all data in // the app's key/value store! function clear(callback) { var self = this; var promise = self.ready().then(function () { var keyPrefix = self._dbInfo.keyPrefix; for (var i = localStorage.length - 1; i >= 0; i--) { var key = localStorage.key(i); if (key.indexOf(keyPrefix) === 0) { localStorage.removeItem(key); } } }); executeCallback(promise, callback); return promise; } // Retrieve an item from the store. Unlike the original async_storage // library in Gaia, we don't modify return values at all. If a key's value // is `undefined`, we pass that value to the callback function. function getItem(key, callback) { var self = this; // Cast the key to a string, as that's all we can set as a key. if (typeof key !== 'string') { globalObject.console.warn(key + ' used as a key, but it is not a string.'); key = String(key); } var promise = self.ready().then(function () { var dbInfo = self._dbInfo; var result = localStorage.getItem(dbInfo.keyPrefix + key); // If a result was found, parse it from the serialized // string into a JS object. If result isn't truthy, the key // is likely undefined and we'll pass it straight to the // callback. if (result) { result = dbInfo.serializer.deserialize(result); } return result; }); executeCallback(promise, callback); return promise; } // Iterate over all items in the store. function iterate(iterator, callback) { var self = this; var promise = self.ready().then(function () { var dbInfo = self._dbInfo; var keyPrefix = dbInfo.keyPrefix; var keyPrefixLength = keyPrefix.length; var length = localStorage.length; // We use a dedicated iterator instead of the `i` variable below // so other keys we fetch in localStorage aren't counted in // the `iterationNumber` argument passed to the `iterate()` // callback. // // See: github.com/mozilla/localForage/pull/435#discussion_r38061530 var iterationNumber = 1; for (var i = 0; i < length; i++) { var key = localStorage.key(i); if (key.indexOf(keyPrefix) !== 0) { continue; } var value = localStorage.getItem(key); // If a result was found, parse it from the serialized // string into a JS object. If result isn't truthy, the // key is likely undefined and we'll pass it straight // to the iterator. if (value) { value = dbInfo.serializer.deserialize(value); } value = iterator(value, key.substring(keyPrefixLength), iterationNumber++); if (value !== void 0) { return value; } } }); executeCallback(promise, callback); return promise; } // Same as localStorage's key() method, except takes a callback. function key(n, callback) { var self = this; var promise = self.ready().then(function () { var dbInfo = self._dbInfo; var result; try { result = localStorage.key(n); } catch (error) { result = null; } // Remove the prefix from the key, if a key is found. if (result) { result = result.substring(dbInfo.keyPrefix.length); } return result; }); executeCallback(promise, callback); return promise; } function keys(callback) { var self = this; var promise = self.ready().then(function () { var dbInfo = self._dbInfo; var length = localStorage.length; var keys = []; for (var i = 0; i < length; i++) { if (localStorage.key(i).indexOf(dbInfo.keyPrefix) === 0) { keys.push(localStorage.key(i).substring(dbInfo.keyPrefix.length)); } } return keys; }); executeCallback(promise, callback); return promise; } // Supply the number of keys in the datastore to the callback function. function length(callback) { var self = this; var promise = self.keys().then(function (keys) { return keys.length; }); executeCallback(promise, callback); return promise; } // Remove an item from the store, nice and simple. function removeItem(key, callback) { var self = this; // Cast the key to a string, as that's all we can set as a key. if (typeof key !== 'string') { globalObject.console.warn(key + ' used as a key, but it is not a string.'); key = String(key); } var promise = self.ready().then(function () { var dbInfo = self._dbInfo; localStorage.removeItem(dbInfo.keyPrefix + key); }); executeCallback(promise, callback); return promise; } // Set a key's value and run an optional callback once the value is set. // Unlike Gaia's implementation, the callback function is passed the value, // in case you want to operate on that value only after you're sure it // saved, or something like that. function setItem(key, value, callback) { var self = this; // Cast the key to a string, as that's all we can set as a key. if (typeof key !== 'string') { globalObject.console.warn(key + ' used as a key, but it is not a string.'); key = String(key); } var promise = self.ready().then(function () { // Convert undefined values to null. // https://github.com/mozilla/localForage/pull/42 if (value === undefined) { value = null; } // Save the original value to pass to the callback. var originalValue = value; return new Promise(function (resolve, reject) { var dbInfo = self._dbInfo; dbInfo.serializer.serialize(value, function (value, error) { if (error) { reject(error); } else { try { localStorage.setItem(dbInfo.keyPrefix + key, value); resolve(originalValue); } catch (e) { // localStorage capacity exceeded. // TODO: Make this a specific error/event. if (e.name === 'QuotaExceededError' || e.name === 'NS_ERROR_DOM_QUOTA_REACHED') { reject(e); } reject(e); } } }); }); }); executeCallback(promise, callback); return promise; } function executeCallback(promise, callback) { if (callback) { promise.then(function (result) { callback(null, result); }, function (error) { callback(error); }); } } var localStorageWrapper = { _driver: 'localStorageWrapper', _initStorage: _initStorage, // Default API, from Gaia/localStorage. iterate: iterate, getItem: getItem, setItem: setItem, removeItem: removeItem, clear: clear, length: length, key: key, keys: keys }; exports['default'] = localStorageWrapper; }).call(typeof window !== 'undefined' ? window : self); module.exports = exports['default']; /***/ }, /* 3 */ /***/ function(module, exports) { 'use strict'; exports.__esModule = true; (function () { 'use strict'; // Sadly, the best way to save binary data in WebSQL/localStorage is serializing // it to Base64, so this is how we store it to prevent very strange errors with less // verbose ways of binary <-> string data storage. var BASE_CHARS = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/'; var BLOB_TYPE_PREFIX = '~~local_forage_type~'; var BLOB_TYPE_PREFIX_REGEX = /^~~local_forage_type~([^~]+)~/; var SERIALIZED_MARKER = '__lfsc__:'; var SERIALIZED_MARKER_LENGTH = SERIALIZED_MARKER.length; // OMG the serializations! var TYPE_ARRAYBUFFER = 'arbf'; var TYPE_BLOB = 'blob'; var TYPE_INT8ARRAY = 'si08'; var TYPE_UINT8ARRAY = 'ui08'; var TYPE_UINT8CLAMPEDARRAY = 'uic8'; var TYPE_INT16ARRAY = 'si16'; var TYPE_INT32ARRAY = 'si32'; var TYPE_UINT16ARRAY = 'ur16'; var TYPE_UINT32ARRAY = 'ui32'; var TYPE_FLOAT32ARRAY = 'fl32'; var TYPE_FLOAT64ARRAY = 'fl64'; var TYPE_SERIALIZED_MARKER_LENGTH = SERIALIZED_MARKER_LENGTH + TYPE_ARRAYBUFFER.length; // Get out of our habit of using `window` inline, at least. var globalObject = this; // Abstracts constructing a Blob object, so it also works in older // browsers that don't support the native Blob constructor. (i.e. // old QtWebKit versions, at least). function _createBlob(parts, properties) { parts = parts || []; properties = properties || {}; try { return new Blob(parts, properties); } catch (err) { if (err.name !== 'TypeError') { throw err; } var BlobBuilder = globalObject.BlobBuilder || globalObject.MSBlobBuilder || globalObject.MozBlobBuilder || globalObject.WebKitBlobBuilder; var builder = new BlobBuilder(); for (var i = 0; i < parts.length; i += 1) { builder.append(parts[i]); } return builder.getBlob(properties.type); } } // Serialize a value, afterwards executing a callback (which usually // instructs the `setItem()` callback/promise to be executed). This is how // we store binary data with localStorage. function serialize(value, callback) { var valueString = ''; if (value) { valueString = value.toString(); } // Cannot use `value instanceof ArrayBuffer` or such here, as these // checks fail when running the tests using casper.js... // // TODO: See why those tests fail and use a better solution. if (value && (value.toString() === '[object ArrayBuffer]' || value.buffer && value.buffer.toString() === '[object ArrayBuffer]')) { // Convert binary arrays to a string and prefix the string with // a special marker. var buffer; var marker = SERIALIZED_MARKER; if (value instanceof ArrayBuffer) { buffer = value; marker += TYPE_ARRAYBUFFER; } else { buffer = value.buffer; if (valueString === '[object Int8Array]') { marker += TYPE_INT8ARRAY; } else if (valueString === '[object Uint8Array]') { marker += TYPE_UINT8ARRAY; } else if (valueString === '[object Uint8ClampedArray]') { marker += TYPE_UINT8CLAMPEDARRAY; } else if (valueString === '[object Int16Array]') { marker += TYPE_INT16ARRAY; } else if (valueString === '[object Uint16Array]') { marker += TYPE_UINT16ARRAY; } else if (valueString === '[object Int32Array]') { marker += TYPE_INT32ARRAY; } else if (valueString === '[object Uint32Array]') { marker += TYPE_UINT32ARRAY; } else if (valueString === '[object Float32Array]') { marker += TYPE_FLOAT32ARRAY; } else if (valueString === '[object Float64Array]') { marker += TYPE_FLOAT64ARRAY; } else { callback(new Error('Failed to get type for BinaryArray')); } } callback(marker + bufferToString(buffer)); } else if (valueString === '[object Blob]') { // Conver the blob to a binaryArray and then to a string. var fileReader = new FileReader(); fileReader.onload = function () { // Backwards-compatible prefix for the blob type. var str = BLOB_TYPE_PREFIX + value.type + '~' + bufferToString(this.result); callback(SERIALIZED_MARKER + TYPE_BLOB + str); }; fileReader.readAsArrayBuffer(value); } else { try { callback(JSON.stringify(value)); } catch (e) { console.error("Couldn't convert value into a JSON string: ", value); callback(null, e); } } } // Deserialize data we've inserted into a value column/field. We place // special markers into our strings to mark them as encoded; this isn't // as nice as a meta field, but it's the only sane thing we can do whilst // keeping localStorage support intact. // // Oftentimes this will just deserialize JSON content, but if we have a // special marker (SERIALIZED_MARKER, defined above), we will extract // some kind of arraybuffer/binary data/typed array out of the string. function deserialize(value) { // If we haven't marked this string as being specially serialized (i.e. // something other than serialized JSON), we can just return it and be // done with it. if (value.substring(0, SERIALIZED_MARKER_LENGTH) !== SERIALIZED_MARKER) { return JSON.parse(value); } // The following code deals with deserializing some kind of Blob or // TypedArray. First we separate out the type of data we're dealing // with from the data itself. var serializedString = value.substring(TYPE_SERIALIZED_MARKER_LENGTH); var type = value.substring(SERIALIZED_MARKER_LENGTH, TYPE_SERIALIZED_MARKER_LENGTH); var blobType; // Backwards-compatible blob type serialization strategy. // DBs created with older versions of localForage will simply not have the blob type. if (type === TYPE_BLOB && BLOB_TYPE_PREFIX_REGEX.test(serializedString)) { var matcher = serializedString.match(BLOB_TYPE_PREFIX_REGEX); blobType = matcher[1]; serializedString = serializedString.substring(matcher[0].length); } var buffer = stringToBuffer(serializedString); // Return the right type based on the code/type set during // serialization. switch (type) { case TYPE_ARRAYBUFFER: return buffer; case TYPE_BLOB: return _createBlob([buffer], { type: blobType }); case TYPE_INT8ARRAY: return new Int8Array(buffer); case TYPE_UINT8ARRAY: return new Uint8Array(buffer); case TYPE_UINT8CLAMPEDARRAY: return new Uint8ClampedArray(buffer); case TYPE_INT16ARRAY: return new Int16Array(buffer); case TYPE_UINT16ARRAY: return new Uint16Array(buffer); case TYPE_INT32ARRAY: return new Int32Array(buffer); case TYPE_UINT32ARRAY: return new Uint32Array(buffer); case TYPE_FLOAT32ARRAY: return new Float32Array(buffer); case TYPE_FLOAT64ARRAY: return new Float64Array(buffer); default: throw new Error('Unkown type: ' + type); } } function stringToBuffer(serializedString) { // Fill the string into a ArrayBuffer. var bufferLength = serializedString.length * 0.75; var len = serializedString.length; var i; var p = 0; var encoded1, encoded2, encoded3, encoded4; if (serializedString[serializedString.length - 1] === '=') { bufferLength--; if (serializedString[serializedString.length - 2] === '=') { bufferLength--; } } var buffer = new ArrayBuffer(bufferLength); var bytes = new Uint8Array(buffer); for (i = 0; i < len; i += 4) { encoded1 = BASE_CHARS.indexOf(serializedString[i]); encoded2 = BASE_CHARS.indexOf(serializedString[i + 1]); encoded3 = BASE_CHARS.indexOf(serializedString[i + 2]); encoded4 = BASE_CHARS.indexOf(serializedString[i + 3]); /*jslint bitwise: true */ bytes[p++] = encoded1 << 2 | encoded2 >> 4; bytes[p++] = (encoded2 & 15) << 4 | encoded3 >> 2; bytes[p++] = (encoded3 & 3) << 6 | encoded4 & 63; } return buffer; } // Converts a buffer to a string to store, serialized, in the backend // storage library. function bufferToString(buffer) { // base64-arraybuffer var bytes = new Uint8Array(buffer); var base64String = ''; var i; for (i = 0; i < bytes.length; i += 3) { /*jslint bitwise: true */ base64String += BASE_CHARS[bytes[i] >> 2]; base64String += BASE_CHARS[(bytes[i] & 3) << 4 | bytes[i + 1] >> 4]; base64String += BASE_CHARS[(bytes[i + 1] & 15) << 2 | bytes[i + 2] >> 6]; base64String += BASE_CHARS[bytes[i + 2] & 63]; } if (bytes.length % 3 === 2) { base64String = base64String.substring(0, base64String.length - 1) + '='; } else if (bytes.length % 3 === 1) { base64String = base64String.substring(0, base64String.length - 2) + '=='; } return base64String; } var localforageSerializer = { serialize: serialize, deserialize: deserialize, stringToBuffer: stringToBuffer, bufferToString: bufferToString }; exports['default'] = localforageSerializer; }).call(typeof window !== 'undefined' ? window : self); module.exports = exports['default']; /***/ }, /* 4 */ /***/ function(module, exports, __webpack_require__) { /* * Includes code from: * * base64-arraybuffer * https://github.com/niklasvh/base64-arraybuffer * * Copyright (c) 2012 Niklas von Hertzen * Licensed under the MIT license. */ 'use strict'; exports.__esModule = true; (function () { 'use strict'; var globalObject = this; var openDatabase = this.openDatabase; // If WebSQL methods aren't available, we can stop now. if (!openDatabase) { return; } // Open the WebSQL database (automatically creates one if one didn't // previously exist), using any options set in the config. function _initStorage(options) { var self = this; var dbInfo = { db: null }; if (options) { for (var i in options) { dbInfo[i] = typeof options[i] !== 'string' ? options[i].toString() : options[i]; } } var dbInfoPromise = new Promise(function (resolve, reject) { // Open the database; the openDatabase API will automatically // create it for us if it doesn't exist. try { dbInfo.db = openDatabase(dbInfo.name, String(dbInfo.version), dbInfo.description, dbInfo.size); } catch (e) { return self.setDriver(self.LOCALSTORAGE).then(function () { return self._initStorage(options); }).then(resolve)['catch'](reject); } // Create our key/value table if it doesn't exist. dbInfo.db.transaction(function (t) { t.executeSql('CREATE TABLE IF NOT EXISTS ' + dbInfo.storeName + ' (id INTEGER PRIMARY KEY, key unique, value)', [], function () { self._dbInfo = dbInfo; resolve(); }, function (t, error) { reject(error); }); }); }); return new Promise(function (resolve, reject) { resolve(__webpack_require__(3)); }).then(function (lib) { dbInfo.serializer = lib; return dbInfoPromise; }); } function getItem(key, callback) { var self = this; // Cast the key to a string, as that's all we can set as a key. if (typeof key !== 'string') { globalObject.console.warn(key + ' used as a key, but it is not a string.'); key = String(key); } var promise = new Promise(function (resolve, reject) { self.ready().then(function () { var dbInfo = self._dbInfo; dbInfo.db.transaction(function (t) { t.executeSql('SELECT * FROM ' + dbInfo.storeName + ' WHERE key = ? LIMIT 1', [key], function (t, results) { var result = results.rows.length ? results.rows.item(0).value : null; // Check to see if this is serialized content we need to // unpack. if (result) { result = dbInfo.serializer.deserialize(result); } resolve(result); }, function (t, error) { reject(error); }); }); })['catch'](reject); }); executeCallback(promise, callback); return promise; } function iterate(iterator, callback) { var self = this; var promise = new Promise(function (resolve, reject) { self.ready().then(function () { var dbInfo = self._dbInfo; dbInfo.db.transaction(function (t) { t.executeSql('SELECT * FROM ' + dbInfo.storeName, [], function (t, results) { var rows = results.rows; var length = rows.length; for (var i = 0; i < length; i++) { var item = rows.item(i); var result = item.value; // Check to see if this is serialized content // we need to unpack. if (result) { result = dbInfo.serializer.deserialize(result); } result = iterator(result, item.key, i + 1); // void(0) prevents problems with redefinition // of `undefined`. if (result !== void 0) { resolve(result); return; } } resolve(); }, function (t, error) { reject(error); }); }); })['catch'](reject); }); executeCallback(promise, callback); return promise; } function setItem(key, value, callback) { var self = this; // Cast the key to a string, as that's all we can set as a key. if (typeof key !== 'string') { globalObject.console.warn(key + ' used as a key, but it is not a string.'); key = String(key); } var promise = new Promise(function (resolve, reject) { self.ready().then(function () { // The localStorage API doesn't return undefined values in an // "expected" way, so undefined is always cast to null in all // drivers. See: https://github.com/mozilla/localForage/pull/42 if (value === undefined) { value = null; } // Save the original value to pass to the callback. var originalValue = value; var dbInfo = self._dbInfo; dbInfo.serializer.serialize(value, function (value, error) { if (error) { reject(error); } else { dbInfo.db.transaction(function (t) { t.executeSql('INSERT OR REPLACE INTO ' + dbInfo.storeName + ' (key, value) VALUES (?, ?)', [key, value], function () { resolve(originalValue); }, function (t, error) { reject(error); }); }, function (sqlError) { // The transaction failed; check // to see if it's a quota error. if (sqlError.code === sqlError.QUOTA_ERR) { // We reject the callback outright for now, but // it's worth trying to re-run the transaction. // Even if the user accepts the prompt to use // more storage on Safari, this error will // be called. // // TODO: Try to re-run the transaction. reject(sqlError); } }); } }); })['catch'](reject); }); executeCallback(promise, callback); return promise; } function removeItem(key, callback) { var self = this; // Cast the key to a string, as that's all we can set as a key. if (typeof key !== 'string') { globalObject.console.warn(key + ' used as a key, but it is not a string.'); key = String(key); } var promise = new Promise(function (resolve, reject) { self.ready().then(function () { var dbInfo = self._dbInfo; dbInfo.db.transaction(function (t) { t.executeSql('DELETE FROM ' + dbInfo.storeName + ' WHERE key = ?', [key], function () { resolve(); }, function (t, error) { reject(error); }); }); })['catch'](reject); }); executeCallback(promise, callback); return promise; } // Deletes every item in the table. // TODO: Find out if this resets the AUTO_INCREMENT number. function clear(callback) { var self = this; var promise = new Promise(function (resolve, reject) { self.ready().then(function () { var dbInfo = self._dbInfo; dbInfo.db.transaction(function (t) { t.executeSql('DELETE FROM ' + dbInfo.storeName, [], function () { resolve(); }, function (t, error) { reject(error); }); }); })['catch'](reject); }); executeCallback(promise, callback); return promise; } // Does a simple `COUNT(key)` to get the number of items stored in // localForage. function length(callback) { var self = this; var promise = new Promise(function (resolve, reject) { self.ready().then(function () { var dbInfo = self._dbInfo; dbInfo.db.transaction(function (t) { // Ahhh, SQL makes this one soooooo easy. t.executeSql('SELECT COUNT(key) as c FROM ' + dbInfo.storeName, [], function (t, results) { var result = results.rows.item(0).c; resolve(result); }, function (t, error) { reject(error); }); }); })['catch'](reject); }); executeCallback(promise, callback); return promise; } // Return the key located at key index X; essentially gets the key from a // `WHERE id = ?`. This is the most efficient way I can think to implement // this rarely-used (in my experience) part of the API, but it can seem // inconsistent, because we do `INSERT OR REPLACE INTO` on `setItem()`, so // the ID of each key will change every time it's updated. Perhaps a stored // procedure for the `setItem()` SQL would solve this problem? // TODO: Don't change ID on `setItem()`. function key(n, callback) { var self = this; var promise = new Promise(function (resolve, reject) { self.ready().then(function () { var dbInfo = self._dbInfo; dbInfo.db.transaction(function (t) { t.executeSql('SELECT key FROM ' + dbInfo.storeName + ' WHERE id = ? LIMIT 1', [n + 1], function (t, results) { var result = results.rows.length ? results.rows.item(0).key : null; resolve(result); }, function (t, error) { reject(error); }); }); })['catch'](reject); }); executeCallback(promise, callback); return promise; } function keys(callback) { var self = this; var promise = new Promise(function (resolve, reject) { self.ready().then(function () { var dbInfo = self._dbInfo; dbInfo.db.transaction(function (t) { t.executeSql('SELECT key FROM ' + dbInfo.storeName, [], function (t, results) { var keys = []; for (var i = 0; i < results.rows.length; i++) { keys.push(results.rows.item(i).key); } resolve(keys); }, function (t, error) { reject(error); }); }); })['catch'](reject); }); executeCallback(promise, callback); return promise; } function executeCallback(promise, callback) { if (callback) { promise.then(function (result) { callback(null, result); }, function (error) { callback(error); }); } } var webSQLStorage = { _driver: 'webSQLStorage', _initStorage: _initStorage, iterate: iterate, getItem: getItem, setItem: setItem, removeItem: removeItem, clear: clear, length: length, key: key, keys: keys }; exports['default'] = webSQLStorage; }).call(typeof window !== 'undefined' ? window : self); module.exports = exports['default']; /***/ } /******/ ]) }); ; }).call(this,_dereq_('_process'),typeof global !== "undefined" ? global : typeof self !== "undefined" ? self : typeof window !== "undefined" ? window : {}) },{"_process":68}],70:[function(_dereq_,module,exports){ // Top level file is just a mixin of submodules & constants 'use strict'; var assign = _dereq_('./lib/utils/common').assign; var deflate = _dereq_('./lib/deflate'); var inflate = _dereq_('./lib/inflate'); var constants = _dereq_('./lib/zlib/constants'); var pako = {}; assign(pako, deflate, inflate, constants); module.exports = pako; },{"./lib/deflate":71,"./lib/inflate":72,"./lib/utils/common":73,"./lib/zlib/constants":76}],71:[function(_dereq_,module,exports){ 'use strict'; var zlib_deflate = _dereq_('./zlib/deflate.js'); var utils = _dereq_('./utils/common'); var strings = _dereq_('./utils/strings'); var msg = _dereq_('./zlib/messages'); var zstream = _dereq_('./zlib/zstream'); var toString = Object.prototype.toString; /* Public constants ==========================================================*/ /* ===========================================================================*/ var Z_NO_FLUSH = 0; var Z_FINISH = 4; var Z_OK = 0; var Z_STREAM_END = 1; var Z_SYNC_FLUSH = 2; var Z_DEFAULT_COMPRESSION = -1; var Z_DEFAULT_STRATEGY = 0; var Z_DEFLATED = 8; /* ===========================================================================*/ /** * class Deflate * * Generic JS-style wrapper for zlib calls. If you don't need * streaming behaviour - use more simple functions: [[deflate]], * [[deflateRaw]] and [[gzip]]. **/ /* internal * Deflate.chunks -> Array * * Chunks of output data, if [[Deflate#onData]] not overriden. **/ /** * Deflate.result -> Uint8Array|Array * * Compressed result, generated by default [[Deflate#onData]] * and [[Deflate#onEnd]] handlers. Filled after you push last chunk * (call [[Deflate#push]] with `Z_FINISH` / `true` param) or if you * push a chunk with explicit flush (call [[Deflate#push]] with * `Z_SYNC_FLUSH` param). **/ /** * Deflate.err -> Number * * Error code after deflate finished. 0 (Z_OK) on success. * You will not need it in real life, because deflate errors * are possible only on wrong options or bad `onData` / `onEnd` * custom handlers. **/ /** * Deflate.msg -> String * * Error message, if [[Deflate.err]] != 0 **/ /** * new Deflate(options) * - options (Object): zlib deflate options. * * Creates new deflator instance with specified params. Throws exception * on bad params. Supported options: * * - `level` * - `windowBits` * - `memLevel` * - `strategy` * * [http://zlib.net/manual.html#Advanced](http://zlib.net/manual.html#Advanced) * for more information on these. * * Additional options, for internal needs: * * - `chunkSize` - size of generated data chunks (16K by default) * - `raw` (Boolean) - do raw deflate * - `gzip` (Boolean) - create gzip wrapper * - `to` (String) - if equal to 'string', then result will be "binary string" * (each char code [0..255]) * - `header` (Object) - custom header for gzip * - `text` (Boolean) - true if compressed data believed to be text * - `time` (Number) - modification time, unix timestamp * - `os` (Number) - operation system code * - `extra` (Array) - array of bytes with extra data (max 65536) * - `name` (String) - file name (binary string) * - `comment` (String) - comment (binary string) * - `hcrc` (Boolean) - true if header crc should be added * * ##### Example: * * ```javascript * var pako = require('pako') * , chunk1 = Uint8Array([1,2,3,4,5,6,7,8,9]) * , chunk2 = Uint8Array([10,11,12,13,14,15,16,17,18,19]); * * var deflate = new pako.Deflate({ level: 3}); * * deflate.push(chunk1, false); * deflate.push(chunk2, true); // true -> last chunk * * if (deflate.err) { throw new Error(deflate.err); } * * console.log(deflate.result); * ``` **/ var Deflate = function(options) { this.options = utils.assign({ level: Z_DEFAULT_COMPRESSION, method: Z_DEFLATED, chunkSize: 16384, windowBits: 15, memLevel: 8, strategy: Z_DEFAULT_STRATEGY, to: '' }, options || {}); var opt = this.options; if (opt.raw && (opt.windowBits > 0)) { opt.windowBits = -opt.windowBits; } else if (opt.gzip && (opt.windowBits > 0) && (opt.windowBits < 16)) { opt.windowBits += 16; } this.err = 0; // error code, if happens (0 = Z_OK) this.msg = ''; // error message this.ended = false; // used to avoid multiple onEnd() calls this.chunks = []; // chunks of compressed data this.strm = new zstream(); this.strm.avail_out = 0; var status = zlib_deflate.deflateInit2( this.strm, opt.level, opt.method, opt.windowBits, opt.memLevel, opt.strategy ); if (status !== Z_OK) { throw new Error(msg[status]); } if (opt.header) { zlib_deflate.deflateSetHeader(this.strm, opt.header); } }; /** * Deflate#push(data[, mode]) -> Boolean * - data (Uint8Array|Array|ArrayBuffer|String): input data. Strings will be * converted to utf8 byte sequence. * - mode (Number|Boolean): 0..6 for corresponding Z_NO_FLUSH..Z_TREE modes. * See constants. Skipped or `false` means Z_NO_FLUSH, `true` meansh Z_FINISH. * * Sends input data to deflate pipe, generating [[Deflate#onData]] calls with * new compressed chunks. Returns `true` on success. The last data block must have * mode Z_FINISH (or `true`). That will flush internal pending buffers and call * [[Deflate#onEnd]]. For interim explicit flushes (without ending the stream) you * can use mode Z_SYNC_FLUSH, keeping the compression context. * * On fail call [[Deflate#onEnd]] with error code and return false. * * We strongly recommend to use `Uint8Array` on input for best speed (output * array format is detected automatically). Also, don't skip last param and always * use the same type in your code (boolean or number). That will improve JS speed. * * For regular `Array`-s make sure all elements are [0..255]. * * ##### Example * * ```javascript * push(chunk, false); // push one of data chunks * ... * push(chunk, true); // push last chunk * ``` **/ Deflate.prototype.push = function(data, mode) { var strm = this.strm; var chunkSize = this.options.chunkSize; var status, _mode; if (this.ended) { return false; } _mode = (mode === ~~mode) ? mode : ((mode === true) ? Z_FINISH : Z_NO_FLUSH); // Convert data if needed if (typeof data === 'string') { // If we need to compress text, change encoding to utf8. strm.input = strings.string2buf(data); } else if (toString.call(data) === '[object ArrayBuffer]') { strm.input = new Uint8Array(data); } else { strm.input = data; } strm.next_in = 0; strm.avail_in = strm.input.length; do { if (strm.avail_out === 0) { strm.output = new utils.Buf8(chunkSize); strm.next_out = 0; strm.avail_out = chunkSize; } status = zlib_deflate.deflate(strm, _mode); /* no bad return value */ if (status !== Z_STREAM_END && status !== Z_OK) { this.onEnd(status); this.ended = true; return false; } if (strm.avail_out === 0 || (strm.avail_in === 0 && (_mode === Z_FINISH || _mode === Z_SYNC_FLUSH))) { if (this.options.to === 'string') { this.onData(strings.buf2binstring(utils.shrinkBuf(strm.output, strm.next_out))); } else { this.onData(utils.shrinkBuf(strm.output, strm.next_out)); } } } while ((strm.avail_in > 0 || strm.avail_out === 0) && status !== Z_STREAM_END); // Finalize on the last chunk. if (_mode === Z_FINISH) { status = zlib_deflate.deflateEnd(this.strm); this.onEnd(status); this.ended = true; return status === Z_OK; } // callback interim results if Z_SYNC_FLUSH. if (_mode === Z_SYNC_FLUSH) { this.onEnd(Z_OK); strm.avail_out = 0; return true; } return true; }; /** * Deflate#onData(chunk) -> Void * - chunk (Uint8Array|Array|String): ouput data. Type of array depends * on js engine support. When string output requested, each chunk * will be string. * * By default, stores data blocks in `chunks[]` property and glue * those in `onEnd`. Override this handler, if you need another behaviour. **/ Deflate.prototype.onData = function(chunk) { this.chunks.push(chunk); }; /** * Deflate#onEnd(status) -> Void * - status (Number): deflate status. 0 (Z_OK) on success, * other if not. * * Called once after you tell deflate that the input stream is * complete (Z_FINISH) or should be flushed (Z_SYNC_FLUSH) * or if an error happened. By default - join collected chunks, * free memory and fill `results` / `err` properties. **/ Deflate.prototype.onEnd = function(status) { // On success - join if (status === Z_OK) { if (this.options.to === 'string') { this.result = this.chunks.join(''); } else { this.result = utils.flattenChunks(this.chunks); } } this.chunks = []; this.err = status; this.msg = this.strm.msg; }; /** * deflate(data[, options]) -> Uint8Array|Array|String * - data (Uint8Array|Array|String): input data to compress. * - options (Object): zlib deflate options. * * Compress `data` with deflate alrorythm and `options`. * * Supported options are: * * - level * - windowBits * - memLevel * - strategy * * [http://zlib.net/manual.html#Advanced](http://zlib.net/manual.html#Advanced) * for more information on these. * * Sugar (options): * * - `raw` (Boolean) - say that we work with raw stream, if you don't wish to specify * negative windowBits implicitly. * - `to` (String) - if equal to 'string', then result will be "binary string" * (each char code [0..255]) * * ##### Example: * * ```javascript * var pako = require('pako') * , data = Uint8Array([1,2,3,4,5,6,7,8,9]); * * console.log(pako.deflate(data)); * ``` **/ function deflate(input, options) { var deflator = new Deflate(options); deflator.push(input, true); // That will never happens, if you don't cheat with options :) if (deflator.err) { throw deflator.msg; } return deflator.result; } /** * deflateRaw(data[, options]) -> Uint8Array|Array|String * - data (Uint8Array|Array|String): input data to compress. * - options (Object): zlib deflate options. * * The same as [[deflate]], but creates raw data, without wrapper * (header and adler32 crc). **/ function deflateRaw(input, options) { options = options || {}; options.raw = true; return deflate(input, options); } /** * gzip(data[, options]) -> Uint8Array|Array|String * - data (Uint8Array|Array|String): input data to compress. * - options (Object): zlib deflate options. * * The same as [[deflate]], but create gzip wrapper instead of * deflate one. **/ function gzip(input, options) { options = options || {}; options.gzip = true; return deflate(input, options); } exports.Deflate = Deflate; exports.deflate = deflate; exports.deflateRaw = deflateRaw; exports.gzip = gzip; },{"./utils/common":73,"./utils/strings":74,"./zlib/deflate.js":78,"./zlib/messages":83,"./zlib/zstream":85}],72:[function(_dereq_,module,exports){ 'use strict'; var zlib_inflate = _dereq_('./zlib/inflate.js'); var utils = _dereq_('./utils/common'); var strings = _dereq_('./utils/strings'); var c = _dereq_('./zlib/constants'); var msg = _dereq_('./zlib/messages'); var zstream = _dereq_('./zlib/zstream'); var gzheader = _dereq_('./zlib/gzheader'); var toString = Object.prototype.toString; /** * class Inflate * * Generic JS-style wrapper for zlib calls. If you don't need * streaming behaviour - use more simple functions: [[inflate]] * and [[inflateRaw]]. **/ /* internal * inflate.chunks -> Array * * Chunks of output data, if [[Inflate#onData]] not overriden. **/ /** * Inflate.result -> Uint8Array|Array|String * * Uncompressed result, generated by default [[Inflate#onData]] * and [[Inflate#onEnd]] handlers. Filled after you push last chunk * (call [[Inflate#push]] with `Z_FINISH` / `true` param) or if you * push a chunk with explicit flush (call [[Inflate#push]] with * `Z_SYNC_FLUSH` param). **/ /** * Inflate.err -> Number * * Error code after inflate finished. 0 (Z_OK) on success. * Should be checked if broken data possible. **/ /** * Inflate.msg -> String * * Error message, if [[Inflate.err]] != 0 **/ /** * new Inflate(options) * - options (Object): zlib inflate options. * * Creates new inflator instance with specified params. Throws exception * on bad params. Supported options: * * - `windowBits` * * [http://zlib.net/manual.html#Advanced](http://zlib.net/manual.html#Advanced) * for more information on these. * * Additional options, for internal needs: * * - `chunkSize` - size of generated data chunks (16K by default) * - `raw` (Boolean) - do raw inflate * - `to` (String) - if equal to 'string', then result will be converted * from utf8 to utf16 (javascript) string. When string output requested, * chunk length can differ from `chunkSize`, depending on content. * * By default, when no options set, autodetect deflate/gzip data format via * wrapper header. * * ##### Example: * * ```javascript * var pako = require('pako') * , chunk1 = Uint8Array([1,2,3,4,5,6,7,8,9]) * , chunk2 = Uint8Array([10,11,12,13,14,15,16,17,18,19]); * * var inflate = new pako.Inflate({ level: 3}); * * inflate.push(chunk1, false); * inflate.push(chunk2, true); // true -> last chunk * * if (inflate.err) { throw new Error(inflate.err); } * * console.log(inflate.result); * ``` **/ var Inflate = function(options) { this.options = utils.assign({ chunkSize: 16384, windowBits: 0, to: '' }, options || {}); var opt = this.options; // Force window size for `raw` data, if not set directly, // because we have no header for autodetect. if (opt.raw && (opt.windowBits >= 0) && (opt.windowBits < 16)) { opt.windowBits = -opt.windowBits; if (opt.windowBits === 0) { opt.windowBits = -15; } } // If `windowBits` not defined (and mode not raw) - set autodetect flag for gzip/deflate if ((opt.windowBits >= 0) && (opt.windowBits < 16) && !(options && options.windowBits)) { opt.windowBits += 32; } // Gzip header has no info about windows size, we can do autodetect only // for deflate. So, if window size not set, force it to max when gzip possible if ((opt.windowBits > 15) && (opt.windowBits < 48)) { // bit 3 (16) -> gzipped data // bit 4 (32) -> autodetect gzip/deflate if ((opt.windowBits & 15) === 0) { opt.windowBits |= 15; } } this.err = 0; // error code, if happens (0 = Z_OK) this.msg = ''; // error message this.ended = false; // used to avoid multiple onEnd() calls this.chunks = []; // chunks of compressed data this.strm = new zstream(); this.strm.avail_out = 0; var status = zlib_inflate.inflateInit2( this.strm, opt.windowBits ); if (status !== c.Z_OK) { throw new Error(msg[status]); } this.header = new gzheader(); zlib_inflate.inflateGetHeader(this.strm, this.header); }; /** * Inflate#push(data[, mode]) -> Boolean * - data (Uint8Array|Array|ArrayBuffer|String): input data * - mode (Number|Boolean): 0..6 for corresponding Z_NO_FLUSH..Z_TREE modes. * See constants. Skipped or `false` means Z_NO_FLUSH, `true` meansh Z_FINISH. * * Sends input data to inflate pipe, generating [[Inflate#onData]] calls with * new output chunks. Returns `true` on success. The last data block must have * mode Z_FINISH (or `true`). That will flush internal pending buffers and call * [[Inflate#onEnd]]. For interim explicit flushes (without ending the stream) you * can use mode Z_SYNC_FLUSH, keeping the decompression context. * * On fail call [[Inflate#onEnd]] with error code and return false. * * We strongly recommend to use `Uint8Array` on input for best speed (output * format is detected automatically). Also, don't skip last param and always * use the same type in your code (boolean or number). That will improve JS speed. * * For regular `Array`-s make sure all elements are [0..255]. * * ##### Example * * ```javascript * push(chunk, false); // push one of data chunks * ... * push(chunk, true); // push last chunk * ``` **/ Inflate.prototype.push = function(data, mode) { var strm = this.strm; var chunkSize = this.options.chunkSize; var status, _mode; var next_out_utf8, tail, utf8str; // Flag to properly process Z_BUF_ERROR on testing inflate call // when we check that all output data was flushed. var allowBufError = false; if (this.ended) { return false; } _mode = (mode === ~~mode) ? mode : ((mode === true) ? c.Z_FINISH : c.Z_NO_FLUSH); // Convert data if needed if (typeof data === 'string') { // Only binary strings can be decompressed on practice strm.input = strings.binstring2buf(data); } else if (toString.call(data) === '[object ArrayBuffer]') { strm.input = new Uint8Array(data); } else { strm.input = data; } strm.next_in = 0; strm.avail_in = strm.input.length; do { if (strm.avail_out === 0) { strm.output = new utils.Buf8(chunkSize); strm.next_out = 0; strm.avail_out = chunkSize; } status = zlib_inflate.inflate(strm, c.Z_NO_FLUSH); /* no bad return value */ if (status === c.Z_BUF_ERROR && allowBufError === true) { status = c.Z_OK; allowBufError = false; } if (status !== c.Z_STREAM_END && status !== c.Z_OK) { this.onEnd(status); this.ended = true; return false; } if (strm.next_out) { if (strm.avail_out === 0 || status === c.Z_STREAM_END || (strm.avail_in === 0 && (_mode === c.Z_FINISH || _mode === c.Z_SYNC_FLUSH))) { if (this.options.to === 'string') { next_out_utf8 = strings.utf8border(strm.output, strm.next_out); tail = strm.next_out - next_out_utf8; utf8str = strings.buf2string(strm.output, next_out_utf8); // move tail strm.next_out = tail; strm.avail_out = chunkSize - tail; if (tail) { utils.arraySet(strm.output, strm.output, next_out_utf8, tail, 0); } this.onData(utf8str); } else { this.onData(utils.shrinkBuf(strm.output, strm.next_out)); } } } // When no more input data, we should check that internal inflate buffers // are flushed. The only way to do it when avail_out = 0 - run one more // inflate pass. But if output data not exists, inflate return Z_BUF_ERROR. // Here we set flag to process this error properly. // // NOTE. Deflate does not return error in this case and does not needs such // logic. if (strm.avail_in === 0 && strm.avail_out === 0) { allowBufError = true; } } while ((strm.avail_in > 0 || strm.avail_out === 0) && status !== c.Z_STREAM_END); if (status === c.Z_STREAM_END) { _mode = c.Z_FINISH; } // Finalize on the last chunk. if (_mode === c.Z_FINISH) { status = zlib_inflate.inflateEnd(this.strm); this.onEnd(status); this.ended = true; return status === c.Z_OK; } // callback interim results if Z_SYNC_FLUSH. if (_mode === c.Z_SYNC_FLUSH) { this.onEnd(c.Z_OK); strm.avail_out = 0; return true; } return true; }; /** * Inflate#onData(chunk) -> Void * - chunk (Uint8Array|Array|String): ouput data. Type of array depends * on js engine support. When string output requested, each chunk * will be string. * * By default, stores data blocks in `chunks[]` property and glue * those in `onEnd`. Override this handler, if you need another behaviour. **/ Inflate.prototype.onData = function(chunk) { this.chunks.push(chunk); }; /** * Inflate#onEnd(status) -> Void * - status (Number): inflate status. 0 (Z_OK) on success, * other if not. * * Called either after you tell inflate that the input stream is * complete (Z_FINISH) or should be flushed (Z_SYNC_FLUSH) * or if an error happened. By default - join collected chunks, * free memory and fill `results` / `err` properties. **/ Inflate.prototype.onEnd = function(status) { // On success - join if (status === c.Z_OK) { if (this.options.to === 'string') { // Glue & convert here, until we teach pako to send // utf8 alligned strings to onData this.result = this.chunks.join(''); } else { this.result = utils.flattenChunks(this.chunks); } } this.chunks = []; this.err = status; this.msg = this.strm.msg; }; /** * inflate(data[, options]) -> Uint8Array|Array|String * - data (Uint8Array|Array|String): input data to decompress. * - options (Object): zlib inflate options. * * Decompress `data` with inflate/ungzip and `options`. Autodetect * format via wrapper header by default. That's why we don't provide * separate `ungzip` method. * * Supported options are: * * - windowBits * * [http://zlib.net/manual.html#Advanced](http://zlib.net/manual.html#Advanced) * for more information. * * Sugar (options): * * - `raw` (Boolean) - say that we work with raw stream, if you don't wish to specify * negative windowBits implicitly. * - `to` (String) - if equal to 'string', then result will be converted * from utf8 to utf16 (javascript) string. When string output requested, * chunk length can differ from `chunkSize`, depending on content. * * * ##### Example: * * ```javascript * var pako = require('pako') * , input = pako.deflate([1,2,3,4,5,6,7,8,9]) * , output; * * try { * output = pako.inflate(input); * } catch (err) * console.log(err); * } * ``` **/ function inflate(input, options) { var inflator = new Inflate(options); inflator.push(input, true); // That will never happens, if you don't cheat with options :) if (inflator.err) { throw inflator.msg; } return inflator.result; } /** * inflateRaw(data[, options]) -> Uint8Array|Array|String * - data (Uint8Array|Array|String): input data to decompress. * - options (Object): zlib inflate options. * * The same as [[inflate]], but creates raw data, without wrapper * (header and adler32 crc). **/ function inflateRaw(input, options) { options = options || {}; options.raw = true; return inflate(input, options); } /** * ungzip(data[, options]) -> Uint8Array|Array|String * - data (Uint8Array|Array|String): input data to decompress. * - options (Object): zlib inflate options. * * Just shortcut to [[inflate]], because it autodetects format * by header.content. Done for convenience. **/ exports.Inflate = Inflate; exports.inflate = inflate; exports.inflateRaw = inflateRaw; exports.ungzip = inflate; },{"./utils/common":73,"./utils/strings":74,"./zlib/constants":76,"./zlib/gzheader":79,"./zlib/inflate.js":81,"./zlib/messages":83,"./zlib/zstream":85}],73:[function(_dereq_,module,exports){ 'use strict'; var TYPED_OK = (typeof Uint8Array !== 'undefined') && (typeof Uint16Array !== 'undefined') && (typeof Int32Array !== 'undefined'); exports.assign = function (obj /*from1, from2, from3, ...*/) { var sources = Array.prototype.slice.call(arguments, 1); while (sources.length) { var source = sources.shift(); if (!source) { continue; } if (typeof source !== 'object') { throw new TypeError(source + 'must be non-object'); } for (var p in source) { if (source.hasOwnProperty(p)) { obj[p] = source[p]; } } } return obj; }; // reduce buffer size, avoiding mem copy exports.shrinkBuf = function (buf, size) { if (buf.length === size) { return buf; } if (buf.subarray) { return buf.subarray(0, size); } buf.length = size; return buf; }; var fnTyped = { arraySet: function (dest, src, src_offs, len, dest_offs) { if (src.subarray && dest.subarray) { dest.set(src.subarray(src_offs, src_offs+len), dest_offs); return; } // Fallback to ordinary array for (var i=0; i<len; i++) { dest[dest_offs + i] = src[src_offs + i]; } }, // Join array of chunks to single array. flattenChunks: function(chunks) { var i, l, len, pos, chunk, result; // calculate data length len = 0; for (i=0, l=chunks.length; i<l; i++) { len += chunks[i].length; } // join chunks result = new Uint8Array(len); pos = 0; for (i=0, l=chunks.length; i<l; i++) { chunk = chunks[i]; result.set(chunk, pos); pos += chunk.length; } return result; } }; var fnUntyped = { arraySet: function (dest, src, src_offs, len, dest_offs) { for (var i=0; i<len; i++) { dest[dest_offs + i] = src[src_offs + i]; } }, // Join array of chunks to single array. flattenChunks: function(chunks) { return [].concat.apply([], chunks); } }; // Enable/Disable typed arrays use, for testing // exports.setTyped = function (on) { if (on) { exports.Buf8 = Uint8Array; exports.Buf16 = Uint16Array; exports.Buf32 = Int32Array; exports.assign(exports, fnTyped); } else { exports.Buf8 = Array; exports.Buf16 = Array; exports.Buf32 = Array; exports.assign(exports, fnUntyped); } }; exports.setTyped(TYPED_OK); },{}],74:[function(_dereq_,module,exports){ // String encode/decode helpers 'use strict'; var utils = _dereq_('./common'); // Quick check if we can use fast array to bin string conversion // // - apply(Array) can fail on Android 2.2 // - apply(Uint8Array) can fail on iOS 5.1 Safary // var STR_APPLY_OK = true; var STR_APPLY_UIA_OK = true; try { String.fromCharCode.apply(null, [0]); } catch(__) { STR_APPLY_OK = false; } try { String.fromCharCode.apply(null, new Uint8Array(1)); } catch(__) { STR_APPLY_UIA_OK = false; } // Table with utf8 lengths (calculated by first byte of sequence) // Note, that 5 & 6-byte values and some 4-byte values can not be represented in JS, // because max possible codepoint is 0x10ffff var _utf8len = new utils.Buf8(256); for (var q=0; q<256; q++) { _utf8len[q] = (q >= 252 ? 6 : q >= 248 ? 5 : q >= 240 ? 4 : q >= 224 ? 3 : q >= 192 ? 2 : 1); } _utf8len[254]=_utf8len[254]=1; // Invalid sequence start // convert string to array (typed, when possible) exports.string2buf = function (str) { var buf, c, c2, m_pos, i, str_len = str.length, buf_len = 0; // count binary size for (m_pos = 0; m_pos < str_len; m_pos++) { c = str.charCodeAt(m_pos); if ((c & 0xfc00) === 0xd800 && (m_pos+1 < str_len)) { c2 = str.charCodeAt(m_pos+1); if ((c2 & 0xfc00) === 0xdc00) { c = 0x10000 + ((c - 0xd800) << 10) + (c2 - 0xdc00); m_pos++; } } buf_len += c < 0x80 ? 1 : c < 0x800 ? 2 : c < 0x10000 ? 3 : 4; } // allocate buffer buf = new utils.Buf8(buf_len); // convert for (i=0, m_pos = 0; i < buf_len; m_pos++) { c = str.charCodeAt(m_pos); if ((c & 0xfc00) === 0xd800 && (m_pos+1 < str_len)) { c2 = str.charCodeAt(m_pos+1); if ((c2 & 0xfc00) === 0xdc00) { c = 0x10000 + ((c - 0xd800) << 10) + (c2 - 0xdc00); m_pos++; } } if (c < 0x80) { /* one byte */ buf[i++] = c; } else if (c < 0x800) { /* two bytes */ buf[i++] = 0xC0 | (c >>> 6); buf[i++] = 0x80 | (c & 0x3f); } else if (c < 0x10000) { /* three bytes */ buf[i++] = 0xE0 | (c >>> 12); buf[i++] = 0x80 | (c >>> 6 & 0x3f); buf[i++] = 0x80 | (c & 0x3f); } else { /* four bytes */ buf[i++] = 0xf0 | (c >>> 18); buf[i++] = 0x80 | (c >>> 12 & 0x3f); buf[i++] = 0x80 | (c >>> 6 & 0x3f); buf[i++] = 0x80 | (c & 0x3f); } } return buf; }; // Helper (used in 2 places) function buf2binstring(buf, len) { // use fallback for big arrays to avoid stack overflow if (len < 65537) { if ((buf.subarray && STR_APPLY_UIA_OK) || (!buf.subarray && STR_APPLY_OK)) { return String.fromCharCode.apply(null, utils.shrinkBuf(buf, len)); } } var result = ''; for (var i=0; i < len; i++) { result += String.fromCharCode(buf[i]); } return result; } // Convert byte array to binary string exports.buf2binstring = function(buf) { return buf2binstring(buf, buf.length); }; // Convert binary string (typed, when possible) exports.binstring2buf = function(str) { var buf = new utils.Buf8(str.length); for (var i=0, len=buf.length; i < len; i++) { buf[i] = str.charCodeAt(i); } return buf; }; // convert array to string exports.buf2string = function (buf, max) { var i, out, c, c_len; var len = max || buf.length; // Reserve max possible length (2 words per char) // NB: by unknown reasons, Array is significantly faster for // String.fromCharCode.apply than Uint16Array. var utf16buf = new Array(len*2); for (out=0, i=0; i<len;) { c = buf[i++]; // quick process ascii if (c < 0x80) { utf16buf[out++] = c; continue; } c_len = _utf8len[c]; // skip 5 & 6 byte codes if (c_len > 4) { utf16buf[out++] = 0xfffd; i += c_len-1; continue; } // apply mask on first byte c &= c_len === 2 ? 0x1f : c_len === 3 ? 0x0f : 0x07; // join the rest while (c_len > 1 && i < len) { c = (c << 6) | (buf[i++] & 0x3f); c_len--; } // terminated by end of string? if (c_len > 1) { utf16buf[out++] = 0xfffd; continue; } if (c < 0x10000) { utf16buf[out++] = c; } else { c -= 0x10000; utf16buf[out++] = 0xd800 | ((c >> 10) & 0x3ff); utf16buf[out++] = 0xdc00 | (c & 0x3ff); } } return buf2binstring(utf16buf, out); }; // Calculate max possible position in utf8 buffer, // that will not break sequence. If that's not possible // - (very small limits) return max size as is. // // buf[] - utf8 bytes array // max - length limit (mandatory); exports.utf8border = function(buf, max) { var pos; max = max || buf.length; if (max > buf.length) { max = buf.length; } // go back from last position, until start of sequence found pos = max-1; while (pos >= 0 && (buf[pos] & 0xC0) === 0x80) { pos--; } // Fuckup - very small and broken sequence, // return max, because we should return something anyway. if (pos < 0) { return max; } // If we came to start of buffer - that means vuffer is too small, // return max too. if (pos === 0) { return max; } return (pos + _utf8len[buf[pos]] > max) ? pos : max; }; },{"./common":73}],75:[function(_dereq_,module,exports){ 'use strict'; // Note: adler32 takes 12% for level 0 and 2% for level 6. // It doesn't worth to make additional optimizationa as in original. // Small size is preferable. function adler32(adler, buf, len, pos) { var s1 = (adler & 0xffff) |0, s2 = ((adler >>> 16) & 0xffff) |0, n = 0; while (len !== 0) { // Set limit ~ twice less than 5552, to keep // s2 in 31-bits, because we force signed ints. // in other case %= will fail. n = len > 2000 ? 2000 : len; len -= n; do { s1 = (s1 + buf[pos++]) |0; s2 = (s2 + s1) |0; } while (--n); s1 %= 65521; s2 %= 65521; } return (s1 | (s2 << 16)) |0; } module.exports = adler32; },{}],76:[function(_dereq_,module,exports){ module.exports = { /* Allowed flush values; see deflate() and inflate() below for details */ Z_NO_FLUSH: 0, Z_PARTIAL_FLUSH: 1, Z_SYNC_FLUSH: 2, Z_FULL_FLUSH: 3, Z_FINISH: 4, Z_BLOCK: 5, Z_TREES: 6, /* Return codes for the compression/decompression functions. Negative values * are errors, positive values are used for special but normal events. */ Z_OK: 0, Z_STREAM_END: 1, Z_NEED_DICT: 2, Z_ERRNO: -1, Z_STREAM_ERROR: -2, Z_DATA_ERROR: -3, //Z_MEM_ERROR: -4, Z_BUF_ERROR: -5, //Z_VERSION_ERROR: -6, /* compression levels */ Z_NO_COMPRESSION: 0, Z_BEST_SPEED: 1, Z_BEST_COMPRESSION: 9, Z_DEFAULT_COMPRESSION: -1, Z_FILTERED: 1, Z_HUFFMAN_ONLY: 2, Z_RLE: 3, Z_FIXED: 4, Z_DEFAULT_STRATEGY: 0, /* Possible values of the data_type field (though see inflate()) */ Z_BINARY: 0, Z_TEXT: 1, //Z_ASCII: 1, // = Z_TEXT (deprecated) Z_UNKNOWN: 2, /* The deflate compression method */ Z_DEFLATED: 8 //Z_NULL: null // Use -1 or null inline, depending on var type }; },{}],77:[function(_dereq_,module,exports){ 'use strict'; // Note: we can't get significant speed boost here. // So write code to minimize size - no pregenerated tables // and array tools dependencies. // Use ordinary array, since untyped makes no boost here function makeTable() { var c, table = []; for (var n =0; n < 256; n++) { c = n; for (var k =0; k < 8; k++) { c = ((c&1) ? (0xEDB88320 ^ (c >>> 1)) : (c >>> 1)); } table[n] = c; } return table; } // Create table on load. Just 255 signed longs. Not a problem. var crcTable = makeTable(); function crc32(crc, buf, len, pos) { var t = crcTable, end = pos + len; crc = crc ^ (-1); for (var i = pos; i < end; i++) { crc = (crc >>> 8) ^ t[(crc ^ buf[i]) & 0xFF]; } return (crc ^ (-1)); // >>> 0; } module.exports = crc32; },{}],78:[function(_dereq_,module,exports){ 'use strict'; var utils = _dereq_('../utils/common'); var trees = _dereq_('./trees'); var adler32 = _dereq_('./adler32'); var crc32 = _dereq_('./crc32'); var msg = _dereq_('./messages'); /* Public constants ==========================================================*/ /* ===========================================================================*/ /* Allowed flush values; see deflate() and inflate() below for details */ var Z_NO_FLUSH = 0; var Z_PARTIAL_FLUSH = 1; //var Z_SYNC_FLUSH = 2; var Z_FULL_FLUSH = 3; var Z_FINISH = 4; var Z_BLOCK = 5; //var Z_TREES = 6; /* Return codes for the compression/decompression functions. Negative values * are errors, positive values are used for special but normal events. */ var Z_OK = 0; var Z_STREAM_END = 1; //var Z_NEED_DICT = 2; //var Z_ERRNO = -1; var Z_STREAM_ERROR = -2; var Z_DATA_ERROR = -3; //var Z_MEM_ERROR = -4; var Z_BUF_ERROR = -5; //var Z_VERSION_ERROR = -6; /* compression levels */ //var Z_NO_COMPRESSION = 0; //var Z_BEST_SPEED = 1; //var Z_BEST_COMPRESSION = 9; var Z_DEFAULT_COMPRESSION = -1; var Z_FILTERED = 1; var Z_HUFFMAN_ONLY = 2; var Z_RLE = 3; var Z_FIXED = 4; var Z_DEFAULT_STRATEGY = 0; /* Possible values of the data_type field (though see inflate()) */ //var Z_BINARY = 0; //var Z_TEXT = 1; //var Z_ASCII = 1; // = Z_TEXT var Z_UNKNOWN = 2; /* The deflate compression method */ var Z_DEFLATED = 8; /*============================================================================*/ var MAX_MEM_LEVEL = 9; /* Maximum value for memLevel in deflateInit2 */ var MAX_WBITS = 15; /* 32K LZ77 window */ var DEF_MEM_LEVEL = 8; var LENGTH_CODES = 29; /* number of length codes, not counting the special END_BLOCK code */ var LITERALS = 256; /* number of literal bytes 0..255 */ var L_CODES = LITERALS + 1 + LENGTH_CODES; /* number of Literal or Length codes, including the END_BLOCK code */ var D_CODES = 30; /* number of distance codes */ var BL_CODES = 19; /* number of codes used to transfer the bit lengths */ var HEAP_SIZE = 2*L_CODES + 1; /* maximum heap size */ var MAX_BITS = 15; /* All codes must not exceed MAX_BITS bits */ var MIN_MATCH = 3; var MAX_MATCH = 258; var MIN_LOOKAHEAD = (MAX_MATCH + MIN_MATCH + 1); var PRESET_DICT = 0x20; var INIT_STATE = 42; var EXTRA_STATE = 69; var NAME_STATE = 73; var COMMENT_STATE = 91; var HCRC_STATE = 103; var BUSY_STATE = 113; var FINISH_STATE = 666; var BS_NEED_MORE = 1; /* block not completed, need more input or more output */ var BS_BLOCK_DONE = 2; /* block flush performed */ var BS_FINISH_STARTED = 3; /* finish started, need only more output at next deflate */ var BS_FINISH_DONE = 4; /* finish done, accept no more input or output */ var OS_CODE = 0x03; // Unix :) . Don't detect, use this default. function err(strm, errorCode) { strm.msg = msg[errorCode]; return errorCode; } function rank(f) { return ((f) << 1) - ((f) > 4 ? 9 : 0); } function zero(buf) { var len = buf.length; while (--len >= 0) { buf[len] = 0; } } /* ========================================================================= * Flush as much pending output as possible. All deflate() output goes * through this function so some applications may wish to modify it * to avoid allocating a large strm->output buffer and copying into it. * (See also read_buf()). */ function flush_pending(strm) { var s = strm.state; //_tr_flush_bits(s); var len = s.pending; if (len > strm.avail_out) { len = strm.avail_out; } if (len === 0) { return; } utils.arraySet(strm.output, s.pending_buf, s.pending_out, len, strm.next_out); strm.next_out += len; s.pending_out += len; strm.total_out += len; strm.avail_out -= len; s.pending -= len; if (s.pending === 0) { s.pending_out = 0; } } function flush_block_only (s, last) { trees._tr_flush_block(s, (s.block_start >= 0 ? s.block_start : -1), s.strstart - s.block_start, last); s.block_start = s.strstart; flush_pending(s.strm); } function put_byte(s, b) { s.pending_buf[s.pending++] = b; } /* ========================================================================= * Put a short in the pending buffer. The 16-bit value is put in MSB order. * IN assertion: the stream state is correct and there is enough room in * pending_buf. */ function putShortMSB(s, b) { // put_byte(s, (Byte)(b >> 8)); // put_byte(s, (Byte)(b & 0xff)); s.pending_buf[s.pending++] = (b >>> 8) & 0xff; s.pending_buf[s.pending++] = b & 0xff; } /* =========================================================================== * Read a new buffer from the current input stream, update the adler32 * and total number of bytes read. All deflate() input goes through * this function so some applications may wish to modify it to avoid * allocating a large strm->input buffer and copying from it. * (See also flush_pending()). */ function read_buf(strm, buf, start, size) { var len = strm.avail_in; if (len > size) { len = size; } if (len === 0) { return 0; } strm.avail_in -= len; utils.arraySet(buf, strm.input, strm.next_in, len, start); if (strm.state.wrap === 1) { strm.adler = adler32(strm.adler, buf, len, start); } else if (strm.state.wrap === 2) { strm.adler = crc32(strm.adler, buf, len, start); } strm.next_in += len; strm.total_in += len; return len; } /* =========================================================================== * Set match_start to the longest match starting at the given string and * return its length. Matches shorter or equal to prev_length are discarded, * in which case the result is equal to prev_length and match_start is * garbage. * IN assertions: cur_match is the head of the hash chain for the current * string (strstart) and its distance is <= MAX_DIST, and prev_length >= 1 * OUT assertion: the match length is not greater than s->lookahead. */ function longest_match(s, cur_match) { var chain_length = s.max_chain_length; /* max hash chain length */ var scan = s.strstart; /* current string */ var match; /* matched string */ var len; /* length of current match */ var best_len = s.prev_length; /* best match length so far */ var nice_match = s.nice_match; /* stop if match long enough */ var limit = (s.strstart > (s.w_size - MIN_LOOKAHEAD)) ? s.strstart - (s.w_size - MIN_LOOKAHEAD) : 0/*NIL*/; var _win = s.window; // shortcut var wmask = s.w_mask; var prev = s.prev; /* Stop when cur_match becomes <= limit. To simplify the code, * we prevent matches with the string of window index 0. */ var strend = s.strstart + MAX_MATCH; var scan_end1 = _win[scan + best_len - 1]; var scan_end = _win[scan + best_len]; /* The code is optimized for HASH_BITS >= 8 and MAX_MATCH-2 multiple of 16. * It is easy to get rid of this optimization if necessary. */ // Assert(s->hash_bits >= 8 && MAX_MATCH == 258, "Code too clever"); /* Do not waste too much time if we already have a good match: */ if (s.prev_length >= s.good_match) { chain_length >>= 2; } /* Do not look for matches beyond the end of the input. This is necessary * to make deflate deterministic. */ if (nice_match > s.lookahead) { nice_match = s.lookahead; } // Assert((ulg)s->strstart <= s->window_size-MIN_LOOKAHEAD, "need lookahead"); do { // Assert(cur_match < s->strstart, "no future"); match = cur_match; /* Skip to next match if the match length cannot increase * or if the match length is less than 2. Note that the checks below * for insufficient lookahead only occur occasionally for performance * reasons. Therefore uninitialized memory will be accessed, and * conditional jumps will be made that depend on those values. * However the length of the match is limited to the lookahead, so * the output of deflate is not affected by the uninitialized values. */ if (_win[match + best_len] !== scan_end || _win[match + best_len - 1] !== scan_end1 || _win[match] !== _win[scan] || _win[++match] !== _win[scan + 1]) { continue; } /* The check at best_len-1 can be removed because it will be made * again later. (This heuristic is not always a win.) * It is not necessary to compare scan[2] and match[2] since they * are always equal when the other bytes match, given that * the hash keys are equal and that HASH_BITS >= 8. */ scan += 2; match++; // Assert(*scan == *match, "match[2]?"); /* We check for insufficient lookahead only every 8th comparison; * the 256th check will be made at strstart+258. */ do { /*jshint noempty:false*/ } while (_win[++scan] === _win[++match] && _win[++scan] === _win[++match] && _win[++scan] === _win[++match] && _win[++scan] === _win[++match] && _win[++scan] === _win[++match] && _win[++scan] === _win[++match] && _win[++scan] === _win[++match] && _win[++scan] === _win[++match] && scan < strend); // Assert(scan <= s->window+(unsigned)(s->window_size-1), "wild scan"); len = MAX_MATCH - (strend - scan); scan = strend - MAX_MATCH; if (len > best_len) { s.match_start = cur_match; best_len = len; if (len >= nice_match) { break; } scan_end1 = _win[scan + best_len - 1]; scan_end = _win[scan + best_len]; } } while ((cur_match = prev[cur_match & wmask]) > limit && --chain_length !== 0); if (best_len <= s.lookahead) { return best_len; } return s.lookahead; } /* =========================================================================== * Fill the window when the lookahead becomes insufficient. * Updates strstart and lookahead. * * IN assertion: lookahead < MIN_LOOKAHEAD * OUT assertions: strstart <= window_size-MIN_LOOKAHEAD * At least one byte has been read, or avail_in == 0; reads are * performed for at least two bytes (required for the zip translate_eol * option -- not supported here). */ function fill_window(s) { var _w_size = s.w_size; var p, n, m, more, str; //Assert(s->lookahead < MIN_LOOKAHEAD, "already enough lookahead"); do { more = s.window_size - s.lookahead - s.strstart; // JS ints have 32 bit, block below not needed /* Deal with !@#$% 64K limit: */ //if (sizeof(int) <= 2) { // if (more == 0 && s->strstart == 0 && s->lookahead == 0) { // more = wsize; // // } else if (more == (unsigned)(-1)) { // /* Very unlikely, but possible on 16 bit machine if // * strstart == 0 && lookahead == 1 (input done a byte at time) // */ // more--; // } //} /* If the window is almost full and there is insufficient lookahead, * move the upper half to the lower one to make room in the upper half. */ if (s.strstart >= _w_size + (_w_size - MIN_LOOKAHEAD)) { utils.arraySet(s.window, s.window, _w_size, _w_size, 0); s.match_start -= _w_size; s.strstart -= _w_size; /* we now have strstart >= MAX_DIST */ s.block_start -= _w_size; /* Slide the hash table (could be avoided with 32 bit values at the expense of memory usage). We slide even when level == 0 to keep the hash table consistent if we switch back to level > 0 later. (Using level 0 permanently is not an optimal usage of zlib, so we don't care about this pathological case.) */ n = s.hash_size; p = n; do { m = s.head[--p]; s.head[p] = (m >= _w_size ? m - _w_size : 0); } while (--n); n = _w_size; p = n; do { m = s.prev[--p]; s.prev[p] = (m >= _w_size ? m - _w_size : 0); /* If n is not on any hash chain, prev[n] is garbage but * its value will never be used. */ } while (--n); more += _w_size; } if (s.strm.avail_in === 0) { break; } /* If there was no sliding: * strstart <= WSIZE+MAX_DIST-1 && lookahead <= MIN_LOOKAHEAD - 1 && * more == window_size - lookahead - strstart * => more >= window_size - (MIN_LOOKAHEAD-1 + WSIZE + MAX_DIST-1) * => more >= window_size - 2*WSIZE + 2 * In the BIG_MEM or MMAP case (not yet supported), * window_size == input_size + MIN_LOOKAHEAD && * strstart + s->lookahead <= input_size => more >= MIN_LOOKAHEAD. * Otherwise, window_size == 2*WSIZE so more >= 2. * If there was sliding, more >= WSIZE. So in all cases, more >= 2. */ //Assert(more >= 2, "more < 2"); n = read_buf(s.strm, s.window, s.strstart + s.lookahead, more); s.lookahead += n; /* Initialize the hash value now that we have some input: */ if (s.lookahead + s.insert >= MIN_MATCH) { str = s.strstart - s.insert; s.ins_h = s.window[str]; /* UPDATE_HASH(s, s->ins_h, s->window[str + 1]); */ s.ins_h = ((s.ins_h << s.hash_shift) ^ s.window[str + 1]) & s.hash_mask; //#if MIN_MATCH != 3 // Call update_hash() MIN_MATCH-3 more times //#endif while (s.insert) { /* UPDATE_HASH(s, s->ins_h, s->window[str + MIN_MATCH-1]); */ s.ins_h = ((s.ins_h << s.hash_shift) ^ s.window[str + MIN_MATCH-1]) & s.hash_mask; s.prev[str & s.w_mask] = s.head[s.ins_h]; s.head[s.ins_h] = str; str++; s.insert--; if (s.lookahead + s.insert < MIN_MATCH) { break; } } } /* If the whole input has less than MIN_MATCH bytes, ins_h is garbage, * but this is not important since only literal bytes will be emitted. */ } while (s.lookahead < MIN_LOOKAHEAD && s.strm.avail_in !== 0); /* If the WIN_INIT bytes after the end of the current data have never been * written, then zero those bytes in order to avoid memory check reports of * the use of uninitialized (or uninitialised as Julian writes) bytes by * the longest match routines. Update the high water mark for the next * time through here. WIN_INIT is set to MAX_MATCH since the longest match * routines allow scanning to strstart + MAX_MATCH, ignoring lookahead. */ // if (s.high_water < s.window_size) { // var curr = s.strstart + s.lookahead; // var init = 0; // // if (s.high_water < curr) { // /* Previous high water mark below current data -- zero WIN_INIT // * bytes or up to end of window, whichever is less. // */ // init = s.window_size - curr; // if (init > WIN_INIT) // init = WIN_INIT; // zmemzero(s->window + curr, (unsigned)init); // s->high_water = curr + init; // } // else if (s->high_water < (ulg)curr + WIN_INIT) { // /* High water mark at or above current data, but below current data // * plus WIN_INIT -- zero out to current data plus WIN_INIT, or up // * to end of window, whichever is less. // */ // init = (ulg)curr + WIN_INIT - s->high_water; // if (init > s->window_size - s->high_water) // init = s->window_size - s->high_water; // zmemzero(s->window + s->high_water, (unsigned)init); // s->high_water += init; // } // } // // Assert((ulg)s->strstart <= s->window_size - MIN_LOOKAHEAD, // "not enough room for search"); } /* =========================================================================== * Copy without compression as much as possible from the input stream, return * the current block state. * This function does not insert new strings in the dictionary since * uncompressible data is probably not useful. This function is used * only for the level=0 compression option. * NOTE: this function should be optimized to avoid extra copying from * window to pending_buf. */ function deflate_stored(s, flush) { /* Stored blocks are limited to 0xffff bytes, pending_buf is limited * to pending_buf_size, and each stored block has a 5 byte header: */ var max_block_size = 0xffff; if (max_block_size > s.pending_buf_size - 5) { max_block_size = s.pending_buf_size - 5; } /* Copy as much as possible from input to output: */ for (;;) { /* Fill the window as much as possible: */ if (s.lookahead <= 1) { //Assert(s->strstart < s->w_size+MAX_DIST(s) || // s->block_start >= (long)s->w_size, "slide too late"); // if (!(s.strstart < s.w_size + (s.w_size - MIN_LOOKAHEAD) || // s.block_start >= s.w_size)) { // throw new Error("slide too late"); // } fill_window(s); if (s.lookahead === 0 && flush === Z_NO_FLUSH) { return BS_NEED_MORE; } if (s.lookahead === 0) { break; } /* flush the current block */ } //Assert(s->block_start >= 0L, "block gone"); // if (s.block_start < 0) throw new Error("block gone"); s.strstart += s.lookahead; s.lookahead = 0; /* Emit a stored block if pending_buf will be full: */ var max_start = s.block_start + max_block_size; if (s.strstart === 0 || s.strstart >= max_start) { /* strstart == 0 is possible when wraparound on 16-bit machine */ s.lookahead = s.strstart - max_start; s.strstart = max_start; /*** FLUSH_BLOCK(s, 0); ***/ flush_block_only(s, false); if (s.strm.avail_out === 0) { return BS_NEED_MORE; } /***/ } /* Flush if we may have to slide, otherwise block_start may become * negative and the data will be gone: */ if (s.strstart - s.block_start >= (s.w_size - MIN_LOOKAHEAD)) { /*** FLUSH_BLOCK(s, 0); ***/ flush_block_only(s, false); if (s.strm.avail_out === 0) { return BS_NEED_MORE; } /***/ } } s.insert = 0; if (flush === Z_FINISH) { /*** FLUSH_BLOCK(s, 1); ***/ flush_block_only(s, true); if (s.strm.avail_out === 0) { return BS_FINISH_STARTED; } /***/ return BS_FINISH_DONE; } if (s.strstart > s.block_start) { /*** FLUSH_BLOCK(s, 0); ***/ flush_block_only(s, false); if (s.strm.avail_out === 0) { return BS_NEED_MORE; } /***/ } return BS_NEED_MORE; } /* =========================================================================== * Compress as much as possible from the input stream, return the current * block state. * This function does not perform lazy evaluation of matches and inserts * new strings in the dictionary only for unmatched strings or for short * matches. It is used only for the fast compression options. */ function deflate_fast(s, flush) { var hash_head; /* head of the hash chain */ var bflush; /* set if current block must be flushed */ for (;;) { /* Make sure that we always have enough lookahead, except * at the end of the input file. We need MAX_MATCH bytes * for the next match, plus MIN_MATCH bytes to insert the * string following the next match. */ if (s.lookahead < MIN_LOOKAHEAD) { fill_window(s); if (s.lookahead < MIN_LOOKAHEAD && flush === Z_NO_FLUSH) { return BS_NEED_MORE; } if (s.lookahead === 0) { break; /* flush the current block */ } } /* Insert the string window[strstart .. strstart+2] in the * dictionary, and set hash_head to the head of the hash chain: */ hash_head = 0/*NIL*/; if (s.lookahead >= MIN_MATCH) { /*** INSERT_STRING(s, s.strstart, hash_head); ***/ s.ins_h = ((s.ins_h << s.hash_shift) ^ s.window[s.strstart + MIN_MATCH - 1]) & s.hash_mask; hash_head = s.prev[s.strstart & s.w_mask] = s.head[s.ins_h]; s.head[s.ins_h] = s.strstart; /***/ } /* Find the longest match, discarding those <= prev_length. * At this point we have always match_length < MIN_MATCH */ if (hash_head !== 0/*NIL*/ && ((s.strstart - hash_head) <= (s.w_size - MIN_LOOKAHEAD))) { /* To simplify the code, we prevent matches with the string * of window index 0 (in particular we have to avoid a match * of the string with itself at the start of the input file). */ s.match_length = longest_match(s, hash_head); /* longest_match() sets match_start */ } if (s.match_length >= MIN_MATCH) { // check_match(s, s.strstart, s.match_start, s.match_length); // for debug only /*** _tr_tally_dist(s, s.strstart - s.match_start, s.match_length - MIN_MATCH, bflush); ***/ bflush = trees._tr_tally(s, s.strstart - s.match_start, s.match_length - MIN_MATCH); s.lookahead -= s.match_length; /* Insert new strings in the hash table only if the match length * is not too large. This saves time but degrades compression. */ if (s.match_length <= s.max_lazy_match/*max_insert_length*/ && s.lookahead >= MIN_MATCH) { s.match_length--; /* string at strstart already in table */ do { s.strstart++; /*** INSERT_STRING(s, s.strstart, hash_head); ***/ s.ins_h = ((s.ins_h << s.hash_shift) ^ s.window[s.strstart + MIN_MATCH - 1]) & s.hash_mask; hash_head = s.prev[s.strstart & s.w_mask] = s.head[s.ins_h]; s.head[s.ins_h] = s.strstart; /***/ /* strstart never exceeds WSIZE-MAX_MATCH, so there are * always MIN_MATCH bytes ahead. */ } while (--s.match_length !== 0); s.strstart++; } else { s.strstart += s.match_length; s.match_length = 0; s.ins_h = s.window[s.strstart]; /* UPDATE_HASH(s, s.ins_h, s.window[s.strstart+1]); */ s.ins_h = ((s.ins_h << s.hash_shift) ^ s.window[s.strstart + 1]) & s.hash_mask; //#if MIN_MATCH != 3 // Call UPDATE_HASH() MIN_MATCH-3 more times //#endif /* If lookahead < MIN_MATCH, ins_h is garbage, but it does not * matter since it will be recomputed at next deflate call. */ } } else { /* No match, output a literal byte */ //Tracevv((stderr,"%c", s.window[s.strstart])); /*** _tr_tally_lit(s, s.window[s.strstart], bflush); ***/ bflush = trees._tr_tally(s, 0, s.window[s.strstart]); s.lookahead--; s.strstart++; } if (bflush) { /*** FLUSH_BLOCK(s, 0); ***/ flush_block_only(s, false); if (s.strm.avail_out === 0) { return BS_NEED_MORE; } /***/ } } s.insert = ((s.strstart < (MIN_MATCH-1)) ? s.strstart : MIN_MATCH-1); if (flush === Z_FINISH) { /*** FLUSH_BLOCK(s, 1); ***/ flush_block_only(s, true); if (s.strm.avail_out === 0) { return BS_FINISH_STARTED; } /***/ return BS_FINISH_DONE; } if (s.last_lit) { /*** FLUSH_BLOCK(s, 0); ***/ flush_block_only(s, false); if (s.strm.avail_out === 0) { return BS_NEED_MORE; } /***/ } return BS_BLOCK_DONE; } /* =========================================================================== * Same as above, but achieves better compression. We use a lazy * evaluation for matches: a match is finally adopted only if there is * no better match at the next window position. */ function deflate_slow(s, flush) { var hash_head; /* head of hash chain */ var bflush; /* set if current block must be flushed */ var max_insert; /* Process the input block. */ for (;;) { /* Make sure that we always have enough lookahead, except * at the end of the input file. We need MAX_MATCH bytes * for the next match, plus MIN_MATCH bytes to insert the * string following the next match. */ if (s.lookahead < MIN_LOOKAHEAD) { fill_window(s); if (s.lookahead < MIN_LOOKAHEAD && flush === Z_NO_FLUSH) { return BS_NEED_MORE; } if (s.lookahead === 0) { break; } /* flush the current block */ } /* Insert the string window[strstart .. strstart+2] in the * dictionary, and set hash_head to the head of the hash chain: */ hash_head = 0/*NIL*/; if (s.lookahead >= MIN_MATCH) { /*** INSERT_STRING(s, s.strstart, hash_head); ***/ s.ins_h = ((s.ins_h << s.hash_shift) ^ s.window[s.strstart + MIN_MATCH - 1]) & s.hash_mask; hash_head = s.prev[s.strstart & s.w_mask] = s.head[s.ins_h]; s.head[s.ins_h] = s.strstart; /***/ } /* Find the longest match, discarding those <= prev_length. */ s.prev_length = s.match_length; s.prev_match = s.match_start; s.match_length = MIN_MATCH-1; if (hash_head !== 0/*NIL*/ && s.prev_length < s.max_lazy_match && s.strstart - hash_head <= (s.w_size-MIN_LOOKAHEAD)/*MAX_DIST(s)*/) { /* To simplify the code, we prevent matches with the string * of window index 0 (in particular we have to avoid a match * of the string with itself at the start of the input file). */ s.match_length = longest_match(s, hash_head); /* longest_match() sets match_start */ if (s.match_length <= 5 && (s.strategy === Z_FILTERED || (s.match_length === MIN_MATCH && s.strstart - s.match_start > 4096/*TOO_FAR*/))) { /* If prev_match is also MIN_MATCH, match_start is garbage * but we will ignore the current match anyway. */ s.match_length = MIN_MATCH-1; } } /* If there was a match at the previous step and the current * match is not better, output the previous match: */ if (s.prev_length >= MIN_MATCH && s.match_length <= s.prev_length) { max_insert = s.strstart + s.lookahead - MIN_MATCH; /* Do not insert strings in hash table beyond this. */ //check_match(s, s.strstart-1, s.prev_match, s.prev_length); /***_tr_tally_dist(s, s.strstart - 1 - s.prev_match, s.prev_length - MIN_MATCH, bflush);***/ bflush = trees._tr_tally(s, s.strstart - 1- s.prev_match, s.prev_length - MIN_MATCH); /* Insert in hash table all strings up to the end of the match. * strstart-1 and strstart are already inserted. If there is not * enough lookahead, the last two strings are not inserted in * the hash table. */ s.lookahead -= s.prev_length-1; s.prev_length -= 2; do { if (++s.strstart <= max_insert) { /*** INSERT_STRING(s, s.strstart, hash_head); ***/ s.ins_h = ((s.ins_h << s.hash_shift) ^ s.window[s.strstart + MIN_MATCH - 1]) & s.hash_mask; hash_head = s.prev[s.strstart & s.w_mask] = s.head[s.ins_h]; s.head[s.ins_h] = s.strstart; /***/ } } while (--s.prev_length !== 0); s.match_available = 0; s.match_length = MIN_MATCH-1; s.strstart++; if (bflush) { /*** FLUSH_BLOCK(s, 0); ***/ flush_block_only(s, false); if (s.strm.avail_out === 0) { return BS_NEED_MORE; } /***/ } } else if (s.match_available) { /* If there was no match at the previous position, output a * single literal. If there was a match but the current match * is longer, truncate the previous match to a single literal. */ //Tracevv((stderr,"%c", s->window[s->strstart-1])); /*** _tr_tally_lit(s, s.window[s.strstart-1], bflush); ***/ bflush = trees._tr_tally(s, 0, s.window[s.strstart-1]); if (bflush) { /*** FLUSH_BLOCK_ONLY(s, 0) ***/ flush_block_only(s, false); /***/ } s.strstart++; s.lookahead--; if (s.strm.avail_out === 0) { return BS_NEED_MORE; } } else { /* There is no previous match to compare with, wait for * the next step to decide. */ s.match_available = 1; s.strstart++; s.lookahead--; } } //Assert (flush != Z_NO_FLUSH, "no flush?"); if (s.match_available) { //Tracevv((stderr,"%c", s->window[s->strstart-1])); /*** _tr_tally_lit(s, s.window[s.strstart-1], bflush); ***/ bflush = trees._tr_tally(s, 0, s.window[s.strstart-1]); s.match_available = 0; } s.insert = s.strstart < MIN_MATCH-1 ? s.strstart : MIN_MATCH-1; if (flush === Z_FINISH) { /*** FLUSH_BLOCK(s, 1); ***/ flush_block_only(s, true); if (s.strm.avail_out === 0) { return BS_FINISH_STARTED; } /***/ return BS_FINISH_DONE; } if (s.last_lit) { /*** FLUSH_BLOCK(s, 0); ***/ flush_block_only(s, false); if (s.strm.avail_out === 0) { return BS_NEED_MORE; } /***/ } return BS_BLOCK_DONE; } /* =========================================================================== * For Z_RLE, simply look for runs of bytes, generate matches only of distance * one. Do not maintain a hash table. (It will be regenerated if this run of * deflate switches away from Z_RLE.) */ function deflate_rle(s, flush) { var bflush; /* set if current block must be flushed */ var prev; /* byte at distance one to match */ var scan, strend; /* scan goes up to strend for length of run */ var _win = s.window; for (;;) { /* Make sure that we always have enough lookahead, except * at the end of the input file. We need MAX_MATCH bytes * for the longest run, plus one for the unrolled loop. */ if (s.lookahead <= MAX_MATCH) { fill_window(s); if (s.lookahead <= MAX_MATCH && flush === Z_NO_FLUSH) { return BS_NEED_MORE; } if (s.lookahead === 0) { break; } /* flush the current block */ } /* See how many times the previous byte repeats */ s.match_length = 0; if (s.lookahead >= MIN_MATCH && s.strstart > 0) { scan = s.strstart - 1; prev = _win[scan]; if (prev === _win[++scan] && prev === _win[++scan] && prev === _win[++scan]) { strend = s.strstart + MAX_MATCH; do { /*jshint noempty:false*/ } while (prev === _win[++scan] && prev === _win[++scan] && prev === _win[++scan] && prev === _win[++scan] && prev === _win[++scan] && prev === _win[++scan] && prev === _win[++scan] && prev === _win[++scan] && scan < strend); s.match_length = MAX_MATCH - (strend - scan); if (s.match_length > s.lookahead) { s.match_length = s.lookahead; } } //Assert(scan <= s->window+(uInt)(s->window_size-1), "wild scan"); } /* Emit match if have run of MIN_MATCH or longer, else emit literal */ if (s.match_length >= MIN_MATCH) { //check_match(s, s.strstart, s.strstart - 1, s.match_length); /*** _tr_tally_dist(s, 1, s.match_length - MIN_MATCH, bflush); ***/ bflush = trees._tr_tally(s, 1, s.match_length - MIN_MATCH); s.lookahead -= s.match_length; s.strstart += s.match_length; s.match_length = 0; } else { /* No match, output a literal byte */ //Tracevv((stderr,"%c", s->window[s->strstart])); /*** _tr_tally_lit(s, s.window[s.strstart], bflush); ***/ bflush = trees._tr_tally(s, 0, s.window[s.strstart]); s.lookahead--; s.strstart++; } if (bflush) { /*** FLUSH_BLOCK(s, 0); ***/ flush_block_only(s, false); if (s.strm.avail_out === 0) { return BS_NEED_MORE; } /***/ } } s.insert = 0; if (flush === Z_FINISH) { /*** FLUSH_BLOCK(s, 1); ***/ flush_block_only(s, true); if (s.strm.avail_out === 0) { return BS_FINISH_STARTED; } /***/ return BS_FINISH_DONE; } if (s.last_lit) { /*** FLUSH_BLOCK(s, 0); ***/ flush_block_only(s, false); if (s.strm.avail_out === 0) { return BS_NEED_MORE; } /***/ } return BS_BLOCK_DONE; } /* =========================================================================== * For Z_HUFFMAN_ONLY, do not look for matches. Do not maintain a hash table. * (It will be regenerated if this run of deflate switches away from Huffman.) */ function deflate_huff(s, flush) { var bflush; /* set if current block must be flushed */ for (;;) { /* Make sure that we have a literal to write. */ if (s.lookahead === 0) { fill_window(s); if (s.lookahead === 0) { if (flush === Z_NO_FLUSH) { return BS_NEED_MORE; } break; /* flush the current block */ } } /* Output a literal byte */ s.match_length = 0; //Tracevv((stderr,"%c", s->window[s->strstart])); /*** _tr_tally_lit(s, s.window[s.strstart], bflush); ***/ bflush = trees._tr_tally(s, 0, s.window[s.strstart]); s.lookahead--; s.strstart++; if (bflush) { /*** FLUSH_BLOCK(s, 0); ***/ flush_block_only(s, false); if (s.strm.avail_out === 0) { return BS_NEED_MORE; } /***/ } } s.insert = 0; if (flush === Z_FINISH) { /*** FLUSH_BLOCK(s, 1); ***/ flush_block_only(s, true); if (s.strm.avail_out === 0) { return BS_FINISH_STARTED; } /***/ return BS_FINISH_DONE; } if (s.last_lit) { /*** FLUSH_BLOCK(s, 0); ***/ flush_block_only(s, false); if (s.strm.avail_out === 0) { return BS_NEED_MORE; } /***/ } return BS_BLOCK_DONE; } /* Values for max_lazy_match, good_match and max_chain_length, depending on * the desired pack level (0..9). The values given below have been tuned to * exclude worst case performance for pathological files. Better values may be * found for specific files. */ var Config = function (good_length, max_lazy, nice_length, max_chain, func) { this.good_length = good_length; this.max_lazy = max_lazy; this.nice_length = nice_length; this.max_chain = max_chain; this.func = func; }; var configuration_table; configuration_table = [ /* good lazy nice chain */ new Config(0, 0, 0, 0, deflate_stored), /* 0 store only */ new Config(4, 4, 8, 4, deflate_fast), /* 1 max speed, no lazy matches */ new Config(4, 5, 16, 8, deflate_fast), /* 2 */ new Config(4, 6, 32, 32, deflate_fast), /* 3 */ new Config(4, 4, 16, 16, deflate_slow), /* 4 lazy matches */ new Config(8, 16, 32, 32, deflate_slow), /* 5 */ new Config(8, 16, 128, 128, deflate_slow), /* 6 */ new Config(8, 32, 128, 256, deflate_slow), /* 7 */ new Config(32, 128, 258, 1024, deflate_slow), /* 8 */ new Config(32, 258, 258, 4096, deflate_slow) /* 9 max compression */ ]; /* =========================================================================== * Initialize the "longest match" routines for a new zlib stream */ function lm_init(s) { s.window_size = 2 * s.w_size; /*** CLEAR_HASH(s); ***/ zero(s.head); // Fill with NIL (= 0); /* Set the default configuration parameters: */ s.max_lazy_match = configuration_table[s.level].max_lazy; s.good_match = configuration_table[s.level].good_length; s.nice_match = configuration_table[s.level].nice_length; s.max_chain_length = configuration_table[s.level].max_chain; s.strstart = 0; s.block_start = 0; s.lookahead = 0; s.insert = 0; s.match_length = s.prev_length = MIN_MATCH - 1; s.match_available = 0; s.ins_h = 0; } function DeflateState() { this.strm = null; /* pointer back to this zlib stream */ this.status = 0; /* as the name implies */ this.pending_buf = null; /* output still pending */ this.pending_buf_size = 0; /* size of pending_buf */ this.pending_out = 0; /* next pending byte to output to the stream */ this.pending = 0; /* nb of bytes in the pending buffer */ this.wrap = 0; /* bit 0 true for zlib, bit 1 true for gzip */ this.gzhead = null; /* gzip header information to write */ this.gzindex = 0; /* where in extra, name, or comment */ this.method = Z_DEFLATED; /* can only be DEFLATED */ this.last_flush = -1; /* value of flush param for previous deflate call */ this.w_size = 0; /* LZ77 window size (32K by default) */ this.w_bits = 0; /* log2(w_size) (8..16) */ this.w_mask = 0; /* w_size - 1 */ this.window = null; /* Sliding window. Input bytes are read into the second half of the window, * and move to the first half later to keep a dictionary of at least wSize * bytes. With this organization, matches are limited to a distance of * wSize-MAX_MATCH bytes, but this ensures that IO is always * performed with a length multiple of the block size. */ this.window_size = 0; /* Actual size of window: 2*wSize, except when the user input buffer * is directly used as sliding window. */ this.prev = null; /* Link to older string with same hash index. To limit the size of this * array to 64K, this link is maintained only for the last 32K strings. * An index in this array is thus a window index modulo 32K. */ this.head = null; /* Heads of the hash chains or NIL. */ this.ins_h = 0; /* hash index of string to be inserted */ this.hash_size = 0; /* number of elements in hash table */ this.hash_bits = 0; /* log2(hash_size) */ this.hash_mask = 0; /* hash_size-1 */ this.hash_shift = 0; /* Number of bits by which ins_h must be shifted at each input * step. It must be such that after MIN_MATCH steps, the oldest * byte no longer takes part in the hash key, that is: * hash_shift * MIN_MATCH >= hash_bits */ this.block_start = 0; /* Window position at the beginning of the current output block. Gets * negative when the window is moved backwards. */ this.match_length = 0; /* length of best match */ this.prev_match = 0; /* previous match */ this.match_available = 0; /* set if previous match exists */ this.strstart = 0; /* start of string to insert */ this.match_start = 0; /* start of matching string */ this.lookahead = 0; /* number of valid bytes ahead in window */ this.prev_length = 0; /* Length of the best match at previous step. Matches not greater than this * are discarded. This is used in the lazy match evaluation. */ this.max_chain_length = 0; /* To speed up deflation, hash chains are never searched beyond this * length. A higher limit improves compression ratio but degrades the * speed. */ this.max_lazy_match = 0; /* Attempt to find a better match only when the current match is strictly * smaller than this value. This mechanism is used only for compression * levels >= 4. */ // That's alias to max_lazy_match, don't use directly //this.max_insert_length = 0; /* Insert new strings in the hash table only if the match length is not * greater than this length. This saves time but degrades compression. * max_insert_length is used only for compression levels <= 3. */ this.level = 0; /* compression level (1..9) */ this.strategy = 0; /* favor or force Huffman coding*/ this.good_match = 0; /* Use a faster search when the previous match is longer than this */ this.nice_match = 0; /* Stop searching when current match exceeds this */ /* used by trees.c: */ /* Didn't use ct_data typedef below to suppress compiler warning */ // struct ct_data_s dyn_ltree[HEAP_SIZE]; /* literal and length tree */ // struct ct_data_s dyn_dtree[2*D_CODES+1]; /* distance tree */ // struct ct_data_s bl_tree[2*BL_CODES+1]; /* Huffman tree for bit lengths */ // Use flat array of DOUBLE size, with interleaved fata, // because JS does not support effective this.dyn_ltree = new utils.Buf16(HEAP_SIZE * 2); this.dyn_dtree = new utils.Buf16((2*D_CODES+1) * 2); this.bl_tree = new utils.Buf16((2*BL_CODES+1) * 2); zero(this.dyn_ltree); zero(this.dyn_dtree); zero(this.bl_tree); this.l_desc = null; /* desc. for literal tree */ this.d_desc = null; /* desc. for distance tree */ this.bl_desc = null; /* desc. for bit length tree */ //ush bl_count[MAX_BITS+1]; this.bl_count = new utils.Buf16(MAX_BITS+1); /* number of codes at each bit length for an optimal tree */ //int heap[2*L_CODES+1]; /* heap used to build the Huffman trees */ this.heap = new utils.Buf16(2*L_CODES+1); /* heap used to build the Huffman trees */ zero(this.heap); this.heap_len = 0; /* number of elements in the heap */ this.heap_max = 0; /* element of largest frequency */ /* The sons of heap[n] are heap[2*n] and heap[2*n+1]. heap[0] is not used. * The same heap array is used to build all trees. */ this.depth = new utils.Buf16(2*L_CODES+1); //uch depth[2*L_CODES+1]; zero(this.depth); /* Depth of each subtree used as tie breaker for trees of equal frequency */ this.l_buf = 0; /* buffer index for literals or lengths */ this.lit_bufsize = 0; /* Size of match buffer for literals/lengths. There are 4 reasons for * limiting lit_bufsize to 64K: * - frequencies can be kept in 16 bit counters * - if compression is not successful for the first block, all input * data is still in the window so we can still emit a stored block even * when input comes from standard input. (This can also be done for * all blocks if lit_bufsize is not greater than 32K.) * - if compression is not successful for a file smaller than 64K, we can * even emit a stored file instead of a stored block (saving 5 bytes). * This is applicable only for zip (not gzip or zlib). * - creating new Huffman trees less frequently may not provide fast * adaptation to changes in the input data statistics. (Take for * example a binary file with poorly compressible code followed by * a highly compressible string table.) Smaller buffer sizes give * fast adaptation but have of course the overhead of transmitting * trees more frequently. * - I can't count above 4 */ this.last_lit = 0; /* running index in l_buf */ this.d_buf = 0; /* Buffer index for distances. To simplify the code, d_buf and l_buf have * the same number of elements. To use different lengths, an extra flag * array would be necessary. */ this.opt_len = 0; /* bit length of current block with optimal trees */ this.static_len = 0; /* bit length of current block with static trees */ this.matches = 0; /* number of string matches in current block */ this.insert = 0; /* bytes at end of window left to insert */ this.bi_buf = 0; /* Output buffer. bits are inserted starting at the bottom (least * significant bits). */ this.bi_valid = 0; /* Number of valid bits in bi_buf. All bits above the last valid bit * are always zero. */ // Used for window memory init. We safely ignore it for JS. That makes // sense only for pointers and memory check tools. //this.high_water = 0; /* High water mark offset in window for initialized bytes -- bytes above * this are set to zero in order to avoid memory check warnings when * longest match routines access bytes past the input. This is then * updated to the new high water mark. */ } function deflateResetKeep(strm) { var s; if (!strm || !strm.state) { return err(strm, Z_STREAM_ERROR); } strm.total_in = strm.total_out = 0; strm.data_type = Z_UNKNOWN; s = strm.state; s.pending = 0; s.pending_out = 0; if (s.wrap < 0) { s.wrap = -s.wrap; /* was made negative by deflate(..., Z_FINISH); */ } s.status = (s.wrap ? INIT_STATE : BUSY_STATE); strm.adler = (s.wrap === 2) ? 0 // crc32(0, Z_NULL, 0) : 1; // adler32(0, Z_NULL, 0) s.last_flush = Z_NO_FLUSH; trees._tr_init(s); return Z_OK; } function deflateReset(strm) { var ret = deflateResetKeep(strm); if (ret === Z_OK) { lm_init(strm.state); } return ret; } function deflateSetHeader(strm, head) { if (!strm || !strm.state) { return Z_STREAM_ERROR; } if (strm.state.wrap !== 2) { return Z_STREAM_ERROR; } strm.state.gzhead = head; return Z_OK; } function deflateInit2(strm, level, method, windowBits, memLevel, strategy) { if (!strm) { // === Z_NULL return Z_STREAM_ERROR; } var wrap = 1; if (level === Z_DEFAULT_COMPRESSION) { level = 6; } if (windowBits < 0) { /* suppress zlib wrapper */ wrap = 0; windowBits = -windowBits; } else if (windowBits > 15) { wrap = 2; /* write gzip wrapper instead */ windowBits -= 16; } if (memLevel < 1 || memLevel > MAX_MEM_LEVEL || method !== Z_DEFLATED || windowBits < 8 || windowBits > 15 || level < 0 || level > 9 || strategy < 0 || strategy > Z_FIXED) { return err(strm, Z_STREAM_ERROR); } if (windowBits === 8) { windowBits = 9; } /* until 256-byte window bug fixed */ var s = new DeflateState(); strm.state = s; s.strm = strm; s.wrap = wrap; s.gzhead = null; s.w_bits = windowBits; s.w_size = 1 << s.w_bits; s.w_mask = s.w_size - 1; s.hash_bits = memLevel + 7; s.hash_size = 1 << s.hash_bits; s.hash_mask = s.hash_size - 1; s.hash_shift = ~~((s.hash_bits + MIN_MATCH - 1) / MIN_MATCH); s.window = new utils.Buf8(s.w_size * 2); s.head = new utils.Buf16(s.hash_size); s.prev = new utils.Buf16(s.w_size); // Don't need mem init magic for JS. //s.high_water = 0; /* nothing written to s->window yet */ s.lit_bufsize = 1 << (memLevel + 6); /* 16K elements by default */ s.pending_buf_size = s.lit_bufsize * 4; s.pending_buf = new utils.Buf8(s.pending_buf_size); s.d_buf = s.lit_bufsize >> 1; s.l_buf = (1 + 2) * s.lit_bufsize; s.level = level; s.strategy = strategy; s.method = method; return deflateReset(strm); } function deflateInit(strm, level) { return deflateInit2(strm, level, Z_DEFLATED, MAX_WBITS, DEF_MEM_LEVEL, Z_DEFAULT_STRATEGY); } function deflate(strm, flush) { var old_flush, s; var beg, val; // for gzip header write only if (!strm || !strm.state || flush > Z_BLOCK || flush < 0) { return strm ? err(strm, Z_STREAM_ERROR) : Z_STREAM_ERROR; } s = strm.state; if (!strm.output || (!strm.input && strm.avail_in !== 0) || (s.status === FINISH_STATE && flush !== Z_FINISH)) { return err(strm, (strm.avail_out === 0) ? Z_BUF_ERROR : Z_STREAM_ERROR); } s.strm = strm; /* just in case */ old_flush = s.last_flush; s.last_flush = flush; /* Write the header */ if (s.status === INIT_STATE) { if (s.wrap === 2) { // GZIP header strm.adler = 0; //crc32(0L, Z_NULL, 0); put_byte(s, 31); put_byte(s, 139); put_byte(s, 8); if (!s.gzhead) { // s->gzhead == Z_NULL put_byte(s, 0); put_byte(s, 0); put_byte(s, 0); put_byte(s, 0); put_byte(s, 0); put_byte(s, s.level === 9 ? 2 : (s.strategy >= Z_HUFFMAN_ONLY || s.level < 2 ? 4 : 0)); put_byte(s, OS_CODE); s.status = BUSY_STATE; } else { put_byte(s, (s.gzhead.text ? 1 : 0) + (s.gzhead.hcrc ? 2 : 0) + (!s.gzhead.extra ? 0 : 4) + (!s.gzhead.name ? 0 : 8) + (!s.gzhead.comment ? 0 : 16) ); put_byte(s, s.gzhead.time & 0xff); put_byte(s, (s.gzhead.time >> 8) & 0xff); put_byte(s, (s.gzhead.time >> 16) & 0xff); put_byte(s, (s.gzhead.time >> 24) & 0xff); put_byte(s, s.level === 9 ? 2 : (s.strategy >= Z_HUFFMAN_ONLY || s.level < 2 ? 4 : 0)); put_byte(s, s.gzhead.os & 0xff); if (s.gzhead.extra && s.gzhead.extra.length) { put_byte(s, s.gzhead.extra.length & 0xff); put_byte(s, (s.gzhead.extra.length >> 8) & 0xff); } if (s.gzhead.hcrc) { strm.adler = crc32(strm.adler, s.pending_buf, s.pending, 0); } s.gzindex = 0; s.status = EXTRA_STATE; } } else // DEFLATE header { var header = (Z_DEFLATED + ((s.w_bits - 8) << 4)) << 8; var level_flags = -1; if (s.strategy >= Z_HUFFMAN_ONLY || s.level < 2) { level_flags = 0; } else if (s.level < 6) { level_flags = 1; } else if (s.level === 6) { level_flags = 2; } else { level_flags = 3; } header |= (level_flags << 6); if (s.strstart !== 0) { header |= PRESET_DICT; } header += 31 - (header % 31); s.status = BUSY_STATE; putShortMSB(s, header); /* Save the adler32 of the preset dictionary: */ if (s.strstart !== 0) { putShortMSB(s, strm.adler >>> 16); putShortMSB(s, strm.adler & 0xffff); } strm.adler = 1; // adler32(0L, Z_NULL, 0); } } //#ifdef GZIP if (s.status === EXTRA_STATE) { if (s.gzhead.extra/* != Z_NULL*/) { beg = s.pending; /* start of bytes to update crc */ while (s.gzindex < (s.gzhead.extra.length & 0xffff)) { if (s.pending === s.pending_buf_size) { if (s.gzhead.hcrc && s.pending > beg) { strm.adler = crc32(strm.adler, s.pending_buf, s.pending - beg, beg); } flush_pending(strm); beg = s.pending; if (s.pending === s.pending_buf_size) { break; } } put_byte(s, s.gzhead.extra[s.gzindex] & 0xff); s.gzindex++; } if (s.gzhead.hcrc && s.pending > beg) { strm.adler = crc32(strm.adler, s.pending_buf, s.pending - beg, beg); } if (s.gzindex === s.gzhead.extra.length) { s.gzindex = 0; s.status = NAME_STATE; } } else { s.status = NAME_STATE; } } if (s.status === NAME_STATE) { if (s.gzhead.name/* != Z_NULL*/) { beg = s.pending; /* start of bytes to update crc */ //int val; do { if (s.pending === s.pending_buf_size) { if (s.gzhead.hcrc && s.pending > beg) { strm.adler = crc32(strm.adler, s.pending_buf, s.pending - beg, beg); } flush_pending(strm); beg = s.pending; if (s.pending === s.pending_buf_size) { val = 1; break; } } // JS specific: little magic to add zero terminator to end of string if (s.gzindex < s.gzhead.name.length) { val = s.gzhead.name.charCodeAt(s.gzindex++) & 0xff; } else { val = 0; } put_byte(s, val); } while (val !== 0); if (s.gzhead.hcrc && s.pending > beg) { strm.adler = crc32(strm.adler, s.pending_buf, s.pending - beg, beg); } if (val === 0) { s.gzindex = 0; s.status = COMMENT_STATE; } } else { s.status = COMMENT_STATE; } } if (s.status === COMMENT_STATE) { if (s.gzhead.comment/* != Z_NULL*/) { beg = s.pending; /* start of bytes to update crc */ //int val; do { if (s.pending === s.pending_buf_size) { if (s.gzhead.hcrc && s.pending > beg) { strm.adler = crc32(strm.adler, s.pending_buf, s.pending - beg, beg); } flush_pending(strm); beg = s.pending; if (s.pending === s.pending_buf_size) { val = 1; break; } } // JS specific: little magic to add zero terminator to end of string if (s.gzindex < s.gzhead.comment.length) { val = s.gzhead.comment.charCodeAt(s.gzindex++) & 0xff; } else { val = 0; } put_byte(s, val); } while (val !== 0); if (s.gzhead.hcrc && s.pending > beg) { strm.adler = crc32(strm.adler, s.pending_buf, s.pending - beg, beg); } if (val === 0) { s.status = HCRC_STATE; } } else { s.status = HCRC_STATE; } } if (s.status === HCRC_STATE) { if (s.gzhead.hcrc) { if (s.pending + 2 > s.pending_buf_size) { flush_pending(strm); } if (s.pending + 2 <= s.pending_buf_size) { put_byte(s, strm.adler & 0xff); put_byte(s, (strm.adler >> 8) & 0xff); strm.adler = 0; //crc32(0L, Z_NULL, 0); s.status = BUSY_STATE; } } else { s.status = BUSY_STATE; } } //#endif /* Flush as much pending output as possible */ if (s.pending !== 0) { flush_pending(strm); if (strm.avail_out === 0) { /* Since avail_out is 0, deflate will be called again with * more output space, but possibly with both pending and * avail_in equal to zero. There won't be anything to do, * but this is not an error situation so make sure we * return OK instead of BUF_ERROR at next call of deflate: */ s.last_flush = -1; return Z_OK; } /* Make sure there is something to do and avoid duplicate consecutive * flushes. For repeated and useless calls with Z_FINISH, we keep * returning Z_STREAM_END instead of Z_BUF_ERROR. */ } else if (strm.avail_in === 0 && rank(flush) <= rank(old_flush) && flush !== Z_FINISH) { return err(strm, Z_BUF_ERROR); } /* User must not provide more input after the first FINISH: */ if (s.status === FINISH_STATE && strm.avail_in !== 0) { return err(strm, Z_BUF_ERROR); } /* Start a new block or continue the current one. */ if (strm.avail_in !== 0 || s.lookahead !== 0 || (flush !== Z_NO_FLUSH && s.status !== FINISH_STATE)) { var bstate = (s.strategy === Z_HUFFMAN_ONLY) ? deflate_huff(s, flush) : (s.strategy === Z_RLE ? deflate_rle(s, flush) : configuration_table[s.level].func(s, flush)); if (bstate === BS_FINISH_STARTED || bstate === BS_FINISH_DONE) { s.status = FINISH_STATE; } if (bstate === BS_NEED_MORE || bstate === BS_FINISH_STARTED) { if (strm.avail_out === 0) { s.last_flush = -1; /* avoid BUF_ERROR next call, see above */ } return Z_OK; /* If flush != Z_NO_FLUSH && avail_out == 0, the next call * of deflate should use the same flush parameter to make sure * that the flush is complete. So we don't have to output an * empty block here, this will be done at next call. This also * ensures that for a very small output buffer, we emit at most * one empty block. */ } if (bstate === BS_BLOCK_DONE) { if (flush === Z_PARTIAL_FLUSH) { trees._tr_align(s); } else if (flush !== Z_BLOCK) { /* FULL_FLUSH or SYNC_FLUSH */ trees._tr_stored_block(s, 0, 0, false); /* For a full flush, this empty block will be recognized * as a special marker by inflate_sync(). */ if (flush === Z_FULL_FLUSH) { /*** CLEAR_HASH(s); ***/ /* forget history */ zero(s.head); // Fill with NIL (= 0); if (s.lookahead === 0) { s.strstart = 0; s.block_start = 0; s.insert = 0; } } } flush_pending(strm); if (strm.avail_out === 0) { s.last_flush = -1; /* avoid BUF_ERROR at next call, see above */ return Z_OK; } } } //Assert(strm->avail_out > 0, "bug2"); //if (strm.avail_out <= 0) { throw new Error("bug2");} if (flush !== Z_FINISH) { return Z_OK; } if (s.wrap <= 0) { return Z_STREAM_END; } /* Write the trailer */ if (s.wrap === 2) { put_byte(s, strm.adler & 0xff); put_byte(s, (strm.adler >> 8) & 0xff); put_byte(s, (strm.adler >> 16) & 0xff); put_byte(s, (strm.adler >> 24) & 0xff); put_byte(s, strm.total_in & 0xff); put_byte(s, (strm.total_in >> 8) & 0xff); put_byte(s, (strm.total_in >> 16) & 0xff); put_byte(s, (strm.total_in >> 24) & 0xff); } else { putShortMSB(s, strm.adler >>> 16); putShortMSB(s, strm.adler & 0xffff); } flush_pending(strm); /* If avail_out is zero, the application will call deflate again * to flush the rest. */ if (s.wrap > 0) { s.wrap = -s.wrap; } /* write the trailer only once! */ return s.pending !== 0 ? Z_OK : Z_STREAM_END; } function deflateEnd(strm) { var status; if (!strm/*== Z_NULL*/ || !strm.state/*== Z_NULL*/) { return Z_STREAM_ERROR; } status = strm.state.status; if (status !== INIT_STATE && status !== EXTRA_STATE && status !== NAME_STATE && status !== COMMENT_STATE && status !== HCRC_STATE && status !== BUSY_STATE && status !== FINISH_STATE ) { return err(strm, Z_STREAM_ERROR); } strm.state = null; return status === BUSY_STATE ? err(strm, Z_DATA_ERROR) : Z_OK; } /* ========================================================================= * Copy the source state to the destination state */ //function deflateCopy(dest, source) { // //} exports.deflateInit = deflateInit; exports.deflateInit2 = deflateInit2; exports.deflateReset = deflateReset; exports.deflateResetKeep = deflateResetKeep; exports.deflateSetHeader = deflateSetHeader; exports.deflate = deflate; exports.deflateEnd = deflateEnd; exports.deflateInfo = 'pako deflate (from Nodeca project)'; /* Not implemented exports.deflateBound = deflateBound; exports.deflateCopy = deflateCopy; exports.deflateSetDictionary = deflateSetDictionary; exports.deflateParams = deflateParams; exports.deflatePending = deflatePending; exports.deflatePrime = deflatePrime; exports.deflateTune = deflateTune; */ },{"../utils/common":73,"./adler32":75,"./crc32":77,"./messages":83,"./trees":84}],79:[function(_dereq_,module,exports){ 'use strict'; function GZheader() { /* true if compressed data believed to be text */ this.text = 0; /* modification time */ this.time = 0; /* extra flags (not used when writing a gzip file) */ this.xflags = 0; /* operating system */ this.os = 0; /* pointer to extra field or Z_NULL if none */ this.extra = null; /* extra field length (valid if extra != Z_NULL) */ this.extra_len = 0; // Actually, we don't need it in JS, // but leave for few code modifications // // Setup limits is not necessary because in js we should not preallocate memory // for inflate use constant limit in 65536 bytes // /* space at extra (only when reading header) */ // this.extra_max = 0; /* pointer to zero-terminated file name or Z_NULL */ this.name = ''; /* space at name (only when reading header) */ // this.name_max = 0; /* pointer to zero-terminated comment or Z_NULL */ this.comment = ''; /* space at comment (only when reading header) */ // this.comm_max = 0; /* true if there was or will be a header crc */ this.hcrc = 0; /* true when done reading gzip header (not used when writing a gzip file) */ this.done = false; } module.exports = GZheader; },{}],80:[function(_dereq_,module,exports){ 'use strict'; // See state defs from inflate.js var BAD = 30; /* got a data error -- remain here until reset */ var TYPE = 12; /* i: waiting for type bits, including last-flag bit */ /* Decode literal, length, and distance codes and write out the resulting literal and match bytes until either not enough input or output is available, an end-of-block is encountered, or a data error is encountered. When large enough input and output buffers are supplied to inflate(), for example, a 16K input buffer and a 64K output buffer, more than 95% of the inflate execution time is spent in this routine. Entry assumptions: state.mode === LEN strm.avail_in >= 6 strm.avail_out >= 258 start >= strm.avail_out state.bits < 8 On return, state.mode is one of: LEN -- ran out of enough output space or enough available input TYPE -- reached end of block code, inflate() to interpret next block BAD -- error in block data Notes: - The maximum input bits used by a length/distance pair is 15 bits for the length code, 5 bits for the length extra, 15 bits for the distance code, and 13 bits for the distance extra. This totals 48 bits, or six bytes. Therefore if strm.avail_in >= 6, then there is enough input to avoid checking for available input while decoding. - The maximum bytes that a single length/distance pair can output is 258 bytes, which is the maximum length that can be coded. inflate_fast() requires strm.avail_out >= 258 for each loop to avoid checking for output space. */ module.exports = function inflate_fast(strm, start) { var state; var _in; /* local strm.input */ var last; /* have enough input while in < last */ var _out; /* local strm.output */ var beg; /* inflate()'s initial strm.output */ var end; /* while out < end, enough space available */ //#ifdef INFLATE_STRICT var dmax; /* maximum distance from zlib header */ //#endif var wsize; /* window size or zero if not using window */ var whave; /* valid bytes in the window */ var wnext; /* window write index */ // Use `s_window` instead `window`, avoid conflict with instrumentation tools var s_window; /* allocated sliding window, if wsize != 0 */ var hold; /* local strm.hold */ var bits; /* local strm.bits */ var lcode; /* local strm.lencode */ var dcode; /* local strm.distcode */ var lmask; /* mask for first level of length codes */ var dmask; /* mask for first level of distance codes */ var here; /* retrieved table entry */ var op; /* code bits, operation, extra bits, or */ /* window position, window bytes to copy */ var len; /* match length, unused bytes */ var dist; /* match distance */ var from; /* where to copy match from */ var from_source; var input, output; // JS specific, because we have no pointers /* copy state to local variables */ state = strm.state; //here = state.here; _in = strm.next_in; input = strm.input; last = _in + (strm.avail_in - 5); _out = strm.next_out; output = strm.output; beg = _out - (start - strm.avail_out); end = _out + (strm.avail_out - 257); //#ifdef INFLATE_STRICT dmax = state.dmax; //#endif wsize = state.wsize; whave = state.whave; wnext = state.wnext; s_window = state.window; hold = state.hold; bits = state.bits; lcode = state.lencode; dcode = state.distcode; lmask = (1 << state.lenbits) - 1; dmask = (1 << state.distbits) - 1; /* decode literals and length/distances until end-of-block or not enough input data or output space */ top: do { if (bits < 15) { hold += input[_in++] << bits; bits += 8; hold += input[_in++] << bits; bits += 8; } here = lcode[hold & lmask]; dolen: for (;;) { // Goto emulation op = here >>> 24/*here.bits*/; hold >>>= op; bits -= op; op = (here >>> 16) & 0xff/*here.op*/; if (op === 0) { /* literal */ //Tracevv((stderr, here.val >= 0x20 && here.val < 0x7f ? // "inflate: literal '%c'\n" : // "inflate: literal 0x%02x\n", here.val)); output[_out++] = here & 0xffff/*here.val*/; } else if (op & 16) { /* length base */ len = here & 0xffff/*here.val*/; op &= 15; /* number of extra bits */ if (op) { if (bits < op) { hold += input[_in++] << bits; bits += 8; } len += hold & ((1 << op) - 1); hold >>>= op; bits -= op; } //Tracevv((stderr, "inflate: length %u\n", len)); if (bits < 15) { hold += input[_in++] << bits; bits += 8; hold += input[_in++] << bits; bits += 8; } here = dcode[hold & dmask]; dodist: for (;;) { // goto emulation op = here >>> 24/*here.bits*/; hold >>>= op; bits -= op; op = (here >>> 16) & 0xff/*here.op*/; if (op & 16) { /* distance base */ dist = here & 0xffff/*here.val*/; op &= 15; /* number of extra bits */ if (bits < op) { hold += input[_in++] << bits; bits += 8; if (bits < op) { hold += input[_in++] << bits; bits += 8; } } dist += hold & ((1 << op) - 1); //#ifdef INFLATE_STRICT if (dist > dmax) { strm.msg = 'invalid distance too far back'; state.mode = BAD; break top; } //#endif hold >>>= op; bits -= op; //Tracevv((stderr, "inflate: distance %u\n", dist)); op = _out - beg; /* max distance in output */ if (dist > op) { /* see if copy from window */ op = dist - op; /* distance back in window */ if (op > whave) { if (state.sane) { strm.msg = 'invalid distance too far back'; state.mode = BAD; break top; } // (!) This block is disabled in zlib defailts, // don't enable it for binary compatibility //#ifdef INFLATE_ALLOW_INVALID_DISTANCE_TOOFAR_ARRR // if (len <= op - whave) { // do { // output[_out++] = 0; // } while (--len); // continue top; // } // len -= op - whave; // do { // output[_out++] = 0; // } while (--op > whave); // if (op === 0) { // from = _out - dist; // do { // output[_out++] = output[from++]; // } while (--len); // continue top; // } //#endif } from = 0; // window index from_source = s_window; if (wnext === 0) { /* very common case */ from += wsize - op; if (op < len) { /* some from window */ len -= op; do { output[_out++] = s_window[from++]; } while (--op); from = _out - dist; /* rest from output */ from_source = output; } } else if (wnext < op) { /* wrap around window */ from += wsize + wnext - op; op -= wnext; if (op < len) { /* some from end of window */ len -= op; do { output[_out++] = s_window[from++]; } while (--op); from = 0; if (wnext < len) { /* some from start of window */ op = wnext; len -= op; do { output[_out++] = s_window[from++]; } while (--op); from = _out - dist; /* rest from output */ from_source = output; } } } else { /* contiguous in window */ from += wnext - op; if (op < len) { /* some from window */ len -= op; do { output[_out++] = s_window[from++]; } while (--op); from = _out - dist; /* rest from output */ from_source = output; } } while (len > 2) { output[_out++] = from_source[from++]; output[_out++] = from_source[from++]; output[_out++] = from_source[from++]; len -= 3; } if (len) { output[_out++] = from_source[from++]; if (len > 1) { output[_out++] = from_source[from++]; } } } else { from = _out - dist; /* copy direct from output */ do { /* minimum length is three */ output[_out++] = output[from++]; output[_out++] = output[from++]; output[_out++] = output[from++]; len -= 3; } while (len > 2); if (len) { output[_out++] = output[from++]; if (len > 1) { output[_out++] = output[from++]; } } } } else if ((op & 64) === 0) { /* 2nd level distance code */ here = dcode[(here & 0xffff)/*here.val*/ + (hold & ((1 << op) - 1))]; continue dodist; } else { strm.msg = 'invalid distance code'; state.mode = BAD; break top; } break; // need to emulate goto via "continue" } } else if ((op & 64) === 0) { /* 2nd level length code */ here = lcode[(here & 0xffff)/*here.val*/ + (hold & ((1 << op) - 1))]; continue dolen; } else if (op & 32) { /* end-of-block */ //Tracevv((stderr, "inflate: end of block\n")); state.mode = TYPE; break top; } else { strm.msg = 'invalid literal/length code'; state.mode = BAD; break top; } break; // need to emulate goto via "continue" } } while (_in < last && _out < end); /* return unused bytes (on entry, bits < 8, so in won't go too far back) */ len = bits >> 3; _in -= len; bits -= len << 3; hold &= (1 << bits) - 1; /* update state and return */ strm.next_in = _in; strm.next_out = _out; strm.avail_in = (_in < last ? 5 + (last - _in) : 5 - (_in - last)); strm.avail_out = (_out < end ? 257 + (end - _out) : 257 - (_out - end)); state.hold = hold; state.bits = bits; return; }; },{}],81:[function(_dereq_,module,exports){ 'use strict'; var utils = _dereq_('../utils/common'); var adler32 = _dereq_('./adler32'); var crc32 = _dereq_('./crc32'); var inflate_fast = _dereq_('./inffast'); var inflate_table = _dereq_('./inftrees'); var CODES = 0; var LENS = 1; var DISTS = 2; /* Public constants ==========================================================*/ /* ===========================================================================*/ /* Allowed flush values; see deflate() and inflate() below for details */ //var Z_NO_FLUSH = 0; //var Z_PARTIAL_FLUSH = 1; //var Z_SYNC_FLUSH = 2; //var Z_FULL_FLUSH = 3; var Z_FINISH = 4; var Z_BLOCK = 5; var Z_TREES = 6; /* Return codes for the compression/decompression functions. Negative values * are errors, positive values are used for special but normal events. */ var Z_OK = 0; var Z_STREAM_END = 1; var Z_NEED_DICT = 2; //var Z_ERRNO = -1; var Z_STREAM_ERROR = -2; var Z_DATA_ERROR = -3; var Z_MEM_ERROR = -4; var Z_BUF_ERROR = -5; //var Z_VERSION_ERROR = -6; /* The deflate compression method */ var Z_DEFLATED = 8; /* STATES ====================================================================*/ /* ===========================================================================*/ var HEAD = 1; /* i: waiting for magic header */ var FLAGS = 2; /* i: waiting for method and flags (gzip) */ var TIME = 3; /* i: waiting for modification time (gzip) */ var OS = 4; /* i: waiting for extra flags and operating system (gzip) */ var EXLEN = 5; /* i: waiting for extra length (gzip) */ var EXTRA = 6; /* i: waiting for extra bytes (gzip) */ var NAME = 7; /* i: waiting for end of file name (gzip) */ var COMMENT = 8; /* i: waiting for end of comment (gzip) */ var HCRC = 9; /* i: waiting for header crc (gzip) */ var DICTID = 10; /* i: waiting for dictionary check value */ var DICT = 11; /* waiting for inflateSetDictionary() call */ var TYPE = 12; /* i: waiting for type bits, including last-flag bit */ var TYPEDO = 13; /* i: same, but skip check to exit inflate on new block */ var STORED = 14; /* i: waiting for stored size (length and complement) */ var COPY_ = 15; /* i/o: same as COPY below, but only first time in */ var COPY = 16; /* i/o: waiting for input or output to copy stored block */ var TABLE = 17; /* i: waiting for dynamic block table lengths */ var LENLENS = 18; /* i: waiting for code length code lengths */ var CODELENS = 19; /* i: waiting for length/lit and distance code lengths */ var LEN_ = 20; /* i: same as LEN below, but only first time in */ var LEN = 21; /* i: waiting for length/lit/eob code */ var LENEXT = 22; /* i: waiting for length extra bits */ var DIST = 23; /* i: waiting for distance code */ var DISTEXT = 24; /* i: waiting for distance extra bits */ var MATCH = 25; /* o: waiting for output space to copy string */ var LIT = 26; /* o: waiting for output space to write literal */ var CHECK = 27; /* i: waiting for 32-bit check value */ var LENGTH = 28; /* i: waiting for 32-bit length (gzip) */ var DONE = 29; /* finished check, done -- remain here until reset */ var BAD = 30; /* got a data error -- remain here until reset */ var MEM = 31; /* got an inflate() memory error -- remain here until reset */ var SYNC = 32; /* looking for synchronization bytes to restart inflate() */ /* ===========================================================================*/ var ENOUGH_LENS = 852; var ENOUGH_DISTS = 592; //var ENOUGH = (ENOUGH_LENS+ENOUGH_DISTS); var MAX_WBITS = 15; /* 32K LZ77 window */ var DEF_WBITS = MAX_WBITS; function ZSWAP32(q) { return (((q >>> 24) & 0xff) + ((q >>> 8) & 0xff00) + ((q & 0xff00) << 8) + ((q & 0xff) << 24)); } function InflateState() { this.mode = 0; /* current inflate mode */ this.last = false; /* true if processing last block */ this.wrap = 0; /* bit 0 true for zlib, bit 1 true for gzip */ this.havedict = false; /* true if dictionary provided */ this.flags = 0; /* gzip header method and flags (0 if zlib) */ this.dmax = 0; /* zlib header max distance (INFLATE_STRICT) */ this.check = 0; /* protected copy of check value */ this.total = 0; /* protected copy of output count */ // TODO: may be {} this.head = null; /* where to save gzip header information */ /* sliding window */ this.wbits = 0; /* log base 2 of requested window size */ this.wsize = 0; /* window size or zero if not using window */ this.whave = 0; /* valid bytes in the window */ this.wnext = 0; /* window write index */ this.window = null; /* allocated sliding window, if needed */ /* bit accumulator */ this.hold = 0; /* input bit accumulator */ this.bits = 0; /* number of bits in "in" */ /* for string and stored block copying */ this.length = 0; /* literal or length of data to copy */ this.offset = 0; /* distance back to copy string from */ /* for table and code decoding */ this.extra = 0; /* extra bits needed */ /* fixed and dynamic code tables */ this.lencode = null; /* starting table for length/literal codes */ this.distcode = null; /* starting table for distance codes */ this.lenbits = 0; /* index bits for lencode */ this.distbits = 0; /* index bits for distcode */ /* dynamic table building */ this.ncode = 0; /* number of code length code lengths */ this.nlen = 0; /* number of length code lengths */ this.ndist = 0; /* number of distance code lengths */ this.have = 0; /* number of code lengths in lens[] */ this.next = null; /* next available space in codes[] */ this.lens = new utils.Buf16(320); /* temporary storage for code lengths */ this.work = new utils.Buf16(288); /* work area for code table building */ /* because we don't have pointers in js, we use lencode and distcode directly as buffers so we don't need codes */ //this.codes = new utils.Buf32(ENOUGH); /* space for code tables */ this.lendyn = null; /* dynamic table for length/literal codes (JS specific) */ this.distdyn = null; /* dynamic table for distance codes (JS specific) */ this.sane = 0; /* if false, allow invalid distance too far */ this.back = 0; /* bits back of last unprocessed length/lit */ this.was = 0; /* initial length of match */ } function inflateResetKeep(strm) { var state; if (!strm || !strm.state) { return Z_STREAM_ERROR; } state = strm.state; strm.total_in = strm.total_out = state.total = 0; strm.msg = ''; /*Z_NULL*/ if (state.wrap) { /* to support ill-conceived Java test suite */ strm.adler = state.wrap & 1; } state.mode = HEAD; state.last = 0; state.havedict = 0; state.dmax = 32768; state.head = null/*Z_NULL*/; state.hold = 0; state.bits = 0; //state.lencode = state.distcode = state.next = state.codes; state.lencode = state.lendyn = new utils.Buf32(ENOUGH_LENS); state.distcode = state.distdyn = new utils.Buf32(ENOUGH_DISTS); state.sane = 1; state.back = -1; //Tracev((stderr, "inflate: reset\n")); return Z_OK; } function inflateReset(strm) { var state; if (!strm || !strm.state) { return Z_STREAM_ERROR; } state = strm.state; state.wsize = 0; state.whave = 0; state.wnext = 0; return inflateResetKeep(strm); } function inflateReset2(strm, windowBits) { var wrap; var state; /* get the state */ if (!strm || !strm.state) { return Z_STREAM_ERROR; } state = strm.state; /* extract wrap request from windowBits parameter */ if (windowBits < 0) { wrap = 0; windowBits = -windowBits; } else { wrap = (windowBits >> 4) + 1; if (windowBits < 48) { windowBits &= 15; } } /* set number of window bits, free window if different */ if (windowBits && (windowBits < 8 || windowBits > 15)) { return Z_STREAM_ERROR; } if (state.window !== null && state.wbits !== windowBits) { state.window = null; } /* update state and reset the rest of it */ state.wrap = wrap; state.wbits = windowBits; return inflateReset(strm); } function inflateInit2(strm, windowBits) { var ret; var state; if (!strm) { return Z_STREAM_ERROR; } //strm.msg = Z_NULL; /* in case we return an error */ state = new InflateState(); //if (state === Z_NULL) return Z_MEM_ERROR; //Tracev((stderr, "inflate: allocated\n")); strm.state = state; state.window = null/*Z_NULL*/; ret = inflateReset2(strm, windowBits); if (ret !== Z_OK) { strm.state = null/*Z_NULL*/; } return ret; } function inflateInit(strm) { return inflateInit2(strm, DEF_WBITS); } /* Return state with length and distance decoding tables and index sizes set to fixed code decoding. Normally this returns fixed tables from inffixed.h. If BUILDFIXED is defined, then instead this routine builds the tables the first time it's called, and returns those tables the first time and thereafter. This reduces the size of the code by about 2K bytes, in exchange for a little execution time. However, BUILDFIXED should not be used for threaded applications, since the rewriting of the tables and virgin may not be thread-safe. */ var virgin = true; var lenfix, distfix; // We have no pointers in JS, so keep tables separate function fixedtables(state) { /* build fixed huffman tables if first call (may not be thread safe) */ if (virgin) { var sym; lenfix = new utils.Buf32(512); distfix = new utils.Buf32(32); /* literal/length table */ sym = 0; while (sym < 144) { state.lens[sym++] = 8; } while (sym < 256) { state.lens[sym++] = 9; } while (sym < 280) { state.lens[sym++] = 7; } while (sym < 288) { state.lens[sym++] = 8; } inflate_table(LENS, state.lens, 0, 288, lenfix, 0, state.work, {bits: 9}); /* distance table */ sym = 0; while (sym < 32) { state.lens[sym++] = 5; } inflate_table(DISTS, state.lens, 0, 32, distfix, 0, state.work, {bits: 5}); /* do this just once */ virgin = false; } state.lencode = lenfix; state.lenbits = 9; state.distcode = distfix; state.distbits = 5; } /* Update the window with the last wsize (normally 32K) bytes written before returning. If window does not exist yet, create it. This is only called when a window is already in use, or when output has been written during this inflate call, but the end of the deflate stream has not been reached yet. It is also called to create a window for dictionary data when a dictionary is loaded. Providing output buffers larger than 32K to inflate() should provide a speed advantage, since only the last 32K of output is copied to the sliding window upon return from inflate(), and since all distances after the first 32K of output will fall in the output data, making match copies simpler and faster. The advantage may be dependent on the size of the processor's data caches. */ function updatewindow(strm, src, end, copy) { var dist; var state = strm.state; /* if it hasn't been done already, allocate space for the window */ if (state.window === null) { state.wsize = 1 << state.wbits; state.wnext = 0; state.whave = 0; state.window = new utils.Buf8(state.wsize); } /* copy state->wsize or less output bytes into the circular window */ if (copy >= state.wsize) { utils.arraySet(state.window,src, end - state.wsize, state.wsize, 0); state.wnext = 0; state.whave = state.wsize; } else { dist = state.wsize - state.wnext; if (dist > copy) { dist = copy; } //zmemcpy(state->window + state->wnext, end - copy, dist); utils.arraySet(state.window,src, end - copy, dist, state.wnext); copy -= dist; if (copy) { //zmemcpy(state->window, end - copy, copy); utils.arraySet(state.window,src, end - copy, copy, 0); state.wnext = copy; state.whave = state.wsize; } else { state.wnext += dist; if (state.wnext === state.wsize) { state.wnext = 0; } if (state.whave < state.wsize) { state.whave += dist; } } } return 0; } function inflate(strm, flush) { var state; var input, output; // input/output buffers var next; /* next input INDEX */ var put; /* next output INDEX */ var have, left; /* available input and output */ var hold; /* bit buffer */ var bits; /* bits in bit buffer */ var _in, _out; /* save starting available input and output */ var copy; /* number of stored or match bytes to copy */ var from; /* where to copy match bytes from */ var from_source; var here = 0; /* current decoding table entry */ var here_bits, here_op, here_val; // paked "here" denormalized (JS specific) //var last; /* parent table entry */ var last_bits, last_op, last_val; // paked "last" denormalized (JS specific) var len; /* length to copy for repeats, bits to drop */ var ret; /* return code */ var hbuf = new utils.Buf8(4); /* buffer for gzip header crc calculation */ var opts; var n; // temporary var for NEED_BITS var order = /* permutation of code lengths */ [16, 17, 18, 0, 8, 7, 9, 6, 10, 5, 11, 4, 12, 3, 13, 2, 14, 1, 15]; if (!strm || !strm.state || !strm.output || (!strm.input && strm.avail_in !== 0)) { return Z_STREAM_ERROR; } state = strm.state; if (state.mode === TYPE) { state.mode = TYPEDO; } /* skip check */ //--- LOAD() --- put = strm.next_out; output = strm.output; left = strm.avail_out; next = strm.next_in; input = strm.input; have = strm.avail_in; hold = state.hold; bits = state.bits; //--- _in = have; _out = left; ret = Z_OK; inf_leave: // goto emulation for (;;) { switch (state.mode) { case HEAD: if (state.wrap === 0) { state.mode = TYPEDO; break; } //=== NEEDBITS(16); while (bits < 16) { if (have === 0) { break inf_leave; } have--; hold += input[next++] << bits; bits += 8; } //===// if ((state.wrap & 2) && hold === 0x8b1f) { /* gzip header */ state.check = 0/*crc32(0L, Z_NULL, 0)*/; //=== CRC2(state.check, hold); hbuf[0] = hold & 0xff; hbuf[1] = (hold >>> 8) & 0xff; state.check = crc32(state.check, hbuf, 2, 0); //===// //=== INITBITS(); hold = 0; bits = 0; //===// state.mode = FLAGS; break; } state.flags = 0; /* expect zlib header */ if (state.head) { state.head.done = false; } if (!(state.wrap & 1) || /* check if zlib header allowed */ (((hold & 0xff)/*BITS(8)*/ << 8) + (hold >> 8)) % 31) { strm.msg = 'incorrect header check'; state.mode = BAD; break; } if ((hold & 0x0f)/*BITS(4)*/ !== Z_DEFLATED) { strm.msg = 'unknown compression method'; state.mode = BAD; break; } //--- DROPBITS(4) ---// hold >>>= 4; bits -= 4; //---// len = (hold & 0x0f)/*BITS(4)*/ + 8; if (state.wbits === 0) { state.wbits = len; } else if (len > state.wbits) { strm.msg = 'invalid window size'; state.mode = BAD; break; } state.dmax = 1 << len; //Tracev((stderr, "inflate: zlib header ok\n")); strm.adler = state.check = 1/*adler32(0L, Z_NULL, 0)*/; state.mode = hold & 0x200 ? DICTID : TYPE; //=== INITBITS(); hold = 0; bits = 0; //===// break; case FLAGS: //=== NEEDBITS(16); */ while (bits < 16) { if (have === 0) { break inf_leave; } have--; hold += input[next++] << bits; bits += 8; } //===// state.flags = hold; if ((state.flags & 0xff) !== Z_DEFLATED) { strm.msg = 'unknown compression method'; state.mode = BAD; break; } if (state.flags & 0xe000) { strm.msg = 'unknown header flags set'; state.mode = BAD; break; } if (state.head) { state.head.text = ((hold >> 8) & 1); } if (state.flags & 0x0200) { //=== CRC2(state.check, hold); hbuf[0] = hold & 0xff; hbuf[1] = (hold >>> 8) & 0xff; state.check = crc32(state.check, hbuf, 2, 0); //===// } //=== INITBITS(); hold = 0; bits = 0; //===// state.mode = TIME; /* falls through */ case TIME: //=== NEEDBITS(32); */ while (bits < 32) { if (have === 0) { break inf_leave; } have--; hold += input[next++] << bits; bits += 8; } //===// if (state.head) { state.head.time = hold; } if (state.flags & 0x0200) { //=== CRC4(state.check, hold) hbuf[0] = hold & 0xff; hbuf[1] = (hold >>> 8) & 0xff; hbuf[2] = (hold >>> 16) & 0xff; hbuf[3] = (hold >>> 24) & 0xff; state.check = crc32(state.check, hbuf, 4, 0); //=== } //=== INITBITS(); hold = 0; bits = 0; //===// state.mode = OS; /* falls through */ case OS: //=== NEEDBITS(16); */ while (bits < 16) { if (have === 0) { break inf_leave; } have--; hold += input[next++] << bits; bits += 8; } //===// if (state.head) { state.head.xflags = (hold & 0xff); state.head.os = (hold >> 8); } if (state.flags & 0x0200) { //=== CRC2(state.check, hold); hbuf[0] = hold & 0xff; hbuf[1] = (hold >>> 8) & 0xff; state.check = crc32(state.check, hbuf, 2, 0); //===// } //=== INITBITS(); hold = 0; bits = 0; //===// state.mode = EXLEN; /* falls through */ case EXLEN: if (state.flags & 0x0400) { //=== NEEDBITS(16); */ while (bits < 16) { if (have === 0) { break inf_leave; } have--; hold += input[next++] << bits; bits += 8; } //===// state.length = hold; if (state.head) { state.head.extra_len = hold; } if (state.flags & 0x0200) { //=== CRC2(state.check, hold); hbuf[0] = hold & 0xff; hbuf[1] = (hold >>> 8) & 0xff; state.check = crc32(state.check, hbuf, 2, 0); //===// } //=== INITBITS(); hold = 0; bits = 0; //===// } else if (state.head) { state.head.extra = null/*Z_NULL*/; } state.mode = EXTRA; /* falls through */ case EXTRA: if (state.flags & 0x0400) { copy = state.length; if (copy > have) { copy = have; } if (copy) { if (state.head) { len = state.head.extra_len - state.length; if (!state.head.extra) { // Use untyped array for more conveniend processing later state.head.extra = new Array(state.head.extra_len); } utils.arraySet( state.head.extra, input, next, // extra field is limited to 65536 bytes // - no need for additional size check copy, /*len + copy > state.head.extra_max - len ? state.head.extra_max : copy,*/ len ); //zmemcpy(state.head.extra + len, next, // len + copy > state.head.extra_max ? // state.head.extra_max - len : copy); } if (state.flags & 0x0200) { state.check = crc32(state.check, input, copy, next); } have -= copy; next += copy; state.length -= copy; } if (state.length) { break inf_leave; } } state.length = 0; state.mode = NAME; /* falls through */ case NAME: if (state.flags & 0x0800) { if (have === 0) { break inf_leave; } copy = 0; do { // TODO: 2 or 1 bytes? len = input[next + copy++]; /* use constant limit because in js we should not preallocate memory */ if (state.head && len && (state.length < 65536 /*state.head.name_max*/)) { state.head.name += String.fromCharCode(len); } } while (len && copy < have); if (state.flags & 0x0200) { state.check = crc32(state.check, input, copy, next); } have -= copy; next += copy; if (len) { break inf_leave; } } else if (state.head) { state.head.name = null; } state.length = 0; state.mode = COMMENT; /* falls through */ case COMMENT: if (state.flags & 0x1000) { if (have === 0) { break inf_leave; } copy = 0; do { len = input[next + copy++]; /* use constant limit because in js we should not preallocate memory */ if (state.head && len && (state.length < 65536 /*state.head.comm_max*/)) { state.head.comment += String.fromCharCode(len); } } while (len && copy < have); if (state.flags & 0x0200) { state.check = crc32(state.check, input, copy, next); } have -= copy; next += copy; if (len) { break inf_leave; } } else if (state.head) { state.head.comment = null; } state.mode = HCRC; /* falls through */ case HCRC: if (state.flags & 0x0200) { //=== NEEDBITS(16); */ while (bits < 16) { if (have === 0) { break inf_leave; } have--; hold += input[next++] << bits; bits += 8; } //===// if (hold !== (state.check & 0xffff)) { strm.msg = 'header crc mismatch'; state.mode = BAD; break; } //=== INITBITS(); hold = 0; bits = 0; //===// } if (state.head) { state.head.hcrc = ((state.flags >> 9) & 1); state.head.done = true; } strm.adler = state.check = 0 /*crc32(0L, Z_NULL, 0)*/; state.mode = TYPE; break; case DICTID: //=== NEEDBITS(32); */ while (bits < 32) { if (have === 0) { break inf_leave; } have--; hold += input[next++] << bits; bits += 8; } //===// strm.adler = state.check = ZSWAP32(hold); //=== INITBITS(); hold = 0; bits = 0; //===// state.mode = DICT; /* falls through */ case DICT: if (state.havedict === 0) { //--- RESTORE() --- strm.next_out = put; strm.avail_out = left; strm.next_in = next; strm.avail_in = have; state.hold = hold; state.bits = bits; //--- return Z_NEED_DICT; } strm.adler = state.check = 1/*adler32(0L, Z_NULL, 0)*/; state.mode = TYPE; /* falls through */ case TYPE: if (flush === Z_BLOCK || flush === Z_TREES) { break inf_leave; } /* falls through */ case TYPEDO: if (state.last) { //--- BYTEBITS() ---// hold >>>= bits & 7; bits -= bits & 7; //---// state.mode = CHECK; break; } //=== NEEDBITS(3); */ while (bits < 3) { if (have === 0) { break inf_leave; } have--; hold += input[next++] << bits; bits += 8; } //===// state.last = (hold & 0x01)/*BITS(1)*/; //--- DROPBITS(1) ---// hold >>>= 1; bits -= 1; //---// switch ((hold & 0x03)/*BITS(2)*/) { case 0: /* stored block */ //Tracev((stderr, "inflate: stored block%s\n", // state.last ? " (last)" : "")); state.mode = STORED; break; case 1: /* fixed block */ fixedtables(state); //Tracev((stderr, "inflate: fixed codes block%s\n", // state.last ? " (last)" : "")); state.mode = LEN_; /* decode codes */ if (flush === Z_TREES) { //--- DROPBITS(2) ---// hold >>>= 2; bits -= 2; //---// break inf_leave; } break; case 2: /* dynamic block */ //Tracev((stderr, "inflate: dynamic codes block%s\n", // state.last ? " (last)" : "")); state.mode = TABLE; break; case 3: strm.msg = 'invalid block type'; state.mode = BAD; } //--- DROPBITS(2) ---// hold >>>= 2; bits -= 2; //---// break; case STORED: //--- BYTEBITS() ---// /* go to byte boundary */ hold >>>= bits & 7; bits -= bits & 7; //---// //=== NEEDBITS(32); */ while (bits < 32) { if (have === 0) { break inf_leave; } have--; hold += input[next++] << bits; bits += 8; } //===// if ((hold & 0xffff) !== ((hold >>> 16) ^ 0xffff)) { strm.msg = 'invalid stored block lengths'; state.mode = BAD; break; } state.length = hold & 0xffff; //Tracev((stderr, "inflate: stored length %u\n", // state.length)); //=== INITBITS(); hold = 0; bits = 0; //===// state.mode = COPY_; if (flush === Z_TREES) { break inf_leave; } /* falls through */ case COPY_: state.mode = COPY; /* falls through */ case COPY: copy = state.length; if (copy) { if (copy > have) { copy = have; } if (copy > left) { copy = left; } if (copy === 0) { break inf_leave; } //--- zmemcpy(put, next, copy); --- utils.arraySet(output, input, next, copy, put); //---// have -= copy; next += copy; left -= copy; put += copy; state.length -= copy; break; } //Tracev((stderr, "inflate: stored end\n")); state.mode = TYPE; break; case TABLE: //=== NEEDBITS(14); */ while (bits < 14) { if (have === 0) { break inf_leave; } have--; hold += input[next++] << bits; bits += 8; } //===// state.nlen = (hold & 0x1f)/*BITS(5)*/ + 257; //--- DROPBITS(5) ---// hold >>>= 5; bits -= 5; //---// state.ndist = (hold & 0x1f)/*BITS(5)*/ + 1; //--- DROPBITS(5) ---// hold >>>= 5; bits -= 5; //---// state.ncode = (hold & 0x0f)/*BITS(4)*/ + 4; //--- DROPBITS(4) ---// hold >>>= 4; bits -= 4; //---// //#ifndef PKZIP_BUG_WORKAROUND if (state.nlen > 286 || state.ndist > 30) { strm.msg = 'too many length or distance symbols'; state.mode = BAD; break; } //#endif //Tracev((stderr, "inflate: table sizes ok\n")); state.have = 0; state.mode = LENLENS; /* falls through */ case LENLENS: while (state.have < state.ncode) { //=== NEEDBITS(3); while (bits < 3) { if (have === 0) { break inf_leave; } have--; hold += input[next++] << bits; bits += 8; } //===// state.lens[order[state.have++]] = (hold & 0x07);//BITS(3); //--- DROPBITS(3) ---// hold >>>= 3; bits -= 3; //---// } while (state.have < 19) { state.lens[order[state.have++]] = 0; } // We have separate tables & no pointers. 2 commented lines below not needed. //state.next = state.codes; //state.lencode = state.next; // Switch to use dynamic table state.lencode = state.lendyn; state.lenbits = 7; opts = {bits: state.lenbits}; ret = inflate_table(CODES, state.lens, 0, 19, state.lencode, 0, state.work, opts); state.lenbits = opts.bits; if (ret) { strm.msg = 'invalid code lengths set'; state.mode = BAD; break; } //Tracev((stderr, "inflate: code lengths ok\n")); state.have = 0; state.mode = CODELENS; /* falls through */ case CODELENS: while (state.have < state.nlen + state.ndist) { for (;;) { here = state.lencode[hold & ((1 << state.lenbits) - 1)];/*BITS(state.lenbits)*/ here_bits = here >>> 24; here_op = (here >>> 16) & 0xff; here_val = here & 0xffff; if ((here_bits) <= bits) { break; } //--- PULLBYTE() ---// if (have === 0) { break inf_leave; } have--; hold += input[next++] << bits; bits += 8; //---// } if (here_val < 16) { //--- DROPBITS(here.bits) ---// hold >>>= here_bits; bits -= here_bits; //---// state.lens[state.have++] = here_val; } else { if (here_val === 16) { //=== NEEDBITS(here.bits + 2); n = here_bits + 2; while (bits < n) { if (have === 0) { break inf_leave; } have--; hold += input[next++] << bits; bits += 8; } //===// //--- DROPBITS(here.bits) ---// hold >>>= here_bits; bits -= here_bits; //---// if (state.have === 0) { strm.msg = 'invalid bit length repeat'; state.mode = BAD; break; } len = state.lens[state.have - 1]; copy = 3 + (hold & 0x03);//BITS(2); //--- DROPBITS(2) ---// hold >>>= 2; bits -= 2; //---// } else if (here_val === 17) { //=== NEEDBITS(here.bits + 3); n = here_bits + 3; while (bits < n) { if (have === 0) { break inf_leave; } have--; hold += input[next++] << bits; bits += 8; } //===// //--- DROPBITS(here.bits) ---// hold >>>= here_bits; bits -= here_bits; //---// len = 0; copy = 3 + (hold & 0x07);//BITS(3); //--- DROPBITS(3) ---// hold >>>= 3; bits -= 3; //---// } else { //=== NEEDBITS(here.bits + 7); n = here_bits + 7; while (bits < n) { if (have === 0) { break inf_leave; } have--; hold += input[next++] << bits; bits += 8; } //===// //--- DROPBITS(here.bits) ---// hold >>>= here_bits; bits -= here_bits; //---// len = 0; copy = 11 + (hold & 0x7f);//BITS(7); //--- DROPBITS(7) ---// hold >>>= 7; bits -= 7; //---// } if (state.have + copy > state.nlen + state.ndist) { strm.msg = 'invalid bit length repeat'; state.mode = BAD; break; } while (copy--) { state.lens[state.have++] = len; } } } /* handle error breaks in while */ if (state.mode === BAD) { break; } /* check for end-of-block code (better have one) */ if (state.lens[256] === 0) { strm.msg = 'invalid code -- missing end-of-block'; state.mode = BAD; break; } /* build code tables -- note: do not change the lenbits or distbits values here (9 and 6) without reading the comments in inftrees.h concerning the ENOUGH constants, which depend on those values */ state.lenbits = 9; opts = {bits: state.lenbits}; ret = inflate_table(LENS, state.lens, 0, state.nlen, state.lencode, 0, state.work, opts); // We have separate tables & no pointers. 2 commented lines below not needed. // state.next_index = opts.table_index; state.lenbits = opts.bits; // state.lencode = state.next; if (ret) { strm.msg = 'invalid literal/lengths set'; state.mode = BAD; break; } state.distbits = 6; //state.distcode.copy(state.codes); // Switch to use dynamic table state.distcode = state.distdyn; opts = {bits: state.distbits}; ret = inflate_table(DISTS, state.lens, state.nlen, state.ndist, state.distcode, 0, state.work, opts); // We have separate tables & no pointers. 2 commented lines below not needed. // state.next_index = opts.table_index; state.distbits = opts.bits; // state.distcode = state.next; if (ret) { strm.msg = 'invalid distances set'; state.mode = BAD; break; } //Tracev((stderr, 'inflate: codes ok\n')); state.mode = LEN_; if (flush === Z_TREES) { break inf_leave; } /* falls through */ case LEN_: state.mode = LEN; /* falls through */ case LEN: if (have >= 6 && left >= 258) { //--- RESTORE() --- strm.next_out = put; strm.avail_out = left; strm.next_in = next; strm.avail_in = have; state.hold = hold; state.bits = bits; //--- inflate_fast(strm, _out); //--- LOAD() --- put = strm.next_out; output = strm.output; left = strm.avail_out; next = strm.next_in; input = strm.input; have = strm.avail_in; hold = state.hold; bits = state.bits; //--- if (state.mode === TYPE) { state.back = -1; } break; } state.back = 0; for (;;) { here = state.lencode[hold & ((1 << state.lenbits) -1)]; /*BITS(state.lenbits)*/ here_bits = here >>> 24; here_op = (here >>> 16) & 0xff; here_val = here & 0xffff; if (here_bits <= bits) { break; } //--- PULLBYTE() ---// if (have === 0) { break inf_leave; } have--; hold += input[next++] << bits; bits += 8; //---// } if (here_op && (here_op & 0xf0) === 0) { last_bits = here_bits; last_op = here_op; last_val = here_val; for (;;) { here = state.lencode[last_val + ((hold & ((1 << (last_bits + last_op)) -1))/*BITS(last.bits + last.op)*/ >> last_bits)]; here_bits = here >>> 24; here_op = (here >>> 16) & 0xff; here_val = here & 0xffff; if ((last_bits + here_bits) <= bits) { break; } //--- PULLBYTE() ---// if (have === 0) { break inf_leave; } have--; hold += input[next++] << bits; bits += 8; //---// } //--- DROPBITS(last.bits) ---// hold >>>= last_bits; bits -= last_bits; //---// state.back += last_bits; } //--- DROPBITS(here.bits) ---// hold >>>= here_bits; bits -= here_bits; //---// state.back += here_bits; state.length = here_val; if (here_op === 0) { //Tracevv((stderr, here.val >= 0x20 && here.val < 0x7f ? // "inflate: literal '%c'\n" : // "inflate: literal 0x%02x\n", here.val)); state.mode = LIT; break; } if (here_op & 32) { //Tracevv((stderr, "inflate: end of block\n")); state.back = -1; state.mode = TYPE; break; } if (here_op & 64) { strm.msg = 'invalid literal/length code'; state.mode = BAD; break; } state.extra = here_op & 15; state.mode = LENEXT; /* falls through */ case LENEXT: if (state.extra) { //=== NEEDBITS(state.extra); n = state.extra; while (bits < n) { if (have === 0) { break inf_leave; } have--; hold += input[next++] << bits; bits += 8; } //===// state.length += hold & ((1 << state.extra) -1)/*BITS(state.extra)*/; //--- DROPBITS(state.extra) ---// hold >>>= state.extra; bits -= state.extra; //---// state.back += state.extra; } //Tracevv((stderr, "inflate: length %u\n", state.length)); state.was = state.length; state.mode = DIST; /* falls through */ case DIST: for (;;) { here = state.distcode[hold & ((1 << state.distbits) -1)];/*BITS(state.distbits)*/ here_bits = here >>> 24; here_op = (here >>> 16) & 0xff; here_val = here & 0xffff; if ((here_bits) <= bits) { break; } //--- PULLBYTE() ---// if (have === 0) { break inf_leave; } have--; hold += input[next++] << bits; bits += 8; //---// } if ((here_op & 0xf0) === 0) { last_bits = here_bits; last_op = here_op; last_val = here_val; for (;;) { here = state.distcode[last_val + ((hold & ((1 << (last_bits + last_op)) -1))/*BITS(last.bits + last.op)*/ >> last_bits)]; here_bits = here >>> 24; here_op = (here >>> 16) & 0xff; here_val = here & 0xffff; if ((last_bits + here_bits) <= bits) { break; } //--- PULLBYTE() ---// if (have === 0) { break inf_leave; } have--; hold += input[next++] << bits; bits += 8; //---// } //--- DROPBITS(last.bits) ---// hold >>>= last_bits; bits -= last_bits; //---// state.back += last_bits; } //--- DROPBITS(here.bits) ---// hold >>>= here_bits; bits -= here_bits; //---// state.back += here_bits; if (here_op & 64) { strm.msg = 'invalid distance code'; state.mode = BAD; break; } state.offset = here_val; state.extra = (here_op) & 15; state.mode = DISTEXT; /* falls through */ case DISTEXT: if (state.extra) { //=== NEEDBITS(state.extra); n = state.extra; while (bits < n) { if (have === 0) { break inf_leave; } have--; hold += input[next++] << bits; bits += 8; } //===// state.offset += hold & ((1 << state.extra) -1)/*BITS(state.extra)*/; //--- DROPBITS(state.extra) ---// hold >>>= state.extra; bits -= state.extra; //---// state.back += state.extra; } //#ifdef INFLATE_STRICT if (state.offset > state.dmax) { strm.msg = 'invalid distance too far back'; state.mode = BAD; break; } //#endif //Tracevv((stderr, "inflate: distance %u\n", state.offset)); state.mode = MATCH; /* falls through */ case MATCH: if (left === 0) { break inf_leave; } copy = _out - left; if (state.offset > copy) { /* copy from window */ copy = state.offset - copy; if (copy > state.whave) { if (state.sane) { strm.msg = 'invalid distance too far back'; state.mode = BAD; break; } // (!) This block is disabled in zlib defailts, // don't enable it for binary compatibility //#ifdef INFLATE_ALLOW_INVALID_DISTANCE_TOOFAR_ARRR // Trace((stderr, "inflate.c too far\n")); // copy -= state.whave; // if (copy > state.length) { copy = state.length; } // if (copy > left) { copy = left; } // left -= copy; // state.length -= copy; // do { // output[put++] = 0; // } while (--copy); // if (state.length === 0) { state.mode = LEN; } // break; //#endif } if (copy > state.wnext) { copy -= state.wnext; from = state.wsize - copy; } else { from = state.wnext - copy; } if (copy > state.length) { copy = state.length; } from_source = state.window; } else { /* copy from output */ from_source = output; from = put - state.offset; copy = state.length; } if (copy > left) { copy = left; } left -= copy; state.length -= copy; do { output[put++] = from_source[from++]; } while (--copy); if (state.length === 0) { state.mode = LEN; } break; case LIT: if (left === 0) { break inf_leave; } output[put++] = state.length; left--; state.mode = LEN; break; case CHECK: if (state.wrap) { //=== NEEDBITS(32); while (bits < 32) { if (have === 0) { break inf_leave; } have--; // Use '|' insdead of '+' to make sure that result is signed hold |= input[next++] << bits; bits += 8; } //===// _out -= left; strm.total_out += _out; state.total += _out; if (_out) { strm.adler = state.check = /*UPDATE(state.check, put - _out, _out);*/ (state.flags ? crc32(state.check, output, _out, put - _out) : adler32(state.check, output, _out, put - _out)); } _out = left; // NB: crc32 stored as signed 32-bit int, ZSWAP32 returns signed too if ((state.flags ? hold : ZSWAP32(hold)) !== state.check) { strm.msg = 'incorrect data check'; state.mode = BAD; break; } //=== INITBITS(); hold = 0; bits = 0; //===// //Tracev((stderr, "inflate: check matches trailer\n")); } state.mode = LENGTH; /* falls through */ case LENGTH: if (state.wrap && state.flags) { //=== NEEDBITS(32); while (bits < 32) { if (have === 0) { break inf_leave; } have--; hold += input[next++] << bits; bits += 8; } //===// if (hold !== (state.total & 0xffffffff)) { strm.msg = 'incorrect length check'; state.mode = BAD; break; } //=== INITBITS(); hold = 0; bits = 0; //===// //Tracev((stderr, "inflate: length matches trailer\n")); } state.mode = DONE; /* falls through */ case DONE: ret = Z_STREAM_END; break inf_leave; case BAD: ret = Z_DATA_ERROR; break inf_leave; case MEM: return Z_MEM_ERROR; case SYNC: /* falls through */ default: return Z_STREAM_ERROR; } } // inf_leave <- here is real place for "goto inf_leave", emulated via "break inf_leave" /* Return from inflate(), updating the total counts and the check value. If there was no progress during the inflate() call, return a buffer error. Call updatewindow() to create and/or update the window state. Note: a memory error from inflate() is non-recoverable. */ //--- RESTORE() --- strm.next_out = put; strm.avail_out = left; strm.next_in = next; strm.avail_in = have; state.hold = hold; state.bits = bits; //--- if (state.wsize || (_out !== strm.avail_out && state.mode < BAD && (state.mode < CHECK || flush !== Z_FINISH))) { if (updatewindow(strm, strm.output, strm.next_out, _out - strm.avail_out)) { state.mode = MEM; return Z_MEM_ERROR; } } _in -= strm.avail_in; _out -= strm.avail_out; strm.total_in += _in; strm.total_out += _out; state.total += _out; if (state.wrap && _out) { strm.adler = state.check = /*UPDATE(state.check, strm.next_out - _out, _out);*/ (state.flags ? crc32(state.check, output, _out, strm.next_out - _out) : adler32(state.check, output, _out, strm.next_out - _out)); } strm.data_type = state.bits + (state.last ? 64 : 0) + (state.mode === TYPE ? 128 : 0) + (state.mode === LEN_ || state.mode === COPY_ ? 256 : 0); if (((_in === 0 && _out === 0) || flush === Z_FINISH) && ret === Z_OK) { ret = Z_BUF_ERROR; } return ret; } function inflateEnd(strm) { if (!strm || !strm.state /*|| strm->zfree == (free_func)0*/) { return Z_STREAM_ERROR; } var state = strm.state; if (state.window) { state.window = null; } strm.state = null; return Z_OK; } function inflateGetHeader(strm, head) { var state; /* check state */ if (!strm || !strm.state) { return Z_STREAM_ERROR; } state = strm.state; if ((state.wrap & 2) === 0) { return Z_STREAM_ERROR; } /* save header structure */ state.head = head; head.done = false; return Z_OK; } exports.inflateReset = inflateReset; exports.inflateReset2 = inflateReset2; exports.inflateResetKeep = inflateResetKeep; exports.inflateInit = inflateInit; exports.inflateInit2 = inflateInit2; exports.inflate = inflate; exports.inflateEnd = inflateEnd; exports.inflateGetHeader = inflateGetHeader; exports.inflateInfo = 'pako inflate (from Nodeca project)'; /* Not implemented exports.inflateCopy = inflateCopy; exports.inflateGetDictionary = inflateGetDictionary; exports.inflateMark = inflateMark; exports.inflatePrime = inflatePrime; exports.inflateSetDictionary = inflateSetDictionary; exports.inflateSync = inflateSync; exports.inflateSyncPoint = inflateSyncPoint; exports.inflateUndermine = inflateUndermine; */ },{"../utils/common":73,"./adler32":75,"./crc32":77,"./inffast":80,"./inftrees":82}],82:[function(_dereq_,module,exports){ 'use strict'; var utils = _dereq_('../utils/common'); var MAXBITS = 15; var ENOUGH_LENS = 852; var ENOUGH_DISTS = 592; //var ENOUGH = (ENOUGH_LENS+ENOUGH_DISTS); var CODES = 0; var LENS = 1; var DISTS = 2; var lbase = [ /* Length codes 257..285 base */ 3, 4, 5, 6, 7, 8, 9, 10, 11, 13, 15, 17, 19, 23, 27, 31, 35, 43, 51, 59, 67, 83, 99, 115, 131, 163, 195, 227, 258, 0, 0 ]; var lext = [ /* Length codes 257..285 extra */ 16, 16, 16, 16, 16, 16, 16, 16, 17, 17, 17, 17, 18, 18, 18, 18, 19, 19, 19, 19, 20, 20, 20, 20, 21, 21, 21, 21, 16, 72, 78 ]; var dbase = [ /* Distance codes 0..29 base */ 1, 2, 3, 4, 5, 7, 9, 13, 17, 25, 33, 49, 65, 97, 129, 193, 257, 385, 513, 769, 1025, 1537, 2049, 3073, 4097, 6145, 8193, 12289, 16385, 24577, 0, 0 ]; var dext = [ /* Distance codes 0..29 extra */ 16, 16, 16, 16, 17, 17, 18, 18, 19, 19, 20, 20, 21, 21, 22, 22, 23, 23, 24, 24, 25, 25, 26, 26, 27, 27, 28, 28, 29, 29, 64, 64 ]; module.exports = function inflate_table(type, lens, lens_index, codes, table, table_index, work, opts) { var bits = opts.bits; //here = opts.here; /* table entry for duplication */ var len = 0; /* a code's length in bits */ var sym = 0; /* index of code symbols */ var min = 0, max = 0; /* minimum and maximum code lengths */ var root = 0; /* number of index bits for root table */ var curr = 0; /* number of index bits for current table */ var drop = 0; /* code bits to drop for sub-table */ var left = 0; /* number of prefix codes available */ var used = 0; /* code entries in table used */ var huff = 0; /* Huffman code */ var incr; /* for incrementing code, index */ var fill; /* index for replicating entries */ var low; /* low bits for current root entry */ var mask; /* mask for low root bits */ var next; /* next available space in table */ var base = null; /* base value table to use */ var base_index = 0; // var shoextra; /* extra bits table to use */ var end; /* use base and extra for symbol > end */ var count = new utils.Buf16(MAXBITS+1); //[MAXBITS+1]; /* number of codes of each length */ var offs = new utils.Buf16(MAXBITS+1); //[MAXBITS+1]; /* offsets in table for each length */ var extra = null; var extra_index = 0; var here_bits, here_op, here_val; /* Process a set of code lengths to create a canonical Huffman code. The code lengths are lens[0..codes-1]. Each length corresponds to the symbols 0..codes-1. The Huffman code is generated by first sorting the symbols by length from short to long, and retaining the symbol order for codes with equal lengths. Then the code starts with all zero bits for the first code of the shortest length, and the codes are integer increments for the same length, and zeros are appended as the length increases. For the deflate format, these bits are stored backwards from their more natural integer increment ordering, and so when the decoding tables are built in the large loop below, the integer codes are incremented backwards. This routine assumes, but does not check, that all of the entries in lens[] are in the range 0..MAXBITS. The caller must assure this. 1..MAXBITS is interpreted as that code length. zero means that that symbol does not occur in this code. The codes are sorted by computing a count of codes for each length, creating from that a table of starting indices for each length in the sorted table, and then entering the symbols in order in the sorted table. The sorted table is work[], with that space being provided by the caller. The length counts are used for other purposes as well, i.e. finding the minimum and maximum length codes, determining if there are any codes at all, checking for a valid set of lengths, and looking ahead at length counts to determine sub-table sizes when building the decoding tables. */ /* accumulate lengths for codes (assumes lens[] all in 0..MAXBITS) */ for (len = 0; len <= MAXBITS; len++) { count[len] = 0; } for (sym = 0; sym < codes; sym++) { count[lens[lens_index + sym]]++; } /* bound code lengths, force root to be within code lengths */ root = bits; for (max = MAXBITS; max >= 1; max--) { if (count[max] !== 0) { break; } } if (root > max) { root = max; } if (max === 0) { /* no symbols to code at all */ //table.op[opts.table_index] = 64; //here.op = (var char)64; /* invalid code marker */ //table.bits[opts.table_index] = 1; //here.bits = (var char)1; //table.val[opts.table_index++] = 0; //here.val = (var short)0; table[table_index++] = (1 << 24) | (64 << 16) | 0; //table.op[opts.table_index] = 64; //table.bits[opts.table_index] = 1; //table.val[opts.table_index++] = 0; table[table_index++] = (1 << 24) | (64 << 16) | 0; opts.bits = 1; return 0; /* no symbols, but wait for decoding to report error */ } for (min = 1; min < max; min++) { if (count[min] !== 0) { break; } } if (root < min) { root = min; } /* check for an over-subscribed or incomplete set of lengths */ left = 1; for (len = 1; len <= MAXBITS; len++) { left <<= 1; left -= count[len]; if (left < 0) { return -1; } /* over-subscribed */ } if (left > 0 && (type === CODES || max !== 1)) { return -1; /* incomplete set */ } /* generate offsets into symbol table for each length for sorting */ offs[1] = 0; for (len = 1; len < MAXBITS; len++) { offs[len + 1] = offs[len] + count[len]; } /* sort symbols by length, by symbol order within each length */ for (sym = 0; sym < codes; sym++) { if (lens[lens_index + sym] !== 0) { work[offs[lens[lens_index + sym]]++] = sym; } } /* Create and fill in decoding tables. In this loop, the table being filled is at next and has curr index bits. The code being used is huff with length len. That code is converted to an index by dropping drop bits off of the bottom. For codes where len is less than drop + curr, those top drop + curr - len bits are incremented through all values to fill the table with replicated entries. root is the number of index bits for the root table. When len exceeds root, sub-tables are created pointed to by the root entry with an index of the low root bits of huff. This is saved in low to check for when a new sub-table should be started. drop is zero when the root table is being filled, and drop is root when sub-tables are being filled. When a new sub-table is needed, it is necessary to look ahead in the code lengths to determine what size sub-table is needed. The length counts are used for this, and so count[] is decremented as codes are entered in the tables. used keeps track of how many table entries have been allocated from the provided *table space. It is checked for LENS and DIST tables against the constants ENOUGH_LENS and ENOUGH_DISTS to guard against changes in the initial root table size constants. See the comments in inftrees.h for more information. sym increments through all symbols, and the loop terminates when all codes of length max, i.e. all codes, have been processed. This routine permits incomplete codes, so another loop after this one fills in the rest of the decoding tables with invalid code markers. */ /* set up for code type */ // poor man optimization - use if-else instead of switch, // to avoid deopts in old v8 if (type === CODES) { base = extra = work; /* dummy value--not used */ end = 19; } else if (type === LENS) { base = lbase; base_index -= 257; extra = lext; extra_index -= 257; end = 256; } else { /* DISTS */ base = dbase; extra = dext; end = -1; } /* initialize opts for loop */ huff = 0; /* starting code */ sym = 0; /* starting code symbol */ len = min; /* starting code length */ next = table_index; /* current table to fill in */ curr = root; /* current table index bits */ drop = 0; /* current bits to drop from code for index */ low = -1; /* trigger new sub-table when len > root */ used = 1 << root; /* use root table entries */ mask = used - 1; /* mask for comparing low */ /* check available table space */ if ((type === LENS && used > ENOUGH_LENS) || (type === DISTS && used > ENOUGH_DISTS)) { return 1; } var i=0; /* process all codes and make table entries */ for (;;) { i++; /* create table entry */ here_bits = len - drop; if (work[sym] < end) { here_op = 0; here_val = work[sym]; } else if (work[sym] > end) { here_op = extra[extra_index + work[sym]]; here_val = base[base_index + work[sym]]; } else { here_op = 32 + 64; /* end of block */ here_val = 0; } /* replicate for those indices with low len bits equal to huff */ incr = 1 << (len - drop); fill = 1 << curr; min = fill; /* save offset to next table */ do { fill -= incr; table[next + (huff >> drop) + fill] = (here_bits << 24) | (here_op << 16) | here_val |0; } while (fill !== 0); /* backwards increment the len-bit code huff */ incr = 1 << (len - 1); while (huff & incr) { incr >>= 1; } if (incr !== 0) { huff &= incr - 1; huff += incr; } else { huff = 0; } /* go to next symbol, update count, len */ sym++; if (--count[len] === 0) { if (len === max) { break; } len = lens[lens_index + work[sym]]; } /* create new sub-table if needed */ if (len > root && (huff & mask) !== low) { /* if first time, transition to sub-tables */ if (drop === 0) { drop = root; } /* increment past last table */ next += min; /* here min is 1 << curr */ /* determine length of next table */ curr = len - drop; left = 1 << curr; while (curr + drop < max) { left -= count[curr + drop]; if (left <= 0) { break; } curr++; left <<= 1; } /* check for enough space */ used += 1 << curr; if ((type === LENS && used > ENOUGH_LENS) || (type === DISTS && used > ENOUGH_DISTS)) { return 1; } /* point entry in root table to sub-table */ low = huff & mask; /*table.op[low] = curr; table.bits[low] = root; table.val[low] = next - opts.table_index;*/ table[low] = (root << 24) | (curr << 16) | (next - table_index) |0; } } /* fill in remaining table entry if code is incomplete (guaranteed to have at most one remaining entry, since if the code is incomplete, the maximum code length that was allowed to get this far is one bit) */ if (huff !== 0) { //table.op[next + huff] = 64; /* invalid code marker */ //table.bits[next + huff] = len - drop; //table.val[next + huff] = 0; table[next + huff] = ((len - drop) << 24) | (64 << 16) |0; } /* set return parameters */ //opts.table_index += used; opts.bits = root; return 0; }; },{"../utils/common":73}],83:[function(_dereq_,module,exports){ 'use strict'; module.exports = { '2': 'need dictionary', /* Z_NEED_DICT 2 */ '1': 'stream end', /* Z_STREAM_END 1 */ '0': '', /* Z_OK 0 */ '-1': 'file error', /* Z_ERRNO (-1) */ '-2': 'stream error', /* Z_STREAM_ERROR (-2) */ '-3': 'data error', /* Z_DATA_ERROR (-3) */ '-4': 'insufficient memory', /* Z_MEM_ERROR (-4) */ '-5': 'buffer error', /* Z_BUF_ERROR (-5) */ '-6': 'incompatible version' /* Z_VERSION_ERROR (-6) */ }; },{}],84:[function(_dereq_,module,exports){ 'use strict'; var utils = _dereq_('../utils/common'); /* Public constants ==========================================================*/ /* ===========================================================================*/ //var Z_FILTERED = 1; //var Z_HUFFMAN_ONLY = 2; //var Z_RLE = 3; var Z_FIXED = 4; //var Z_DEFAULT_STRATEGY = 0; /* Possible values of the data_type field (though see inflate()) */ var Z_BINARY = 0; var Z_TEXT = 1; //var Z_ASCII = 1; // = Z_TEXT var Z_UNKNOWN = 2; /*============================================================================*/ function zero(buf) { var len = buf.length; while (--len >= 0) { buf[len] = 0; } } // From zutil.h var STORED_BLOCK = 0; var STATIC_TREES = 1; var DYN_TREES = 2; /* The three kinds of block type */ var MIN_MATCH = 3; var MAX_MATCH = 258; /* The minimum and maximum match lengths */ // From deflate.h /* =========================================================================== * Internal compression state. */ var LENGTH_CODES = 29; /* number of length codes, not counting the special END_BLOCK code */ var LITERALS = 256; /* number of literal bytes 0..255 */ var L_CODES = LITERALS + 1 + LENGTH_CODES; /* number of Literal or Length codes, including the END_BLOCK code */ var D_CODES = 30; /* number of distance codes */ var BL_CODES = 19; /* number of codes used to transfer the bit lengths */ var HEAP_SIZE = 2*L_CODES + 1; /* maximum heap size */ var MAX_BITS = 15; /* All codes must not exceed MAX_BITS bits */ var Buf_size = 16; /* size of bit buffer in bi_buf */ /* =========================================================================== * Constants */ var MAX_BL_BITS = 7; /* Bit length codes must not exceed MAX_BL_BITS bits */ var END_BLOCK = 256; /* end of block literal code */ var REP_3_6 = 16; /* repeat previous bit length 3-6 times (2 bits of repeat count) */ var REPZ_3_10 = 17; /* repeat a zero length 3-10 times (3 bits of repeat count) */ var REPZ_11_138 = 18; /* repeat a zero length 11-138 times (7 bits of repeat count) */ var extra_lbits = /* extra bits for each length code */ [0,0,0,0,0,0,0,0,1,1,1,1,2,2,2,2,3,3,3,3,4,4,4,4,5,5,5,5,0]; var extra_dbits = /* extra bits for each distance code */ [0,0,0,0,1,1,2,2,3,3,4,4,5,5,6,6,7,7,8,8,9,9,10,10,11,11,12,12,13,13]; var extra_blbits = /* extra bits for each bit length code */ [0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,2,3,7]; var bl_order = [16,17,18,0,8,7,9,6,10,5,11,4,12,3,13,2,14,1,15]; /* The lengths of the bit length codes are sent in order of decreasing * probability, to avoid transmitting the lengths for unused bit length codes. */ /* =========================================================================== * Local data. These are initialized only once. */ // We pre-fill arrays with 0 to avoid uninitialized gaps var DIST_CODE_LEN = 512; /* see definition of array dist_code below */ // !!!! Use flat array insdead of structure, Freq = i*2, Len = i*2+1 var static_ltree = new Array((L_CODES+2) * 2); zero(static_ltree); /* The static literal tree. Since the bit lengths are imposed, there is no * need for the L_CODES extra codes used during heap construction. However * The codes 286 and 287 are needed to build a canonical tree (see _tr_init * below). */ var static_dtree = new Array(D_CODES * 2); zero(static_dtree); /* The static distance tree. (Actually a trivial tree since all codes use * 5 bits.) */ var _dist_code = new Array(DIST_CODE_LEN); zero(_dist_code); /* Distance codes. The first 256 values correspond to the distances * 3 .. 258, the last 256 values correspond to the top 8 bits of * the 15 bit distances. */ var _length_code = new Array(MAX_MATCH-MIN_MATCH+1); zero(_length_code); /* length code for each normalized match length (0 == MIN_MATCH) */ var base_length = new Array(LENGTH_CODES); zero(base_length); /* First normalized length for each code (0 = MIN_MATCH) */ var base_dist = new Array(D_CODES); zero(base_dist); /* First normalized distance for each code (0 = distance of 1) */ var StaticTreeDesc = function (static_tree, extra_bits, extra_base, elems, max_length) { this.static_tree = static_tree; /* static tree or NULL */ this.extra_bits = extra_bits; /* extra bits for each code or NULL */ this.extra_base = extra_base; /* base index for extra_bits */ this.elems = elems; /* max number of elements in the tree */ this.max_length = max_length; /* max bit length for the codes */ // show if `static_tree` has data or dummy - needed for monomorphic objects this.has_stree = static_tree && static_tree.length; }; var static_l_desc; var static_d_desc; var static_bl_desc; var TreeDesc = function(dyn_tree, stat_desc) { this.dyn_tree = dyn_tree; /* the dynamic tree */ this.max_code = 0; /* largest code with non zero frequency */ this.stat_desc = stat_desc; /* the corresponding static tree */ }; function d_code(dist) { return dist < 256 ? _dist_code[dist] : _dist_code[256 + (dist >>> 7)]; } /* =========================================================================== * Output a short LSB first on the stream. * IN assertion: there is enough room in pendingBuf. */ function put_short (s, w) { // put_byte(s, (uch)((w) & 0xff)); // put_byte(s, (uch)((ush)(w) >> 8)); s.pending_buf[s.pending++] = (w) & 0xff; s.pending_buf[s.pending++] = (w >>> 8) & 0xff; } /* =========================================================================== * Send a value on a given number of bits. * IN assertion: length <= 16 and value fits in length bits. */ function send_bits(s, value, length) { if (s.bi_valid > (Buf_size - length)) { s.bi_buf |= (value << s.bi_valid) & 0xffff; put_short(s, s.bi_buf); s.bi_buf = value >> (Buf_size - s.bi_valid); s.bi_valid += length - Buf_size; } else { s.bi_buf |= (value << s.bi_valid) & 0xffff; s.bi_valid += length; } } function send_code(s, c, tree) { send_bits(s, tree[c*2]/*.Code*/, tree[c*2 + 1]/*.Len*/); } /* =========================================================================== * Reverse the first len bits of a code, using straightforward code (a faster * method would use a table) * IN assertion: 1 <= len <= 15 */ function bi_reverse(code, len) { var res = 0; do { res |= code & 1; code >>>= 1; res <<= 1; } while (--len > 0); return res >>> 1; } /* =========================================================================== * Flush the bit buffer, keeping at most 7 bits in it. */ function bi_flush(s) { if (s.bi_valid === 16) { put_short(s, s.bi_buf); s.bi_buf = 0; s.bi_valid = 0; } else if (s.bi_valid >= 8) { s.pending_buf[s.pending++] = s.bi_buf & 0xff; s.bi_buf >>= 8; s.bi_valid -= 8; } } /* =========================================================================== * Compute the optimal bit lengths for a tree and update the total bit length * for the current block. * IN assertion: the fields freq and dad are set, heap[heap_max] and * above are the tree nodes sorted by increasing frequency. * OUT assertions: the field len is set to the optimal bit length, the * array bl_count contains the frequencies for each bit length. * The length opt_len is updated; static_len is also updated if stree is * not null. */ function gen_bitlen(s, desc) // deflate_state *s; // tree_desc *desc; /* the tree descriptor */ { var tree = desc.dyn_tree; var max_code = desc.max_code; var stree = desc.stat_desc.static_tree; var has_stree = desc.stat_desc.has_stree; var extra = desc.stat_desc.extra_bits; var base = desc.stat_desc.extra_base; var max_length = desc.stat_desc.max_length; var h; /* heap index */ var n, m; /* iterate over the tree elements */ var bits; /* bit length */ var xbits; /* extra bits */ var f; /* frequency */ var overflow = 0; /* number of elements with bit length too large */ for (bits = 0; bits <= MAX_BITS; bits++) { s.bl_count[bits] = 0; } /* In a first pass, compute the optimal bit lengths (which may * overflow in the case of the bit length tree). */ tree[s.heap[s.heap_max]*2 + 1]/*.Len*/ = 0; /* root of the heap */ for (h = s.heap_max+1; h < HEAP_SIZE; h++) { n = s.heap[h]; bits = tree[tree[n*2 +1]/*.Dad*/ * 2 + 1]/*.Len*/ + 1; if (bits > max_length) { bits = max_length; overflow++; } tree[n*2 + 1]/*.Len*/ = bits; /* We overwrite tree[n].Dad which is no longer needed */ if (n > max_code) { continue; } /* not a leaf node */ s.bl_count[bits]++; xbits = 0; if (n >= base) { xbits = extra[n-base]; } f = tree[n * 2]/*.Freq*/; s.opt_len += f * (bits + xbits); if (has_stree) { s.static_len += f * (stree[n*2 + 1]/*.Len*/ + xbits); } } if (overflow === 0) { return; } // Trace((stderr,"\nbit length overflow\n")); /* This happens for example on obj2 and pic of the Calgary corpus */ /* Find the first bit length which could increase: */ do { bits = max_length-1; while (s.bl_count[bits] === 0) { bits--; } s.bl_count[bits]--; /* move one leaf down the tree */ s.bl_count[bits+1] += 2; /* move one overflow item as its brother */ s.bl_count[max_length]--; /* The brother of the overflow item also moves one step up, * but this does not affect bl_count[max_length] */ overflow -= 2; } while (overflow > 0); /* Now recompute all bit lengths, scanning in increasing frequency. * h is still equal to HEAP_SIZE. (It is simpler to reconstruct all * lengths instead of fixing only the wrong ones. This idea is taken * from 'ar' written by Haruhiko Okumura.) */ for (bits = max_length; bits !== 0; bits--) { n = s.bl_count[bits]; while (n !== 0) { m = s.heap[--h]; if (m > max_code) { continue; } if (tree[m*2 + 1]/*.Len*/ !== bits) { // Trace((stderr,"code %d bits %d->%d\n", m, tree[m].Len, bits)); s.opt_len += (bits - tree[m*2 + 1]/*.Len*/)*tree[m*2]/*.Freq*/; tree[m*2 + 1]/*.Len*/ = bits; } n--; } } } /* =========================================================================== * Generate the codes for a given tree and bit counts (which need not be * optimal). * IN assertion: the array bl_count contains the bit length statistics for * the given tree and the field len is set for all tree elements. * OUT assertion: the field code is set for all tree elements of non * zero code length. */ function gen_codes(tree, max_code, bl_count) // ct_data *tree; /* the tree to decorate */ // int max_code; /* largest code with non zero frequency */ // ushf *bl_count; /* number of codes at each bit length */ { var next_code = new Array(MAX_BITS+1); /* next code value for each bit length */ var code = 0; /* running code value */ var bits; /* bit index */ var n; /* code index */ /* The distribution counts are first used to generate the code values * without bit reversal. */ for (bits = 1; bits <= MAX_BITS; bits++) { next_code[bits] = code = (code + bl_count[bits-1]) << 1; } /* Check that the bit counts in bl_count are consistent. The last code * must be all ones. */ //Assert (code + bl_count[MAX_BITS]-1 == (1<<MAX_BITS)-1, // "inconsistent bit counts"); //Tracev((stderr,"\ngen_codes: max_code %d ", max_code)); for (n = 0; n <= max_code; n++) { var len = tree[n*2 + 1]/*.Len*/; if (len === 0) { continue; } /* Now reverse the bits */ tree[n*2]/*.Code*/ = bi_reverse(next_code[len]++, len); //Tracecv(tree != static_ltree, (stderr,"\nn %3d %c l %2d c %4x (%x) ", // n, (isgraph(n) ? n : ' '), len, tree[n].Code, next_code[len]-1)); } } /* =========================================================================== * Initialize the various 'constant' tables. */ function tr_static_init() { var n; /* iterates over tree elements */ var bits; /* bit counter */ var length; /* length value */ var code; /* code value */ var dist; /* distance index */ var bl_count = new Array(MAX_BITS+1); /* number of codes at each bit length for an optimal tree */ // do check in _tr_init() //if (static_init_done) return; /* For some embedded targets, global variables are not initialized: */ /*#ifdef NO_INIT_GLOBAL_POINTERS static_l_desc.static_tree = static_ltree; static_l_desc.extra_bits = extra_lbits; static_d_desc.static_tree = static_dtree; static_d_desc.extra_bits = extra_dbits; static_bl_desc.extra_bits = extra_blbits; #endif*/ /* Initialize the mapping length (0..255) -> length code (0..28) */ length = 0; for (code = 0; code < LENGTH_CODES-1; code++) { base_length[code] = length; for (n = 0; n < (1<<extra_lbits[code]); n++) { _length_code[length++] = code; } } //Assert (length == 256, "tr_static_init: length != 256"); /* Note that the length 255 (match length 258) can be represented * in two different ways: code 284 + 5 bits or code 285, so we * overwrite length_code[255] to use the best encoding: */ _length_code[length-1] = code; /* Initialize the mapping dist (0..32K) -> dist code (0..29) */ dist = 0; for (code = 0 ; code < 16; code++) { base_dist[code] = dist; for (n = 0; n < (1<<extra_dbits[code]); n++) { _dist_code[dist++] = code; } } //Assert (dist == 256, "tr_static_init: dist != 256"); dist >>= 7; /* from now on, all distances are divided by 128 */ for (; code < D_CODES; code++) { base_dist[code] = dist << 7; for (n = 0; n < (1<<(extra_dbits[code]-7)); n++) { _dist_code[256 + dist++] = code; } } //Assert (dist == 256, "tr_static_init: 256+dist != 512"); /* Construct the codes of the static literal tree */ for (bits = 0; bits <= MAX_BITS; bits++) { bl_count[bits] = 0; } n = 0; while (n <= 143) { static_ltree[n*2 + 1]/*.Len*/ = 8; n++; bl_count[8]++; } while (n <= 255) { static_ltree[n*2 + 1]/*.Len*/ = 9; n++; bl_count[9]++; } while (n <= 279) { static_ltree[n*2 + 1]/*.Len*/ = 7; n++; bl_count[7]++; } while (n <= 287) { static_ltree[n*2 + 1]/*.Len*/ = 8; n++; bl_count[8]++; } /* Codes 286 and 287 do not exist, but we must include them in the * tree construction to get a canonical Huffman tree (longest code * all ones) */ gen_codes(static_ltree, L_CODES+1, bl_count); /* The static distance tree is trivial: */ for (n = 0; n < D_CODES; n++) { static_dtree[n*2 + 1]/*.Len*/ = 5; static_dtree[n*2]/*.Code*/ = bi_reverse(n, 5); } // Now data ready and we can init static trees static_l_desc = new StaticTreeDesc(static_ltree, extra_lbits, LITERALS+1, L_CODES, MAX_BITS); static_d_desc = new StaticTreeDesc(static_dtree, extra_dbits, 0, D_CODES, MAX_BITS); static_bl_desc =new StaticTreeDesc(new Array(0), extra_blbits, 0, BL_CODES, MAX_BL_BITS); //static_init_done = true; } /* =========================================================================== * Initialize a new block. */ function init_block(s) { var n; /* iterates over tree elements */ /* Initialize the trees. */ for (n = 0; n < L_CODES; n++) { s.dyn_ltree[n*2]/*.Freq*/ = 0; } for (n = 0; n < D_CODES; n++) { s.dyn_dtree[n*2]/*.Freq*/ = 0; } for (n = 0; n < BL_CODES; n++) { s.bl_tree[n*2]/*.Freq*/ = 0; } s.dyn_ltree[END_BLOCK*2]/*.Freq*/ = 1; s.opt_len = s.static_len = 0; s.last_lit = s.matches = 0; } /* =========================================================================== * Flush the bit buffer and align the output on a byte boundary */ function bi_windup(s) { if (s.bi_valid > 8) { put_short(s, s.bi_buf); } else if (s.bi_valid > 0) { //put_byte(s, (Byte)s->bi_buf); s.pending_buf[s.pending++] = s.bi_buf; } s.bi_buf = 0; s.bi_valid = 0; } /* =========================================================================== * Copy a stored block, storing first the length and its * one's complement if requested. */ function copy_block(s, buf, len, header) //DeflateState *s; //charf *buf; /* the input data */ //unsigned len; /* its length */ //int header; /* true if block header must be written */ { bi_windup(s); /* align on byte boundary */ if (header) { put_short(s, len); put_short(s, ~len); } // while (len--) { // put_byte(s, *buf++); // } utils.arraySet(s.pending_buf, s.window, buf, len, s.pending); s.pending += len; } /* =========================================================================== * Compares to subtrees, using the tree depth as tie breaker when * the subtrees have equal frequency. This minimizes the worst case length. */ function smaller(tree, n, m, depth) { var _n2 = n*2; var _m2 = m*2; return (tree[_n2]/*.Freq*/ < tree[_m2]/*.Freq*/ || (tree[_n2]/*.Freq*/ === tree[_m2]/*.Freq*/ && depth[n] <= depth[m])); } /* =========================================================================== * Restore the heap property by moving down the tree starting at node k, * exchanging a node with the smallest of its two sons if necessary, stopping * when the heap property is re-established (each father smaller than its * two sons). */ function pqdownheap(s, tree, k) // deflate_state *s; // ct_data *tree; /* the tree to restore */ // int k; /* node to move down */ { var v = s.heap[k]; var j = k << 1; /* left son of k */ while (j <= s.heap_len) { /* Set j to the smallest of the two sons: */ if (j < s.heap_len && smaller(tree, s.heap[j+1], s.heap[j], s.depth)) { j++; } /* Exit if v is smaller than both sons */ if (smaller(tree, v, s.heap[j], s.depth)) { break; } /* Exchange v with the smallest son */ s.heap[k] = s.heap[j]; k = j; /* And continue down the tree, setting j to the left son of k */ j <<= 1; } s.heap[k] = v; } // inlined manually // var SMALLEST = 1; /* =========================================================================== * Send the block data compressed using the given Huffman trees */ function compress_block(s, ltree, dtree) // deflate_state *s; // const ct_data *ltree; /* literal tree */ // const ct_data *dtree; /* distance tree */ { var dist; /* distance of matched string */ var lc; /* match length or unmatched char (if dist == 0) */ var lx = 0; /* running index in l_buf */ var code; /* the code to send */ var extra; /* number of extra bits to send */ if (s.last_lit !== 0) { do { dist = (s.pending_buf[s.d_buf + lx*2] << 8) | (s.pending_buf[s.d_buf + lx*2 + 1]); lc = s.pending_buf[s.l_buf + lx]; lx++; if (dist === 0) { send_code(s, lc, ltree); /* send a literal byte */ //Tracecv(isgraph(lc), (stderr," '%c' ", lc)); } else { /* Here, lc is the match length - MIN_MATCH */ code = _length_code[lc]; send_code(s, code+LITERALS+1, ltree); /* send the length code */ extra = extra_lbits[code]; if (extra !== 0) { lc -= base_length[code]; send_bits(s, lc, extra); /* send the extra length bits */ } dist--; /* dist is now the match distance - 1 */ code = d_code(dist); //Assert (code < D_CODES, "bad d_code"); send_code(s, code, dtree); /* send the distance code */ extra = extra_dbits[code]; if (extra !== 0) { dist -= base_dist[code]; send_bits(s, dist, extra); /* send the extra distance bits */ } } /* literal or match pair ? */ /* Check that the overlay between pending_buf and d_buf+l_buf is ok: */ //Assert((uInt)(s->pending) < s->lit_bufsize + 2*lx, // "pendingBuf overflow"); } while (lx < s.last_lit); } send_code(s, END_BLOCK, ltree); } /* =========================================================================== * Construct one Huffman tree and assigns the code bit strings and lengths. * Update the total bit length for the current block. * IN assertion: the field freq is set for all tree elements. * OUT assertions: the fields len and code are set to the optimal bit length * and corresponding code. The length opt_len is updated; static_len is * also updated if stree is not null. The field max_code is set. */ function build_tree(s, desc) // deflate_state *s; // tree_desc *desc; /* the tree descriptor */ { var tree = desc.dyn_tree; var stree = desc.stat_desc.static_tree; var has_stree = desc.stat_desc.has_stree; var elems = desc.stat_desc.elems; var n, m; /* iterate over heap elements */ var max_code = -1; /* largest code with non zero frequency */ var node; /* new node being created */ /* Construct the initial heap, with least frequent element in * heap[SMALLEST]. The sons of heap[n] are heap[2*n] and heap[2*n+1]. * heap[0] is not used. */ s.heap_len = 0; s.heap_max = HEAP_SIZE; for (n = 0; n < elems; n++) { if (tree[n * 2]/*.Freq*/ !== 0) { s.heap[++s.heap_len] = max_code = n; s.depth[n] = 0; } else { tree[n*2 + 1]/*.Len*/ = 0; } } /* The pkzip format requires that at least one distance code exists, * and that at least one bit should be sent even if there is only one * possible code. So to avoid special checks later on we force at least * two codes of non zero frequency. */ while (s.heap_len < 2) { node = s.heap[++s.heap_len] = (max_code < 2 ? ++max_code : 0); tree[node * 2]/*.Freq*/ = 1; s.depth[node] = 0; s.opt_len--; if (has_stree) { s.static_len -= stree[node*2 + 1]/*.Len*/; } /* node is 0 or 1 so it does not have extra bits */ } desc.max_code = max_code; /* The elements heap[heap_len/2+1 .. heap_len] are leaves of the tree, * establish sub-heaps of increasing lengths: */ for (n = (s.heap_len >> 1/*int /2*/); n >= 1; n--) { pqdownheap(s, tree, n); } /* Construct the Huffman tree by repeatedly combining the least two * frequent nodes. */ node = elems; /* next internal node of the tree */ do { //pqremove(s, tree, n); /* n = node of least frequency */ /*** pqremove ***/ n = s.heap[1/*SMALLEST*/]; s.heap[1/*SMALLEST*/] = s.heap[s.heap_len--]; pqdownheap(s, tree, 1/*SMALLEST*/); /***/ m = s.heap[1/*SMALLEST*/]; /* m = node of next least frequency */ s.heap[--s.heap_max] = n; /* keep the nodes sorted by frequency */ s.heap[--s.heap_max] = m; /* Create a new node father of n and m */ tree[node * 2]/*.Freq*/ = tree[n * 2]/*.Freq*/ + tree[m * 2]/*.Freq*/; s.depth[node] = (s.depth[n] >= s.depth[m] ? s.depth[n] : s.depth[m]) + 1; tree[n*2 + 1]/*.Dad*/ = tree[m*2 + 1]/*.Dad*/ = node; /* and insert the new node in the heap */ s.heap[1/*SMALLEST*/] = node++; pqdownheap(s, tree, 1/*SMALLEST*/); } while (s.heap_len >= 2); s.heap[--s.heap_max] = s.heap[1/*SMALLEST*/]; /* At this point, the fields freq and dad are set. We can now * generate the bit lengths. */ gen_bitlen(s, desc); /* The field len is now set, we can generate the bit codes */ gen_codes(tree, max_code, s.bl_count); } /* =========================================================================== * Scan a literal or distance tree to determine the frequencies of the codes * in the bit length tree. */ function scan_tree(s, tree, max_code) // deflate_state *s; // ct_data *tree; /* the tree to be scanned */ // int max_code; /* and its largest code of non zero frequency */ { var n; /* iterates over all tree elements */ var prevlen = -1; /* last emitted length */ var curlen; /* length of current code */ var nextlen = tree[0*2 + 1]/*.Len*/; /* length of next code */ var count = 0; /* repeat count of the current code */ var max_count = 7; /* max repeat count */ var min_count = 4; /* min repeat count */ if (nextlen === 0) { max_count = 138; min_count = 3; } tree[(max_code+1)*2 + 1]/*.Len*/ = 0xffff; /* guard */ for (n = 0; n <= max_code; n++) { curlen = nextlen; nextlen = tree[(n+1)*2 + 1]/*.Len*/; if (++count < max_count && curlen === nextlen) { continue; } else if (count < min_count) { s.bl_tree[curlen * 2]/*.Freq*/ += count; } else if (curlen !== 0) { if (curlen !== prevlen) { s.bl_tree[curlen * 2]/*.Freq*/++; } s.bl_tree[REP_3_6*2]/*.Freq*/++; } else if (count <= 10) { s.bl_tree[REPZ_3_10*2]/*.Freq*/++; } else { s.bl_tree[REPZ_11_138*2]/*.Freq*/++; } count = 0; prevlen = curlen; if (nextlen === 0) { max_count = 138; min_count = 3; } else if (curlen === nextlen) { max_count = 6; min_count = 3; } else { max_count = 7; min_count = 4; } } } /* =========================================================================== * Send a literal or distance tree in compressed form, using the codes in * bl_tree. */ function send_tree(s, tree, max_code) // deflate_state *s; // ct_data *tree; /* the tree to be scanned */ // int max_code; /* and its largest code of non zero frequency */ { var n; /* iterates over all tree elements */ var prevlen = -1; /* last emitted length */ var curlen; /* length of current code */ var nextlen = tree[0*2 + 1]/*.Len*/; /* length of next code */ var count = 0; /* repeat count of the current code */ var max_count = 7; /* max repeat count */ var min_count = 4; /* min repeat count */ /* tree[max_code+1].Len = -1; */ /* guard already set */ if (nextlen === 0) { max_count = 138; min_count = 3; } for (n = 0; n <= max_code; n++) { curlen = nextlen; nextlen = tree[(n+1)*2 + 1]/*.Len*/; if (++count < max_count && curlen === nextlen) { continue; } else if (count < min_count) { do { send_code(s, curlen, s.bl_tree); } while (--count !== 0); } else if (curlen !== 0) { if (curlen !== prevlen) { send_code(s, curlen, s.bl_tree); count--; } //Assert(count >= 3 && count <= 6, " 3_6?"); send_code(s, REP_3_6, s.bl_tree); send_bits(s, count-3, 2); } else if (count <= 10) { send_code(s, REPZ_3_10, s.bl_tree); send_bits(s, count-3, 3); } else { send_code(s, REPZ_11_138, s.bl_tree); send_bits(s, count-11, 7); } count = 0; prevlen = curlen; if (nextlen === 0) { max_count = 138; min_count = 3; } else if (curlen === nextlen) { max_count = 6; min_count = 3; } else { max_count = 7; min_count = 4; } } } /* =========================================================================== * Construct the Huffman tree for the bit lengths and return the index in * bl_order of the last bit length code to send. */ function build_bl_tree(s) { var max_blindex; /* index of last bit length code of non zero freq */ /* Determine the bit length frequencies for literal and distance trees */ scan_tree(s, s.dyn_ltree, s.l_desc.max_code); scan_tree(s, s.dyn_dtree, s.d_desc.max_code); /* Build the bit length tree: */ build_tree(s, s.bl_desc); /* opt_len now includes the length of the tree representations, except * the lengths of the bit lengths codes and the 5+5+4 bits for the counts. */ /* Determine the number of bit length codes to send. The pkzip format * requires that at least 4 bit length codes be sent. (appnote.txt says * 3 but the actual value used is 4.) */ for (max_blindex = BL_CODES-1; max_blindex >= 3; max_blindex--) { if (s.bl_tree[bl_order[max_blindex]*2 + 1]/*.Len*/ !== 0) { break; } } /* Update opt_len to include the bit length tree and counts */ s.opt_len += 3*(max_blindex+1) + 5+5+4; //Tracev((stderr, "\ndyn trees: dyn %ld, stat %ld", // s->opt_len, s->static_len)); return max_blindex; } /* =========================================================================== * Send the header for a block using dynamic Huffman trees: the counts, the * lengths of the bit length codes, the literal tree and the distance tree. * IN assertion: lcodes >= 257, dcodes >= 1, blcodes >= 4. */ function send_all_trees(s, lcodes, dcodes, blcodes) // deflate_state *s; // int lcodes, dcodes, blcodes; /* number of codes for each tree */ { var rank; /* index in bl_order */ //Assert (lcodes >= 257 && dcodes >= 1 && blcodes >= 4, "not enough codes"); //Assert (lcodes <= L_CODES && dcodes <= D_CODES && blcodes <= BL_CODES, // "too many codes"); //Tracev((stderr, "\nbl counts: ")); send_bits(s, lcodes-257, 5); /* not +255 as stated in appnote.txt */ send_bits(s, dcodes-1, 5); send_bits(s, blcodes-4, 4); /* not -3 as stated in appnote.txt */ for (rank = 0; rank < blcodes; rank++) { //Tracev((stderr, "\nbl code %2d ", bl_order[rank])); send_bits(s, s.bl_tree[bl_order[rank]*2 + 1]/*.Len*/, 3); } //Tracev((stderr, "\nbl tree: sent %ld", s->bits_sent)); send_tree(s, s.dyn_ltree, lcodes-1); /* literal tree */ //Tracev((stderr, "\nlit tree: sent %ld", s->bits_sent)); send_tree(s, s.dyn_dtree, dcodes-1); /* distance tree */ //Tracev((stderr, "\ndist tree: sent %ld", s->bits_sent)); } /* =========================================================================== * Check if the data type is TEXT or BINARY, using the following algorithm: * - TEXT if the two conditions below are satisfied: * a) There are no non-portable control characters belonging to the * "black list" (0..6, 14..25, 28..31). * b) There is at least one printable character belonging to the * "white list" (9 {TAB}, 10 {LF}, 13 {CR}, 32..255). * - BINARY otherwise. * - The following partially-portable control characters form a * "gray list" that is ignored in this detection algorithm: * (7 {BEL}, 8 {BS}, 11 {VT}, 12 {FF}, 26 {SUB}, 27 {ESC}). * IN assertion: the fields Freq of dyn_ltree are set. */ function detect_data_type(s) { /* black_mask is the bit mask of black-listed bytes * set bits 0..6, 14..25, and 28..31 * 0xf3ffc07f = binary 11110011111111111100000001111111 */ var black_mask = 0xf3ffc07f; var n; /* Check for non-textual ("black-listed") bytes. */ for (n = 0; n <= 31; n++, black_mask >>>= 1) { if ((black_mask & 1) && (s.dyn_ltree[n*2]/*.Freq*/ !== 0)) { return Z_BINARY; } } /* Check for textual ("white-listed") bytes. */ if (s.dyn_ltree[9 * 2]/*.Freq*/ !== 0 || s.dyn_ltree[10 * 2]/*.Freq*/ !== 0 || s.dyn_ltree[13 * 2]/*.Freq*/ !== 0) { return Z_TEXT; } for (n = 32; n < LITERALS; n++) { if (s.dyn_ltree[n * 2]/*.Freq*/ !== 0) { return Z_TEXT; } } /* There are no "black-listed" or "white-listed" bytes: * this stream either is empty or has tolerated ("gray-listed") bytes only. */ return Z_BINARY; } var static_init_done = false; /* =========================================================================== * Initialize the tree data structures for a new zlib stream. */ function _tr_init(s) { if (!static_init_done) { tr_static_init(); static_init_done = true; } s.l_desc = new TreeDesc(s.dyn_ltree, static_l_desc); s.d_desc = new TreeDesc(s.dyn_dtree, static_d_desc); s.bl_desc = new TreeDesc(s.bl_tree, static_bl_desc); s.bi_buf = 0; s.bi_valid = 0; /* Initialize the first block of the first file: */ init_block(s); } /* =========================================================================== * Send a stored block */ function _tr_stored_block(s, buf, stored_len, last) //DeflateState *s; //charf *buf; /* input block */ //ulg stored_len; /* length of input block */ //int last; /* one if this is the last block for a file */ { send_bits(s, (STORED_BLOCK<<1)+(last ? 1 : 0), 3); /* send block type */ copy_block(s, buf, stored_len, true); /* with header */ } /* =========================================================================== * Send one empty static block to give enough lookahead for inflate. * This takes 10 bits, of which 7 may remain in the bit buffer. */ function _tr_align(s) { send_bits(s, STATIC_TREES<<1, 3); send_code(s, END_BLOCK, static_ltree); bi_flush(s); } /* =========================================================================== * Determine the best encoding for the current block: dynamic trees, static * trees or store, and output the encoded block to the zip file. */ function _tr_flush_block(s, buf, stored_len, last) //DeflateState *s; //charf *buf; /* input block, or NULL if too old */ //ulg stored_len; /* length of input block */ //int last; /* one if this is the last block for a file */ { var opt_lenb, static_lenb; /* opt_len and static_len in bytes */ var max_blindex = 0; /* index of last bit length code of non zero freq */ /* Build the Huffman trees unless a stored block is forced */ if (s.level > 0) { /* Check if the file is binary or text */ if (s.strm.data_type === Z_UNKNOWN) { s.strm.data_type = detect_data_type(s); } /* Construct the literal and distance trees */ build_tree(s, s.l_desc); // Tracev((stderr, "\nlit data: dyn %ld, stat %ld", s->opt_len, // s->static_len)); build_tree(s, s.d_desc); // Tracev((stderr, "\ndist data: dyn %ld, stat %ld", s->opt_len, // s->static_len)); /* At this point, opt_len and static_len are the total bit lengths of * the compressed block data, excluding the tree representations. */ /* Build the bit length tree for the above two trees, and get the index * in bl_order of the last bit length code to send. */ max_blindex = build_bl_tree(s); /* Determine the best encoding. Compute the block lengths in bytes. */ opt_lenb = (s.opt_len+3+7) >>> 3; static_lenb = (s.static_len+3+7) >>> 3; // Tracev((stderr, "\nopt %lu(%lu) stat %lu(%lu) stored %lu lit %u ", // opt_lenb, s->opt_len, static_lenb, s->static_len, stored_len, // s->last_lit)); if (static_lenb <= opt_lenb) { opt_lenb = static_lenb; } } else { // Assert(buf != (char*)0, "lost buf"); opt_lenb = static_lenb = stored_len + 5; /* force a stored block */ } if ((stored_len+4 <= opt_lenb) && (buf !== -1)) { /* 4: two words for the lengths */ /* The test buf != NULL is only necessary if LIT_BUFSIZE > WSIZE. * Otherwise we can't have processed more than WSIZE input bytes since * the last block flush, because compression would have been * successful. If LIT_BUFSIZE <= WSIZE, it is never too late to * transform a block into a stored block. */ _tr_stored_block(s, buf, stored_len, last); } else if (s.strategy === Z_FIXED || static_lenb === opt_lenb) { send_bits(s, (STATIC_TREES<<1) + (last ? 1 : 0), 3); compress_block(s, static_ltree, static_dtree); } else { send_bits(s, (DYN_TREES<<1) + (last ? 1 : 0), 3); send_all_trees(s, s.l_desc.max_code+1, s.d_desc.max_code+1, max_blindex+1); compress_block(s, s.dyn_ltree, s.dyn_dtree); } // Assert (s->compressed_len == s->bits_sent, "bad compressed size"); /* The above check is made mod 2^32, for files larger than 512 MB * and uLong implemented on 32 bits. */ init_block(s); if (last) { bi_windup(s); } // Tracev((stderr,"\ncomprlen %lu(%lu) ", s->compressed_len>>3, // s->compressed_len-7*last)); } /* =========================================================================== * Save the match info and tally the frequency counts. Return true if * the current block must be flushed. */ function _tr_tally(s, dist, lc) // deflate_state *s; // unsigned dist; /* distance of matched string */ // unsigned lc; /* match length-MIN_MATCH or unmatched char (if dist==0) */ { //var out_length, in_length, dcode; s.pending_buf[s.d_buf + s.last_lit * 2] = (dist >>> 8) & 0xff; s.pending_buf[s.d_buf + s.last_lit * 2 + 1] = dist & 0xff; s.pending_buf[s.l_buf + s.last_lit] = lc & 0xff; s.last_lit++; if (dist === 0) { /* lc is the unmatched char */ s.dyn_ltree[lc*2]/*.Freq*/++; } else { s.matches++; /* Here, lc is the match length - MIN_MATCH */ dist--; /* dist = match distance - 1 */ //Assert((ush)dist < (ush)MAX_DIST(s) && // (ush)lc <= (ush)(MAX_MATCH-MIN_MATCH) && // (ush)d_code(dist) < (ush)D_CODES, "_tr_tally: bad match"); s.dyn_ltree[(_length_code[lc]+LITERALS+1) * 2]/*.Freq*/++; s.dyn_dtree[d_code(dist) * 2]/*.Freq*/++; } // (!) This block is disabled in zlib defailts, // don't enable it for binary compatibility //#ifdef TRUNCATE_BLOCK // /* Try to guess if it is profitable to stop the current block here */ // if ((s.last_lit & 0x1fff) === 0 && s.level > 2) { // /* Compute an upper bound for the compressed length */ // out_length = s.last_lit*8; // in_length = s.strstart - s.block_start; // // for (dcode = 0; dcode < D_CODES; dcode++) { // out_length += s.dyn_dtree[dcode*2]/*.Freq*/ * (5 + extra_dbits[dcode]); // } // out_length >>>= 3; // //Tracev((stderr,"\nlast_lit %u, in %ld, out ~%ld(%ld%%) ", // // s->last_lit, in_length, out_length, // // 100L - out_length*100L/in_length)); // if (s.matches < (s.last_lit>>1)/*int /2*/ && out_length < (in_length>>1)/*int /2*/) { // return true; // } // } //#endif return (s.last_lit === s.lit_bufsize-1); /* We avoid equality with lit_bufsize because of wraparound at 64K * on 16 bit machines and because stored blocks are restricted to * 64K-1 bytes. */ } exports._tr_init = _tr_init; exports._tr_stored_block = _tr_stored_block; exports._tr_flush_block = _tr_flush_block; exports._tr_tally = _tr_tally; exports._tr_align = _tr_align; },{"../utils/common":73}],85:[function(_dereq_,module,exports){ 'use strict'; function ZStream() { /* next input byte */ this.input = null; // JS specific, because we have no pointers this.next_in = 0; /* number of bytes available at input */ this.avail_in = 0; /* total number of input bytes read so far */ this.total_in = 0; /* next output byte should be put there */ this.output = null; // JS specific, because we have no pointers this.next_out = 0; /* remaining free space at output */ this.avail_out = 0; /* total number of bytes output so far */ this.total_out = 0; /* last error message, NULL if no error */ this.msg = ''/*Z_NULL*/; /* not visible by applications */ this.state = null; /* best guess about the data type: binary or text */ this.data_type = 2/*Z_UNKNOWN*/; /* adler32 value of the uncompressed data */ this.adler = 0; } module.exports = ZStream; },{}]},{},[1]);
src/routes/register/Register.js
louisukiri/react-starter-kit
/** * React Starter Kit (https://www.reactstarterkit.com/) * * Copyright © 2014-present Kriasoft, LLC. All rights reserved. * * This source code is licensed under the MIT license found in the * LICENSE.txt file in the root directory of this source tree. */ import React from 'react'; import PropTypes from 'prop-types'; import withStyles from 'isomorphic-style-loader/lib/withStyles'; import s from './Register.css'; class Register extends React.Component { static propTypes = { title: PropTypes.string.isRequired, }; render() { return ( <div className={s.root}> <div className={s.container}> <h1> {this.props.title} </h1> <p>...</p> </div> </div> ); } } export default withStyles(s)(Register);
src/js/index.js
banmunongtian/react-es6-webpack
import React from 'react'; import ReactDom from 'react-dom'; import '../css/csd.css'; export default class Hello extends React.Component { constructor(props) { super(props) this.state = { id: 1 } } componentWillMont() { } render() { return ( <div> <div className="cls">hello word</div> </div> ) } } ReactDom.render(<Hello/>, document.getElementById('content'))
client/components/CommentPage.js
IBM-Bluemix/SSComments
//------------------------------------------------------------------------------ // Copyright IBM Corp. 2015 // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. //------------------------------------------------------------------------------ import React from 'react'; import CommentList from './CommentList'; import TimeTabs from './TimeTabs'; import PageStore from '../stores/PageStore'; import CommentStore from '../stores/CommentStore'; class CommentPage extends React.Component { constructor (props) { super(props); this.state = this._getStateObj(); this._onChange = e => this.setState(this._getStateObj()); } render () { return ( <div className="page comment-page"> <TimeTabs openTab={this.state.openTab} /> <CommentList comments={this.state.comments} /> </div> ); } /** When first in the page, set up change handlers */ componentDidMount () { CommentStore.addChangeListener(this._onChange); PageStore.addChangeListener(this._onChange); } /** The state for this page */ _getStateObj () { return { comments: CommentStore.getComments(), openTab: PageStore.getOpenTab() } } /** When removing, clean up change handlers */ componentWillUnmount () { CommentStore.removeChangeListener(this._onChange); PageStore.removeChangeListener(this._onChange); } } module.exports = CommentPage;
content-srv/src/components/mdc/Button/index.js
ronanamsterdam/lemonapp
var _extends = Object.assign || function (target) { for (var i = 1; i < arguments.length; i++) { var source = arguments[i]; for (var key in source) { if (Object.prototype.hasOwnProperty.call(source, key)) { target[key] = source[key]; } } } return target; }; import { h } from "preact"; import MaterialComponent from "../MaterialComponent"; import './style.css'; /** * @prop dense = false * @prop raised = false * @prop compact = false * @prop primary = false * @prop accent = false * @prop disabled = false */ export default class Button extends MaterialComponent { constructor() { super(); this.componentName = "button"; this._mdcProps = ["dense", "raised", "compact", "primary", "accent"]; } componentDidMount() { super.attachRipple(); } materialDom(props) { return h( "button", _extends({ ref: control => { this.control = control; } }, props), this.props.children ); } }
test/integration/client-navigation/pages/fragment-syntax.js
BlancheXu/test
/* eslint-disable */ import React from 'react' export default () => <>My component!</>
ajax/libs/material-ui/5.0.0-alpha.28/node/internal/svg-icons/Star.min.js
cdnjs/cdnjs
"use strict";var _interopRequireDefault=require("@babel/runtime/helpers/interopRequireDefault"),_interopRequireWildcard=require("@babel/runtime/helpers/interopRequireWildcard");Object.defineProperty(exports,"__esModule",{value:!0}),exports.default=void 0;var React=_interopRequireWildcard(require("react")),_createSvgIcon=_interopRequireDefault(require("../../utils/createSvgIcon")),_jsxRuntime=require("react/jsx-runtime"),_default=(0,_createSvgIcon.default)((0,_jsxRuntime.jsx)("path",{d:"M12 17.27L18.18 21l-1.64-7.03L22 9.24l-7.19-.61L12 2 9.19 8.63 2 9.24l5.46 4.73L5.82 21z"}),"Star");exports.default=_default;
ajax/libs/video.js/5.0.0-rc.104/alt/video.novtt.js
amoyeh/cdnjs
/** * @license * Video.js 5.0.0-rc.104 <http://videojs.com/> * Copyright Brightcove, Inc. <https://www.brightcove.com/> * Available under Apache License Version 2.0 * <https://github.com/videojs/video.js/blob/master/LICENSE> */ (function(f){if(typeof exports==="object"&&typeof module!=="undefined"){module.exports=f()}else if(typeof define==="function"&&define.amd){define([],f)}else{var g;if(typeof window!=="undefined"){g=window}else if(typeof global!=="undefined"){g=global}else if(typeof self!=="undefined"){g=self}else{g=this}g.videojs = f()}})(function(){var define,module,exports;return (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<r.length;o++)s(r[o]);return s})({1:[function(_dereq_,module,exports){ (function (global){ var topLevel = typeof global !== 'undefined' ? global : typeof window !== 'undefined' ? window : {} var minDoc = _dereq_('min-document'); if (typeof document !== 'undefined') { module.exports = document; } else { var doccy = topLevel['__GLOBAL_DOCUMENT_CACHE@4']; if (!doccy) { doccy = topLevel['__GLOBAL_DOCUMENT_CACHE@4'] = minDoc; } module.exports = doccy; } }).call(this,typeof global !== "undefined" ? global : typeof self !== "undefined" ? self : typeof window !== "undefined" ? window : {}) //# sourceMappingURL=data:application/json;charset:utf-8;base64,eyJ2ZXJzaW9uIjozLCJzb3VyY2VzIjpbIm5vZGVfbW9kdWxlcy9nbG9iYWwvZG9jdW1lbnQuanMiXSwibmFtZXMiOltdLCJtYXBwaW5ncyI6IjtBQUFBO0FBQ0E7QUFDQTtBQUNBO0FBQ0E7QUFDQTtBQUNBO0FBQ0E7QUFDQTtBQUNBO0FBQ0E7QUFDQTtBQUNBO0FBQ0E7QUFDQTtBQUNBIiwiZmlsZSI6ImdlbmVyYXRlZC5qcyIsInNvdXJjZVJvb3QiOiIiLCJzb3VyY2VzQ29udGVudCI6WyJ2YXIgdG9wTGV2ZWwgPSB0eXBlb2YgZ2xvYmFsICE9PSAndW5kZWZpbmVkJyA/IGdsb2JhbCA6XG4gICAgdHlwZW9mIHdpbmRvdyAhPT0gJ3VuZGVmaW5lZCcgPyB3aW5kb3cgOiB7fVxudmFyIG1pbkRvYyA9IHJlcXVpcmUoJ21pbi1kb2N1bWVudCcpO1xuXG5pZiAodHlwZW9mIGRvY3VtZW50ICE9PSAndW5kZWZpbmVkJykge1xuICAgIG1vZHVsZS5leHBvcnRzID0gZG9jdW1lbnQ7XG59IGVsc2Uge1xuICAgIHZhciBkb2NjeSA9IHRvcExldmVsWydfX0dMT0JBTF9ET0NVTUVOVF9DQUNIRUA0J107XG5cbiAgICBpZiAoIWRvY2N5KSB7XG4gICAgICAgIGRvY2N5ID0gdG9wTGV2ZWxbJ19fR0xPQkFMX0RPQ1VNRU5UX0NBQ0hFQDQnXSA9IG1pbkRvYztcbiAgICB9XG5cbiAgICBtb2R1bGUuZXhwb3J0cyA9IGRvY2N5O1xufVxuIl19 },{"min-document":3}],2:[function(_dereq_,module,exports){ (function (global){ if (typeof window !== "undefined") { module.exports = window; } else if (typeof global !== "undefined") { module.exports = global; } else if (typeof self !== "undefined"){ module.exports = self; } else { module.exports = {}; } }).call(this,typeof global !== "undefined" ? global : typeof self !== "undefined" ? self : typeof window !== "undefined" ? window : {}) //# sourceMappingURL=data:application/json;charset:utf-8;base64,eyJ2ZXJzaW9uIjozLCJzb3VyY2VzIjpbIm5vZGVfbW9kdWxlcy9nbG9iYWwvd2luZG93LmpzIl0sIm5hbWVzIjpbXSwibWFwcGluZ3MiOiI7QUFBQTtBQUNBO0FBQ0E7QUFDQTtBQUNBO0FBQ0E7QUFDQTtBQUNBO0FBQ0E7QUFDQSIsImZpbGUiOiJnZW5lcmF0ZWQuanMiLCJzb3VyY2VSb290IjoiIiwic291cmNlc0NvbnRlbnQiOlsiaWYgKHR5cGVvZiB3aW5kb3cgIT09IFwidW5kZWZpbmVkXCIpIHtcbiAgICBtb2R1bGUuZXhwb3J0cyA9IHdpbmRvdztcbn0gZWxzZSBpZiAodHlwZW9mIGdsb2JhbCAhPT0gXCJ1bmRlZmluZWRcIikge1xuICAgIG1vZHVsZS5leHBvcnRzID0gZ2xvYmFsO1xufSBlbHNlIGlmICh0eXBlb2Ygc2VsZiAhPT0gXCJ1bmRlZmluZWRcIil7XG4gICAgbW9kdWxlLmV4cG9ydHMgPSBzZWxmO1xufSBlbHNlIHtcbiAgICBtb2R1bGUuZXhwb3J0cyA9IHt9O1xufVxuIl19 },{}],3:[function(_dereq_,module,exports){ },{}],4:[function(_dereq_,module,exports){ var getNative = _dereq_('../internal/getNative'); /* Native method references for those with the same name as other `lodash` methods. */ var nativeNow = getNative(Date, 'now'); /** * Gets the number of milliseconds that have elapsed since the Unix epoch * (1 January 1970 00:00:00 UTC). * * @static * @memberOf _ * @category Date * @example * * _.defer(function(stamp) { * console.log(_.now() - stamp); * }, _.now()); * // => logs the number of milliseconds it took for the deferred function to be invoked */ var now = nativeNow || function() { return new Date().getTime(); }; module.exports = now; },{"../internal/getNative":20}],5:[function(_dereq_,module,exports){ var isObject = _dereq_('../lang/isObject'), now = _dereq_('../date/now'); /** Used as the `TypeError` message for "Functions" methods. */ var FUNC_ERROR_TEXT = 'Expected a function'; /* Native method references for those with the same name as other `lodash` methods. */ var nativeMax = Math.max; /** * Creates a debounced function that delays invoking `func` until after `wait` * milliseconds have elapsed since the last time the debounced function was * invoked. The debounced function comes with a `cancel` method to cancel * delayed invocations. Provide an options object to indicate that `func` * should be invoked on the leading and/or trailing edge of the `wait` timeout. * Subsequent calls to the debounced function return the result of the last * `func` invocation. * * **Note:** If `leading` and `trailing` options are `true`, `func` is invoked * on the trailing edge of the timeout only if the the debounced function is * invoked more than once during the `wait` timeout. * * See [David Corbacho's article](http://drupalmotion.com/article/debounce-and-throttle-visual-explanation) * for details over the differences between `_.debounce` and `_.throttle`. * * @static * @memberOf _ * @category Function * @param {Function} func The function to debounce. * @param {number} [wait=0] The number of milliseconds to delay. * @param {Object} [options] The options object. * @param {boolean} [options.leading=false] Specify invoking on the leading * edge of the timeout. * @param {number} [options.maxWait] The maximum time `func` is allowed to be * delayed before it's invoked. * @param {boolean} [options.trailing=true] Specify invoking on the trailing * edge of the timeout. * @returns {Function} Returns the new debounced function. * @example * * // avoid costly calculations while the window size is in flux * jQuery(window).on('resize', _.debounce(calculateLayout, 150)); * * // invoke `sendMail` when the click event is fired, debouncing subsequent calls * jQuery('#postbox').on('click', _.debounce(sendMail, 300, { * 'leading': true, * 'trailing': false * })); * * // ensure `batchLog` is invoked once after 1 second of debounced calls * var source = new EventSource('/stream'); * jQuery(source).on('message', _.debounce(batchLog, 250, { * 'maxWait': 1000 * })); * * // cancel a debounced call * var todoChanges = _.debounce(batchLog, 1000); * Object.observe(models.todo, todoChanges); * * Object.observe(models, function(changes) { * if (_.find(changes, { 'user': 'todo', 'type': 'delete'})) { * todoChanges.cancel(); * } * }, ['delete']); * * // ...at some point `models.todo` is changed * models.todo.completed = true; * * // ...before 1 second has passed `models.todo` is deleted * // which cancels the debounced `todoChanges` call * delete models.todo; */ function debounce(func, wait, options) { var args, maxTimeoutId, result, stamp, thisArg, timeoutId, trailingCall, lastCalled = 0, maxWait = false, trailing = true; if (typeof func != 'function') { throw new TypeError(FUNC_ERROR_TEXT); } wait = wait < 0 ? 0 : (+wait || 0); if (options === true) { var leading = true; trailing = false; } else if (isObject(options)) { leading = !!options.leading; maxWait = 'maxWait' in options && nativeMax(+options.maxWait || 0, wait); trailing = 'trailing' in options ? !!options.trailing : trailing; } function cancel() { if (timeoutId) { clearTimeout(timeoutId); } if (maxTimeoutId) { clearTimeout(maxTimeoutId); } lastCalled = 0; maxTimeoutId = timeoutId = trailingCall = undefined; } function complete(isCalled, id) { if (id) { clearTimeout(id); } maxTimeoutId = timeoutId = trailingCall = undefined; if (isCalled) { lastCalled = now(); result = func.apply(thisArg, args); if (!timeoutId && !maxTimeoutId) { args = thisArg = undefined; } } } function delayed() { var remaining = wait - (now() - stamp); if (remaining <= 0 || remaining > wait) { complete(trailingCall, maxTimeoutId); } else { timeoutId = setTimeout(delayed, remaining); } } function maxDelayed() { complete(trailing, timeoutId); } function debounced() { args = arguments; stamp = now(); thisArg = this; trailingCall = trailing && (timeoutId || !leading); if (maxWait === false) { var leadingCall = leading && !timeoutId; } else { if (!maxTimeoutId && !leading) { lastCalled = stamp; } var remaining = maxWait - (stamp - lastCalled), isCalled = remaining <= 0 || remaining > maxWait; if (isCalled) { if (maxTimeoutId) { maxTimeoutId = clearTimeout(maxTimeoutId); } lastCalled = stamp; result = func.apply(thisArg, args); } else if (!maxTimeoutId) { maxTimeoutId = setTimeout(maxDelayed, remaining); } } if (isCalled && timeoutId) { timeoutId = clearTimeout(timeoutId); } else if (!timeoutId && wait !== maxWait) { timeoutId = setTimeout(delayed, wait); } if (leadingCall) { isCalled = true; result = func.apply(thisArg, args); } if (isCalled && !timeoutId && !maxTimeoutId) { args = thisArg = undefined; } return result; } debounced.cancel = cancel; return debounced; } module.exports = debounce; },{"../date/now":4,"../lang/isObject":33}],6:[function(_dereq_,module,exports){ /** Used as the `TypeError` message for "Functions" methods. */ var FUNC_ERROR_TEXT = 'Expected a function'; /* Native method references for those with the same name as other `lodash` methods. */ var nativeMax = Math.max; /** * Creates a function that invokes `func` with the `this` binding of the * created function and arguments from `start` and beyond provided as an array. * * **Note:** This method is based on the [rest parameter](https://developer.mozilla.org/Web/JavaScript/Reference/Functions/rest_parameters). * * @static * @memberOf _ * @category Function * @param {Function} func The function to apply a rest parameter to. * @param {number} [start=func.length-1] The start position of the rest parameter. * @returns {Function} Returns the new function. * @example * * var say = _.restParam(function(what, names) { * return what + ' ' + _.initial(names).join(', ') + * (_.size(names) > 1 ? ', & ' : '') + _.last(names); * }); * * say('hello', 'fred', 'barney', 'pebbles'); * // => 'hello fred, barney, & pebbles' */ function restParam(func, start) { if (typeof func != 'function') { throw new TypeError(FUNC_ERROR_TEXT); } start = nativeMax(start === undefined ? (func.length - 1) : (+start || 0), 0); return function() { var args = arguments, index = -1, length = nativeMax(args.length - start, 0), rest = Array(length); while (++index < length) { rest[index] = args[start + index]; } switch (start) { case 0: return func.call(this, rest); case 1: return func.call(this, args[0], rest); case 2: return func.call(this, args[0], args[1], rest); } var otherArgs = Array(start + 1); index = -1; while (++index < start) { otherArgs[index] = args[index]; } otherArgs[start] = rest; return func.apply(this, otherArgs); }; } module.exports = restParam; },{}],7:[function(_dereq_,module,exports){ var debounce = _dereq_('./debounce'), isObject = _dereq_('../lang/isObject'); /** Used as the `TypeError` message for "Functions" methods. */ var FUNC_ERROR_TEXT = 'Expected a function'; /** * Creates a throttled function that only invokes `func` at most once per * every `wait` milliseconds. The throttled function comes with a `cancel` * method to cancel delayed invocations. Provide an options object to indicate * that `func` should be invoked on the leading and/or trailing edge of the * `wait` timeout. Subsequent calls to the throttled function return the * result of the last `func` call. * * **Note:** If `leading` and `trailing` options are `true`, `func` is invoked * on the trailing edge of the timeout only if the the throttled function is * invoked more than once during the `wait` timeout. * * See [David Corbacho's article](http://drupalmotion.com/article/debounce-and-throttle-visual-explanation) * for details over the differences between `_.throttle` and `_.debounce`. * * @static * @memberOf _ * @category Function * @param {Function} func The function to throttle. * @param {number} [wait=0] The number of milliseconds to throttle invocations to. * @param {Object} [options] The options object. * @param {boolean} [options.leading=true] Specify invoking on the leading * edge of the timeout. * @param {boolean} [options.trailing=true] Specify invoking on the trailing * edge of the timeout. * @returns {Function} Returns the new throttled function. * @example * * // avoid excessively updating the position while scrolling * jQuery(window).on('scroll', _.throttle(updatePosition, 100)); * * // invoke `renewToken` when the click event is fired, but not more than once every 5 minutes * jQuery('.interactive').on('click', _.throttle(renewToken, 300000, { * 'trailing': false * })); * * // cancel a trailing throttled call * jQuery(window).on('popstate', throttled.cancel); */ function throttle(func, wait, options) { var leading = true, trailing = true; if (typeof func != 'function') { throw new TypeError(FUNC_ERROR_TEXT); } if (options === false) { leading = false; } else if (isObject(options)) { leading = 'leading' in options ? !!options.leading : leading; trailing = 'trailing' in options ? !!options.trailing : trailing; } return debounce(func, wait, { 'leading': leading, 'maxWait': +wait, 'trailing': trailing }); } module.exports = throttle; },{"../lang/isObject":33,"./debounce":5}],8:[function(_dereq_,module,exports){ /** * Copies the values of `source` to `array`. * * @private * @param {Array} source The array to copy values from. * @param {Array} [array=[]] The array to copy values to. * @returns {Array} Returns `array`. */ function arrayCopy(source, array) { var index = -1, length = source.length; array || (array = Array(length)); while (++index < length) { array[index] = source[index]; } return array; } module.exports = arrayCopy; },{}],9:[function(_dereq_,module,exports){ /** * A specialized version of `_.forEach` for arrays without support for callback * shorthands and `this` binding. * * @private * @param {Array} array The array to iterate over. * @param {Function} iteratee The function invoked per iteration. * @returns {Array} Returns `array`. */ function arrayEach(array, iteratee) { var index = -1, length = array.length; while (++index < length) { if (iteratee(array[index], index, array) === false) { break; } } return array; } module.exports = arrayEach; },{}],10:[function(_dereq_,module,exports){ /** * Copies properties of `source` to `object`. * * @private * @param {Object} source The object to copy properties from. * @param {Array} props The property names to copy. * @param {Object} [object={}] The object to copy properties to. * @returns {Object} Returns `object`. */ function baseCopy(source, props, object) { object || (object = {}); var index = -1, length = props.length; while (++index < length) { var key = props[index]; object[key] = source[key]; } return object; } module.exports = baseCopy; },{}],11:[function(_dereq_,module,exports){ var createBaseFor = _dereq_('./createBaseFor'); /** * The base implementation of `baseForIn` and `baseForOwn` which iterates * over `object` properties returned by `keysFunc` invoking `iteratee` for * each property. Iteratee functions may exit iteration early by explicitly * returning `false`. * * @private * @param {Object} object The object to iterate over. * @param {Function} iteratee The function invoked per iteration. * @param {Function} keysFunc The function to get the keys of `object`. * @returns {Object} Returns `object`. */ var baseFor = createBaseFor(); module.exports = baseFor; },{"./createBaseFor":18}],12:[function(_dereq_,module,exports){ var baseFor = _dereq_('./baseFor'), keysIn = _dereq_('../object/keysIn'); /** * The base implementation of `_.forIn` without support for callback * shorthands and `this` binding. * * @private * @param {Object} object The object to iterate over. * @param {Function} iteratee The function invoked per iteration. * @returns {Object} Returns `object`. */ function baseForIn(object, iteratee) { return baseFor(object, iteratee, keysIn); } module.exports = baseForIn; },{"../object/keysIn":39,"./baseFor":11}],13:[function(_dereq_,module,exports){ var arrayEach = _dereq_('./arrayEach'), baseMergeDeep = _dereq_('./baseMergeDeep'), isArray = _dereq_('../lang/isArray'), isArrayLike = _dereq_('./isArrayLike'), isObject = _dereq_('../lang/isObject'), isObjectLike = _dereq_('./isObjectLike'), isTypedArray = _dereq_('../lang/isTypedArray'), keys = _dereq_('../object/keys'); /** * The base implementation of `_.merge` without support for argument juggling, * multiple sources, and `this` binding `customizer` functions. * * @private * @param {Object} object The destination object. * @param {Object} source The source object. * @param {Function} [customizer] The function to customize merged values. * @param {Array} [stackA=[]] Tracks traversed source objects. * @param {Array} [stackB=[]] Associates values with source counterparts. * @returns {Object} Returns `object`. */ function baseMerge(object, source, customizer, stackA, stackB) { if (!isObject(object)) { return object; } var isSrcArr = isArrayLike(source) && (isArray(source) || isTypedArray(source)), props = isSrcArr ? undefined : keys(source); arrayEach(props || source, function(srcValue, key) { if (props) { key = srcValue; srcValue = source[key]; } if (isObjectLike(srcValue)) { stackA || (stackA = []); stackB || (stackB = []); baseMergeDeep(object, source, key, baseMerge, customizer, stackA, stackB); } else { var value = object[key], result = customizer ? customizer(value, srcValue, key, object, source) : undefined, isCommon = result === undefined; if (isCommon) { result = srcValue; } if ((result !== undefined || (isSrcArr && !(key in object))) && (isCommon || (result === result ? (result !== value) : (value === value)))) { object[key] = result; } } }); return object; } module.exports = baseMerge; },{"../lang/isArray":30,"../lang/isObject":33,"../lang/isTypedArray":36,"../object/keys":38,"./arrayEach":9,"./baseMergeDeep":14,"./isArrayLike":21,"./isObjectLike":26}],14:[function(_dereq_,module,exports){ var arrayCopy = _dereq_('./arrayCopy'), isArguments = _dereq_('../lang/isArguments'), isArray = _dereq_('../lang/isArray'), isArrayLike = _dereq_('./isArrayLike'), isPlainObject = _dereq_('../lang/isPlainObject'), isTypedArray = _dereq_('../lang/isTypedArray'), toPlainObject = _dereq_('../lang/toPlainObject'); /** * A specialized version of `baseMerge` for arrays and objects which performs * deep merges and tracks traversed objects enabling objects with circular * references to be merged. * * @private * @param {Object} object The destination object. * @param {Object} source The source object. * @param {string} key The key of the value to merge. * @param {Function} mergeFunc The function to merge values. * @param {Function} [customizer] The function to customize merged values. * @param {Array} [stackA=[]] Tracks traversed source objects. * @param {Array} [stackB=[]] Associates values with source counterparts. * @returns {boolean} Returns `true` if the objects are equivalent, else `false`. */ function baseMergeDeep(object, source, key, mergeFunc, customizer, stackA, stackB) { var length = stackA.length, srcValue = source[key]; while (length--) { if (stackA[length] == srcValue) { object[key] = stackB[length]; return; } } var value = object[key], result = customizer ? customizer(value, srcValue, key, object, source) : undefined, isCommon = result === undefined; if (isCommon) { result = srcValue; if (isArrayLike(srcValue) && (isArray(srcValue) || isTypedArray(srcValue))) { result = isArray(value) ? value : (isArrayLike(value) ? arrayCopy(value) : []); } else if (isPlainObject(srcValue) || isArguments(srcValue)) { result = isArguments(value) ? toPlainObject(value) : (isPlainObject(value) ? value : {}); } else { isCommon = false; } } // Add the source value to the stack of traversed objects and associate // it with its merged value. stackA.push(srcValue); stackB.push(result); if (isCommon) { // Recursively merge objects and arrays (susceptible to call stack limits). object[key] = mergeFunc(result, srcValue, customizer, stackA, stackB); } else if (result === result ? (result !== value) : (value === value)) { object[key] = result; } } module.exports = baseMergeDeep; },{"../lang/isArguments":29,"../lang/isArray":30,"../lang/isPlainObject":34,"../lang/isTypedArray":36,"../lang/toPlainObject":37,"./arrayCopy":8,"./isArrayLike":21}],15:[function(_dereq_,module,exports){ var toObject = _dereq_('./toObject'); /** * The base implementation of `_.property` without support for deep paths. * * @private * @param {string} key The key of the property to get. * @returns {Function} Returns the new function. */ function baseProperty(key) { return function(object) { return object == null ? undefined : toObject(object)[key]; }; } module.exports = baseProperty; },{"./toObject":28}],16:[function(_dereq_,module,exports){ var identity = _dereq_('../utility/identity'); /** * A specialized version of `baseCallback` which only supports `this` binding * and specifying the number of arguments to provide to `func`. * * @private * @param {Function} func The function to bind. * @param {*} thisArg The `this` binding of `func`. * @param {number} [argCount] The number of arguments to provide to `func`. * @returns {Function} Returns the callback. */ function bindCallback(func, thisArg, argCount) { if (typeof func != 'function') { return identity; } if (thisArg === undefined) { return func; } switch (argCount) { case 1: return function(value) { return func.call(thisArg, value); }; case 3: return function(value, index, collection) { return func.call(thisArg, value, index, collection); }; case 4: return function(accumulator, value, index, collection) { return func.call(thisArg, accumulator, value, index, collection); }; case 5: return function(value, other, key, object, source) { return func.call(thisArg, value, other, key, object, source); }; } return function() { return func.apply(thisArg, arguments); }; } module.exports = bindCallback; },{"../utility/identity":42}],17:[function(_dereq_,module,exports){ var bindCallback = _dereq_('./bindCallback'), isIterateeCall = _dereq_('./isIterateeCall'), restParam = _dereq_('../function/restParam'); /** * Creates a `_.assign`, `_.defaults`, or `_.merge` function. * * @private * @param {Function} assigner The function to assign values. * @returns {Function} Returns the new assigner function. */ function createAssigner(assigner) { return restParam(function(object, sources) { var index = -1, length = object == null ? 0 : sources.length, customizer = length > 2 ? sources[length - 2] : undefined, guard = length > 2 ? sources[2] : undefined, thisArg = length > 1 ? sources[length - 1] : undefined; if (typeof customizer == 'function') { customizer = bindCallback(customizer, thisArg, 5); length -= 2; } else { customizer = typeof thisArg == 'function' ? thisArg : undefined; length -= (customizer ? 1 : 0); } if (guard && isIterateeCall(sources[0], sources[1], guard)) { customizer = length < 3 ? undefined : customizer; length = 1; } while (++index < length) { var source = sources[index]; if (source) { assigner(object, source, customizer); } } return object; }); } module.exports = createAssigner; },{"../function/restParam":6,"./bindCallback":16,"./isIterateeCall":24}],18:[function(_dereq_,module,exports){ var toObject = _dereq_('./toObject'); /** * Creates a base function for `_.forIn` or `_.forInRight`. * * @private * @param {boolean} [fromRight] Specify iterating from right to left. * @returns {Function} Returns the new base function. */ function createBaseFor(fromRight) { return function(object, iteratee, keysFunc) { var iterable = toObject(object), props = keysFunc(object), length = props.length, index = fromRight ? length : -1; while ((fromRight ? index-- : ++index < length)) { var key = props[index]; if (iteratee(iterable[key], key, iterable) === false) { break; } } return object; }; } module.exports = createBaseFor; },{"./toObject":28}],19:[function(_dereq_,module,exports){ var baseProperty = _dereq_('./baseProperty'); /** * Gets the "length" property value of `object`. * * **Note:** This function is used to avoid a [JIT bug](https://bugs.webkit.org/show_bug.cgi?id=142792) * that affects Safari on at least iOS 8.1-8.3 ARM64. * * @private * @param {Object} object The object to query. * @returns {*} Returns the "length" value. */ var getLength = baseProperty('length'); module.exports = getLength; },{"./baseProperty":15}],20:[function(_dereq_,module,exports){ var isNative = _dereq_('../lang/isNative'); /** * Gets the native function at `key` of `object`. * * @private * @param {Object} object The object to query. * @param {string} key The key of the method to get. * @returns {*} Returns the function if it's native, else `undefined`. */ function getNative(object, key) { var value = object == null ? undefined : object[key]; return isNative(value) ? value : undefined; } module.exports = getNative; },{"../lang/isNative":32}],21:[function(_dereq_,module,exports){ var getLength = _dereq_('./getLength'), isLength = _dereq_('./isLength'); /** * Checks if `value` is array-like. * * @private * @param {*} value The value to check. * @returns {boolean} Returns `true` if `value` is array-like, else `false`. */ function isArrayLike(value) { return value != null && isLength(getLength(value)); } module.exports = isArrayLike; },{"./getLength":19,"./isLength":25}],22:[function(_dereq_,module,exports){ /** * Checks if `value` is a host object in IE < 9. * * @private * @param {*} value The value to check. * @returns {boolean} Returns `true` if `value` is a host object, else `false`. */ var isHostObject = (function() { try { Object({ 'toString': 0 } + ''); } catch(e) { return function() { return false; }; } return function(value) { // IE < 9 presents many host objects as `Object` objects that can coerce // to strings despite having improperly defined `toString` methods. return typeof value.toString != 'function' && typeof (value + '') == 'string'; }; }()); module.exports = isHostObject; },{}],23:[function(_dereq_,module,exports){ /** Used to detect unsigned integer values. */ var reIsUint = /^\d+$/; /** * Used as the [maximum length](http://ecma-international.org/ecma-262/6.0/#sec-number.max_safe_integer) * of an array-like value. */ var MAX_SAFE_INTEGER = 9007199254740991; /** * Checks if `value` is a valid array-like index. * * @private * @param {*} value The value to check. * @param {number} [length=MAX_SAFE_INTEGER] The upper bounds of a valid index. * @returns {boolean} Returns `true` if `value` is a valid index, else `false`. */ function isIndex(value, length) { value = (typeof value == 'number' || reIsUint.test(value)) ? +value : -1; length = length == null ? MAX_SAFE_INTEGER : length; return value > -1 && value % 1 == 0 && value < length; } module.exports = isIndex; },{}],24:[function(_dereq_,module,exports){ var isArrayLike = _dereq_('./isArrayLike'), isIndex = _dereq_('./isIndex'), isObject = _dereq_('../lang/isObject'); /** * Checks if the provided arguments are from an iteratee call. * * @private * @param {*} value The potential iteratee value argument. * @param {*} index The potential iteratee index or key argument. * @param {*} object The potential iteratee object argument. * @returns {boolean} Returns `true` if the arguments are from an iteratee call, else `false`. */ function isIterateeCall(value, index, object) { if (!isObject(object)) { return false; } var type = typeof index; if (type == 'number' ? (isArrayLike(object) && isIndex(index, object.length)) : (type == 'string' && index in object)) { var other = object[index]; return value === value ? (value === other) : (other !== other); } return false; } module.exports = isIterateeCall; },{"../lang/isObject":33,"./isArrayLike":21,"./isIndex":23}],25:[function(_dereq_,module,exports){ /** * Used as the [maximum length](http://ecma-international.org/ecma-262/6.0/#sec-number.max_safe_integer) * of an array-like value. */ var MAX_SAFE_INTEGER = 9007199254740991; /** * Checks if `value` is a valid array-like length. * * **Note:** This function is based on [`ToLength`](http://ecma-international.org/ecma-262/6.0/#sec-tolength). * * @private * @param {*} value The value to check. * @returns {boolean} Returns `true` if `value` is a valid length, else `false`. */ function isLength(value) { return typeof value == 'number' && value > -1 && value % 1 == 0 && value <= MAX_SAFE_INTEGER; } module.exports = isLength; },{}],26:[function(_dereq_,module,exports){ /** * Checks if `value` is object-like. * * @private * @param {*} value The value to check. * @returns {boolean} Returns `true` if `value` is object-like, else `false`. */ function isObjectLike(value) { return !!value && typeof value == 'object'; } module.exports = isObjectLike; },{}],27:[function(_dereq_,module,exports){ var isArguments = _dereq_('../lang/isArguments'), isArray = _dereq_('../lang/isArray'), isIndex = _dereq_('./isIndex'), isLength = _dereq_('./isLength'), isString = _dereq_('../lang/isString'), keysIn = _dereq_('../object/keysIn'); /** Used for native method references. */ var objectProto = Object.prototype; /** Used to check objects for own properties. */ var hasOwnProperty = objectProto.hasOwnProperty; /** * A fallback implementation of `Object.keys` which creates an array of the * own enumerable property names of `object`. * * @private * @param {Object} object The object to query. * @returns {Array} Returns the array of property names. */ function shimKeys(object) { var props = keysIn(object), propsLength = props.length, length = propsLength && object.length; var allowIndexes = !!length && isLength(length) && (isArray(object) || isArguments(object) || isString(object)); var index = -1, result = []; while (++index < propsLength) { var key = props[index]; if ((allowIndexes && isIndex(key, length)) || hasOwnProperty.call(object, key)) { result.push(key); } } return result; } module.exports = shimKeys; },{"../lang/isArguments":29,"../lang/isArray":30,"../lang/isString":35,"../object/keysIn":39,"./isIndex":23,"./isLength":25}],28:[function(_dereq_,module,exports){ var isObject = _dereq_('../lang/isObject'), isString = _dereq_('../lang/isString'), support = _dereq_('../support'); /** * Converts `value` to an object if it's not one. * * @private * @param {*} value The value to process. * @returns {Object} Returns the object. */ function toObject(value) { if (support.unindexedChars && isString(value)) { var index = -1, length = value.length, result = Object(value); while (++index < length) { result[index] = value.charAt(index); } return result; } return isObject(value) ? value : Object(value); } module.exports = toObject; },{"../lang/isObject":33,"../lang/isString":35,"../support":41}],29:[function(_dereq_,module,exports){ var isArrayLike = _dereq_('../internal/isArrayLike'), isObjectLike = _dereq_('../internal/isObjectLike'); /** Used for native method references. */ var objectProto = Object.prototype; /** Used to check objects for own properties. */ var hasOwnProperty = objectProto.hasOwnProperty; /** Native method references. */ var propertyIsEnumerable = objectProto.propertyIsEnumerable; /** * Checks if `value` is classified as an `arguments` object. * * @static * @memberOf _ * @category Lang * @param {*} value The value to check. * @returns {boolean} Returns `true` if `value` is correctly classified, else `false`. * @example * * _.isArguments(function() { return arguments; }()); * // => true * * _.isArguments([1, 2, 3]); * // => false */ function isArguments(value) { return isObjectLike(value) && isArrayLike(value) && hasOwnProperty.call(value, 'callee') && !propertyIsEnumerable.call(value, 'callee'); } module.exports = isArguments; },{"../internal/isArrayLike":21,"../internal/isObjectLike":26}],30:[function(_dereq_,module,exports){ var getNative = _dereq_('../internal/getNative'), isLength = _dereq_('../internal/isLength'), isObjectLike = _dereq_('../internal/isObjectLike'); /** `Object#toString` result references. */ var arrayTag = '[object Array]'; /** Used for native method references. */ var objectProto = Object.prototype; /** * Used to resolve the [`toStringTag`](http://ecma-international.org/ecma-262/6.0/#sec-object.prototype.tostring) * of values. */ var objToString = objectProto.toString; /* Native method references for those with the same name as other `lodash` methods. */ var nativeIsArray = getNative(Array, 'isArray'); /** * Checks if `value` is classified as an `Array` object. * * @static * @memberOf _ * @category Lang * @param {*} value The value to check. * @returns {boolean} Returns `true` if `value` is correctly classified, else `false`. * @example * * _.isArray([1, 2, 3]); * // => true * * _.isArray(function() { return arguments; }()); * // => false */ var isArray = nativeIsArray || function(value) { return isObjectLike(value) && isLength(value.length) && objToString.call(value) == arrayTag; }; module.exports = isArray; },{"../internal/getNative":20,"../internal/isLength":25,"../internal/isObjectLike":26}],31:[function(_dereq_,module,exports){ var isObject = _dereq_('./isObject'); /** `Object#toString` result references. */ var funcTag = '[object Function]'; /** Used for native method references. */ var objectProto = Object.prototype; /** * Used to resolve the [`toStringTag`](http://ecma-international.org/ecma-262/6.0/#sec-object.prototype.tostring) * of values. */ var objToString = objectProto.toString; /** * Checks if `value` is classified as a `Function` object. * * @static * @memberOf _ * @category Lang * @param {*} value The value to check. * @returns {boolean} Returns `true` if `value` is correctly classified, else `false`. * @example * * _.isFunction(_); * // => true * * _.isFunction(/abc/); * // => false */ function isFunction(value) { // The use of `Object#toString` avoids issues with the `typeof` operator // in older versions of Chrome and Safari which return 'function' for regexes // and Safari 8 which returns 'object' for typed array constructors. return isObject(value) && objToString.call(value) == funcTag; } module.exports = isFunction; },{"./isObject":33}],32:[function(_dereq_,module,exports){ var isFunction = _dereq_('./isFunction'), isHostObject = _dereq_('../internal/isHostObject'), isObjectLike = _dereq_('../internal/isObjectLike'); /** Used to detect host constructors (Safari > 5). */ var reIsHostCtor = /^\[object .+?Constructor\]$/; /** Used for native method references. */ var objectProto = Object.prototype; /** Used to resolve the decompiled source of functions. */ var fnToString = Function.prototype.toString; /** Used to check objects for own properties. */ var hasOwnProperty = objectProto.hasOwnProperty; /** Used to detect if a method is native. */ var reIsNative = RegExp('^' + fnToString.call(hasOwnProperty).replace(/[\\^$.*+?()[\]{}|]/g, '\\$&') .replace(/hasOwnProperty|(function).*?(?=\\\()| for .+?(?=\\\])/g, '$1.*?') + '$' ); /** * Checks if `value` is a native function. * * @static * @memberOf _ * @category Lang * @param {*} value The value to check. * @returns {boolean} Returns `true` if `value` is a native function, else `false`. * @example * * _.isNative(Array.prototype.push); * // => true * * _.isNative(_); * // => false */ function isNative(value) { if (value == null) { return false; } if (isFunction(value)) { return reIsNative.test(fnToString.call(value)); } return isObjectLike(value) && (isHostObject(value) ? reIsNative : reIsHostCtor).test(value); } module.exports = isNative; },{"../internal/isHostObject":22,"../internal/isObjectLike":26,"./isFunction":31}],33:[function(_dereq_,module,exports){ /** * Checks if `value` is the [language type](https://es5.github.io/#x8) of `Object`. * (e.g. arrays, functions, objects, regexes, `new Number(0)`, and `new String('')`) * * @static * @memberOf _ * @category Lang * @param {*} value The value to check. * @returns {boolean} Returns `true` if `value` is an object, else `false`. * @example * * _.isObject({}); * // => true * * _.isObject([1, 2, 3]); * // => true * * _.isObject(1); * // => false */ function isObject(value) { // Avoid a V8 JIT bug in Chrome 19-20. // See https://code.google.com/p/v8/issues/detail?id=2291 for more details. var type = typeof value; return !!value && (type == 'object' || type == 'function'); } module.exports = isObject; },{}],34:[function(_dereq_,module,exports){ var baseForIn = _dereq_('../internal/baseForIn'), isArguments = _dereq_('./isArguments'), isHostObject = _dereq_('../internal/isHostObject'), isObjectLike = _dereq_('../internal/isObjectLike'), support = _dereq_('../support'); /** `Object#toString` result references. */ var objectTag = '[object Object]'; /** Used for native method references. */ var objectProto = Object.prototype; /** Used to check objects for own properties. */ var hasOwnProperty = objectProto.hasOwnProperty; /** * Used to resolve the [`toStringTag`](http://ecma-international.org/ecma-262/6.0/#sec-object.prototype.tostring) * of values. */ var objToString = objectProto.toString; /** * Checks if `value` is a plain object, that is, an object created by the * `Object` constructor or one with a `[[Prototype]]` of `null`. * * **Note:** This method assumes objects created by the `Object` constructor * have no inherited enumerable properties. * * @static * @memberOf _ * @category Lang * @param {*} value The value to check. * @returns {boolean} Returns `true` if `value` is a plain object, else `false`. * @example * * function Foo() { * this.a = 1; * } * * _.isPlainObject(new Foo); * // => false * * _.isPlainObject([1, 2, 3]); * // => false * * _.isPlainObject({ 'x': 0, 'y': 0 }); * // => true * * _.isPlainObject(Object.create(null)); * // => true */ function isPlainObject(value) { var Ctor; // Exit early for non `Object` objects. if (!(isObjectLike(value) && objToString.call(value) == objectTag && !isHostObject(value) && !isArguments(value)) || (!hasOwnProperty.call(value, 'constructor') && (Ctor = value.constructor, typeof Ctor == 'function' && !(Ctor instanceof Ctor)))) { return false; } // IE < 9 iterates inherited properties before own properties. If the first // iterated property is an object's own property then there are no inherited // enumerable properties. var result; if (support.ownLast) { baseForIn(value, function(subValue, key, object) { result = hasOwnProperty.call(object, key); return false; }); return result !== false; } // In most environments an object's own properties are iterated before // its inherited properties. If the last iterated property is an object's // own property then there are no inherited enumerable properties. baseForIn(value, function(subValue, key) { result = key; }); return result === undefined || hasOwnProperty.call(value, result); } module.exports = isPlainObject; },{"../internal/baseForIn":12,"../internal/isHostObject":22,"../internal/isObjectLike":26,"../support":41,"./isArguments":29}],35:[function(_dereq_,module,exports){ var isObjectLike = _dereq_('../internal/isObjectLike'); /** `Object#toString` result references. */ var stringTag = '[object String]'; /** Used for native method references. */ var objectProto = Object.prototype; /** * Used to resolve the [`toStringTag`](http://ecma-international.org/ecma-262/6.0/#sec-object.prototype.tostring) * of values. */ var objToString = objectProto.toString; /** * Checks if `value` is classified as a `String` primitive or object. * * @static * @memberOf _ * @category Lang * @param {*} value The value to check. * @returns {boolean} Returns `true` if `value` is correctly classified, else `false`. * @example * * _.isString('abc'); * // => true * * _.isString(1); * // => false */ function isString(value) { return typeof value == 'string' || (isObjectLike(value) && objToString.call(value) == stringTag); } module.exports = isString; },{"../internal/isObjectLike":26}],36:[function(_dereq_,module,exports){ var isLength = _dereq_('../internal/isLength'), isObjectLike = _dereq_('../internal/isObjectLike'); /** `Object#toString` result references. */ var argsTag = '[object Arguments]', arrayTag = '[object Array]', boolTag = '[object Boolean]', dateTag = '[object Date]', errorTag = '[object Error]', funcTag = '[object Function]', mapTag = '[object Map]', numberTag = '[object Number]', objectTag = '[object Object]', regexpTag = '[object RegExp]', setTag = '[object Set]', stringTag = '[object String]', weakMapTag = '[object WeakMap]'; var arrayBufferTag = '[object ArrayBuffer]', float32Tag = '[object Float32Array]', float64Tag = '[object Float64Array]', int8Tag = '[object Int8Array]', int16Tag = '[object Int16Array]', int32Tag = '[object Int32Array]', uint8Tag = '[object Uint8Array]', uint8ClampedTag = '[object Uint8ClampedArray]', uint16Tag = '[object Uint16Array]', uint32Tag = '[object Uint32Array]'; /** Used to identify `toStringTag` values of typed arrays. */ var typedArrayTags = {}; typedArrayTags[float32Tag] = typedArrayTags[float64Tag] = typedArrayTags[int8Tag] = typedArrayTags[int16Tag] = typedArrayTags[int32Tag] = typedArrayTags[uint8Tag] = typedArrayTags[uint8ClampedTag] = typedArrayTags[uint16Tag] = typedArrayTags[uint32Tag] = true; typedArrayTags[argsTag] = typedArrayTags[arrayTag] = typedArrayTags[arrayBufferTag] = typedArrayTags[boolTag] = typedArrayTags[dateTag] = typedArrayTags[errorTag] = typedArrayTags[funcTag] = typedArrayTags[mapTag] = typedArrayTags[numberTag] = typedArrayTags[objectTag] = typedArrayTags[regexpTag] = typedArrayTags[setTag] = typedArrayTags[stringTag] = typedArrayTags[weakMapTag] = false; /** Used for native method references. */ var objectProto = Object.prototype; /** * Used to resolve the [`toStringTag`](http://ecma-international.org/ecma-262/6.0/#sec-object.prototype.tostring) * of values. */ var objToString = objectProto.toString; /** * Checks if `value` is classified as a typed array. * * @static * @memberOf _ * @category Lang * @param {*} value The value to check. * @returns {boolean} Returns `true` if `value` is correctly classified, else `false`. * @example * * _.isTypedArray(new Uint8Array); * // => true * * _.isTypedArray([]); * // => false */ function isTypedArray(value) { return isObjectLike(value) && isLength(value.length) && !!typedArrayTags[objToString.call(value)]; } module.exports = isTypedArray; },{"../internal/isLength":25,"../internal/isObjectLike":26}],37:[function(_dereq_,module,exports){ var baseCopy = _dereq_('../internal/baseCopy'), keysIn = _dereq_('../object/keysIn'); /** * Converts `value` to a plain object flattening inherited enumerable * properties of `value` to own properties of the plain object. * * @static * @memberOf _ * @category Lang * @param {*} value The value to convert. * @returns {Object} Returns the converted plain object. * @example * * function Foo() { * this.b = 2; * } * * Foo.prototype.c = 3; * * _.assign({ 'a': 1 }, new Foo); * // => { 'a': 1, 'b': 2 } * * _.assign({ 'a': 1 }, _.toPlainObject(new Foo)); * // => { 'a': 1, 'b': 2, 'c': 3 } */ function toPlainObject(value) { return baseCopy(value, keysIn(value)); } module.exports = toPlainObject; },{"../internal/baseCopy":10,"../object/keysIn":39}],38:[function(_dereq_,module,exports){ var getNative = _dereq_('../internal/getNative'), isArrayLike = _dereq_('../internal/isArrayLike'), isObject = _dereq_('../lang/isObject'), shimKeys = _dereq_('../internal/shimKeys'), support = _dereq_('../support'); /* Native method references for those with the same name as other `lodash` methods. */ var nativeKeys = getNative(Object, 'keys'); /** * Creates an array of the own enumerable property names of `object`. * * **Note:** Non-object values are coerced to objects. See the * [ES spec](http://ecma-international.org/ecma-262/6.0/#sec-object.keys) * for more details. * * @static * @memberOf _ * @category Object * @param {Object} object The object to query. * @returns {Array} Returns the array of property names. * @example * * function Foo() { * this.a = 1; * this.b = 2; * } * * Foo.prototype.c = 3; * * _.keys(new Foo); * // => ['a', 'b'] (iteration order is not guaranteed) * * _.keys('hi'); * // => ['0', '1'] */ var keys = !nativeKeys ? shimKeys : function(object) { var Ctor = object == null ? undefined : object.constructor; if ((typeof Ctor == 'function' && Ctor.prototype === object) || (typeof object == 'function' ? support.enumPrototypes : isArrayLike(object))) { return shimKeys(object); } return isObject(object) ? nativeKeys(object) : []; }; module.exports = keys; },{"../internal/getNative":20,"../internal/isArrayLike":21,"../internal/shimKeys":27,"../lang/isObject":33,"../support":41}],39:[function(_dereq_,module,exports){ var arrayEach = _dereq_('../internal/arrayEach'), isArguments = _dereq_('../lang/isArguments'), isArray = _dereq_('../lang/isArray'), isFunction = _dereq_('../lang/isFunction'), isIndex = _dereq_('../internal/isIndex'), isLength = _dereq_('../internal/isLength'), isObject = _dereq_('../lang/isObject'), isString = _dereq_('../lang/isString'), support = _dereq_('../support'); /** `Object#toString` result references. */ var arrayTag = '[object Array]', boolTag = '[object Boolean]', dateTag = '[object Date]', errorTag = '[object Error]', funcTag = '[object Function]', numberTag = '[object Number]', objectTag = '[object Object]', regexpTag = '[object RegExp]', stringTag = '[object String]'; /** Used to fix the JScript `[[DontEnum]]` bug. */ var shadowProps = [ 'constructor', 'hasOwnProperty', 'isPrototypeOf', 'propertyIsEnumerable', 'toLocaleString', 'toString', 'valueOf' ]; /** Used for native method references. */ var errorProto = Error.prototype, objectProto = Object.prototype, stringProto = String.prototype; /** Used to check objects for own properties. */ var hasOwnProperty = objectProto.hasOwnProperty; /** * Used to resolve the [`toStringTag`](http://ecma-international.org/ecma-262/6.0/#sec-object.prototype.tostring) * of values. */ var objToString = objectProto.toString; /** Used to avoid iterating over non-enumerable properties in IE < 9. */ var nonEnumProps = {}; nonEnumProps[arrayTag] = nonEnumProps[dateTag] = nonEnumProps[numberTag] = { 'constructor': true, 'toLocaleString': true, 'toString': true, 'valueOf': true }; nonEnumProps[boolTag] = nonEnumProps[stringTag] = { 'constructor': true, 'toString': true, 'valueOf': true }; nonEnumProps[errorTag] = nonEnumProps[funcTag] = nonEnumProps[regexpTag] = { 'constructor': true, 'toString': true }; nonEnumProps[objectTag] = { 'constructor': true }; arrayEach(shadowProps, function(key) { for (var tag in nonEnumProps) { if (hasOwnProperty.call(nonEnumProps, tag)) { var props = nonEnumProps[tag]; props[key] = hasOwnProperty.call(props, key); } } }); /** * Creates an array of the own and inherited enumerable property names of `object`. * * **Note:** Non-object values are coerced to objects. * * @static * @memberOf _ * @category Object * @param {Object} object The object to query. * @returns {Array} Returns the array of property names. * @example * * function Foo() { * this.a = 1; * this.b = 2; * } * * Foo.prototype.c = 3; * * _.keysIn(new Foo); * // => ['a', 'b', 'c'] (iteration order is not guaranteed) */ function keysIn(object) { if (object == null) { return []; } if (!isObject(object)) { object = Object(object); } var length = object.length; length = (length && isLength(length) && (isArray(object) || isArguments(object) || isString(object)) && length) || 0; var Ctor = object.constructor, index = -1, proto = (isFunction(Ctor) && Ctor.prototype) || objectProto, isProto = proto === object, result = Array(length), skipIndexes = length > 0, skipErrorProps = support.enumErrorProps && (object === errorProto || object instanceof Error), skipProto = support.enumPrototypes && isFunction(object); while (++index < length) { result[index] = (index + ''); } // lodash skips the `constructor` property when it infers it's iterating // over a `prototype` object because IE < 9 can't set the `[[Enumerable]]` // attribute of an existing property and the `constructor` property of a // prototype defaults to non-enumerable. for (var key in object) { if (!(skipProto && key == 'prototype') && !(skipErrorProps && (key == 'message' || key == 'name')) && !(skipIndexes && isIndex(key, length)) && !(key == 'constructor' && (isProto || !hasOwnProperty.call(object, key)))) { result.push(key); } } if (support.nonEnumShadows && object !== objectProto) { var tag = object === stringProto ? stringTag : (object === errorProto ? errorTag : objToString.call(object)), nonEnums = nonEnumProps[tag] || nonEnumProps[objectTag]; if (tag == objectTag) { proto = objectProto; } length = shadowProps.length; while (length--) { key = shadowProps[length]; var nonEnum = nonEnums[key]; if (!(isProto && nonEnum) && (nonEnum ? hasOwnProperty.call(object, key) : object[key] !== proto[key])) { result.push(key); } } } return result; } module.exports = keysIn; },{"../internal/arrayEach":9,"../internal/isIndex":23,"../internal/isLength":25,"../lang/isArguments":29,"../lang/isArray":30,"../lang/isFunction":31,"../lang/isObject":33,"../lang/isString":35,"../support":41}],40:[function(_dereq_,module,exports){ var baseMerge = _dereq_('../internal/baseMerge'), createAssigner = _dereq_('../internal/createAssigner'); /** * Recursively merges own enumerable properties of the source object(s), that * don't resolve to `undefined` into the destination object. Subsequent sources * overwrite property assignments of previous sources. If `customizer` is * provided it's invoked to produce the merged values of the destination and * source properties. If `customizer` returns `undefined` merging is handled * by the method instead. The `customizer` is bound to `thisArg` and invoked * with five arguments: (objectValue, sourceValue, key, object, source). * * @static * @memberOf _ * @category Object * @param {Object} object The destination object. * @param {...Object} [sources] The source objects. * @param {Function} [customizer] The function to customize assigned values. * @param {*} [thisArg] The `this` binding of `customizer`. * @returns {Object} Returns `object`. * @example * * var users = { * 'data': [{ 'user': 'barney' }, { 'user': 'fred' }] * }; * * var ages = { * 'data': [{ 'age': 36 }, { 'age': 40 }] * }; * * _.merge(users, ages); * // => { 'data': [{ 'user': 'barney', 'age': 36 }, { 'user': 'fred', 'age': 40 }] } * * // using a customizer callback * var object = { * 'fruits': ['apple'], * 'vegetables': ['beet'] * }; * * var other = { * 'fruits': ['banana'], * 'vegetables': ['carrot'] * }; * * _.merge(object, other, function(a, b) { * if (_.isArray(a)) { * return a.concat(b); * } * }); * // => { 'fruits': ['apple', 'banana'], 'vegetables': ['beet', 'carrot'] } */ var merge = createAssigner(baseMerge); module.exports = merge; },{"../internal/baseMerge":13,"../internal/createAssigner":17}],41:[function(_dereq_,module,exports){ /** Used for native method references. */ var arrayProto = Array.prototype, errorProto = Error.prototype, objectProto = Object.prototype; /** Native method references. */ var propertyIsEnumerable = objectProto.propertyIsEnumerable, splice = arrayProto.splice; /** * An object environment feature flags. * * @static * @memberOf _ * @type Object */ var support = {}; (function(x) { var Ctor = function() { this.x = x; }, object = { '0': x, 'length': x }, props = []; Ctor.prototype = { 'valueOf': x, 'y': x }; for (var key in new Ctor) { props.push(key); } /** * Detect if `name` or `message` properties of `Error.prototype` are * enumerable by default (IE < 9, Safari < 5.1). * * @memberOf _.support * @type boolean */ support.enumErrorProps = propertyIsEnumerable.call(errorProto, 'message') || propertyIsEnumerable.call(errorProto, 'name'); /** * Detect if `prototype` properties are enumerable by default. * * Firefox < 3.6, Opera > 9.50 - Opera < 11.60, and Safari < 5.1 * (if the prototype or a property on the prototype has been set) * incorrectly set the `[[Enumerable]]` value of a function's `prototype` * property to `true`. * * @memberOf _.support * @type boolean */ support.enumPrototypes = propertyIsEnumerable.call(Ctor, 'prototype'); /** * Detect if properties shadowing those on `Object.prototype` are non-enumerable. * * In IE < 9 an object's own properties, shadowing non-enumerable ones, * are made non-enumerable as well (a.k.a the JScript `[[DontEnum]]` bug). * * @memberOf _.support * @type boolean */ support.nonEnumShadows = !/valueOf/.test(props); /** * Detect if own properties are iterated after inherited properties (IE < 9). * * @memberOf _.support * @type boolean */ support.ownLast = props[0] != 'x'; /** * Detect if `Array#shift` and `Array#splice` augment array-like objects * correctly. * * Firefox < 10, compatibility modes of IE 8, and IE < 9 have buggy Array * `shift()` and `splice()` functions that fail to remove the last element, * `value[0]`, of array-like objects even though the "length" property is * set to `0`. The `shift()` method is buggy in compatibility modes of IE 8, * while `splice()` is buggy regardless of mode in IE < 9. * * @memberOf _.support * @type boolean */ support.spliceObjects = (splice.call(object, 0, 1), !object[0]); /** * Detect lack of support for accessing string characters by index. * * IE < 8 can't access characters by index. IE 8 can only access characters * by index on string literals, not string objects. * * @memberOf _.support * @type boolean */ support.unindexedChars = ('x'[0] + Object('x')[0]) != 'xx'; }(1, 0)); module.exports = support; },{}],42:[function(_dereq_,module,exports){ /** * This method returns the first argument provided to it. * * @static * @memberOf _ * @category Utility * @param {*} value Any value. * @returns {*} Returns `value`. * @example * * var object = { 'user': 'fred' }; * * _.identity(object) === object; * // => true */ function identity(value) { return value; } module.exports = identity; },{}],43:[function(_dereq_,module,exports){ 'use strict'; // modified from https://github.com/es-shims/es6-shim var keys = _dereq_('object-keys'); var canBeObject = function (obj) { return typeof obj !== 'undefined' && obj !== null; }; var hasSymbols = typeof Symbol === 'function' && typeof Symbol() === 'symbol'; var defineProperties = _dereq_('define-properties'); var toObject = Object; var push = Array.prototype.push; var propIsEnumerable = Object.prototype.propertyIsEnumerable; var assignShim = function assign(target, source1) { if (!canBeObject(target)) { throw new TypeError('target must be an object'); } var objTarget = toObject(target); var s, source, i, props, syms; for (s = 1; s < arguments.length; ++s) { source = toObject(arguments[s]); props = keys(source); if (hasSymbols && Object.getOwnPropertySymbols) { syms = Object.getOwnPropertySymbols(source); for (i = 0; i < syms.length; ++i) { if (propIsEnumerable.call(source, syms[i])) { push.call(props, syms[i]); } } } for (i = 0; i < props.length; ++i) { objTarget[props[i]] = source[props[i]]; } } return objTarget; }; defineProperties(assignShim, { shim: function shimObjectAssign() { var assignHasPendingExceptions = function () { if (!Object.assign || !Object.preventExtensions) { return false; } // Firefox 37 still has "pending exception" logic in its Object.assign implementation, // which is 72% slower than our shim, and Firefox 40's native implementation. var thrower = Object.preventExtensions({ 1: 2 }); try { Object.assign(thrower, 'xy'); } catch (e) { return thrower[1] === 'y'; } }; defineProperties( Object, { assign: assignShim }, { assign: assignHasPendingExceptions } ); return Object.assign || assignShim; } }); module.exports = assignShim; },{"define-properties":44,"object-keys":46}],44:[function(_dereq_,module,exports){ 'use strict'; var keys = _dereq_('object-keys'); var foreach = _dereq_('foreach'); var hasSymbols = typeof Symbol === 'function' && typeof Symbol() === 'symbol'; var toStr = Object.prototype.toString; var isFunction = function (fn) { return typeof fn === 'function' && toStr.call(fn) === '[object Function]'; }; var arePropertyDescriptorsSupported = function () { var obj = {}; try { Object.defineProperty(obj, 'x', { value: obj, enumerable: false }); /* eslint-disable no-unused-vars */ for (var _ in obj) { return false; } /* eslint-enable no-unused-vars */ return obj.x === obj; } catch (e) { /* this is IE 8. */ return false; } }; var supportsDescriptors = Object.defineProperty && arePropertyDescriptorsSupported(); var defineProperty = function (object, name, value, predicate) { if (name in object && (!isFunction(predicate) || !predicate())) { return; } if (supportsDescriptors) { Object.defineProperty(object, name, { configurable: true, enumerable: false, writable: true, value: value }); } else { object[name] = value; } }; var defineProperties = function (object, map) { var predicates = arguments.length > 2 ? arguments[2] : {}; var props = keys(map); if (hasSymbols) { props = props.concat(Object.getOwnPropertySymbols(map)); } foreach(props, function (name) { defineProperty(object, name, map[name], predicates[name]); }); }; defineProperties.supportsDescriptors = !!supportsDescriptors; module.exports = defineProperties; },{"foreach":45,"object-keys":46}],45:[function(_dereq_,module,exports){ var hasOwn = Object.prototype.hasOwnProperty; var toString = Object.prototype.toString; module.exports = function forEach (obj, fn, ctx) { if (toString.call(fn) !== '[object Function]') { throw new TypeError('iterator must be a function'); } var l = obj.length; if (l === +l) { for (var i = 0; i < l; i++) { fn.call(ctx, obj[i], i, obj); } } else { for (var k in obj) { if (hasOwn.call(obj, k)) { fn.call(ctx, obj[k], k, obj); } } } }; },{}],46:[function(_dereq_,module,exports){ 'use strict'; // modified from https://github.com/es-shims/es5-shim var has = Object.prototype.hasOwnProperty; var toStr = Object.prototype.toString; var slice = Array.prototype.slice; var isArgs = _dereq_('./isArguments'); var hasDontEnumBug = !({ 'toString': null }).propertyIsEnumerable('toString'); var hasProtoEnumBug = function () {}.propertyIsEnumerable('prototype'); var dontEnums = [ 'toString', 'toLocaleString', 'valueOf', 'hasOwnProperty', 'isPrototypeOf', 'propertyIsEnumerable', 'constructor' ]; var equalsConstructorPrototype = function (o) { var ctor = o.constructor; return ctor && ctor.prototype === o; }; var blacklistedKeys = { $window: true, $console: true, $parent: true, $self: true, $frames: true, $webkitIndexedDB: true, $webkitStorageInfo: true }; var hasAutomationEqualityBug = (function () { /* global window */ if (typeof window === 'undefined') { return false; } for (var k in window) { if (!blacklistedKeys['$' + k] && has.call(window, k) && window[k] !== null && typeof window[k] === 'object') { try { equalsConstructorPrototype(window[k]); } catch (e) { return true; } } } return false; }()); var equalsConstructorPrototypeIfNotBuggy = function (o) { /* global window */ if (typeof window === 'undefined' && !hasAutomationEqualityBug) { return equalsConstructorPrototype(o); } try { return equalsConstructorPrototype(o); } catch (e) { return false; } }; var keysShim = function keys(object) { var isObject = object !== null && typeof object === 'object'; var isFunction = toStr.call(object) === '[object Function]'; var isArguments = isArgs(object); var isString = isObject && toStr.call(object) === '[object String]'; var theKeys = []; if (!isObject && !isFunction && !isArguments) { throw new TypeError('Object.keys called on a non-object'); } var skipProto = hasProtoEnumBug && isFunction; if (isString && object.length > 0 && !has.call(object, 0)) { for (var i = 0; i < object.length; ++i) { theKeys.push(String(i)); } } if (isArguments && object.length > 0) { for (var j = 0; j < object.length; ++j) { theKeys.push(String(j)); } } else { for (var name in object) { if (!(skipProto && name === 'prototype') && has.call(object, name)) { theKeys.push(String(name)); } } } if (hasDontEnumBug) { var skipConstructor = equalsConstructorPrototypeIfNotBuggy(object); for (var k = 0; k < dontEnums.length; ++k) { if (!(skipConstructor && dontEnums[k] === 'constructor') && has.call(object, dontEnums[k])) { theKeys.push(dontEnums[k]); } } } return theKeys; }; keysShim.shim = function shimObjectKeys() { if (!Object.keys) { Object.keys = keysShim; } else { var keysWorksWithArguments = (function () { // Safari 5.0 bug return (Object.keys(arguments) || '').length === 2; }(1, 2)); if (!keysWorksWithArguments) { var originalKeys = Object.keys; Object.keys = function keys(object) { if (isArgs(object)) { return originalKeys(slice.call(object)); } else { return originalKeys(object); } }; } } return Object.keys || keysShim; }; module.exports = keysShim; },{"./isArguments":47}],47:[function(_dereq_,module,exports){ 'use strict'; var toStr = Object.prototype.toString; module.exports = function isArguments(value) { var str = toStr.call(value); var isArgs = str === '[object Arguments]'; if (!isArgs) { isArgs = str !== '[object Array]' && value !== null && typeof value === 'object' && typeof value.length === 'number' && value.length >= 0 && toStr.call(value.callee) === '[object Function]'; } return isArgs; }; },{}],48:[function(_dereq_,module,exports){ module.exports = SafeParseTuple function SafeParseTuple(obj, reviver) { var json var error = null try { json = JSON.parse(obj, reviver) } catch (err) { error = err } return [error, json] } },{}],49:[function(_dereq_,module,exports){ function clean (s) { return s.replace(/\n\r?\s*/g, '') } module.exports = function tsml (sa) { var s = '' , i = 0 for (; i < arguments.length; i++) s += clean(sa[i]) + (arguments[i + 1] || '') return s } },{}],50:[function(_dereq_,module,exports){ "use strict"; var window = _dereq_("global/window") var once = _dereq_("once") var parseHeaders = _dereq_("parse-headers") module.exports = createXHR createXHR.XMLHttpRequest = window.XMLHttpRequest || noop createXHR.XDomainRequest = "withCredentials" in (new createXHR.XMLHttpRequest()) ? createXHR.XMLHttpRequest : window.XDomainRequest function isEmpty(obj){ for(var i in obj){ if(obj.hasOwnProperty(i)) return false } return true } function createXHR(options, callback) { function readystatechange() { if (xhr.readyState === 4) { loadFunc() } } function getBody() { // Chrome with requestType=blob throws errors arround when even testing access to responseText var body = undefined if (xhr.response) { body = xhr.response } else if (xhr.responseType === "text" || !xhr.responseType) { body = xhr.responseText || xhr.responseXML } if (isJson) { try { body = JSON.parse(body) } catch (e) {} } return body } var failureResponse = { body: undefined, headers: {}, statusCode: 0, method: method, url: uri, rawRequest: xhr } function errorFunc(evt) { clearTimeout(timeoutTimer) if(!(evt instanceof Error)){ evt = new Error("" + (evt || "Unknown XMLHttpRequest Error") ) } evt.statusCode = 0 callback(evt, failureResponse) } // will load the data & process the response in a special response object function loadFunc() { if (aborted) return var status clearTimeout(timeoutTimer) if(options.useXDR && xhr.status===undefined) { //IE8 CORS GET successful response doesn't have a status field, but body is fine status = 200 } else { status = (xhr.status === 1223 ? 204 : xhr.status) } var response = failureResponse var err = null if (status !== 0){ response = { body: getBody(), statusCode: status, method: method, headers: {}, url: uri, rawRequest: xhr } if(xhr.getAllResponseHeaders){ //remember xhr can in fact be XDR for CORS in IE response.headers = parseHeaders(xhr.getAllResponseHeaders()) } } else { err = new Error("Internal XMLHttpRequest Error") } callback(err, response, response.body) } if (typeof options === "string") { options = { uri: options } } options = options || {} if(typeof callback === "undefined"){ throw new Error("callback argument missing") } callback = once(callback) var xhr = options.xhr || null if (!xhr) { if (options.cors || options.useXDR) { xhr = new createXHR.XDomainRequest() }else{ xhr = new createXHR.XMLHttpRequest() } } var key var aborted var uri = xhr.url = options.uri || options.url var method = xhr.method = options.method || "GET" var body = options.body || options.data var headers = xhr.headers = options.headers || {} var sync = !!options.sync var isJson = false var timeoutTimer if ("json" in options) { isJson = true headers["accept"] || headers["Accept"] || (headers["Accept"] = "application/json") //Don't override existing accept header declared by user if (method !== "GET" && method !== "HEAD") { headers["content-type"] || headers["Content-Type"] || (headers["Content-Type"] = "application/json") //Don't override existing accept header declared by user body = JSON.stringify(options.json) } } xhr.onreadystatechange = readystatechange xhr.onload = loadFunc xhr.onerror = errorFunc // IE9 must have onprogress be set to a unique function. xhr.onprogress = function () { // IE must die } xhr.ontimeout = errorFunc xhr.open(method, uri, !sync, options.username, options.password) //has to be after open if(!sync) { xhr.withCredentials = !!options.withCredentials } // Cannot set timeout with sync request // not setting timeout on the xhr object, because of old webkits etc. not handling that correctly // both npm's request and jquery 1.x use this kind of timeout, so this is being consistent if (!sync && options.timeout > 0 ) { timeoutTimer = setTimeout(function(){ aborted=true//IE9 may still call readystatechange xhr.abort("timeout") var e = new Error("XMLHttpRequest timeout") e.code = "ETIMEDOUT" errorFunc(e) }, options.timeout ) } if (xhr.setRequestHeader) { for(key in headers){ if(headers.hasOwnProperty(key)){ xhr.setRequestHeader(key, headers[key]) } } } else if (options.headers && !isEmpty(options.headers)) { throw new Error("Headers cannot be set on an XDomainRequest object") } if ("responseType" in options) { xhr.responseType = options.responseType } if ("beforeSend" in options && typeof options.beforeSend === "function" ) { options.beforeSend(xhr) } xhr.send(body) return xhr } function noop() {} },{"global/window":2,"once":51,"parse-headers":55}],51:[function(_dereq_,module,exports){ module.exports = once once.proto = once(function () { Object.defineProperty(Function.prototype, 'once', { value: function () { return once(this) }, configurable: true }) }) function once (fn) { var called = false return function () { if (called) return called = true return fn.apply(this, arguments) } } },{}],52:[function(_dereq_,module,exports){ var isFunction = _dereq_('is-function') module.exports = forEach var toString = Object.prototype.toString var hasOwnProperty = Object.prototype.hasOwnProperty function forEach(list, iterator, context) { if (!isFunction(iterator)) { throw new TypeError('iterator must be a function') } if (arguments.length < 3) { context = this } if (toString.call(list) === '[object Array]') forEachArray(list, iterator, context) else if (typeof list === 'string') forEachString(list, iterator, context) else forEachObject(list, iterator, context) } function forEachArray(array, iterator, context) { for (var i = 0, len = array.length; i < len; i++) { if (hasOwnProperty.call(array, i)) { iterator.call(context, array[i], i, array) } } } function forEachString(string, iterator, context) { for (var i = 0, len = string.length; i < len; i++) { // no such thing as a sparse string. iterator.call(context, string.charAt(i), i, string) } } function forEachObject(object, iterator, context) { for (var k in object) { if (hasOwnProperty.call(object, k)) { iterator.call(context, object[k], k, object) } } } },{"is-function":53}],53:[function(_dereq_,module,exports){ module.exports = isFunction var toString = Object.prototype.toString function isFunction (fn) { var string = toString.call(fn) return string === '[object Function]' || (typeof fn === 'function' && string !== '[object RegExp]') || (typeof window !== 'undefined' && // IE8 and below (fn === window.setTimeout || fn === window.alert || fn === window.confirm || fn === window.prompt)) }; },{}],54:[function(_dereq_,module,exports){ exports = module.exports = trim; function trim(str){ return str.replace(/^\s*|\s*$/g, ''); } exports.left = function(str){ return str.replace(/^\s*/, ''); }; exports.right = function(str){ return str.replace(/\s*$/, ''); }; },{}],55:[function(_dereq_,module,exports){ var trim = _dereq_('trim') , forEach = _dereq_('for-each') , isArray = function(arg) { return Object.prototype.toString.call(arg) === '[object Array]'; } module.exports = function (headers) { if (!headers) return {} var result = {} forEach( trim(headers).split('\n') , function (row) { var index = row.indexOf(':') , key = trim(row.slice(0, index)).toLowerCase() , value = trim(row.slice(index + 1)) if (typeof(result[key]) === 'undefined') { result[key] = value } else if (isArray(result[key])) { result[key].push(value) } else { result[key] = [ result[key], value ] } } ) return result } },{"for-each":52,"trim":54}],56:[function(_dereq_,module,exports){ /** * @file big-play-button.js */ 'use strict'; exports.__esModule = true; function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { 'default': obj }; } function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError('Cannot call a class as a function'); } } function _inherits(subClass, superClass) { if (typeof superClass !== 'function' && superClass !== null) { throw new TypeError('Super expression must either be null or a function, not ' + typeof superClass); } subClass.prototype = Object.create(superClass && superClass.prototype, { constructor: { value: subClass, enumerable: false, writable: true, configurable: true } }); if (superClass) Object.setPrototypeOf ? Object.setPrototypeOf(subClass, superClass) : subClass.__proto__ = superClass; } var _buttonJs = _dereq_('./button.js'); var _buttonJs2 = _interopRequireDefault(_buttonJs); var _componentJs = _dereq_('./component.js'); var _componentJs2 = _interopRequireDefault(_componentJs); /** * Initial play button. Shows before the video has played. The hiding of the * big play button is done via CSS and player states. * * @param {Object} player Main Player * @param {Object=} options Object of option names and values * @extends Button * @class BigPlayButton */ var BigPlayButton = (function (_Button) { _inherits(BigPlayButton, _Button); function BigPlayButton(player, options) { _classCallCheck(this, BigPlayButton); _Button.call(this, player, options); } /** * Allow sub components to stack CSS class names * * @return {String} The constructed class name * @method buildCSSClass */ BigPlayButton.prototype.buildCSSClass = function buildCSSClass() { return 'vjs-big-play-button'; }; /** * Handles click for play * * @method handleClick */ BigPlayButton.prototype.handleClick = function handleClick() { this.player_.play(); }; return BigPlayButton; })(_buttonJs2['default']); BigPlayButton.prototype.controlText_ = 'Play Video'; _componentJs2['default'].registerComponent('BigPlayButton', BigPlayButton); exports['default'] = BigPlayButton; module.exports = exports['default']; },{"./button.js":57,"./component.js":58}],57:[function(_dereq_,module,exports){ /** * @file button.js */ 'use strict'; exports.__esModule = true; function _interopRequireWildcard(obj) { if (obj && obj.__esModule) { return obj; } else { var newObj = {}; if (obj != null) { for (var key in obj) { if (Object.prototype.hasOwnProperty.call(obj, key)) newObj[key] = obj[key]; } } newObj['default'] = obj; return newObj; } } function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { 'default': obj }; } function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError('Cannot call a class as a function'); } } function _inherits(subClass, superClass) { if (typeof superClass !== 'function' && superClass !== null) { throw new TypeError('Super expression must either be null or a function, not ' + typeof superClass); } subClass.prototype = Object.create(superClass && superClass.prototype, { constructor: { value: subClass, enumerable: false, writable: true, configurable: true } }); if (superClass) Object.setPrototypeOf ? Object.setPrototypeOf(subClass, superClass) : subClass.__proto__ = superClass; } var _component = _dereq_('./component'); var _component2 = _interopRequireDefault(_component); var _utilsDomJs = _dereq_('./utils/dom.js'); var Dom = _interopRequireWildcard(_utilsDomJs); var _utilsEventsJs = _dereq_('./utils/events.js'); var Events = _interopRequireWildcard(_utilsEventsJs); var _utilsFnJs = _dereq_('./utils/fn.js'); var Fn = _interopRequireWildcard(_utilsFnJs); var _globalDocument = _dereq_('global/document'); var _globalDocument2 = _interopRequireDefault(_globalDocument); var _objectAssign = _dereq_('object.assign'); var _objectAssign2 = _interopRequireDefault(_objectAssign); /** * Base class for all buttons * * @param {Object} player Main Player * @param {Object=} options Object of option names and values * @extends Component * @class Button */ var Button = (function (_Component) { _inherits(Button, _Component); function Button(player, options) { _classCallCheck(this, Button); _Component.call(this, player, options); this.emitTapEvents(); this.on('tap', this.handleClick); this.on('click', this.handleClick); this.on('focus', this.handleFocus); this.on('blur', this.handleBlur); } /** * Create the component's DOM element * * @param {String=} type Element's node type. e.g. 'div' * @param {Object=} props An object of element attributes that should be set on the element Tag name * @return {Element} * @method createEl */ Button.prototype.createEl = function createEl() { var tag = arguments.length <= 0 || arguments[0] === undefined ? 'button' : arguments[0]; var props = arguments.length <= 1 || arguments[1] === undefined ? {} : arguments[1]; var attributes = arguments.length <= 2 || arguments[2] === undefined ? {} : arguments[2]; props = _objectAssign2['default']({ className: this.buildCSSClass(), tabIndex: 0 }, props); // Add standard Aria info attributes = _objectAssign2['default']({ role: 'button', type: 'button', // Necessary since the default button type is "submit" 'aria-live': 'polite' // let the screen reader user know that the text of the button may change }, attributes); var el = _Component.prototype.createEl.call(this, tag, props, attributes); this.controlTextEl_ = Dom.createEl('span', { className: 'vjs-control-text' }); el.appendChild(this.controlTextEl_); this.controlText(this.controlText_); return el; }; /** * Controls text - both request and localize * * @param {String} text Text for button * @return {String} * @method controlText */ Button.prototype.controlText = function controlText(text) { if (!text) return this.controlText_ || 'Need Text'; this.controlText_ = text; this.controlTextEl_.innerHTML = this.localize(this.controlText_); return this; }; /** * Allows sub components to stack CSS class names * * @return {String} * @method buildCSSClass */ Button.prototype.buildCSSClass = function buildCSSClass() { return 'vjs-control vjs-button ' + _Component.prototype.buildCSSClass.call(this); }; /** * Handle Click - Override with specific functionality for button * * @method handleClick */ Button.prototype.handleClick = function handleClick() {}; /** * Handle Focus - Add keyboard functionality to element * * @method handleFocus */ Button.prototype.handleFocus = function handleFocus() { Events.on(_globalDocument2['default'], 'keydown', Fn.bind(this, this.handleKeyPress)); }; /** * Handle KeyPress (document level) - Trigger click when keys are pressed * * @method handleKeyPress */ Button.prototype.handleKeyPress = function handleKeyPress(event) { // Check for space bar (32) or enter (13) keys if (event.which === 32 || event.which === 13) { event.preventDefault(); this.handleClick(event); } }; /** * Handle Blur - Remove keyboard triggers * * @method handleBlur */ Button.prototype.handleBlur = function handleBlur() { Events.off(_globalDocument2['default'], 'keydown', Fn.bind(this, this.handleKeyPress)); }; return Button; })(_component2['default']); _component2['default'].registerComponent('Button', Button); exports['default'] = Button; module.exports = exports['default']; },{"./component":58,"./utils/dom.js":118,"./utils/events.js":119,"./utils/fn.js":120,"global/document":1,"object.assign":43}],58:[function(_dereq_,module,exports){ /** * @file component.js * * Player Component - Base class for all UI objects */ 'use strict'; exports.__esModule = true; function _interopRequireWildcard(obj) { if (obj && obj.__esModule) { return obj; } else { var newObj = {}; if (obj != null) { for (var key in obj) { if (Object.prototype.hasOwnProperty.call(obj, key)) newObj[key] = obj[key]; } } newObj['default'] = obj; return newObj; } } function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { 'default': obj }; } function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError('Cannot call a class as a function'); } } var _globalWindow = _dereq_('global/window'); var _globalWindow2 = _interopRequireDefault(_globalWindow); var _utilsDomJs = _dereq_('./utils/dom.js'); var Dom = _interopRequireWildcard(_utilsDomJs); var _utilsFnJs = _dereq_('./utils/fn.js'); var Fn = _interopRequireWildcard(_utilsFnJs); var _utilsGuidJs = _dereq_('./utils/guid.js'); var Guid = _interopRequireWildcard(_utilsGuidJs); var _utilsEventsJs = _dereq_('./utils/events.js'); var Events = _interopRequireWildcard(_utilsEventsJs); var _utilsLogJs = _dereq_('./utils/log.js'); var _utilsLogJs2 = _interopRequireDefault(_utilsLogJs); var _utilsToTitleCaseJs = _dereq_('./utils/to-title-case.js'); var _utilsToTitleCaseJs2 = _interopRequireDefault(_utilsToTitleCaseJs); var _objectAssign = _dereq_('object.assign'); var _objectAssign2 = _interopRequireDefault(_objectAssign); var _utilsMergeOptionsJs = _dereq_('./utils/merge-options.js'); var _utilsMergeOptionsJs2 = _interopRequireDefault(_utilsMergeOptionsJs); /** * Base UI Component class * Components are embeddable UI objects that are represented by both a * javascript object and an element in the DOM. They can be children of other * components, and can have many children themselves. * ```js * // adding a button to the player * var button = player.addChild('button'); * button.el(); // -> button element * ``` * ```html * <div class="video-js"> * <div class="vjs-button">Button</div> * </div> * ``` * Components are also event targets. * ```js * button.on('click', function(){ * console.log('Button Clicked!'); * }); * button.trigger('customevent'); * ``` * * @param {Object} player Main Player * @param {Object=} options Object of option names and values * @param {Function=} ready Ready callback function * @class Component */ var Component = (function () { function Component(player, options, ready) { _classCallCheck(this, Component); // The component might be the player itself and we can't pass `this` to super if (!player && this.play) { this.player_ = player = this; // eslint-disable-line } else { this.player_ = player; } // Make a copy of prototype.options_ to protect against overriding defaults this.options_ = _utilsMergeOptionsJs2['default']({}, this.options_); // Updated options with supplied options options = this.options_ = _utilsMergeOptionsJs2['default'](this.options_, options); // Get ID from options or options element if one is supplied this.id_ = options.id || options.el && options.el.id; // If there was no ID from the options, generate one if (!this.id_) { // Don't require the player ID function in the case of mock players var id = player && player.id && player.id() || 'no_player'; this.id_ = id + '_component_' + Guid.newGUID(); } this.name_ = options.name || null; // Create element if one wasn't provided in options if (options.el) { this.el_ = options.el; } else if (options.createEl !== false) { this.el_ = this.createEl(); } this.children_ = []; this.childIndex_ = {}; this.childNameIndex_ = {}; // Add any child components in options if (options.initChildren !== false) { this.initChildren(); } this.ready(ready); // Don't want to trigger ready here or it will before init is actually // finished for all children that run this constructor if (options.reportTouchActivity !== false) { this.enableTouchActivity(); } } /** * Dispose of the component and all child components * * @method dispose */ Component.prototype.dispose = function dispose() { this.trigger({ type: 'dispose', bubbles: false }); // Dispose all children. if (this.children_) { for (var i = this.children_.length - 1; i >= 0; i--) { if (this.children_[i].dispose) { this.children_[i].dispose(); } } } // Delete child references this.children_ = null; this.childIndex_ = null; this.childNameIndex_ = null; // Remove all event listeners. this.off(); // Remove element from DOM if (this.el_.parentNode) { this.el_.parentNode.removeChild(this.el_); } Dom.removeElData(this.el_); this.el_ = null; }; /** * Return the component's player * * @return {Player} * @method player */ Component.prototype.player = function player() { return this.player_; }; /** * Deep merge of options objects * Whenever a property is an object on both options objects * the two properties will be merged using mergeOptions. * * ```js * Parent.prototype.options_ = { * optionSet: { * 'childOne': { 'foo': 'bar', 'asdf': 'fdsa' }, * 'childTwo': {}, * 'childThree': {} * } * } * newOptions = { * optionSet: { * 'childOne': { 'foo': 'baz', 'abc': '123' } * 'childTwo': null, * 'childFour': {} * } * } * * this.options(newOptions); * ``` * RESULT * ```js * { * optionSet: { * 'childOne': { 'foo': 'baz', 'asdf': 'fdsa', 'abc': '123' }, * 'childTwo': null, // Disabled. Won't be initialized. * 'childThree': {}, * 'childFour': {} * } * } * ``` * * @param {Object} obj Object of new option values * @return {Object} A NEW object of this.options_ and obj merged * @method options */ Component.prototype.options = function options(obj) { _utilsLogJs2['default'].warn('this.options() has been deprecated and will be moved to the constructor in 6.0'); if (!obj) { return this.options_; } this.options_ = _utilsMergeOptionsJs2['default'](this.options_, obj); return this.options_; }; /** * Get the component's DOM element * ```js * var domEl = myComponent.el(); * ``` * * @return {Element} * @method el */ Component.prototype.el = function el() { return this.el_; }; /** * Create the component's DOM element * * @param {String=} tagName Element's node type. e.g. 'div' * @param {Object=} properties An object of properties that should be set * @param {Object=} attributes An object of attributes that should be set * @return {Element} * @method createEl */ Component.prototype.createEl = function createEl(tagName, properties, attributes) { return Dom.createEl(tagName, properties, attributes); }; Component.prototype.localize = function localize(string) { var code = this.player_.language && this.player_.language(); var languages = this.player_.languages && this.player_.languages(); if (!code || !languages) { return string; } var language = languages[code]; if (language && language[string]) { return language[string]; } var primaryCode = code.split('-')[0]; var primaryLang = languages[primaryCode]; if (primaryLang && primaryLang[string]) { return primaryLang[string]; } return string; }; /** * Return the component's DOM element where children are inserted. * Will either be the same as el() or a new element defined in createEl(). * * @return {Element} * @method contentEl */ Component.prototype.contentEl = function contentEl() { return this.contentEl_ || this.el_; }; /** * Get the component's ID * ```js * var id = myComponent.id(); * ``` * * @return {String} * @method id */ Component.prototype.id = function id() { return this.id_; }; /** * Get the component's name. The name is often used to reference the component. * ```js * var name = myComponent.name(); * ``` * * @return {String} * @method name */ Component.prototype.name = function name() { return this.name_; }; /** * Get an array of all child components * ```js * var kids = myComponent.children(); * ``` * * @return {Array} The children * @method children */ Component.prototype.children = function children() { return this.children_; }; /** * Returns a child component with the provided ID * * @return {Component} * @method getChildById */ Component.prototype.getChildById = function getChildById(id) { return this.childIndex_[id]; }; /** * Returns a child component with the provided name * * @return {Component} * @method getChild */ Component.prototype.getChild = function getChild(name) { return this.childNameIndex_[name]; }; /** * Adds a child component inside this component * ```js * myComponent.el(); * // -> <div class='my-component'></div> * myComponent.children(); * // [empty array] * * var myButton = myComponent.addChild('MyButton'); * // -> <div class='my-component'><div class="my-button">myButton<div></div> * // -> myButton === myComponent.children()[0]; * ``` * Pass in options for child constructors and options for children of the child * ```js * var myButton = myComponent.addChild('MyButton', { * text: 'Press Me', * buttonChildExample: { * buttonChildOption: true * } * }); * ``` * * @param {String|Component} child The class name or instance of a child to add * @param {Object=} options Options, including options to be passed to children of the child. * @return {Component} The child component (created by this process if a string was used) * @method addChild */ Component.prototype.addChild = function addChild(child) { var options = arguments.length <= 1 || arguments[1] === undefined ? {} : arguments[1]; var component = undefined; var componentName = undefined; // If child is a string, create nt with options if (typeof child === 'string') { componentName = child; // Options can also be specified as a boolean, so convert to an empty object if false. if (!options) { options = {}; } // Same as above, but true is deprecated so show a warning. if (options === true) { _utilsLogJs2['default'].warn('Initializing a child component with `true` is deprecated. Children should be defined in an array when possible, but if necessary use an object instead of `true`.'); options = {}; } // If no componentClass in options, assume componentClass is the name lowercased // (e.g. playButton) var componentClassName = options.componentClass || _utilsToTitleCaseJs2['default'](componentName); // Set name through options options.name = componentName; // Create a new object & element for this controls set // If there's no .player_, this is a player var ComponentClass = Component.getComponent(componentClassName); component = new ComponentClass(this.player_ || this, options); // child is a component instance } else { component = child; } this.children_.push(component); if (typeof component.id === 'function') { this.childIndex_[component.id()] = component; } // If a name wasn't used to create the component, check if we can use the // name function of the component componentName = componentName || component.name && component.name(); if (componentName) { this.childNameIndex_[componentName] = component; } // Add the UI object's element to the container div (box) // Having an element is not required if (typeof component.el === 'function' && component.el()) { this.contentEl().appendChild(component.el()); } // Return so it can stored on parent object if desired. return component; }; /** * Remove a child component from this component's list of children, and the * child component's element from this component's element * * @param {Component} component Component to remove * @method removeChild */ Component.prototype.removeChild = function removeChild(component) { if (typeof component === 'string') { component = this.getChild(component); } if (!component || !this.children_) { return; } var childFound = false; for (var i = this.children_.length - 1; i >= 0; i--) { if (this.children_[i] === component) { childFound = true; this.children_.splice(i, 1); break; } } if (!childFound) { return; } this.childIndex_[component.id()] = null; this.childNameIndex_[component.name()] = null; var compEl = component.el(); if (compEl && compEl.parentNode === this.contentEl()) { this.contentEl().removeChild(component.el()); } }; /** * Add and initialize default child components from options * ```js * // when an instance of MyComponent is created, all children in options * // will be added to the instance by their name strings and options * MyComponent.prototype.options_ = { * children: [ * 'myChildComponent' * ], * myChildComponent: { * myChildOption: true * } * }; * * // Or when creating the component * var myComp = new MyComponent(player, { * children: [ * 'myChildComponent' * ], * myChildComponent: { * myChildOption: true * } * }); * ``` * The children option can also be an array of * child options objects (that also include a 'name' key). * This can be used if you have two child components of the * same type that need different options. * ```js * var myComp = new MyComponent(player, { * children: [ * 'button', * { * name: 'button', * someOtherOption: true * }, * { * name: 'button', * someOtherOption: false * } * ] * }); * ``` * * @method initChildren */ Component.prototype.initChildren = function initChildren() { var _this = this; var children = this.options_.children; if (children) { (function () { // `this` is `parent` var parentOptions = _this.options_; var handleAdd = function handleAdd(name, opts) { // Allow options for children to be set at the parent options // e.g. videojs(id, { controlBar: false }); // instead of videojs(id, { children: { controlBar: false }); if (parentOptions[name] !== undefined) { opts = parentOptions[name]; } // Allow for disabling default components // e.g. options['children']['posterImage'] = false if (opts === false) { return; } // Allow options to be passed as a simple boolean if no configuration // is necessary. if (opts === true) { opts = {}; } // We also want to pass the original player options to each component as well so they don't need to // reach back into the player for options later. opts.playerOptions = _this.options_.playerOptions; // Create and add the child component. // Add a direct reference to the child by name on the parent instance. // If two of the same component are used, different names should be supplied // for each _this[name] = _this.addChild(name, opts); }; // Allow for an array of children details to passed in the options if (Array.isArray(children)) { for (var i = 0; i < children.length; i++) { var child = children[i]; var _name = undefined; var opts = undefined; if (typeof child === 'string') { // ['myComponent'] _name = child; opts = {}; } else { // [{ name: 'myComponent', otherOption: true }] _name = child.name; opts = child; } handleAdd(_name, opts); } } else { Object.getOwnPropertyNames(children).forEach(function (name) { handleAdd(name, children[name]); }); } })(); } }; /** * Allows sub components to stack CSS class names * * @return {String} The constructed class name * @method buildCSSClass */ Component.prototype.buildCSSClass = function buildCSSClass() { // Child classes can include a function that does: // return 'CLASS NAME' + this._super(); return ''; }; /** * Add an event listener to this component's element * ```js * var myFunc = function(){ * var myComponent = this; * // Do something when the event is fired * }; * * myComponent.on('eventType', myFunc); * ``` * The context of myFunc will be myComponent unless previously bound. * Alternatively, you can add a listener to another element or component. * ```js * myComponent.on(otherElement, 'eventName', myFunc); * myComponent.on(otherComponent, 'eventName', myFunc); * ``` * The benefit of using this over `VjsEvents.on(otherElement, 'eventName', myFunc)` * and `otherComponent.on('eventName', myFunc)` is that this way the listeners * will be automatically cleaned up when either component is disposed. * It will also bind myComponent as the context of myFunc. * **NOTE**: When using this on elements in the page other than window * and document (both permanent), if you remove the element from the DOM * you need to call `myComponent.trigger(el, 'dispose')` on it to clean up * references to it and allow the browser to garbage collect it. * * @param {String|Component} first The event type or other component * @param {Function|String} second The event handler or event type * @param {Function} third The event handler * @return {Component} * @method on */ Component.prototype.on = function on(first, second, third) { var _this2 = this; if (typeof first === 'string' || Array.isArray(first)) { Events.on(this.el_, first, Fn.bind(this, second)); // Targeting another component or element } else { (function () { var target = first; var type = second; var fn = Fn.bind(_this2, third); // When this component is disposed, remove the listener from the other component var removeOnDispose = function removeOnDispose() { return _this2.off(target, type, fn); }; // Use the same function ID so we can remove it later it using the ID // of the original listener removeOnDispose.guid = fn.guid; _this2.on('dispose', removeOnDispose); // If the other component is disposed first we need to clean the reference // to the other component in this component's removeOnDispose listener // Otherwise we create a memory leak. var cleanRemover = function cleanRemover() { return _this2.off('dispose', removeOnDispose); }; // Add the same function ID so we can easily remove it later cleanRemover.guid = fn.guid; // Check if this is a DOM node if (first.nodeName) { // Add the listener to the other element Events.on(target, type, fn); Events.on(target, 'dispose', cleanRemover); // Should be a component // Not using `instanceof Component` because it makes mock players difficult } else if (typeof first.on === 'function') { // Add the listener to the other component target.on(type, fn); target.on('dispose', cleanRemover); } })(); } return this; }; /** * Remove an event listener from this component's element * ```js * myComponent.off('eventType', myFunc); * ``` * If myFunc is excluded, ALL listeners for the event type will be removed. * If eventType is excluded, ALL listeners will be removed from the component. * Alternatively you can use `off` to remove listeners that were added to other * elements or components using `myComponent.on(otherComponent...`. * In this case both the event type and listener function are REQUIRED. * ```js * myComponent.off(otherElement, 'eventType', myFunc); * myComponent.off(otherComponent, 'eventType', myFunc); * ``` * * @param {String=|Component} first The event type or other component * @param {Function=|String} second The listener function or event type * @param {Function=} third The listener for other component * @return {Component} * @method off */ Component.prototype.off = function off(first, second, third) { if (!first || typeof first === 'string' || Array.isArray(first)) { Events.off(this.el_, first, second); } else { var target = first; var type = second; // Ensure there's at least a guid, even if the function hasn't been used var fn = Fn.bind(this, third); // Remove the dispose listener on this component, // which was given the same guid as the event listener this.off('dispose', fn); if (first.nodeName) { // Remove the listener Events.off(target, type, fn); // Remove the listener for cleaning the dispose listener Events.off(target, 'dispose', fn); } else { target.off(type, fn); target.off('dispose', fn); } } return this; }; /** * Add an event listener to be triggered only once and then removed * ```js * myComponent.one('eventName', myFunc); * ``` * Alternatively you can add a listener to another element or component * that will be triggered only once. * ```js * myComponent.one(otherElement, 'eventName', myFunc); * myComponent.one(otherComponent, 'eventName', myFunc); * ``` * * @param {String|Component} first The event type or other component * @param {Function|String} second The listener function or event type * @param {Function=} third The listener function for other component * @return {Component} * @method one */ Component.prototype.one = function one(first, second, third) { var _this3 = this, _arguments = arguments; if (typeof first === 'string' || Array.isArray(first)) { Events.one(this.el_, first, Fn.bind(this, second)); } else { (function () { var target = first; var type = second; var fn = Fn.bind(_this3, third); var newFunc = function newFunc() { _this3.off(target, type, newFunc); fn.apply(null, _arguments); }; // Keep the same function ID so we can remove it later newFunc.guid = fn.guid; _this3.on(target, type, newFunc); })(); } return this; }; /** * Trigger an event on an element * ```js * myComponent.trigger('eventName'); * myComponent.trigger({'type':'eventName'}); * myComponent.trigger('eventName', {data: 'some data'}); * myComponent.trigger({'type':'eventName'}, {data: 'some data'}); * ``` * * @param {Event|Object|String} event A string (the type) or an event object with a type attribute * @param {Object} [hash] data hash to pass along with the event * @return {Component} self * @method trigger */ Component.prototype.trigger = function trigger(event, hash) { Events.trigger(this.el_, event, hash); return this; }; /** * Bind a listener to the component's ready state. * Different from event listeners in that if the ready event has already happened * it will trigger the function immediately. * * @param {Function} fn Ready listener * @param {Boolean} sync Exec the listener synchronously if component is ready * @return {Component} * @method ready */ Component.prototype.ready = function ready(fn) { var sync = arguments.length <= 1 || arguments[1] === undefined ? false : arguments[1]; if (fn) { if (this.isReady_) { if (sync) { fn.call(this); } else { // Call the function asynchronously by default for consistency this.setTimeout(fn, 1); } } else { this.readyQueue_ = this.readyQueue_ || []; this.readyQueue_.push(fn); } } return this; }; /** * Trigger the ready listeners * * @return {Component} * @method triggerReady */ Component.prototype.triggerReady = function triggerReady() { this.isReady_ = true; // Ensure ready is triggerd asynchronously this.setTimeout(function () { var readyQueue = this.readyQueue_; if (readyQueue && readyQueue.length > 0) { readyQueue.forEach(function (fn) { fn.call(this); }, this); // Reset Ready Queue this.readyQueue_ = []; } // Allow for using event listeners also this.trigger('ready'); }, 1); }; /** * Check if a component's element has a CSS class name * * @param {String} classToCheck Classname to check * @return {Component} * @method hasClass */ Component.prototype.hasClass = function hasClass(classToCheck) { return Dom.hasElClass(this.el_, classToCheck); }; /** * Add a CSS class name to the component's element * * @param {String} classToAdd Classname to add * @return {Component} * @method addClass */ Component.prototype.addClass = function addClass(classToAdd) { Dom.addElClass(this.el_, classToAdd); return this; }; /** * Remove and return a CSS class name from the component's element * * @param {String} classToRemove Classname to remove * @return {Component} * @method removeClass */ Component.prototype.removeClass = function removeClass(classToRemove) { Dom.removeElClass(this.el_, classToRemove); return this; }; /** * Show the component element if hidden * * @return {Component} * @method show */ Component.prototype.show = function show() { this.removeClass('vjs-hidden'); return this; }; /** * Hide the component element if currently showing * * @return {Component} * @method hide */ Component.prototype.hide = function hide() { this.addClass('vjs-hidden'); return this; }; /** * Lock an item in its visible state * To be used with fadeIn/fadeOut. * * @return {Component} * @private * @method lockShowing */ Component.prototype.lockShowing = function lockShowing() { this.addClass('vjs-lock-showing'); return this; }; /** * Unlock an item to be hidden * To be used with fadeIn/fadeOut. * * @return {Component} * @private * @method unlockShowing */ Component.prototype.unlockShowing = function unlockShowing() { this.removeClass('vjs-lock-showing'); return this; }; /** * Set or get the width of the component (CSS values) * Setting the video tag dimension values only works with values in pixels. * Percent values will not work. * Some percents can be used, but width()/height() will return the number + %, * not the actual computed width/height. * * @param {Number|String=} num Optional width number * @param {Boolean} skipListeners Skip the 'resize' event trigger * @return {Component} This component, when setting the width * @return {Number|String} The width, when getting * @method width */ Component.prototype.width = function width(num, skipListeners) { return this.dimension('width', num, skipListeners); }; /** * Get or set the height of the component (CSS values) * Setting the video tag dimension values only works with values in pixels. * Percent values will not work. * Some percents can be used, but width()/height() will return the number + %, * not the actual computed width/height. * * @param {Number|String=} num New component height * @param {Boolean=} skipListeners Skip the resize event trigger * @return {Component} This component, when setting the height * @return {Number|String} The height, when getting * @method height */ Component.prototype.height = function height(num, skipListeners) { return this.dimension('height', num, skipListeners); }; /** * Set both width and height at the same time * * @param {Number|String} width Width of player * @param {Number|String} height Height of player * @return {Component} The component * @method dimensions */ Component.prototype.dimensions = function dimensions(width, height) { // Skip resize listeners on width for optimization return this.width(width, true).height(height); }; /** * Get or set width or height * This is the shared code for the width() and height() methods. * All for an integer, integer + 'px' or integer + '%'; * Known issue: Hidden elements officially have a width of 0. We're defaulting * to the style.width value and falling back to computedStyle which has the * hidden element issue. Info, but probably not an efficient fix: * http://www.foliotek.com/devblog/getting-the-width-of-a-hidden-element-with-jquery-using-width/ * * @param {String} widthOrHeight 'width' or 'height' * @param {Number|String=} num New dimension * @param {Boolean=} skipListeners Skip resize event trigger * @return {Component} The component if a dimension was set * @return {Number|String} The dimension if nothing was set * @private * @method dimension */ Component.prototype.dimension = function dimension(widthOrHeight, num, skipListeners) { if (num !== undefined) { // Set to zero if null or literally NaN (NaN !== NaN) if (num === null || num !== num) { num = 0; } // Check if using css width/height (% or px) and adjust if (('' + num).indexOf('%') !== -1 || ('' + num).indexOf('px') !== -1) { this.el_.style[widthOrHeight] = num; } else if (num === 'auto') { this.el_.style[widthOrHeight] = ''; } else { this.el_.style[widthOrHeight] = num + 'px'; } // skipListeners allows us to avoid triggering the resize event when setting both width and height if (!skipListeners) { this.trigger('resize'); } // Return component return this; } // Not setting a value, so getting it // Make sure element exists if (!this.el_) { return 0; } // Get dimension value from style var val = this.el_.style[widthOrHeight]; var pxIndex = val.indexOf('px'); if (pxIndex !== -1) { // Return the pixel value with no 'px' return parseInt(val.slice(0, pxIndex), 10); } // No px so using % or no style was set, so falling back to offsetWidth/height // If component has display:none, offset will return 0 // TODO: handle display:none and no dimension style using px return parseInt(this.el_['offset' + _utilsToTitleCaseJs2['default'](widthOrHeight)], 10); }; /** * Emit 'tap' events when touch events are supported * This is used to support toggling the controls through a tap on the video. * We're requiring them to be enabled because otherwise every component would * have this extra overhead unnecessarily, on mobile devices where extra * overhead is especially bad. * * @private * @method emitTapEvents */ Component.prototype.emitTapEvents = function emitTapEvents() { // Track the start time so we can determine how long the touch lasted var touchStart = 0; var firstTouch = null; // Maximum movement allowed during a touch event to still be considered a tap // Other popular libs use anywhere from 2 (hammer.js) to 15, so 10 seems like a nice, round number. var tapMovementThreshold = 10; // The maximum length a touch can be while still being considered a tap var touchTimeThreshold = 200; var couldBeTap = undefined; this.on('touchstart', function (event) { // If more than one finger, don't consider treating this as a click if (event.touches.length === 1) { // Copy the touches object to prevent modifying the original firstTouch = _objectAssign2['default']({}, event.touches[0]); // Record start time so we can detect a tap vs. "touch and hold" touchStart = new Date().getTime(); // Reset couldBeTap tracking couldBeTap = true; } }); this.on('touchmove', function (event) { // If more than one finger, don't consider treating this as a click if (event.touches.length > 1) { couldBeTap = false; } else if (firstTouch) { // Some devices will throw touchmoves for all but the slightest of taps. // So, if we moved only a small distance, this could still be a tap var xdiff = event.touches[0].pageX - firstTouch.pageX; var ydiff = event.touches[0].pageY - firstTouch.pageY; var touchDistance = Math.sqrt(xdiff * xdiff + ydiff * ydiff); if (touchDistance > tapMovementThreshold) { couldBeTap = false; } } }); var noTap = function noTap() { couldBeTap = false; }; // TODO: Listen to the original target. http://youtu.be/DujfpXOKUp8?t=13m8s this.on('touchleave', noTap); this.on('touchcancel', noTap); // When the touch ends, measure how long it took and trigger the appropriate // event this.on('touchend', function (event) { firstTouch = null; // Proceed only if the touchmove/leave/cancel event didn't happen if (couldBeTap === true) { // Measure how long the touch lasted var touchTime = new Date().getTime() - touchStart; // Make sure the touch was less than the threshold to be considered a tap if (touchTime < touchTimeThreshold) { // Don't let browser turn this into a click event.preventDefault(); this.trigger('tap'); // It may be good to copy the touchend event object and change the // type to tap, if the other event properties aren't exact after // Events.fixEvent runs (e.g. event.target) } } }); }; /** * Report user touch activity when touch events occur * User activity is used to determine when controls should show/hide. It's * relatively simple when it comes to mouse events, because any mouse event * should show the controls. So we capture mouse events that bubble up to the * player and report activity when that happens. * With touch events it isn't as easy. We can't rely on touch events at the * player level, because a tap (touchstart + touchend) on the video itself on * mobile devices is meant to turn controls off (and on). User activity is * checked asynchronously, so what could happen is a tap event on the video * turns the controls off, then the touchend event bubbles up to the player, * which if it reported user activity, would turn the controls right back on. * (We also don't want to completely block touch events from bubbling up) * Also a touchmove, touch+hold, and anything other than a tap is not supposed * to turn the controls back on on a mobile device. * Here we're setting the default component behavior to report user activity * whenever touch events happen, and this can be turned off by components that * want touch events to act differently. * * @method enableTouchActivity */ Component.prototype.enableTouchActivity = function enableTouchActivity() { // Don't continue if the root player doesn't support reporting user activity if (!this.player() || !this.player().reportUserActivity) { return; } // listener for reporting that the user is active var report = Fn.bind(this.player(), this.player().reportUserActivity); var touchHolding = undefined; this.on('touchstart', function () { report(); // For as long as the they are touching the device or have their mouse down, // we consider them active even if they're not moving their finger or mouse. // So we want to continue to update that they are active this.clearInterval(touchHolding); // report at the same interval as activityCheck touchHolding = this.setInterval(report, 250); }); var touchEnd = function touchEnd(event) { report(); // stop the interval that maintains activity if the touch is holding this.clearInterval(touchHolding); }; this.on('touchmove', report); this.on('touchend', touchEnd); this.on('touchcancel', touchEnd); }; /** * Creates timeout and sets up disposal automatically. * * @param {Function} fn The function to run after the timeout. * @param {Number} timeout Number of ms to delay before executing specified function. * @return {Number} Returns the timeout ID * @method setTimeout */ Component.prototype.setTimeout = function setTimeout(fn, timeout) { fn = Fn.bind(this, fn); // window.setTimeout would be preferable here, but due to some bizarre issue with Sinon and/or Phantomjs, we can't. var timeoutId = _globalWindow2['default'].setTimeout(fn, timeout); var disposeFn = function disposeFn() { this.clearTimeout(timeoutId); }; disposeFn.guid = 'vjs-timeout-' + timeoutId; this.on('dispose', disposeFn); return timeoutId; }; /** * Clears a timeout and removes the associated dispose listener * * @param {Number} timeoutId The id of the timeout to clear * @return {Number} Returns the timeout ID * @method clearTimeout */ Component.prototype.clearTimeout = function clearTimeout(timeoutId) { _globalWindow2['default'].clearTimeout(timeoutId); var disposeFn = function disposeFn() {}; disposeFn.guid = 'vjs-timeout-' + timeoutId; this.off('dispose', disposeFn); return timeoutId; }; /** * Creates an interval and sets up disposal automatically. * * @param {Function} fn The function to run every N seconds. * @param {Number} interval Number of ms to delay before executing specified function. * @return {Number} Returns the interval ID * @method setInterval */ Component.prototype.setInterval = function setInterval(fn, interval) { fn = Fn.bind(this, fn); var intervalId = _globalWindow2['default'].setInterval(fn, interval); var disposeFn = function disposeFn() { this.clearInterval(intervalId); }; disposeFn.guid = 'vjs-interval-' + intervalId; this.on('dispose', disposeFn); return intervalId; }; /** * Clears an interval and removes the associated dispose listener * * @param {Number} intervalId The id of the interval to clear * @return {Number} Returns the interval ID * @method clearInterval */ Component.prototype.clearInterval = function clearInterval(intervalId) { _globalWindow2['default'].clearInterval(intervalId); var disposeFn = function disposeFn() {}; disposeFn.guid = 'vjs-interval-' + intervalId; this.off('dispose', disposeFn); return intervalId; }; /** * Registers a component * * @param {String} name Name of the component to register * @param {Object} comp The component to register * @static * @method registerComponent */ Component.registerComponent = function registerComponent(name, comp) { if (!Component.components_) { Component.components_ = {}; } Component.components_[name] = comp; return comp; }; /** * Gets a component by name * * @param {String} name Name of the component to get * @return {Component} * @static * @method getComponent */ Component.getComponent = function getComponent(name) { if (Component.components_ && Component.components_[name]) { return Component.components_[name]; } if (_globalWindow2['default'] && _globalWindow2['default'].videojs && _globalWindow2['default'].videojs[name]) { _utilsLogJs2['default'].warn('The ' + name + ' component was added to the videojs object when it should be registered using videojs.registerComponent(name, component)'); return _globalWindow2['default'].videojs[name]; } }; /** * Sets up the constructor using the supplied init method * or uses the init of the parent object * * @param {Object} props An object of properties * @static * @deprecated * @method extend */ Component.extend = function extend(props) { props = props || {}; _utilsLogJs2['default'].warn('Component.extend({}) has been deprecated, use videojs.extend(Component, {}) instead'); // Set up the constructor using the supplied init method // or using the init of the parent object // Make sure to check the unobfuscated version for external libs var init = props.init || props.init || this.prototype.init || this.prototype.init || function () {}; // In Resig's simple class inheritance (previously used) the constructor // is a function that calls `this.init.apply(arguments)` // However that would prevent us from using `ParentObject.call(this);` // in a Child constructor because the `this` in `this.init` // would still refer to the Child and cause an infinite loop. // We would instead have to do // `ParentObject.prototype.init.apply(this, arguments);` // Bleh. We're not creating a _super() function, so it's good to keep // the parent constructor reference simple. var subObj = function subObj() { init.apply(this, arguments); }; // Inherit from this object's prototype subObj.prototype = Object.create(this.prototype); // Reset the constructor property for subObj otherwise // instances of subObj would have the constructor of the parent Object subObj.prototype.constructor = subObj; // Make the class extendable subObj.extend = Component.extend; // Extend subObj's prototype with functions and other properties from props for (var _name2 in props) { if (props.hasOwnProperty(_name2)) { subObj.prototype[_name2] = props[_name2]; } } return subObj; }; return Component; })(); Component.registerComponent('Component', Component); exports['default'] = Component; module.exports = exports['default']; },{"./utils/dom.js":118,"./utils/events.js":119,"./utils/fn.js":120,"./utils/guid.js":122,"./utils/log.js":123,"./utils/merge-options.js":124,"./utils/to-title-case.js":127,"global/window":2,"object.assign":43}],59:[function(_dereq_,module,exports){ /** * @file control-bar.js */ 'use strict'; exports.__esModule = true; function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { 'default': obj }; } function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError('Cannot call a class as a function'); } } function _inherits(subClass, superClass) { if (typeof superClass !== 'function' && superClass !== null) { throw new TypeError('Super expression must either be null or a function, not ' + typeof superClass); } subClass.prototype = Object.create(superClass && superClass.prototype, { constructor: { value: subClass, enumerable: false, writable: true, configurable: true } }); if (superClass) Object.setPrototypeOf ? Object.setPrototypeOf(subClass, superClass) : subClass.__proto__ = superClass; } var _componentJs = _dereq_('../component.js'); var _componentJs2 = _interopRequireDefault(_componentJs); // Required children var _playToggleJs = _dereq_('./play-toggle.js'); var _playToggleJs2 = _interopRequireDefault(_playToggleJs); var _timeControlsCurrentTimeDisplayJs = _dereq_('./time-controls/current-time-display.js'); var _timeControlsCurrentTimeDisplayJs2 = _interopRequireDefault(_timeControlsCurrentTimeDisplayJs); var _timeControlsDurationDisplayJs = _dereq_('./time-controls/duration-display.js'); var _timeControlsDurationDisplayJs2 = _interopRequireDefault(_timeControlsDurationDisplayJs); var _timeControlsTimeDividerJs = _dereq_('./time-controls/time-divider.js'); var _timeControlsTimeDividerJs2 = _interopRequireDefault(_timeControlsTimeDividerJs); var _timeControlsRemainingTimeDisplayJs = _dereq_('./time-controls/remaining-time-display.js'); var _timeControlsRemainingTimeDisplayJs2 = _interopRequireDefault(_timeControlsRemainingTimeDisplayJs); var _liveDisplayJs = _dereq_('./live-display.js'); var _liveDisplayJs2 = _interopRequireDefault(_liveDisplayJs); var _progressControlProgressControlJs = _dereq_('./progress-control/progress-control.js'); var _progressControlProgressControlJs2 = _interopRequireDefault(_progressControlProgressControlJs); var _fullscreenToggleJs = _dereq_('./fullscreen-toggle.js'); var _fullscreenToggleJs2 = _interopRequireDefault(_fullscreenToggleJs); var _volumeControlVolumeControlJs = _dereq_('./volume-control/volume-control.js'); var _volumeControlVolumeControlJs2 = _interopRequireDefault(_volumeControlVolumeControlJs); var _volumeMenuButtonJs = _dereq_('./volume-menu-button.js'); var _volumeMenuButtonJs2 = _interopRequireDefault(_volumeMenuButtonJs); var _muteToggleJs = _dereq_('./mute-toggle.js'); var _muteToggleJs2 = _interopRequireDefault(_muteToggleJs); var _textTrackControlsChaptersButtonJs = _dereq_('./text-track-controls/chapters-button.js'); var _textTrackControlsChaptersButtonJs2 = _interopRequireDefault(_textTrackControlsChaptersButtonJs); var _textTrackControlsSubtitlesButtonJs = _dereq_('./text-track-controls/subtitles-button.js'); var _textTrackControlsSubtitlesButtonJs2 = _interopRequireDefault(_textTrackControlsSubtitlesButtonJs); var _textTrackControlsCaptionsButtonJs = _dereq_('./text-track-controls/captions-button.js'); var _textTrackControlsCaptionsButtonJs2 = _interopRequireDefault(_textTrackControlsCaptionsButtonJs); var _playbackRateMenuPlaybackRateMenuButtonJs = _dereq_('./playback-rate-menu/playback-rate-menu-button.js'); var _playbackRateMenuPlaybackRateMenuButtonJs2 = _interopRequireDefault(_playbackRateMenuPlaybackRateMenuButtonJs); var _spacerControlsCustomControlSpacerJs = _dereq_('./spacer-controls/custom-control-spacer.js'); var _spacerControlsCustomControlSpacerJs2 = _interopRequireDefault(_spacerControlsCustomControlSpacerJs); /** * Container of main controls * * @extends Component * @class ControlBar */ var ControlBar = (function (_Component) { _inherits(ControlBar, _Component); function ControlBar() { _classCallCheck(this, ControlBar); _Component.apply(this, arguments); } /** * Create the component's DOM element * * @return {Element} * @method createEl */ ControlBar.prototype.createEl = function createEl() { return _Component.prototype.createEl.call(this, 'div', { className: 'vjs-control-bar' }); }; return ControlBar; })(_componentJs2['default']); ControlBar.prototype.options_ = { loadEvent: 'play', children: ['playToggle', 'volumeMenuButton', 'currentTimeDisplay', 'timeDivider', 'durationDisplay', 'progressControl', 'liveDisplay', 'remainingTimeDisplay', 'customControlSpacer', 'playbackRateMenuButton', 'chaptersButton', 'subtitlesButton', 'captionsButton', 'fullscreenToggle'] }; _componentJs2['default'].registerComponent('ControlBar', ControlBar); exports['default'] = ControlBar; module.exports = exports['default']; },{"../component.js":58,"./fullscreen-toggle.js":60,"./live-display.js":61,"./mute-toggle.js":62,"./play-toggle.js":63,"./playback-rate-menu/playback-rate-menu-button.js":64,"./progress-control/progress-control.js":69,"./spacer-controls/custom-control-spacer.js":71,"./text-track-controls/captions-button.js":74,"./text-track-controls/chapters-button.js":75,"./text-track-controls/subtitles-button.js":78,"./time-controls/current-time-display.js":81,"./time-controls/duration-display.js":82,"./time-controls/remaining-time-display.js":83,"./time-controls/time-divider.js":84,"./volume-control/volume-control.js":86,"./volume-menu-button.js":88}],60:[function(_dereq_,module,exports){ /** * @file fullscreen-toggle.js */ 'use strict'; exports.__esModule = true; function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { 'default': obj }; } function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError('Cannot call a class as a function'); } } function _inherits(subClass, superClass) { if (typeof superClass !== 'function' && superClass !== null) { throw new TypeError('Super expression must either be null or a function, not ' + typeof superClass); } subClass.prototype = Object.create(superClass && superClass.prototype, { constructor: { value: subClass, enumerable: false, writable: true, configurable: true } }); if (superClass) Object.setPrototypeOf ? Object.setPrototypeOf(subClass, superClass) : subClass.__proto__ = superClass; } var _buttonJs = _dereq_('../button.js'); var _buttonJs2 = _interopRequireDefault(_buttonJs); var _componentJs = _dereq_('../component.js'); var _componentJs2 = _interopRequireDefault(_componentJs); /** * Toggle fullscreen video * * @extends Button * @class FullscreenToggle */ var FullscreenToggle = (function (_Button) { _inherits(FullscreenToggle, _Button); function FullscreenToggle() { _classCallCheck(this, FullscreenToggle); _Button.apply(this, arguments); } /** * Allow sub components to stack CSS class names * * @return {String} The constructed class name * @method buildCSSClass */ FullscreenToggle.prototype.buildCSSClass = function buildCSSClass() { return 'vjs-fullscreen-control ' + _Button.prototype.buildCSSClass.call(this); }; /** * Handles click for full screen * * @method handleClick */ FullscreenToggle.prototype.handleClick = function handleClick() { if (!this.player_.isFullscreen()) { this.player_.requestFullscreen(); this.controlText('Non-Fullscreen'); } else { this.player_.exitFullscreen(); this.controlText('Fullscreen'); } }; return FullscreenToggle; })(_buttonJs2['default']); FullscreenToggle.prototype.controlText_ = 'Fullscreen'; _componentJs2['default'].registerComponent('FullscreenToggle', FullscreenToggle); exports['default'] = FullscreenToggle; module.exports = exports['default']; },{"../button.js":57,"../component.js":58}],61:[function(_dereq_,module,exports){ /** * @file live-display.js */ 'use strict'; exports.__esModule = true; function _interopRequireWildcard(obj) { if (obj && obj.__esModule) { return obj; } else { var newObj = {}; if (obj != null) { for (var key in obj) { if (Object.prototype.hasOwnProperty.call(obj, key)) newObj[key] = obj[key]; } } newObj['default'] = obj; return newObj; } } function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { 'default': obj }; } function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError('Cannot call a class as a function'); } } function _inherits(subClass, superClass) { if (typeof superClass !== 'function' && superClass !== null) { throw new TypeError('Super expression must either be null or a function, not ' + typeof superClass); } subClass.prototype = Object.create(superClass && superClass.prototype, { constructor: { value: subClass, enumerable: false, writable: true, configurable: true } }); if (superClass) Object.setPrototypeOf ? Object.setPrototypeOf(subClass, superClass) : subClass.__proto__ = superClass; } var _component = _dereq_('../component'); var _component2 = _interopRequireDefault(_component); var _utilsDomJs = _dereq_('../utils/dom.js'); var Dom = _interopRequireWildcard(_utilsDomJs); /** * Displays the live indicator * TODO - Future make it click to snap to live * * @extends Component * @class LiveDisplay */ var LiveDisplay = (function (_Component) { _inherits(LiveDisplay, _Component); function LiveDisplay(player, options) { _classCallCheck(this, LiveDisplay); _Component.call(this, player, options); this.updateShowing(); this.on(this.player(), 'durationchange', this.updateShowing); } /** * Create the component's DOM element * * @return {Element} * @method createEl */ LiveDisplay.prototype.createEl = function createEl() { var el = _Component.prototype.createEl.call(this, 'div', { className: 'vjs-live-control vjs-control' }); this.contentEl_ = Dom.createEl('div', { className: 'vjs-live-display', innerHTML: '<span class="vjs-control-text">' + this.localize('Stream Type') + '</span>' + this.localize('LIVE') }, { 'aria-live': 'off' }); el.appendChild(this.contentEl_); return el; }; LiveDisplay.prototype.updateShowing = function updateShowing() { if (this.player().duration() === Infinity) { this.show(); } else { this.hide(); } }; return LiveDisplay; })(_component2['default']); _component2['default'].registerComponent('LiveDisplay', LiveDisplay); exports['default'] = LiveDisplay; module.exports = exports['default']; },{"../component":58,"../utils/dom.js":118}],62:[function(_dereq_,module,exports){ /** * @file mute-toggle.js */ 'use strict'; exports.__esModule = true; function _interopRequireWildcard(obj) { if (obj && obj.__esModule) { return obj; } else { var newObj = {}; if (obj != null) { for (var key in obj) { if (Object.prototype.hasOwnProperty.call(obj, key)) newObj[key] = obj[key]; } } newObj['default'] = obj; return newObj; } } function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { 'default': obj }; } function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError('Cannot call a class as a function'); } } function _inherits(subClass, superClass) { if (typeof superClass !== 'function' && superClass !== null) { throw new TypeError('Super expression must either be null or a function, not ' + typeof superClass); } subClass.prototype = Object.create(superClass && superClass.prototype, { constructor: { value: subClass, enumerable: false, writable: true, configurable: true } }); if (superClass) Object.setPrototypeOf ? Object.setPrototypeOf(subClass, superClass) : subClass.__proto__ = superClass; } var _button = _dereq_('../button'); var _button2 = _interopRequireDefault(_button); var _component = _dereq_('../component'); var _component2 = _interopRequireDefault(_component); var _utilsDomJs = _dereq_('../utils/dom.js'); var Dom = _interopRequireWildcard(_utilsDomJs); /** * A button component for muting the audio * * @param {Player|Object} player * @param {Object=} options * @extends Button * @class MuteToggle */ var MuteToggle = (function (_Button) { _inherits(MuteToggle, _Button); function MuteToggle(player, options) { _classCallCheck(this, MuteToggle); _Button.call(this, player, options); this.on(player, 'volumechange', this.update); // hide mute toggle if the current tech doesn't support volume control if (player.tech_ && player.tech_['featuresVolumeControl'] === false) { this.addClass('vjs-hidden'); } this.on(player, 'loadstart', function () { this.update(); // We need to update the button to account for a default muted state. if (player.tech_['featuresVolumeControl'] === false) { this.addClass('vjs-hidden'); } else { this.removeClass('vjs-hidden'); } }); } /** * Allow sub components to stack CSS class names * * @return {String} The constructed class name * @method buildCSSClass */ MuteToggle.prototype.buildCSSClass = function buildCSSClass() { return 'vjs-mute-control ' + _Button.prototype.buildCSSClass.call(this); }; /** * Handle click on mute * * @method handleClick */ MuteToggle.prototype.handleClick = function handleClick() { this.player_.muted(this.player_.muted() ? false : true); }; /** * Update volume * * @method update */ MuteToggle.prototype.update = function update() { var vol = this.player_.volume(), level = 3; if (vol === 0 || this.player_.muted()) { level = 0; } else if (vol < 0.33) { level = 1; } else if (vol < 0.67) { level = 2; } // Don't rewrite the button text if the actual text doesn't change. // This causes unnecessary and confusing information for screen reader users. // This check is needed because this function gets called every time the volume level is changed. var toMute = this.player_.muted() ? 'Unmute' : 'Mute'; var localizedMute = this.localize(toMute); if (this.controlText() !== localizedMute) { this.controlText(localizedMute); } /* TODO improve muted icon classes */ for (var i = 0; i < 4; i++) { Dom.removeElClass(this.el_, 'vjs-vol-' + i); } Dom.addElClass(this.el_, 'vjs-vol-' + level); }; return MuteToggle; })(_button2['default']); MuteToggle.prototype.controlText_ = 'Mute'; _component2['default'].registerComponent('MuteToggle', MuteToggle); exports['default'] = MuteToggle; module.exports = exports['default']; },{"../button":57,"../component":58,"../utils/dom.js":118}],63:[function(_dereq_,module,exports){ /** * @file play-toggle.js */ 'use strict'; exports.__esModule = true; function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { 'default': obj }; } function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError('Cannot call a class as a function'); } } function _inherits(subClass, superClass) { if (typeof superClass !== 'function' && superClass !== null) { throw new TypeError('Super expression must either be null or a function, not ' + typeof superClass); } subClass.prototype = Object.create(superClass && superClass.prototype, { constructor: { value: subClass, enumerable: false, writable: true, configurable: true } }); if (superClass) Object.setPrototypeOf ? Object.setPrototypeOf(subClass, superClass) : subClass.__proto__ = superClass; } var _buttonJs = _dereq_('../button.js'); var _buttonJs2 = _interopRequireDefault(_buttonJs); var _componentJs = _dereq_('../component.js'); var _componentJs2 = _interopRequireDefault(_componentJs); /** * Button to toggle between play and pause * * @param {Player|Object} player * @param {Object=} options * @extends Button * @class PlayToggle */ var PlayToggle = (function (_Button) { _inherits(PlayToggle, _Button); function PlayToggle(player, options) { _classCallCheck(this, PlayToggle); _Button.call(this, player, options); this.on(player, 'play', this.handlePlay); this.on(player, 'pause', this.handlePause); } /** * Allow sub components to stack CSS class names * * @return {String} The constructed class name * @method buildCSSClass */ PlayToggle.prototype.buildCSSClass = function buildCSSClass() { return 'vjs-play-control ' + _Button.prototype.buildCSSClass.call(this); }; /** * Handle click to toggle between play and pause * * @method handleClick */ PlayToggle.prototype.handleClick = function handleClick() { if (this.player_.paused()) { this.player_.play(); } else { this.player_.pause(); } }; /** * Add the vjs-playing class to the element so it can change appearance * * @method handlePlay */ PlayToggle.prototype.handlePlay = function handlePlay() { this.removeClass('vjs-paused'); this.addClass('vjs-playing'); this.controlText('Pause'); // change the button text to "Pause" }; /** * Add the vjs-paused class to the element so it can change appearance * * @method handlePause */ PlayToggle.prototype.handlePause = function handlePause() { this.removeClass('vjs-playing'); this.addClass('vjs-paused'); this.controlText('Play'); // change the button text to "Play" }; return PlayToggle; })(_buttonJs2['default']); PlayToggle.prototype.controlText_ = 'Play'; _componentJs2['default'].registerComponent('PlayToggle', PlayToggle); exports['default'] = PlayToggle; module.exports = exports['default']; },{"../button.js":57,"../component.js":58}],64:[function(_dereq_,module,exports){ /** * @file playback-rate-menu-button.js */ 'use strict'; exports.__esModule = true; function _interopRequireWildcard(obj) { if (obj && obj.__esModule) { return obj; } else { var newObj = {}; if (obj != null) { for (var key in obj) { if (Object.prototype.hasOwnProperty.call(obj, key)) newObj[key] = obj[key]; } } newObj['default'] = obj; return newObj; } } function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { 'default': obj }; } function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError('Cannot call a class as a function'); } } function _inherits(subClass, superClass) { if (typeof superClass !== 'function' && superClass !== null) { throw new TypeError('Super expression must either be null or a function, not ' + typeof superClass); } subClass.prototype = Object.create(superClass && superClass.prototype, { constructor: { value: subClass, enumerable: false, writable: true, configurable: true } }); if (superClass) Object.setPrototypeOf ? Object.setPrototypeOf(subClass, superClass) : subClass.__proto__ = superClass; } var _menuMenuButtonJs = _dereq_('../../menu/menu-button.js'); var _menuMenuButtonJs2 = _interopRequireDefault(_menuMenuButtonJs); var _menuMenuJs = _dereq_('../../menu/menu.js'); var _menuMenuJs2 = _interopRequireDefault(_menuMenuJs); var _playbackRateMenuItemJs = _dereq_('./playback-rate-menu-item.js'); var _playbackRateMenuItemJs2 = _interopRequireDefault(_playbackRateMenuItemJs); var _componentJs = _dereq_('../../component.js'); var _componentJs2 = _interopRequireDefault(_componentJs); var _utilsDomJs = _dereq_('../../utils/dom.js'); var Dom = _interopRequireWildcard(_utilsDomJs); /** * The component for controlling the playback rate * * @param {Player|Object} player * @param {Object=} options * @extends MenuButton * @class PlaybackRateMenuButton */ var PlaybackRateMenuButton = (function (_MenuButton) { _inherits(PlaybackRateMenuButton, _MenuButton); function PlaybackRateMenuButton(player, options) { _classCallCheck(this, PlaybackRateMenuButton); _MenuButton.call(this, player, options); this.updateVisibility(); this.updateLabel(); this.on(player, 'loadstart', this.updateVisibility); this.on(player, 'ratechange', this.updateLabel); } /** * Create the component's DOM element * * @return {Element} * @method createEl */ PlaybackRateMenuButton.prototype.createEl = function createEl() { var el = _MenuButton.prototype.createEl.call(this); this.labelEl_ = Dom.createEl('div', { className: 'vjs-playback-rate-value', innerHTML: 1.0 }); el.appendChild(this.labelEl_); return el; }; /** * Allow sub components to stack CSS class names * * @return {String} The constructed class name * @method buildCSSClass */ PlaybackRateMenuButton.prototype.buildCSSClass = function buildCSSClass() { return 'vjs-playback-rate ' + _MenuButton.prototype.buildCSSClass.call(this); }; /** * Create the playback rate menu * * @return {Menu} Menu object populated with items * @method createMenu */ PlaybackRateMenuButton.prototype.createMenu = function createMenu() { var menu = new _menuMenuJs2['default'](this.player()); var rates = this.playbackRates(); if (rates) { for (var i = rates.length - 1; i >= 0; i--) { menu.addChild(new _playbackRateMenuItemJs2['default'](this.player(), { 'rate': rates[i] + 'x' })); } } return menu; }; /** * Updates ARIA accessibility attributes * * @method updateARIAAttributes */ PlaybackRateMenuButton.prototype.updateARIAAttributes = function updateARIAAttributes() { // Current playback rate this.el().setAttribute('aria-valuenow', this.player().playbackRate()); }; /** * Handle menu item click * * @method handleClick */ PlaybackRateMenuButton.prototype.handleClick = function handleClick() { // select next rate option var currentRate = this.player().playbackRate(); var rates = this.playbackRates(); // this will select first one if the last one currently selected var newRate = rates[0]; for (var i = 0; i < rates.length; i++) { if (rates[i] > currentRate) { newRate = rates[i]; break; } } this.player().playbackRate(newRate); }; /** * Get possible playback rates * * @return {Array} Possible playback rates * @method playbackRates */ PlaybackRateMenuButton.prototype.playbackRates = function playbackRates() { return this.options_['playbackRates'] || this.options_.playerOptions && this.options_.playerOptions['playbackRates']; }; /** * Get supported playback rates * * @return {Array} Supported playback rates * @method playbackRateSupported */ PlaybackRateMenuButton.prototype.playbackRateSupported = function playbackRateSupported() { return this.player().tech_ && this.player().tech_['featuresPlaybackRate'] && this.playbackRates() && this.playbackRates().length > 0; }; /** * Hide playback rate controls when they're no playback rate options to select * * @method updateVisibility */ PlaybackRateMenuButton.prototype.updateVisibility = function updateVisibility() { if (this.playbackRateSupported()) { this.removeClass('vjs-hidden'); } else { this.addClass('vjs-hidden'); } }; /** * Update button label when rate changed * * @method updateLabel */ PlaybackRateMenuButton.prototype.updateLabel = function updateLabel() { if (this.playbackRateSupported()) { this.labelEl_.innerHTML = this.player().playbackRate() + 'x'; } }; return PlaybackRateMenuButton; })(_menuMenuButtonJs2['default']); PlaybackRateMenuButton.prototype.controlText_ = 'Playback Rate'; _componentJs2['default'].registerComponent('PlaybackRateMenuButton', PlaybackRateMenuButton); exports['default'] = PlaybackRateMenuButton; module.exports = exports['default']; },{"../../component.js":58,"../../menu/menu-button.js":95,"../../menu/menu.js":97,"../../utils/dom.js":118,"./playback-rate-menu-item.js":65}],65:[function(_dereq_,module,exports){ /** * @file playback-rate-menu-item.js */ 'use strict'; exports.__esModule = true; function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { 'default': obj }; } function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError('Cannot call a class as a function'); } } function _inherits(subClass, superClass) { if (typeof superClass !== 'function' && superClass !== null) { throw new TypeError('Super expression must either be null or a function, not ' + typeof superClass); } subClass.prototype = Object.create(superClass && superClass.prototype, { constructor: { value: subClass, enumerable: false, writable: true, configurable: true } }); if (superClass) Object.setPrototypeOf ? Object.setPrototypeOf(subClass, superClass) : subClass.__proto__ = superClass; } var _menuMenuItemJs = _dereq_('../../menu/menu-item.js'); var _menuMenuItemJs2 = _interopRequireDefault(_menuMenuItemJs); var _componentJs = _dereq_('../../component.js'); var _componentJs2 = _interopRequireDefault(_componentJs); /** * The specific menu item type for selecting a playback rate * * @param {Player|Object} player * @param {Object=} options * @extends MenuItem * @class PlaybackRateMenuItem */ var PlaybackRateMenuItem = (function (_MenuItem) { _inherits(PlaybackRateMenuItem, _MenuItem); function PlaybackRateMenuItem(player, options) { _classCallCheck(this, PlaybackRateMenuItem); var label = options['rate']; var rate = parseFloat(label, 10); // Modify options for parent MenuItem class's init. options['label'] = label; options['selected'] = rate === 1; _MenuItem.call(this, player, options); this.label = label; this.rate = rate; this.on(player, 'ratechange', this.update); } /** * Handle click on menu item * * @method handleClick */ PlaybackRateMenuItem.prototype.handleClick = function handleClick() { _MenuItem.prototype.handleClick.call(this); this.player().playbackRate(this.rate); }; /** * Update playback rate with selected rate * * @method update */ PlaybackRateMenuItem.prototype.update = function update() { this.selected(this.player().playbackRate() === this.rate); }; return PlaybackRateMenuItem; })(_menuMenuItemJs2['default']); PlaybackRateMenuItem.prototype.contentElType = 'button'; _componentJs2['default'].registerComponent('PlaybackRateMenuItem', PlaybackRateMenuItem); exports['default'] = PlaybackRateMenuItem; module.exports = exports['default']; },{"../../component.js":58,"../../menu/menu-item.js":96}],66:[function(_dereq_,module,exports){ /** * @file load-progress-bar.js */ 'use strict'; exports.__esModule = true; function _interopRequireWildcard(obj) { if (obj && obj.__esModule) { return obj; } else { var newObj = {}; if (obj != null) { for (var key in obj) { if (Object.prototype.hasOwnProperty.call(obj, key)) newObj[key] = obj[key]; } } newObj['default'] = obj; return newObj; } } function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { 'default': obj }; } function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError('Cannot call a class as a function'); } } function _inherits(subClass, superClass) { if (typeof superClass !== 'function' && superClass !== null) { throw new TypeError('Super expression must either be null or a function, not ' + typeof superClass); } subClass.prototype = Object.create(superClass && superClass.prototype, { constructor: { value: subClass, enumerable: false, writable: true, configurable: true } }); if (superClass) Object.setPrototypeOf ? Object.setPrototypeOf(subClass, superClass) : subClass.__proto__ = superClass; } var _componentJs = _dereq_('../../component.js'); var _componentJs2 = _interopRequireDefault(_componentJs); var _utilsDomJs = _dereq_('../../utils/dom.js'); var Dom = _interopRequireWildcard(_utilsDomJs); /** * Shows load progress * * @param {Player|Object} player * @param {Object=} options * @extends Component * @class LoadProgressBar */ var LoadProgressBar = (function (_Component) { _inherits(LoadProgressBar, _Component); function LoadProgressBar(player, options) { _classCallCheck(this, LoadProgressBar); _Component.call(this, player, options); this.on(player, 'progress', this.update); } /** * Create the component's DOM element * * @return {Element} * @method createEl */ LoadProgressBar.prototype.createEl = function createEl() { return _Component.prototype.createEl.call(this, 'div', { className: 'vjs-load-progress', innerHTML: '<span class="vjs-control-text"><span>' + this.localize('Loaded') + '</span>: 0%</span>' }); }; /** * Update progress bar * * @method update */ LoadProgressBar.prototype.update = function update() { var buffered = this.player_.buffered(); var duration = this.player_.duration(); var bufferedEnd = this.player_.bufferedEnd(); var children = this.el_.children; // get the percent width of a time compared to the total end var percentify = function percentify(time, end) { var percent = time / end || 0; // no NaN return (percent >= 1 ? 1 : percent) * 100 + '%'; }; // update the width of the progress bar this.el_.style.width = percentify(bufferedEnd, duration); // add child elements to represent the individual buffered time ranges for (var i = 0; i < buffered.length; i++) { var start = buffered.start(i); var end = buffered.end(i); var part = children[i]; if (!part) { part = this.el_.appendChild(Dom.createEl()); } // set the percent based on the width of the progress bar (bufferedEnd) part.style.left = percentify(start, bufferedEnd); part.style.width = percentify(end - start, bufferedEnd); } // remove unused buffered range elements for (var i = children.length; i > buffered.length; i--) { this.el_.removeChild(children[i - 1]); } }; return LoadProgressBar; })(_componentJs2['default']); _componentJs2['default'].registerComponent('LoadProgressBar', LoadProgressBar); exports['default'] = LoadProgressBar; module.exports = exports['default']; },{"../../component.js":58,"../../utils/dom.js":118}],67:[function(_dereq_,module,exports){ /** * @file mouse-time-display.js */ 'use strict'; exports.__esModule = true; function _interopRequireWildcard(obj) { if (obj && obj.__esModule) { return obj; } else { var newObj = {}; if (obj != null) { for (var key in obj) { if (Object.prototype.hasOwnProperty.call(obj, key)) newObj[key] = obj[key]; } } newObj['default'] = obj; return newObj; } } function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { 'default': obj }; } function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError('Cannot call a class as a function'); } } function _inherits(subClass, superClass) { if (typeof superClass !== 'function' && superClass !== null) { throw new TypeError('Super expression must either be null or a function, not ' + typeof superClass); } subClass.prototype = Object.create(superClass && superClass.prototype, { constructor: { value: subClass, enumerable: false, writable: true, configurable: true } }); if (superClass) Object.setPrototypeOf ? Object.setPrototypeOf(subClass, superClass) : subClass.__proto__ = superClass; } var _componentJs = _dereq_('../../component.js'); var _componentJs2 = _interopRequireDefault(_componentJs); var _utilsDomJs = _dereq_('../../utils/dom.js'); var Dom = _interopRequireWildcard(_utilsDomJs); var _utilsFnJs = _dereq_('../../utils/fn.js'); var Fn = _interopRequireWildcard(_utilsFnJs); var _utilsFormatTimeJs = _dereq_('../../utils/format-time.js'); var _utilsFormatTimeJs2 = _interopRequireDefault(_utilsFormatTimeJs); var _lodashCompatFunctionThrottle = _dereq_('lodash-compat/function/throttle'); var _lodashCompatFunctionThrottle2 = _interopRequireDefault(_lodashCompatFunctionThrottle); /** * The Mouse Time Display component shows the time you will seek to * when hovering over the progress bar * * @param {Player|Object} player * @param {Object=} options * @extends Component * @class MouseTimeDisplay */ var MouseTimeDisplay = (function (_Component) { _inherits(MouseTimeDisplay, _Component); function MouseTimeDisplay(player, options) { var _this = this; _classCallCheck(this, MouseTimeDisplay); _Component.call(this, player, options); this.update(0, 0); player.on('ready', function () { _this.on(player.controlBar.progressControl.el(), 'mousemove', _lodashCompatFunctionThrottle2['default'](Fn.bind(_this, _this.handleMouseMove), 25)); }); } /** * Create the component's DOM element * * @return {Element} * @method createEl */ MouseTimeDisplay.prototype.createEl = function createEl() { return _Component.prototype.createEl.call(this, 'div', { className: 'vjs-mouse-display' }); }; MouseTimeDisplay.prototype.handleMouseMove = function handleMouseMove(event) { var duration = this.player_.duration(); var newTime = this.calculateDistance(event) * duration; var position = event.pageX - Dom.findElPosition(this.el().parentNode).left; this.update(newTime, position); }; MouseTimeDisplay.prototype.update = function update(newTime, position) { var time = _utilsFormatTimeJs2['default'](newTime, this.player_.duration()); this.el().style.left = position + 'px'; this.el().setAttribute('data-current-time', time); }; MouseTimeDisplay.prototype.calculateDistance = function calculateDistance(event) { return Dom.getPointerPosition(this.el().parentNode, event).x; }; return MouseTimeDisplay; })(_componentJs2['default']); _componentJs2['default'].registerComponent('MouseTimeDisplay', MouseTimeDisplay); exports['default'] = MouseTimeDisplay; module.exports = exports['default']; },{"../../component.js":58,"../../utils/dom.js":118,"../../utils/fn.js":120,"../../utils/format-time.js":121,"lodash-compat/function/throttle":7}],68:[function(_dereq_,module,exports){ /** * @file play-progress-bar.js */ 'use strict'; exports.__esModule = true; function _interopRequireWildcard(obj) { if (obj && obj.__esModule) { return obj; } else { var newObj = {}; if (obj != null) { for (var key in obj) { if (Object.prototype.hasOwnProperty.call(obj, key)) newObj[key] = obj[key]; } } newObj['default'] = obj; return newObj; } } function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { 'default': obj }; } function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError('Cannot call a class as a function'); } } function _inherits(subClass, superClass) { if (typeof superClass !== 'function' && superClass !== null) { throw new TypeError('Super expression must either be null or a function, not ' + typeof superClass); } subClass.prototype = Object.create(superClass && superClass.prototype, { constructor: { value: subClass, enumerable: false, writable: true, configurable: true } }); if (superClass) Object.setPrototypeOf ? Object.setPrototypeOf(subClass, superClass) : subClass.__proto__ = superClass; } var _componentJs = _dereq_('../../component.js'); var _componentJs2 = _interopRequireDefault(_componentJs); var _utilsFnJs = _dereq_('../../utils/fn.js'); var Fn = _interopRequireWildcard(_utilsFnJs); var _utilsFormatTimeJs = _dereq_('../../utils/format-time.js'); var _utilsFormatTimeJs2 = _interopRequireDefault(_utilsFormatTimeJs); /** * Shows play progress * * @param {Player|Object} player * @param {Object=} options * @extends Component * @class PlayProgressBar */ var PlayProgressBar = (function (_Component) { _inherits(PlayProgressBar, _Component); function PlayProgressBar(player, options) { _classCallCheck(this, PlayProgressBar); _Component.call(this, player, options); this.updateDataAttr(); this.on(player, 'timeupdate', this.updateDataAttr); player.ready(Fn.bind(this, this.updateDataAttr)); } /** * Create the component's DOM element * * @return {Element} * @method createEl */ PlayProgressBar.prototype.createEl = function createEl() { return _Component.prototype.createEl.call(this, 'div', { className: 'vjs-play-progress vjs-slider-bar', innerHTML: '<span class="vjs-control-text"><span>' + this.localize('Progress') + '</span>: 0%</span>' }); }; PlayProgressBar.prototype.updateDataAttr = function updateDataAttr() { var time = this.player_.scrubbing() ? this.player_.getCache().currentTime : this.player_.currentTime(); this.el_.setAttribute('data-current-time', _utilsFormatTimeJs2['default'](time, this.player_.duration())); }; return PlayProgressBar; })(_componentJs2['default']); _componentJs2['default'].registerComponent('PlayProgressBar', PlayProgressBar); exports['default'] = PlayProgressBar; module.exports = exports['default']; },{"../../component.js":58,"../../utils/fn.js":120,"../../utils/format-time.js":121}],69:[function(_dereq_,module,exports){ /** * @file progress-control.js */ 'use strict'; exports.__esModule = true; function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { 'default': obj }; } function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError('Cannot call a class as a function'); } } function _inherits(subClass, superClass) { if (typeof superClass !== 'function' && superClass !== null) { throw new TypeError('Super expression must either be null or a function, not ' + typeof superClass); } subClass.prototype = Object.create(superClass && superClass.prototype, { constructor: { value: subClass, enumerable: false, writable: true, configurable: true } }); if (superClass) Object.setPrototypeOf ? Object.setPrototypeOf(subClass, superClass) : subClass.__proto__ = superClass; } var _componentJs = _dereq_('../../component.js'); var _componentJs2 = _interopRequireDefault(_componentJs); var _seekBarJs = _dereq_('./seek-bar.js'); var _seekBarJs2 = _interopRequireDefault(_seekBarJs); var _mouseTimeDisplayJs = _dereq_('./mouse-time-display.js'); var _mouseTimeDisplayJs2 = _interopRequireDefault(_mouseTimeDisplayJs); /** * The Progress Control component contains the seek bar, load progress, * and play progress * * @param {Player|Object} player * @param {Object=} options * @extends Component * @class ProgressControl */ var ProgressControl = (function (_Component) { _inherits(ProgressControl, _Component); function ProgressControl() { _classCallCheck(this, ProgressControl); _Component.apply(this, arguments); } /** * Create the component's DOM element * * @return {Element} * @method createEl */ ProgressControl.prototype.createEl = function createEl() { return _Component.prototype.createEl.call(this, 'div', { className: 'vjs-progress-control vjs-control' }); }; return ProgressControl; })(_componentJs2['default']); ProgressControl.prototype.options_ = { children: ['seekBar'] }; _componentJs2['default'].registerComponent('ProgressControl', ProgressControl); exports['default'] = ProgressControl; module.exports = exports['default']; },{"../../component.js":58,"./mouse-time-display.js":67,"./seek-bar.js":70}],70:[function(_dereq_,module,exports){ /** * @file seek-bar.js */ 'use strict'; exports.__esModule = true; function _interopRequireWildcard(obj) { if (obj && obj.__esModule) { return obj; } else { var newObj = {}; if (obj != null) { for (var key in obj) { if (Object.prototype.hasOwnProperty.call(obj, key)) newObj[key] = obj[key]; } } newObj['default'] = obj; return newObj; } } function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { 'default': obj }; } function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError('Cannot call a class as a function'); } } function _inherits(subClass, superClass) { if (typeof superClass !== 'function' && superClass !== null) { throw new TypeError('Super expression must either be null or a function, not ' + typeof superClass); } subClass.prototype = Object.create(superClass && superClass.prototype, { constructor: { value: subClass, enumerable: false, writable: true, configurable: true } }); if (superClass) Object.setPrototypeOf ? Object.setPrototypeOf(subClass, superClass) : subClass.__proto__ = superClass; } var _sliderSliderJs = _dereq_('../../slider/slider.js'); var _sliderSliderJs2 = _interopRequireDefault(_sliderSliderJs); var _componentJs = _dereq_('../../component.js'); var _componentJs2 = _interopRequireDefault(_componentJs); var _loadProgressBarJs = _dereq_('./load-progress-bar.js'); var _loadProgressBarJs2 = _interopRequireDefault(_loadProgressBarJs); var _playProgressBarJs = _dereq_('./play-progress-bar.js'); var _playProgressBarJs2 = _interopRequireDefault(_playProgressBarJs); var _utilsFnJs = _dereq_('../../utils/fn.js'); var Fn = _interopRequireWildcard(_utilsFnJs); var _utilsFormatTimeJs = _dereq_('../../utils/format-time.js'); var _utilsFormatTimeJs2 = _interopRequireDefault(_utilsFormatTimeJs); var _objectAssign = _dereq_('object.assign'); var _objectAssign2 = _interopRequireDefault(_objectAssign); /** * Seek Bar and holder for the progress bars * * @param {Player|Object} player * @param {Object=} options * @extends Slider * @class SeekBar */ var SeekBar = (function (_Slider) { _inherits(SeekBar, _Slider); function SeekBar(player, options) { _classCallCheck(this, SeekBar); _Slider.call(this, player, options); this.on(player, 'timeupdate', this.updateARIAAttributes); player.ready(Fn.bind(this, this.updateARIAAttributes)); } /** * Create the component's DOM element * * @return {Element} * @method createEl */ SeekBar.prototype.createEl = function createEl() { return _Slider.prototype.createEl.call(this, 'div', { className: 'vjs-progress-holder' }, { 'aria-label': 'video progress bar' }); }; /** * Update ARIA accessibility attributes * * @method updateARIAAttributes */ SeekBar.prototype.updateARIAAttributes = function updateARIAAttributes() { // Allows for smooth scrubbing, when player can't keep up. var time = this.player_.scrubbing() ? this.player_.getCache().currentTime : this.player_.currentTime(); this.el_.setAttribute('aria-valuenow', (this.getPercent() * 100).toFixed(2)); // machine readable value of progress bar (percentage complete) this.el_.setAttribute('aria-valuetext', _utilsFormatTimeJs2['default'](time, this.player_.duration())); // human readable value of progress bar (time complete) }; /** * Get percentage of video played * * @return {Number} Percentage played * @method getPercent */ SeekBar.prototype.getPercent = function getPercent() { var percent = this.player_.currentTime() / this.player_.duration(); return percent >= 1 ? 1 : percent; }; /** * Handle mouse down on seek bar * * @method handleMouseDown */ SeekBar.prototype.handleMouseDown = function handleMouseDown(event) { _Slider.prototype.handleMouseDown.call(this, event); this.player_.scrubbing(true); this.videoWasPlaying = !this.player_.paused(); this.player_.pause(); }; /** * Handle mouse move on seek bar * * @method handleMouseMove */ SeekBar.prototype.handleMouseMove = function handleMouseMove(event) { var newTime = this.calculateDistance(event) * this.player_.duration(); // Don't let video end while scrubbing. if (newTime === this.player_.duration()) { newTime = newTime - 0.1; } // Set new time (tell player to seek to new time) this.player_.currentTime(newTime); }; /** * Handle mouse up on seek bar * * @method handleMouseUp */ SeekBar.prototype.handleMouseUp = function handleMouseUp(event) { _Slider.prototype.handleMouseUp.call(this, event); this.player_.scrubbing(false); if (this.videoWasPlaying) { this.player_.play(); } }; /** * Move more quickly fast forward for keyboard-only users * * @method stepForward */ SeekBar.prototype.stepForward = function stepForward() { this.player_.currentTime(this.player_.currentTime() + 5); // more quickly fast forward for keyboard-only users }; /** * Move more quickly rewind for keyboard-only users * * @method stepBack */ SeekBar.prototype.stepBack = function stepBack() { this.player_.currentTime(this.player_.currentTime() - 5); // more quickly rewind for keyboard-only users }; return SeekBar; })(_sliderSliderJs2['default']); SeekBar.prototype.options_ = { children: ['loadProgressBar', 'mouseTimeDisplay', 'playProgressBar'], 'barName': 'playProgressBar' }; SeekBar.prototype.playerEvent = 'timeupdate'; _componentJs2['default'].registerComponent('SeekBar', SeekBar); exports['default'] = SeekBar; module.exports = exports['default']; },{"../../component.js":58,"../../slider/slider.js":102,"../../utils/fn.js":120,"../../utils/format-time.js":121,"./load-progress-bar.js":66,"./play-progress-bar.js":68,"object.assign":43}],71:[function(_dereq_,module,exports){ /** * @file custom-control-spacer.js */ 'use strict'; exports.__esModule = true; function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { 'default': obj }; } function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError('Cannot call a class as a function'); } } function _inherits(subClass, superClass) { if (typeof superClass !== 'function' && superClass !== null) { throw new TypeError('Super expression must either be null or a function, not ' + typeof superClass); } subClass.prototype = Object.create(superClass && superClass.prototype, { constructor: { value: subClass, enumerable: false, writable: true, configurable: true } }); if (superClass) Object.setPrototypeOf ? Object.setPrototypeOf(subClass, superClass) : subClass.__proto__ = superClass; } var _spacerJs = _dereq_('./spacer.js'); var _spacerJs2 = _interopRequireDefault(_spacerJs); var _componentJs = _dereq_('../../component.js'); var _componentJs2 = _interopRequireDefault(_componentJs); /** * Spacer specifically meant to be used as an insertion point for new plugins, etc. * * @extends Spacer * @class CustomControlSpacer */ var CustomControlSpacer = (function (_Spacer) { _inherits(CustomControlSpacer, _Spacer); function CustomControlSpacer() { _classCallCheck(this, CustomControlSpacer); _Spacer.apply(this, arguments); } /** * Allow sub components to stack CSS class names * * @return {String} The constructed class name * @method buildCSSClass */ CustomControlSpacer.prototype.buildCSSClass = function buildCSSClass() { return 'vjs-custom-control-spacer ' + _Spacer.prototype.buildCSSClass.call(this); }; /** * Create the component's DOM element * * @return {Element} * @method createEl */ CustomControlSpacer.prototype.createEl = function createEl() { var el = _Spacer.prototype.createEl.call(this, { className: this.buildCSSClass() }); // No-flex/table-cell mode requires there be some content // in the cell to fill the remaining space of the table. el.innerHTML = '&nbsp;'; return el; }; return CustomControlSpacer; })(_spacerJs2['default']); _componentJs2['default'].registerComponent('CustomControlSpacer', CustomControlSpacer); exports['default'] = CustomControlSpacer; module.exports = exports['default']; },{"../../component.js":58,"./spacer.js":72}],72:[function(_dereq_,module,exports){ /** * @file spacer.js */ 'use strict'; exports.__esModule = true; function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { 'default': obj }; } function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError('Cannot call a class as a function'); } } function _inherits(subClass, superClass) { if (typeof superClass !== 'function' && superClass !== null) { throw new TypeError('Super expression must either be null or a function, not ' + typeof superClass); } subClass.prototype = Object.create(superClass && superClass.prototype, { constructor: { value: subClass, enumerable: false, writable: true, configurable: true } }); if (superClass) Object.setPrototypeOf ? Object.setPrototypeOf(subClass, superClass) : subClass.__proto__ = superClass; } var _componentJs = _dereq_('../../component.js'); var _componentJs2 = _interopRequireDefault(_componentJs); /** * Just an empty spacer element that can be used as an append point for plugins, etc. * Also can be used to create space between elements when necessary. * * @extends Component * @class Spacer */ var Spacer = (function (_Component) { _inherits(Spacer, _Component); function Spacer() { _classCallCheck(this, Spacer); _Component.apply(this, arguments); } /** * Allow sub components to stack CSS class names * * @return {String} The constructed class name * @method buildCSSClass */ Spacer.prototype.buildCSSClass = function buildCSSClass() { return 'vjs-spacer ' + _Component.prototype.buildCSSClass.call(this); }; /** * Create the component's DOM element * * @return {Element} * @method createEl */ Spacer.prototype.createEl = function createEl() { return _Component.prototype.createEl.call(this, 'div', { className: this.buildCSSClass() }); }; return Spacer; })(_componentJs2['default']); _componentJs2['default'].registerComponent('Spacer', Spacer); exports['default'] = Spacer; module.exports = exports['default']; },{"../../component.js":58}],73:[function(_dereq_,module,exports){ /** * @file caption-settings-menu-item.js */ 'use strict'; exports.__esModule = true; function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { 'default': obj }; } function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError('Cannot call a class as a function'); } } function _inherits(subClass, superClass) { if (typeof superClass !== 'function' && superClass !== null) { throw new TypeError('Super expression must either be null or a function, not ' + typeof superClass); } subClass.prototype = Object.create(superClass && superClass.prototype, { constructor: { value: subClass, enumerable: false, writable: true, configurable: true } }); if (superClass) Object.setPrototypeOf ? Object.setPrototypeOf(subClass, superClass) : subClass.__proto__ = superClass; } var _textTrackMenuItemJs = _dereq_('./text-track-menu-item.js'); var _textTrackMenuItemJs2 = _interopRequireDefault(_textTrackMenuItemJs); var _componentJs = _dereq_('../../component.js'); var _componentJs2 = _interopRequireDefault(_componentJs); /** * The menu item for caption track settings menu * * @param {Player|Object} player * @param {Object=} options * @extends TextTrackMenuItem * @class CaptionSettingsMenuItem */ var CaptionSettingsMenuItem = (function (_TextTrackMenuItem) { _inherits(CaptionSettingsMenuItem, _TextTrackMenuItem); function CaptionSettingsMenuItem(player, options) { _classCallCheck(this, CaptionSettingsMenuItem); options['track'] = { 'kind': options['kind'], 'player': player, 'label': options['kind'] + ' settings', 'default': false, mode: 'disabled' }; _TextTrackMenuItem.call(this, player, options); this.addClass('vjs-texttrack-settings'); } /** * Handle click on menu item * * @method handleClick */ CaptionSettingsMenuItem.prototype.handleClick = function handleClick() { this.player().getChild('textTrackSettings').show(); }; return CaptionSettingsMenuItem; })(_textTrackMenuItemJs2['default']); _componentJs2['default'].registerComponent('CaptionSettingsMenuItem', CaptionSettingsMenuItem); exports['default'] = CaptionSettingsMenuItem; module.exports = exports['default']; },{"../../component.js":58,"./text-track-menu-item.js":80}],74:[function(_dereq_,module,exports){ /** * @file captions-button.js */ 'use strict'; exports.__esModule = true; function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { 'default': obj }; } function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError('Cannot call a class as a function'); } } function _inherits(subClass, superClass) { if (typeof superClass !== 'function' && superClass !== null) { throw new TypeError('Super expression must either be null or a function, not ' + typeof superClass); } subClass.prototype = Object.create(superClass && superClass.prototype, { constructor: { value: subClass, enumerable: false, writable: true, configurable: true } }); if (superClass) Object.setPrototypeOf ? Object.setPrototypeOf(subClass, superClass) : subClass.__proto__ = superClass; } var _textTrackButtonJs = _dereq_('./text-track-button.js'); var _textTrackButtonJs2 = _interopRequireDefault(_textTrackButtonJs); var _componentJs = _dereq_('../../component.js'); var _componentJs2 = _interopRequireDefault(_componentJs); var _captionSettingsMenuItemJs = _dereq_('./caption-settings-menu-item.js'); var _captionSettingsMenuItemJs2 = _interopRequireDefault(_captionSettingsMenuItemJs); /** * The button component for toggling and selecting captions * * @param {Object} player Player object * @param {Object=} options Object of option names and values * @param {Function=} ready Ready callback function * @extends TextTrackButton * @class CaptionsButton */ var CaptionsButton = (function (_TextTrackButton) { _inherits(CaptionsButton, _TextTrackButton); function CaptionsButton(player, options, ready) { _classCallCheck(this, CaptionsButton); _TextTrackButton.call(this, player, options, ready); this.el_.setAttribute('aria-label', 'Captions Menu'); } /** * Allow sub components to stack CSS class names * * @return {String} The constructed class name * @method buildCSSClass */ CaptionsButton.prototype.buildCSSClass = function buildCSSClass() { return 'vjs-captions-button ' + _TextTrackButton.prototype.buildCSSClass.call(this); }; /** * Update caption menu items * * @method update */ CaptionsButton.prototype.update = function update() { var threshold = 2; _TextTrackButton.prototype.update.call(this); // if native, then threshold is 1 because no settings button if (this.player().tech_ && this.player().tech_['featuresNativeTextTracks']) { threshold = 1; } if (this.items && this.items.length > threshold) { this.show(); } else { this.hide(); } }; /** * Create caption menu items * * @return {Array} Array of menu items * @method createItems */ CaptionsButton.prototype.createItems = function createItems() { var items = []; if (!(this.player().tech_ && this.player().tech_['featuresNativeTextTracks'])) { items.push(new _captionSettingsMenuItemJs2['default'](this.player_, { 'kind': this.kind_ })); } return _TextTrackButton.prototype.createItems.call(this, items); }; return CaptionsButton; })(_textTrackButtonJs2['default']); CaptionsButton.prototype.kind_ = 'captions'; CaptionsButton.prototype.controlText_ = 'Captions'; _componentJs2['default'].registerComponent('CaptionsButton', CaptionsButton); exports['default'] = CaptionsButton; module.exports = exports['default']; },{"../../component.js":58,"./caption-settings-menu-item.js":73,"./text-track-button.js":79}],75:[function(_dereq_,module,exports){ /** * @file chapters-button.js */ 'use strict'; exports.__esModule = true; function _interopRequireWildcard(obj) { if (obj && obj.__esModule) { return obj; } else { var newObj = {}; if (obj != null) { for (var key in obj) { if (Object.prototype.hasOwnProperty.call(obj, key)) newObj[key] = obj[key]; } } newObj['default'] = obj; return newObj; } } function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { 'default': obj }; } function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError('Cannot call a class as a function'); } } function _inherits(subClass, superClass) { if (typeof superClass !== 'function' && superClass !== null) { throw new TypeError('Super expression must either be null or a function, not ' + typeof superClass); } subClass.prototype = Object.create(superClass && superClass.prototype, { constructor: { value: subClass, enumerable: false, writable: true, configurable: true } }); if (superClass) Object.setPrototypeOf ? Object.setPrototypeOf(subClass, superClass) : subClass.__proto__ = superClass; } var _textTrackButtonJs = _dereq_('./text-track-button.js'); var _textTrackButtonJs2 = _interopRequireDefault(_textTrackButtonJs); var _componentJs = _dereq_('../../component.js'); var _componentJs2 = _interopRequireDefault(_componentJs); var _textTrackMenuItemJs = _dereq_('./text-track-menu-item.js'); var _textTrackMenuItemJs2 = _interopRequireDefault(_textTrackMenuItemJs); var _chaptersTrackMenuItemJs = _dereq_('./chapters-track-menu-item.js'); var _chaptersTrackMenuItemJs2 = _interopRequireDefault(_chaptersTrackMenuItemJs); var _menuMenuJs = _dereq_('../../menu/menu.js'); var _menuMenuJs2 = _interopRequireDefault(_menuMenuJs); var _utilsDomJs = _dereq_('../../utils/dom.js'); var Dom = _interopRequireWildcard(_utilsDomJs); var _utilsFnJs = _dereq_('../../utils/fn.js'); var Fn = _interopRequireWildcard(_utilsFnJs); var _utilsToTitleCaseJs = _dereq_('../../utils/to-title-case.js'); var _utilsToTitleCaseJs2 = _interopRequireDefault(_utilsToTitleCaseJs); var _globalWindow = _dereq_('global/window'); var _globalWindow2 = _interopRequireDefault(_globalWindow); /** * The button component for toggling and selecting chapters * Chapters act much differently than other text tracks * Cues are navigation vs. other tracks of alternative languages * * @param {Object} player Player object * @param {Object=} options Object of option names and values * @param {Function=} ready Ready callback function * @extends TextTrackButton * @class ChaptersButton */ var ChaptersButton = (function (_TextTrackButton) { _inherits(ChaptersButton, _TextTrackButton); function ChaptersButton(player, options, ready) { _classCallCheck(this, ChaptersButton); _TextTrackButton.call(this, player, options, ready); this.el_.setAttribute('aria-label', 'Chapters Menu'); } /** * Allow sub components to stack CSS class names * * @return {String} The constructed class name * @method buildCSSClass */ ChaptersButton.prototype.buildCSSClass = function buildCSSClass() { return 'vjs-chapters-button ' + _TextTrackButton.prototype.buildCSSClass.call(this); }; /** * Create a menu item for each text track * * @return {Array} Array of menu items * @method createItems */ ChaptersButton.prototype.createItems = function createItems() { var items = []; var tracks = this.player_.textTracks(); if (!tracks) { return items; } for (var i = 0; i < tracks.length; i++) { var track = tracks[i]; if (track['kind'] === this.kind_) { items.push(new _textTrackMenuItemJs2['default'](this.player_, { 'track': track })); } } return items; }; /** * Create menu from chapter buttons * * @return {Menu} Menu of chapter buttons * @method createMenu */ ChaptersButton.prototype.createMenu = function createMenu() { var tracks = this.player_.textTracks() || []; var chaptersTrack = undefined; var items = this.items = []; for (var i = 0, l = tracks.length; i < l; i++) { var track = tracks[i]; if (track['kind'] === this.kind_) { if (!track.cues) { track['mode'] = 'hidden'; /* jshint loopfunc:true */ // TODO see if we can figure out a better way of doing this https://github.com/videojs/video.js/issues/1864 _globalWindow2['default'].setTimeout(Fn.bind(this, function () { this.createMenu(); }), 100); /* jshint loopfunc:false */ } else { chaptersTrack = track; break; } } } var menu = this.menu; if (menu === undefined) { menu = new _menuMenuJs2['default'](this.player_); menu.contentEl().appendChild(Dom.createEl('li', { className: 'vjs-menu-title', innerHTML: _utilsToTitleCaseJs2['default'](this.kind_), tabIndex: -1 })); } if (chaptersTrack) { var cues = chaptersTrack['cues'], cue = undefined; for (var i = 0, l = cues.length; i < l; i++) { cue = cues[i]; var mi = new _chaptersTrackMenuItemJs2['default'](this.player_, { 'track': chaptersTrack, 'cue': cue }); items.push(mi); menu.addChild(mi); } this.addChild(menu); } if (this.items.length > 0) { this.show(); } return menu; }; return ChaptersButton; })(_textTrackButtonJs2['default']); ChaptersButton.prototype.kind_ = 'chapters'; ChaptersButton.prototype.controlText_ = 'Chapters'; _componentJs2['default'].registerComponent('ChaptersButton', ChaptersButton); exports['default'] = ChaptersButton; module.exports = exports['default']; },{"../../component.js":58,"../../menu/menu.js":97,"../../utils/dom.js":118,"../../utils/fn.js":120,"../../utils/to-title-case.js":127,"./chapters-track-menu-item.js":76,"./text-track-button.js":79,"./text-track-menu-item.js":80,"global/window":2}],76:[function(_dereq_,module,exports){ /** * @file chapters-track-menu-item.js */ 'use strict'; exports.__esModule = true; function _interopRequireWildcard(obj) { if (obj && obj.__esModule) { return obj; } else { var newObj = {}; if (obj != null) { for (var key in obj) { if (Object.prototype.hasOwnProperty.call(obj, key)) newObj[key] = obj[key]; } } newObj['default'] = obj; return newObj; } } function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { 'default': obj }; } function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError('Cannot call a class as a function'); } } function _inherits(subClass, superClass) { if (typeof superClass !== 'function' && superClass !== null) { throw new TypeError('Super expression must either be null or a function, not ' + typeof superClass); } subClass.prototype = Object.create(superClass && superClass.prototype, { constructor: { value: subClass, enumerable: false, writable: true, configurable: true } }); if (superClass) Object.setPrototypeOf ? Object.setPrototypeOf(subClass, superClass) : subClass.__proto__ = superClass; } var _menuMenuItemJs = _dereq_('../../menu/menu-item.js'); var _menuMenuItemJs2 = _interopRequireDefault(_menuMenuItemJs); var _componentJs = _dereq_('../../component.js'); var _componentJs2 = _interopRequireDefault(_componentJs); var _utilsFnJs = _dereq_('../../utils/fn.js'); var Fn = _interopRequireWildcard(_utilsFnJs); /** * The chapter track menu item * * @param {Player|Object} player * @param {Object=} options * @extends MenuItem * @class ChaptersTrackMenuItem */ var ChaptersTrackMenuItem = (function (_MenuItem) { _inherits(ChaptersTrackMenuItem, _MenuItem); function ChaptersTrackMenuItem(player, options) { _classCallCheck(this, ChaptersTrackMenuItem); var track = options['track']; var cue = options['cue']; var currentTime = player.currentTime(); // Modify options for parent MenuItem class's init. options['label'] = cue.text; options['selected'] = cue['startTime'] <= currentTime && currentTime < cue['endTime']; _MenuItem.call(this, player, options); this.track = track; this.cue = cue; track.addEventListener('cuechange', Fn.bind(this, this.update)); } /** * Handle click on menu item * * @method handleClick */ ChaptersTrackMenuItem.prototype.handleClick = function handleClick() { _MenuItem.prototype.handleClick.call(this); this.player_.currentTime(this.cue.startTime); this.update(this.cue.startTime); }; /** * Update chapter menu item * * @method update */ ChaptersTrackMenuItem.prototype.update = function update() { var cue = this.cue; var currentTime = this.player_.currentTime(); // vjs.log(currentTime, cue.startTime); this.selected(cue['startTime'] <= currentTime && currentTime < cue['endTime']); }; return ChaptersTrackMenuItem; })(_menuMenuItemJs2['default']); _componentJs2['default'].registerComponent('ChaptersTrackMenuItem', ChaptersTrackMenuItem); exports['default'] = ChaptersTrackMenuItem; module.exports = exports['default']; },{"../../component.js":58,"../../menu/menu-item.js":96,"../../utils/fn.js":120}],77:[function(_dereq_,module,exports){ /** * @file off-text-track-menu-item.js */ 'use strict'; exports.__esModule = true; function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { 'default': obj }; } function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError('Cannot call a class as a function'); } } function _inherits(subClass, superClass) { if (typeof superClass !== 'function' && superClass !== null) { throw new TypeError('Super expression must either be null or a function, not ' + typeof superClass); } subClass.prototype = Object.create(superClass && superClass.prototype, { constructor: { value: subClass, enumerable: false, writable: true, configurable: true } }); if (superClass) Object.setPrototypeOf ? Object.setPrototypeOf(subClass, superClass) : subClass.__proto__ = superClass; } var _textTrackMenuItemJs = _dereq_('./text-track-menu-item.js'); var _textTrackMenuItemJs2 = _interopRequireDefault(_textTrackMenuItemJs); var _componentJs = _dereq_('../../component.js'); var _componentJs2 = _interopRequireDefault(_componentJs); /** * A special menu item for turning of a specific type of text track * * @param {Player|Object} player * @param {Object=} options * @extends TextTrackMenuItem * @class OffTextTrackMenuItem */ var OffTextTrackMenuItem = (function (_TextTrackMenuItem) { _inherits(OffTextTrackMenuItem, _TextTrackMenuItem); function OffTextTrackMenuItem(player, options) { _classCallCheck(this, OffTextTrackMenuItem); // Create pseudo track info // Requires options['kind'] options['track'] = { 'kind': options['kind'], 'player': player, 'label': options['kind'] + ' off', 'default': false, 'mode': 'disabled' }; _TextTrackMenuItem.call(this, player, options); this.selected(true); } /** * Handle text track change * * @param {Object} event Event object * @method handleTracksChange */ OffTextTrackMenuItem.prototype.handleTracksChange = function handleTracksChange(event) { var tracks = this.player().textTracks(); var selected = true; for (var i = 0, l = tracks.length; i < l; i++) { var track = tracks[i]; if (track['kind'] === this.track['kind'] && track['mode'] === 'showing') { selected = false; break; } } this.selected(selected); }; return OffTextTrackMenuItem; })(_textTrackMenuItemJs2['default']); _componentJs2['default'].registerComponent('OffTextTrackMenuItem', OffTextTrackMenuItem); exports['default'] = OffTextTrackMenuItem; module.exports = exports['default']; },{"../../component.js":58,"./text-track-menu-item.js":80}],78:[function(_dereq_,module,exports){ /** * @file subtitles-button.js */ 'use strict'; exports.__esModule = true; function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { 'default': obj }; } function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError('Cannot call a class as a function'); } } function _inherits(subClass, superClass) { if (typeof superClass !== 'function' && superClass !== null) { throw new TypeError('Super expression must either be null or a function, not ' + typeof superClass); } subClass.prototype = Object.create(superClass && superClass.prototype, { constructor: { value: subClass, enumerable: false, writable: true, configurable: true } }); if (superClass) Object.setPrototypeOf ? Object.setPrototypeOf(subClass, superClass) : subClass.__proto__ = superClass; } var _textTrackButtonJs = _dereq_('./text-track-button.js'); var _textTrackButtonJs2 = _interopRequireDefault(_textTrackButtonJs); var _componentJs = _dereq_('../../component.js'); var _componentJs2 = _interopRequireDefault(_componentJs); /** * The button component for toggling and selecting subtitles * * @param {Object} player Player object * @param {Object=} options Object of option names and values * @param {Function=} ready Ready callback function * @extends TextTrackButton * @class SubtitlesButton */ var SubtitlesButton = (function (_TextTrackButton) { _inherits(SubtitlesButton, _TextTrackButton); function SubtitlesButton(player, options, ready) { _classCallCheck(this, SubtitlesButton); _TextTrackButton.call(this, player, options, ready); this.el_.setAttribute('aria-label', 'Subtitles Menu'); } /** * Allow sub components to stack CSS class names * * @return {String} The constructed class name * @method buildCSSClass */ SubtitlesButton.prototype.buildCSSClass = function buildCSSClass() { return 'vjs-subtitles-button ' + _TextTrackButton.prototype.buildCSSClass.call(this); }; return SubtitlesButton; })(_textTrackButtonJs2['default']); SubtitlesButton.prototype.kind_ = 'subtitles'; SubtitlesButton.prototype.controlText_ = 'Subtitles'; _componentJs2['default'].registerComponent('SubtitlesButton', SubtitlesButton); exports['default'] = SubtitlesButton; module.exports = exports['default']; },{"../../component.js":58,"./text-track-button.js":79}],79:[function(_dereq_,module,exports){ /** * @file text-track-button.js */ 'use strict'; exports.__esModule = true; function _interopRequireWildcard(obj) { if (obj && obj.__esModule) { return obj; } else { var newObj = {}; if (obj != null) { for (var key in obj) { if (Object.prototype.hasOwnProperty.call(obj, key)) newObj[key] = obj[key]; } } newObj['default'] = obj; return newObj; } } function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { 'default': obj }; } function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError('Cannot call a class as a function'); } } function _inherits(subClass, superClass) { if (typeof superClass !== 'function' && superClass !== null) { throw new TypeError('Super expression must either be null or a function, not ' + typeof superClass); } subClass.prototype = Object.create(superClass && superClass.prototype, { constructor: { value: subClass, enumerable: false, writable: true, configurable: true } }); if (superClass) Object.setPrototypeOf ? Object.setPrototypeOf(subClass, superClass) : subClass.__proto__ = superClass; } var _menuMenuButtonJs = _dereq_('../../menu/menu-button.js'); var _menuMenuButtonJs2 = _interopRequireDefault(_menuMenuButtonJs); var _componentJs = _dereq_('../../component.js'); var _componentJs2 = _interopRequireDefault(_componentJs); var _utilsFnJs = _dereq_('../../utils/fn.js'); var Fn = _interopRequireWildcard(_utilsFnJs); var _textTrackMenuItemJs = _dereq_('./text-track-menu-item.js'); var _textTrackMenuItemJs2 = _interopRequireDefault(_textTrackMenuItemJs); var _offTextTrackMenuItemJs = _dereq_('./off-text-track-menu-item.js'); var _offTextTrackMenuItemJs2 = _interopRequireDefault(_offTextTrackMenuItemJs); /** * The base class for buttons that toggle specific text track types (e.g. subtitles) * * @param {Player|Object} player * @param {Object=} options * @extends MenuButton * @class TextTrackButton */ var TextTrackButton = (function (_MenuButton) { _inherits(TextTrackButton, _MenuButton); function TextTrackButton(player, options) { _classCallCheck(this, TextTrackButton); _MenuButton.call(this, player, options); var tracks = this.player_.textTracks(); if (this.items.length <= 1) { this.hide(); } if (!tracks) { return; } var updateHandler = Fn.bind(this, this.update); tracks.addEventListener('removetrack', updateHandler); tracks.addEventListener('addtrack', updateHandler); this.player_.on('dispose', function () { tracks.removeEventListener('removetrack', updateHandler); tracks.removeEventListener('addtrack', updateHandler); }); } // Create a menu item for each text track TextTrackButton.prototype.createItems = function createItems() { var items = arguments.length <= 0 || arguments[0] === undefined ? [] : arguments[0]; // Add an OFF menu item to turn all tracks off items.push(new _offTextTrackMenuItemJs2['default'](this.player_, { 'kind': this.kind_ })); var tracks = this.player_.textTracks(); if (!tracks) { return items; } for (var i = 0; i < tracks.length; i++) { var track = tracks[i]; // only add tracks that are of the appropriate kind and have a label if (track['kind'] === this.kind_) { items.push(new _textTrackMenuItemJs2['default'](this.player_, { 'track': track })); } } return items; }; return TextTrackButton; })(_menuMenuButtonJs2['default']); _componentJs2['default'].registerComponent('TextTrackButton', TextTrackButton); exports['default'] = TextTrackButton; module.exports = exports['default']; },{"../../component.js":58,"../../menu/menu-button.js":95,"../../utils/fn.js":120,"./off-text-track-menu-item.js":77,"./text-track-menu-item.js":80}],80:[function(_dereq_,module,exports){ /** * @file text-track-menu-item.js */ 'use strict'; exports.__esModule = true; function _interopRequireWildcard(obj) { if (obj && obj.__esModule) { return obj; } else { var newObj = {}; if (obj != null) { for (var key in obj) { if (Object.prototype.hasOwnProperty.call(obj, key)) newObj[key] = obj[key]; } } newObj['default'] = obj; return newObj; } } function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { 'default': obj }; } function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError('Cannot call a class as a function'); } } function _inherits(subClass, superClass) { if (typeof superClass !== 'function' && superClass !== null) { throw new TypeError('Super expression must either be null or a function, not ' + typeof superClass); } subClass.prototype = Object.create(superClass && superClass.prototype, { constructor: { value: subClass, enumerable: false, writable: true, configurable: true } }); if (superClass) Object.setPrototypeOf ? Object.setPrototypeOf(subClass, superClass) : subClass.__proto__ = superClass; } var _menuMenuItemJs = _dereq_('../../menu/menu-item.js'); var _menuMenuItemJs2 = _interopRequireDefault(_menuMenuItemJs); var _componentJs = _dereq_('../../component.js'); var _componentJs2 = _interopRequireDefault(_componentJs); var _utilsFnJs = _dereq_('../../utils/fn.js'); var Fn = _interopRequireWildcard(_utilsFnJs); var _globalWindow = _dereq_('global/window'); var _globalWindow2 = _interopRequireDefault(_globalWindow); var _globalDocument = _dereq_('global/document'); var _globalDocument2 = _interopRequireDefault(_globalDocument); /** * The specific menu item type for selecting a language within a text track kind * * @param {Player|Object} player * @param {Object=} options * @extends MenuItem * @class TextTrackMenuItem */ var TextTrackMenuItem = (function (_MenuItem) { _inherits(TextTrackMenuItem, _MenuItem); function TextTrackMenuItem(player, options) { var _this = this; _classCallCheck(this, TextTrackMenuItem); var track = options['track']; var tracks = player.textTracks(); // Modify options for parent MenuItem class's init. options['label'] = track['label'] || track['language'] || 'Unknown'; options['selected'] = track['default'] || track['mode'] === 'showing'; _MenuItem.call(this, player, options); this.track = track; if (tracks) { (function () { var changeHandler = Fn.bind(_this, _this.handleTracksChange); tracks.addEventListener('change', changeHandler); _this.on('dispose', function () { tracks.removeEventListener('change', changeHandler); }); })(); } // iOS7 doesn't dispatch change events to TextTrackLists when an // associated track's mode changes. Without something like // Object.observe() (also not present on iOS7), it's not // possible to detect changes to the mode attribute and polyfill // the change event. As a poor substitute, we manually dispatch // change events whenever the controls modify the mode. if (tracks && tracks.onchange === undefined) { (function () { var event = undefined; _this.on(['tap', 'click'], function () { if (typeof _globalWindow2['default'].Event !== 'object') { // Android 2.3 throws an Illegal Constructor error for window.Event try { event = new _globalWindow2['default'].Event('change'); } catch (err) {} } if (!event) { event = _globalDocument2['default'].createEvent('Event'); event.initEvent('change', true, true); } tracks.dispatchEvent(event); }); })(); } } /** * Handle click on text track * * @method handleClick */ TextTrackMenuItem.prototype.handleClick = function handleClick(event) { var kind = this.track['kind']; var tracks = this.player_.textTracks(); _MenuItem.prototype.handleClick.call(this, event); if (!tracks) return; for (var i = 0; i < tracks.length; i++) { var track = tracks[i]; if (track['kind'] !== kind) { continue; } if (track === this.track) { track['mode'] = 'showing'; } else { track['mode'] = 'disabled'; } } }; /** * Handle text track change * * @method handleTracksChange */ TextTrackMenuItem.prototype.handleTracksChange = function handleTracksChange(event) { this.selected(this.track['mode'] === 'showing'); }; return TextTrackMenuItem; })(_menuMenuItemJs2['default']); _componentJs2['default'].registerComponent('TextTrackMenuItem', TextTrackMenuItem); exports['default'] = TextTrackMenuItem; module.exports = exports['default']; },{"../../component.js":58,"../../menu/menu-item.js":96,"../../utils/fn.js":120,"global/document":1,"global/window":2}],81:[function(_dereq_,module,exports){ /** * @file current-time-display.js */ 'use strict'; exports.__esModule = true; function _interopRequireWildcard(obj) { if (obj && obj.__esModule) { return obj; } else { var newObj = {}; if (obj != null) { for (var key in obj) { if (Object.prototype.hasOwnProperty.call(obj, key)) newObj[key] = obj[key]; } } newObj['default'] = obj; return newObj; } } function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { 'default': obj }; } function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError('Cannot call a class as a function'); } } function _inherits(subClass, superClass) { if (typeof superClass !== 'function' && superClass !== null) { throw new TypeError('Super expression must either be null or a function, not ' + typeof superClass); } subClass.prototype = Object.create(superClass && superClass.prototype, { constructor: { value: subClass, enumerable: false, writable: true, configurable: true } }); if (superClass) Object.setPrototypeOf ? Object.setPrototypeOf(subClass, superClass) : subClass.__proto__ = superClass; } var _componentJs = _dereq_('../../component.js'); var _componentJs2 = _interopRequireDefault(_componentJs); var _utilsDomJs = _dereq_('../../utils/dom.js'); var Dom = _interopRequireWildcard(_utilsDomJs); var _utilsFormatTimeJs = _dereq_('../../utils/format-time.js'); var _utilsFormatTimeJs2 = _interopRequireDefault(_utilsFormatTimeJs); /** * Displays the current time * * @param {Player|Object} player * @param {Object=} options * @extends Component * @class CurrentTimeDisplay */ var CurrentTimeDisplay = (function (_Component) { _inherits(CurrentTimeDisplay, _Component); function CurrentTimeDisplay(player, options) { _classCallCheck(this, CurrentTimeDisplay); _Component.call(this, player, options); this.on(player, 'timeupdate', this.updateContent); } /** * Create the component's DOM element * * @return {Element} * @method createEl */ CurrentTimeDisplay.prototype.createEl = function createEl() { var el = _Component.prototype.createEl.call(this, 'div', { className: 'vjs-current-time vjs-time-control vjs-control' }); this.contentEl_ = Dom.createEl('div', { className: 'vjs-current-time-display', // label the current time for screen reader users innerHTML: '<span class="vjs-control-text">Current Time </span>' + '0:00' }, { // tell screen readers not to automatically read the time as it changes 'aria-live': 'off' }); el.appendChild(this.contentEl_); return el; }; /** * Update current time display * * @method updateContent */ CurrentTimeDisplay.prototype.updateContent = function updateContent() { // Allows for smooth scrubbing, when player can't keep up. var time = this.player_.scrubbing() ? this.player_.getCache().currentTime : this.player_.currentTime(); var localizedText = this.localize('Current Time'); var formattedTime = _utilsFormatTimeJs2['default'](time, this.player_.duration()); this.contentEl_.innerHTML = '<span class="vjs-control-text">' + localizedText + '</span> ' + formattedTime; }; return CurrentTimeDisplay; })(_componentJs2['default']); _componentJs2['default'].registerComponent('CurrentTimeDisplay', CurrentTimeDisplay); exports['default'] = CurrentTimeDisplay; module.exports = exports['default']; },{"../../component.js":58,"../../utils/dom.js":118,"../../utils/format-time.js":121}],82:[function(_dereq_,module,exports){ /** * @file duration-display.js */ 'use strict'; exports.__esModule = true; function _interopRequireWildcard(obj) { if (obj && obj.__esModule) { return obj; } else { var newObj = {}; if (obj != null) { for (var key in obj) { if (Object.prototype.hasOwnProperty.call(obj, key)) newObj[key] = obj[key]; } } newObj['default'] = obj; return newObj; } } function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { 'default': obj }; } function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError('Cannot call a class as a function'); } } function _inherits(subClass, superClass) { if (typeof superClass !== 'function' && superClass !== null) { throw new TypeError('Super expression must either be null or a function, not ' + typeof superClass); } subClass.prototype = Object.create(superClass && superClass.prototype, { constructor: { value: subClass, enumerable: false, writable: true, configurable: true } }); if (superClass) Object.setPrototypeOf ? Object.setPrototypeOf(subClass, superClass) : subClass.__proto__ = superClass; } var _componentJs = _dereq_('../../component.js'); var _componentJs2 = _interopRequireDefault(_componentJs); var _utilsDomJs = _dereq_('../../utils/dom.js'); var Dom = _interopRequireWildcard(_utilsDomJs); var _utilsFormatTimeJs = _dereq_('../../utils/format-time.js'); var _utilsFormatTimeJs2 = _interopRequireDefault(_utilsFormatTimeJs); /** * Displays the duration * * @param {Player|Object} player * @param {Object=} options * @extends Component * @class DurationDisplay */ var DurationDisplay = (function (_Component) { _inherits(DurationDisplay, _Component); function DurationDisplay(player, options) { _classCallCheck(this, DurationDisplay); _Component.call(this, player, options); // this might need to be changed to 'durationchange' instead of 'timeupdate' eventually, // however the durationchange event fires before this.player_.duration() is set, // so the value cannot be written out using this method. // Once the order of durationchange and this.player_.duration() being set is figured out, // this can be updated. this.on(player, 'timeupdate', this.updateContent); this.on(player, 'loadedmetadata', this.updateContent); } /** * Create the component's DOM element * * @return {Element} * @method createEl */ DurationDisplay.prototype.createEl = function createEl() { var el = _Component.prototype.createEl.call(this, 'div', { className: 'vjs-duration vjs-time-control vjs-control' }); this.contentEl_ = Dom.createEl('div', { className: 'vjs-duration-display', // label the duration time for screen reader users innerHTML: '<span class="vjs-control-text">' + this.localize('Duration Time') + '</span> 0:00' }, { // tell screen readers not to automatically read the time as it changes 'aria-live': 'off' }); el.appendChild(this.contentEl_); return el; }; /** * Update duration time display * * @method updateContent */ DurationDisplay.prototype.updateContent = function updateContent() { var duration = this.player_.duration(); if (duration) { var localizedText = this.localize('Duration Time'); var formattedTime = _utilsFormatTimeJs2['default'](duration); this.contentEl_.innerHTML = '<span class="vjs-control-text">' + localizedText + '</span> ' + formattedTime; // label the duration time for screen reader users } }; return DurationDisplay; })(_componentJs2['default']); _componentJs2['default'].registerComponent('DurationDisplay', DurationDisplay); exports['default'] = DurationDisplay; module.exports = exports['default']; },{"../../component.js":58,"../../utils/dom.js":118,"../../utils/format-time.js":121}],83:[function(_dereq_,module,exports){ /** * @file remaining-time-display.js */ 'use strict'; exports.__esModule = true; function _interopRequireWildcard(obj) { if (obj && obj.__esModule) { return obj; } else { var newObj = {}; if (obj != null) { for (var key in obj) { if (Object.prototype.hasOwnProperty.call(obj, key)) newObj[key] = obj[key]; } } newObj['default'] = obj; return newObj; } } function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { 'default': obj }; } function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError('Cannot call a class as a function'); } } function _inherits(subClass, superClass) { if (typeof superClass !== 'function' && superClass !== null) { throw new TypeError('Super expression must either be null or a function, not ' + typeof superClass); } subClass.prototype = Object.create(superClass && superClass.prototype, { constructor: { value: subClass, enumerable: false, writable: true, configurable: true } }); if (superClass) Object.setPrototypeOf ? Object.setPrototypeOf(subClass, superClass) : subClass.__proto__ = superClass; } var _componentJs = _dereq_('../../component.js'); var _componentJs2 = _interopRequireDefault(_componentJs); var _utilsDomJs = _dereq_('../../utils/dom.js'); var Dom = _interopRequireWildcard(_utilsDomJs); var _utilsFormatTimeJs = _dereq_('../../utils/format-time.js'); var _utilsFormatTimeJs2 = _interopRequireDefault(_utilsFormatTimeJs); /** * Displays the time left in the video * * @param {Player|Object} player * @param {Object=} options * @extends Component * @class RemainingTimeDisplay */ var RemainingTimeDisplay = (function (_Component) { _inherits(RemainingTimeDisplay, _Component); function RemainingTimeDisplay(player, options) { _classCallCheck(this, RemainingTimeDisplay); _Component.call(this, player, options); this.on(player, 'timeupdate', this.updateContent); } /** * Create the component's DOM element * * @return {Element} * @method createEl */ RemainingTimeDisplay.prototype.createEl = function createEl() { var el = _Component.prototype.createEl.call(this, 'div', { className: 'vjs-remaining-time vjs-time-control vjs-control' }); this.contentEl_ = Dom.createEl('div', { className: 'vjs-remaining-time-display', // label the remaining time for screen reader users innerHTML: '<span class="vjs-control-text">' + this.localize('Remaining Time') + '</span> -0:00' }, { // tell screen readers not to automatically read the time as it changes 'aria-live': 'off' }); el.appendChild(this.contentEl_); return el; }; /** * Update remaining time display * * @method updateContent */ RemainingTimeDisplay.prototype.updateContent = function updateContent() { if (this.player_.duration()) { var localizedText = this.localize('Remaining Time'); var formattedTime = _utilsFormatTimeJs2['default'](this.player_.remainingTime()); this.contentEl_.innerHTML = '<span class="vjs-control-text">' + localizedText + '</span> -' + formattedTime; } // Allows for smooth scrubbing, when player can't keep up. // var time = (this.player_.scrubbing()) ? this.player_.getCache().currentTime : this.player_.currentTime(); // this.contentEl_.innerHTML = vjs.formatTime(time, this.player_.duration()); }; return RemainingTimeDisplay; })(_componentJs2['default']); _componentJs2['default'].registerComponent('RemainingTimeDisplay', RemainingTimeDisplay); exports['default'] = RemainingTimeDisplay; module.exports = exports['default']; },{"../../component.js":58,"../../utils/dom.js":118,"../../utils/format-time.js":121}],84:[function(_dereq_,module,exports){ /** * @file time-divider.js */ 'use strict'; exports.__esModule = true; function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { 'default': obj }; } function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError('Cannot call a class as a function'); } } function _inherits(subClass, superClass) { if (typeof superClass !== 'function' && superClass !== null) { throw new TypeError('Super expression must either be null or a function, not ' + typeof superClass); } subClass.prototype = Object.create(superClass && superClass.prototype, { constructor: { value: subClass, enumerable: false, writable: true, configurable: true } }); if (superClass) Object.setPrototypeOf ? Object.setPrototypeOf(subClass, superClass) : subClass.__proto__ = superClass; } var _componentJs = _dereq_('../../component.js'); var _componentJs2 = _interopRequireDefault(_componentJs); /** * The separator between the current time and duration. * Can be hidden if it's not needed in the design. * * @param {Player|Object} player * @param {Object=} options * @extends Component * @class TimeDivider */ var TimeDivider = (function (_Component) { _inherits(TimeDivider, _Component); function TimeDivider() { _classCallCheck(this, TimeDivider); _Component.apply(this, arguments); } /** * Create the component's DOM element * * @return {Element} * @method createEl */ TimeDivider.prototype.createEl = function createEl() { return _Component.prototype.createEl.call(this, 'div', { className: 'vjs-time-control vjs-time-divider', innerHTML: '<div><span>/</span></div>' }); }; return TimeDivider; })(_componentJs2['default']); _componentJs2['default'].registerComponent('TimeDivider', TimeDivider); exports['default'] = TimeDivider; module.exports = exports['default']; },{"../../component.js":58}],85:[function(_dereq_,module,exports){ /** * @file volume-bar.js */ 'use strict'; exports.__esModule = true; function _interopRequireWildcard(obj) { if (obj && obj.__esModule) { return obj; } else { var newObj = {}; if (obj != null) { for (var key in obj) { if (Object.prototype.hasOwnProperty.call(obj, key)) newObj[key] = obj[key]; } } newObj['default'] = obj; return newObj; } } function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { 'default': obj }; } function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError('Cannot call a class as a function'); } } function _inherits(subClass, superClass) { if (typeof superClass !== 'function' && superClass !== null) { throw new TypeError('Super expression must either be null or a function, not ' + typeof superClass); } subClass.prototype = Object.create(superClass && superClass.prototype, { constructor: { value: subClass, enumerable: false, writable: true, configurable: true } }); if (superClass) Object.setPrototypeOf ? Object.setPrototypeOf(subClass, superClass) : subClass.__proto__ = superClass; } var _sliderSliderJs = _dereq_('../../slider/slider.js'); var _sliderSliderJs2 = _interopRequireDefault(_sliderSliderJs); var _componentJs = _dereq_('../../component.js'); var _componentJs2 = _interopRequireDefault(_componentJs); var _utilsFnJs = _dereq_('../../utils/fn.js'); var Fn = _interopRequireWildcard(_utilsFnJs); // Required children var _volumeLevelJs = _dereq_('./volume-level.js'); var _volumeLevelJs2 = _interopRequireDefault(_volumeLevelJs); /** * The bar that contains the volume level and can be clicked on to adjust the level * * @param {Player|Object} player * @param {Object=} options * @extends Slider * @class VolumeBar */ var VolumeBar = (function (_Slider) { _inherits(VolumeBar, _Slider); function VolumeBar(player, options) { _classCallCheck(this, VolumeBar); _Slider.call(this, player, options); this.on(player, 'volumechange', this.updateARIAAttributes); player.ready(Fn.bind(this, this.updateARIAAttributes)); } /** * Create the component's DOM element * * @return {Element} * @method createEl */ VolumeBar.prototype.createEl = function createEl() { return _Slider.prototype.createEl.call(this, 'div', { className: 'vjs-volume-bar vjs-slider-bar' }, { 'aria-label': 'volume level' }); }; /** * Handle mouse move on volume bar * * @method handleMouseMove */ VolumeBar.prototype.handleMouseMove = function handleMouseMove(event) { if (this.player_.muted()) { this.player_.muted(false); } this.player_.volume(this.calculateDistance(event)); }; /** * Get percent of volume level * * @retun {Number} Volume level percent * @method getPercent */ VolumeBar.prototype.getPercent = function getPercent() { if (this.player_.muted()) { return 0; } else { return this.player_.volume(); } }; /** * Increase volume level for keyboard users * * @method stepForward */ VolumeBar.prototype.stepForward = function stepForward() { this.player_.volume(this.player_.volume() + 0.1); }; /** * Decrease volume level for keyboard users * * @method stepBack */ VolumeBar.prototype.stepBack = function stepBack() { this.player_.volume(this.player_.volume() - 0.1); }; /** * Update ARIA accessibility attributes * * @method updateARIAAttributes */ VolumeBar.prototype.updateARIAAttributes = function updateARIAAttributes() { // Current value of volume bar as a percentage var volume = (this.player_.volume() * 100).toFixed(2); this.el_.setAttribute('aria-valuenow', volume); this.el_.setAttribute('aria-valuetext', volume + '%'); }; return VolumeBar; })(_sliderSliderJs2['default']); VolumeBar.prototype.options_ = { children: ['volumeLevel'], 'barName': 'volumeLevel' }; VolumeBar.prototype.playerEvent = 'volumechange'; _componentJs2['default'].registerComponent('VolumeBar', VolumeBar); exports['default'] = VolumeBar; module.exports = exports['default']; },{"../../component.js":58,"../../slider/slider.js":102,"../../utils/fn.js":120,"./volume-level.js":87}],86:[function(_dereq_,module,exports){ /** * @file volume-control.js */ 'use strict'; exports.__esModule = true; function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { 'default': obj }; } function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError('Cannot call a class as a function'); } } function _inherits(subClass, superClass) { if (typeof superClass !== 'function' && superClass !== null) { throw new TypeError('Super expression must either be null or a function, not ' + typeof superClass); } subClass.prototype = Object.create(superClass && superClass.prototype, { constructor: { value: subClass, enumerable: false, writable: true, configurable: true } }); if (superClass) Object.setPrototypeOf ? Object.setPrototypeOf(subClass, superClass) : subClass.__proto__ = superClass; } var _componentJs = _dereq_('../../component.js'); var _componentJs2 = _interopRequireDefault(_componentJs); // Required children var _volumeBarJs = _dereq_('./volume-bar.js'); var _volumeBarJs2 = _interopRequireDefault(_volumeBarJs); /** * The component for controlling the volume level * * @param {Player|Object} player * @param {Object=} options * @extends Component * @class VolumeControl */ var VolumeControl = (function (_Component) { _inherits(VolumeControl, _Component); function VolumeControl(player, options) { _classCallCheck(this, VolumeControl); _Component.call(this, player, options); // hide volume controls when they're not supported by the current tech if (player.tech_ && player.tech_['featuresVolumeControl'] === false) { this.addClass('vjs-hidden'); } this.on(player, 'loadstart', function () { if (player.tech_['featuresVolumeControl'] === false) { this.addClass('vjs-hidden'); } else { this.removeClass('vjs-hidden'); } }); } /** * Create the component's DOM element * * @return {Element} * @method createEl */ VolumeControl.prototype.createEl = function createEl() { return _Component.prototype.createEl.call(this, 'div', { className: 'vjs-volume-control vjs-control' }); }; return VolumeControl; })(_componentJs2['default']); VolumeControl.prototype.options_ = { children: ['volumeBar'] }; _componentJs2['default'].registerComponent('VolumeControl', VolumeControl); exports['default'] = VolumeControl; module.exports = exports['default']; },{"../../component.js":58,"./volume-bar.js":85}],87:[function(_dereq_,module,exports){ /** * @file volume-level.js */ 'use strict'; exports.__esModule = true; function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { 'default': obj }; } function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError('Cannot call a class as a function'); } } function _inherits(subClass, superClass) { if (typeof superClass !== 'function' && superClass !== null) { throw new TypeError('Super expression must either be null or a function, not ' + typeof superClass); } subClass.prototype = Object.create(superClass && superClass.prototype, { constructor: { value: subClass, enumerable: false, writable: true, configurable: true } }); if (superClass) Object.setPrototypeOf ? Object.setPrototypeOf(subClass, superClass) : subClass.__proto__ = superClass; } var _componentJs = _dereq_('../../component.js'); var _componentJs2 = _interopRequireDefault(_componentJs); /** * Shows volume level * * @param {Player|Object} player * @param {Object=} options * @extends Component * @class VolumeLevel */ var VolumeLevel = (function (_Component) { _inherits(VolumeLevel, _Component); function VolumeLevel() { _classCallCheck(this, VolumeLevel); _Component.apply(this, arguments); } /** * Create the component's DOM element * * @return {Element} * @method createEl */ VolumeLevel.prototype.createEl = function createEl() { return _Component.prototype.createEl.call(this, 'div', { className: 'vjs-volume-level', innerHTML: '<span class="vjs-control-text"></span>' }); }; return VolumeLevel; })(_componentJs2['default']); _componentJs2['default'].registerComponent('VolumeLevel', VolumeLevel); exports['default'] = VolumeLevel; module.exports = exports['default']; },{"../../component.js":58}],88:[function(_dereq_,module,exports){ /** * @file volume-menu-button.js */ 'use strict'; exports.__esModule = true; function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { 'default': obj }; } function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError('Cannot call a class as a function'); } } function _inherits(subClass, superClass) { if (typeof superClass !== 'function' && superClass !== null) { throw new TypeError('Super expression must either be null or a function, not ' + typeof superClass); } subClass.prototype = Object.create(superClass && superClass.prototype, { constructor: { value: subClass, enumerable: false, writable: true, configurable: true } }); if (superClass) Object.setPrototypeOf ? Object.setPrototypeOf(subClass, superClass) : subClass.__proto__ = superClass; } var _buttonJs = _dereq_('../button.js'); var _buttonJs2 = _interopRequireDefault(_buttonJs); var _componentJs = _dereq_('../component.js'); var _componentJs2 = _interopRequireDefault(_componentJs); var _menuMenuJs = _dereq_('../menu/menu.js'); var _menuMenuJs2 = _interopRequireDefault(_menuMenuJs); var _menuMenuButtonJs = _dereq_('../menu/menu-button.js'); var _menuMenuButtonJs2 = _interopRequireDefault(_menuMenuButtonJs); var _muteToggleJs = _dereq_('./mute-toggle.js'); var _muteToggleJs2 = _interopRequireDefault(_muteToggleJs); var _volumeControlVolumeBarJs = _dereq_('./volume-control/volume-bar.js'); var _volumeControlVolumeBarJs2 = _interopRequireDefault(_volumeControlVolumeBarJs); /** * Button for volume menu * * @param {Player|Object} player * @param {Object=} options * @extends MenuButton * @class VolumeMenuButton */ var VolumeMenuButton = (function (_MenuButton) { _inherits(VolumeMenuButton, _MenuButton); function VolumeMenuButton(player) { var options = arguments.length <= 1 || arguments[1] === undefined ? {} : arguments[1]; _classCallCheck(this, VolumeMenuButton); // Default to inline if (options.inline === undefined) { options.inline = true; } // If the vertical option isn't passed at all, default to true. if (options.vertical === undefined) { // If an inline volumeMenuButton is used, we should default to using // a horizontal slider for obvious reasons. if (options.inline) { options.vertical = false; } else { options.vertical = true; } } // The vertical option needs to be set on the volumeBar as well, // since that will need to be passed along to the VolumeBar constructor options.volumeBar = options.volumeBar || {}; options.volumeBar.vertical = !!options.vertical; _MenuButton.call(this, player, options); // Same listeners as MuteToggle this.on(player, 'volumechange', this.volumeUpdate); this.on(player, 'loadstart', this.volumeUpdate); // hide mute toggle if the current tech doesn't support volume control function updateVisibility() { if (player.tech_ && player.tech_['featuresVolumeControl'] === false) { this.addClass('vjs-hidden'); } else { this.removeClass('vjs-hidden'); } } updateVisibility.call(this); this.on(player, 'loadstart', updateVisibility); this.on(this.volumeBar, ['slideractive', 'focus'], function () { this.addClass('vjs-slider-active'); }); this.on(this.volumeBar, ['sliderinactive', 'blur'], function () { this.removeClass('vjs-slider-active'); }); } /** * Allow sub components to stack CSS class names * * @return {String} The constructed class name * @method buildCSSClass */ VolumeMenuButton.prototype.buildCSSClass = function buildCSSClass() { var orientationClass = ''; if (!!this.options_.vertical) { orientationClass = 'vjs-volume-menu-button-vertical'; } else { orientationClass = 'vjs-volume-menu-button-horizontal'; } return 'vjs-volume-menu-button ' + _MenuButton.prototype.buildCSSClass.call(this) + ' ' + orientationClass; }; /** * Allow sub components to stack CSS class names * * @return {Menu} The volume menu button * @method createMenu */ VolumeMenuButton.prototype.createMenu = function createMenu() { var menu = new _menuMenuJs2['default'](this.player_, { contentElType: 'div' }); var vb = new _volumeControlVolumeBarJs2['default'](this.player_, this.options_.volumeBar); menu.addChild(vb); this.volumeBar = vb; return menu; }; /** * Handle click on volume menu and calls super * * @method handleClick */ VolumeMenuButton.prototype.handleClick = function handleClick() { _muteToggleJs2['default'].prototype.handleClick.call(this); _MenuButton.prototype.handleClick.call(this); }; return VolumeMenuButton; })(_menuMenuButtonJs2['default']); VolumeMenuButton.prototype.volumeUpdate = _muteToggleJs2['default'].prototype.update; VolumeMenuButton.prototype.controlText_ = 'Mute'; _componentJs2['default'].registerComponent('VolumeMenuButton', VolumeMenuButton); exports['default'] = VolumeMenuButton; module.exports = exports['default']; },{"../button.js":57,"../component.js":58,"../menu/menu-button.js":95,"../menu/menu.js":97,"./mute-toggle.js":62,"./volume-control/volume-bar.js":85}],89:[function(_dereq_,module,exports){ /** * @file error-display.js */ 'use strict'; exports.__esModule = true; function _interopRequireWildcard(obj) { if (obj && obj.__esModule) { return obj; } else { var newObj = {}; if (obj != null) { for (var key in obj) { if (Object.prototype.hasOwnProperty.call(obj, key)) newObj[key] = obj[key]; } } newObj['default'] = obj; return newObj; } } function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { 'default': obj }; } function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError('Cannot call a class as a function'); } } function _inherits(subClass, superClass) { if (typeof superClass !== 'function' && superClass !== null) { throw new TypeError('Super expression must either be null or a function, not ' + typeof superClass); } subClass.prototype = Object.create(superClass && superClass.prototype, { constructor: { value: subClass, enumerable: false, writable: true, configurable: true } }); if (superClass) Object.setPrototypeOf ? Object.setPrototypeOf(subClass, superClass) : subClass.__proto__ = superClass; } var _component = _dereq_('./component'); var _component2 = _interopRequireDefault(_component); var _utilsDomJs = _dereq_('./utils/dom.js'); var Dom = _interopRequireWildcard(_utilsDomJs); /** * Display that an error has occurred making the video unplayable * * @param {Object} player Main Player * @param {Object=} options Object of option names and values * @extends Component * @class ErrorDisplay */ var ErrorDisplay = (function (_Component) { _inherits(ErrorDisplay, _Component); function ErrorDisplay(player, options) { _classCallCheck(this, ErrorDisplay); _Component.call(this, player, options); this.update(); this.on(player, 'error', this.update); } /** * Create the component's DOM element * * @return {Element} * @method createEl */ ErrorDisplay.prototype.createEl = function createEl() { var el = _Component.prototype.createEl.call(this, 'div', { className: 'vjs-error-display' }); this.contentEl_ = Dom.createEl('div'); el.appendChild(this.contentEl_); return el; }; /** * Update the error message in localized language * * @method update */ ErrorDisplay.prototype.update = function update() { if (this.player().error()) { this.contentEl_.innerHTML = this.localize(this.player().error().message); } }; return ErrorDisplay; })(_component2['default']); _component2['default'].registerComponent('ErrorDisplay', ErrorDisplay); exports['default'] = ErrorDisplay; module.exports = exports['default']; },{"./component":58,"./utils/dom.js":118}],90:[function(_dereq_,module,exports){ /** * @file event-target.js */ 'use strict'; exports.__esModule = true; function _interopRequireWildcard(obj) { if (obj && obj.__esModule) { return obj; } else { var newObj = {}; if (obj != null) { for (var key in obj) { if (Object.prototype.hasOwnProperty.call(obj, key)) newObj[key] = obj[key]; } } newObj['default'] = obj; return newObj; } } var _utilsEventsJs = _dereq_('./utils/events.js'); var Events = _interopRequireWildcard(_utilsEventsJs); var EventTarget = function EventTarget() {}; EventTarget.prototype.allowedEvents_ = {}; EventTarget.prototype.on = function (type, fn) { // Remove the addEventListener alias before calling Events.on // so we don't get into an infinite type loop var ael = this.addEventListener; this.addEventListener = Function.prototype; Events.on(this, type, fn); this.addEventListener = ael; }; EventTarget.prototype.addEventListener = EventTarget.prototype.on; EventTarget.prototype.off = function (type, fn) { Events.off(this, type, fn); }; EventTarget.prototype.removeEventListener = EventTarget.prototype.off; EventTarget.prototype.one = function (type, fn) { Events.one(this, type, fn); }; EventTarget.prototype.trigger = function (event) { var type = event.type || event; if (typeof event === 'string') { event = { type: type }; } event = Events.fixEvent(event); if (this.allowedEvents_[type] && this['on' + type]) { this['on' + type](event); } Events.trigger(this, event); }; // The standard DOM EventTarget.dispatchEvent() is aliased to trigger() EventTarget.prototype.dispatchEvent = EventTarget.prototype.trigger; exports['default'] = EventTarget; module.exports = exports['default']; },{"./utils/events.js":119}],91:[function(_dereq_,module,exports){ 'use strict'; exports.__esModule = true; function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { 'default': obj }; } var _utilsLog = _dereq_('./utils/log'); var _utilsLog2 = _interopRequireDefault(_utilsLog); /* * @file extend.js * * A combination of node inherits and babel's inherits (after transpile). * Both work the same but node adds `super_` to the subClass * and Bable adds the superClass as __proto__. Both seem useful. */ var _inherits = function _inherits(subClass, superClass) { if (typeof superClass !== 'function' && superClass !== null) { throw new TypeError('Super expression must either be null or a function, not ' + typeof superClass); } subClass.prototype = Object.create(superClass && superClass.prototype, { constructor: { value: subClass, enumerable: false, writable: true, configurable: true } }); if (superClass) { // node subClass.super_ = superClass; } }; /* * Function for subclassing using the same inheritance that * videojs uses internally * ```js * var Button = videojs.getComponent('Button'); * ``` * ```js * var MyButton = videojs.extend(Button, { * constructor: function(player, options) { * Button.call(this, player, options); * }, * onClick: function() { * // doSomething * } * }); * ``` */ var extendFn = function extendFn(superClass) { var subClassMethods = arguments.length <= 1 || arguments[1] === undefined ? {} : arguments[1]; var subClass = function subClass() { superClass.apply(this, arguments); }; var methods = {}; if (typeof subClassMethods === 'object') { if (typeof subClassMethods.init === 'function') { _utilsLog2['default'].warn('Constructor logic via init() is deprecated; please use constructor() instead.'); subClassMethods.constructor = subClassMethods.init; } if (subClassMethods.constructor !== Object.prototype.constructor) { subClass = subClassMethods.constructor; } methods = subClassMethods; } else if (typeof subClassMethods === 'function') { subClass = subClassMethods; } _inherits(subClass, superClass); // Extend subObj's prototype with functions and other properties from props for (var name in methods) { if (methods.hasOwnProperty(name)) { subClass.prototype[name] = methods[name]; } } return subClass; }; exports['default'] = extendFn; module.exports = exports['default']; },{"./utils/log":123}],92:[function(_dereq_,module,exports){ /** * @file fullscreen-api.js */ 'use strict'; exports.__esModule = true; function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { 'default': obj }; } var _globalDocument = _dereq_('global/document'); var _globalDocument2 = _interopRequireDefault(_globalDocument); /* * Store the browser-specific methods for the fullscreen API * @type {Object|undefined} * @private */ var FullscreenApi = {}; // browser API methods // map approach from Screenful.js - https://github.com/sindresorhus/screenfull.js var apiMap = [ // Spec: https://dvcs.w3.org/hg/fullscreen/raw-file/tip/Overview.html ['requestFullscreen', 'exitFullscreen', 'fullscreenElement', 'fullscreenEnabled', 'fullscreenchange', 'fullscreenerror'], // WebKit ['webkitRequestFullscreen', 'webkitExitFullscreen', 'webkitFullscreenElement', 'webkitFullscreenEnabled', 'webkitfullscreenchange', 'webkitfullscreenerror'], // Old WebKit (Safari 5.1) ['webkitRequestFullScreen', 'webkitCancelFullScreen', 'webkitCurrentFullScreenElement', 'webkitCancelFullScreen', 'webkitfullscreenchange', 'webkitfullscreenerror'], // Mozilla ['mozRequestFullScreen', 'mozCancelFullScreen', 'mozFullScreenElement', 'mozFullScreenEnabled', 'mozfullscreenchange', 'mozfullscreenerror'], // Microsoft ['msRequestFullscreen', 'msExitFullscreen', 'msFullscreenElement', 'msFullscreenEnabled', 'MSFullscreenChange', 'MSFullscreenError']]; var specApi = apiMap[0]; var browserApi = undefined; // determine the supported set of functions for (var i = 0; i < apiMap.length; i++) { // check for exitFullscreen function if (apiMap[i][1] in _globalDocument2['default']) { browserApi = apiMap[i]; break; } } // map the browser API names to the spec API names if (browserApi) { for (var i = 0; i < browserApi.length; i++) { FullscreenApi[specApi[i]] = browserApi[i]; } } exports['default'] = FullscreenApi; module.exports = exports['default']; },{"global/document":1}],93:[function(_dereq_,module,exports){ /** * @file loading-spinner.js */ 'use strict'; exports.__esModule = true; function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { 'default': obj }; } function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError('Cannot call a class as a function'); } } function _inherits(subClass, superClass) { if (typeof superClass !== 'function' && superClass !== null) { throw new TypeError('Super expression must either be null or a function, not ' + typeof superClass); } subClass.prototype = Object.create(superClass && superClass.prototype, { constructor: { value: subClass, enumerable: false, writable: true, configurable: true } }); if (superClass) Object.setPrototypeOf ? Object.setPrototypeOf(subClass, superClass) : subClass.__proto__ = superClass; } var _component = _dereq_('./component'); var _component2 = _interopRequireDefault(_component); /* Loading Spinner ================================================================================ */ /** * Loading spinner for waiting events * * @extends Component * @class LoadingSpinner */ var LoadingSpinner = (function (_Component) { _inherits(LoadingSpinner, _Component); function LoadingSpinner() { _classCallCheck(this, LoadingSpinner); _Component.apply(this, arguments); } /** * Create the component's DOM element * * @method createEl */ LoadingSpinner.prototype.createEl = function createEl() { return _Component.prototype.createEl.call(this, 'div', { className: 'vjs-loading-spinner' }); }; return LoadingSpinner; })(_component2['default']); _component2['default'].registerComponent('LoadingSpinner', LoadingSpinner); exports['default'] = LoadingSpinner; module.exports = exports['default']; },{"./component":58}],94:[function(_dereq_,module,exports){ /** * @file media-error.js */ 'use strict'; exports.__esModule = true; function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { 'default': obj }; } var _objectAssign = _dereq_('object.assign'); var _objectAssign2 = _interopRequireDefault(_objectAssign); /* * Custom MediaError to mimic the HTML5 MediaError * * @param {Number} code The media error code */ var MediaError = function MediaError(code) { if (typeof code === 'number') { this.code = code; } else if (typeof code === 'string') { // default code is zero, so this is a custom error this.message = code; } else if (typeof code === 'object') { // object _objectAssign2['default'](this, code); } if (!this.message) { this.message = MediaError.defaultMessages[this.code] || ''; } }; /* * The error code that refers two one of the defined * MediaError types * * @type {Number} */ MediaError.prototype.code = 0; /* * An optional message to be shown with the error. * Message is not part of the HTML5 video spec * but allows for more informative custom errors. * * @type {String} */ MediaError.prototype.message = ''; /* * An optional status code that can be set by plugins * to allow even more detail about the error. * For example the HLS plugin might provide the specific * HTTP status code that was returned when the error * occurred, then allowing a custom error overlay * to display more information. * * @type {Array} */ MediaError.prototype.status = null; MediaError.errorTypes = ['MEDIA_ERR_CUSTOM', // = 0 'MEDIA_ERR_ABORTED', // = 1 'MEDIA_ERR_NETWORK', // = 2 'MEDIA_ERR_DECODE', // = 3 'MEDIA_ERR_SRC_NOT_SUPPORTED', // = 4 'MEDIA_ERR_ENCRYPTED' // = 5 ]; MediaError.defaultMessages = { 1: 'You aborted the media playback', 2: 'A network error caused the media download to fail part-way.', 3: 'The media playback was aborted due to a corruption problem or because the media used features your browser did not support.', 4: 'The media could not be loaded, either because the server or network failed or because the format is not supported.', 5: 'The media is encrypted and we do not have the keys to decrypt it.' }; // Add types as properties on MediaError // e.g. MediaError.MEDIA_ERR_SRC_NOT_SUPPORTED = 4; for (var errNum = 0; errNum < MediaError.errorTypes.length; errNum++) { MediaError[MediaError.errorTypes[errNum]] = errNum; // values should be accessible on both the class and instance MediaError.prototype[MediaError.errorTypes[errNum]] = errNum; } exports['default'] = MediaError; module.exports = exports['default']; },{"object.assign":43}],95:[function(_dereq_,module,exports){ /** * @file menu-button.js */ 'use strict'; exports.__esModule = true; function _interopRequireWildcard(obj) { if (obj && obj.__esModule) { return obj; } else { var newObj = {}; if (obj != null) { for (var key in obj) { if (Object.prototype.hasOwnProperty.call(obj, key)) newObj[key] = obj[key]; } } newObj['default'] = obj; return newObj; } } function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { 'default': obj }; } function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError('Cannot call a class as a function'); } } function _inherits(subClass, superClass) { if (typeof superClass !== 'function' && superClass !== null) { throw new TypeError('Super expression must either be null or a function, not ' + typeof superClass); } subClass.prototype = Object.create(superClass && superClass.prototype, { constructor: { value: subClass, enumerable: false, writable: true, configurable: true } }); if (superClass) Object.setPrototypeOf ? Object.setPrototypeOf(subClass, superClass) : subClass.__proto__ = superClass; } var _buttonJs = _dereq_('../button.js'); var _buttonJs2 = _interopRequireDefault(_buttonJs); var _componentJs = _dereq_('../component.js'); var _componentJs2 = _interopRequireDefault(_componentJs); var _menuJs = _dereq_('./menu.js'); var _menuJs2 = _interopRequireDefault(_menuJs); var _utilsDomJs = _dereq_('../utils/dom.js'); var Dom = _interopRequireWildcard(_utilsDomJs); var _utilsFnJs = _dereq_('../utils/fn.js'); var Fn = _interopRequireWildcard(_utilsFnJs); var _utilsToTitleCaseJs = _dereq_('../utils/to-title-case.js'); var _utilsToTitleCaseJs2 = _interopRequireDefault(_utilsToTitleCaseJs); /** * A button class with a popup menu * * @param {Player|Object} player * @param {Object=} options * @extends Button * @class MenuButton */ var MenuButton = (function (_Button) { _inherits(MenuButton, _Button); function MenuButton(player) { var options = arguments.length <= 1 || arguments[1] === undefined ? {} : arguments[1]; _classCallCheck(this, MenuButton); _Button.call(this, player, options); this.update(); this.on('keydown', this.handleKeyPress); this.el_.setAttribute('aria-haspopup', true); this.el_.setAttribute('role', 'button'); } /** * Update menu * * @method update */ MenuButton.prototype.update = function update() { var menu = this.createMenu(); if (this.menu) { this.removeChild(this.menu); } this.menu = menu; this.addChild(menu); /** * Track the state of the menu button * * @type {Boolean} * @private */ this.buttonPressed_ = false; if (this.items && this.items.length === 0) { this.hide(); } else if (this.items && this.items.length > 1) { this.show(); } }; /** * Create menu * * @return {Menu} The constructed menu * @method createMenu */ MenuButton.prototype.createMenu = function createMenu() { var menu = new _menuJs2['default'](this.player_); // Add a title list item to the top if (this.options_.title) { menu.contentEl().appendChild(Dom.createEl('li', { className: 'vjs-menu-title', innerHTML: _utilsToTitleCaseJs2['default'](this.options_.title), tabIndex: -1 })); } this.items = this['createItems'](); if (this.items) { // Add menu items to the menu for (var i = 0; i < this.items.length; i++) { menu.addItem(this.items[i]); } } return menu; }; /** * Create the list of menu items. Specific to each subclass. * * @method createItems */ MenuButton.prototype.createItems = function createItems() {}; /** * Create the component's DOM element * * @return {Element} * @method createEl */ MenuButton.prototype.createEl = function createEl() { return _Button.prototype.createEl.call(this, 'div', { className: this.buildCSSClass() }); }; /** * Allow sub components to stack CSS class names * * @return {String} The constructed class name * @method buildCSSClass */ MenuButton.prototype.buildCSSClass = function buildCSSClass() { var menuButtonClass = 'vjs-menu-button'; // If the inline option is passed, we want to use different styles altogether. if (this.options_.inline === true) { menuButtonClass += '-inline'; } else { menuButtonClass += '-popup'; } return 'vjs-menu-button ' + menuButtonClass + ' ' + _Button.prototype.buildCSSClass.call(this); }; /** * Focus - Add keyboard functionality to element * This function is not needed anymore. Instead, the * keyboard functionality is handled by * treating the button as triggering a submenu. * When the button is pressed, the submenu * appears. Pressing the button again makes * the submenu disappear. * * @method handleFocus */ MenuButton.prototype.handleFocus = function handleFocus() {}; /** * Can't turn off list display that we turned * on with focus, because list would go away. * * @method handleBlur */ MenuButton.prototype.handleBlur = function handleBlur() {}; /** * When you click the button it adds focus, which * will show the menu indefinitely. * So we'll remove focus when the mouse leaves the button. * Focus is needed for tab navigation. * Allow sub components to stack CSS class names * * @method handleClick */ MenuButton.prototype.handleClick = function handleClick() { this.one('mouseout', Fn.bind(this, function () { this.menu.unlockShowing(); this.el_.blur(); })); if (this.buttonPressed_) { this.unpressButton(); } else { this.pressButton(); } }; /** * Handle key press on menu * * @param {Object} Key press event * @method handleKeyPress */ MenuButton.prototype.handleKeyPress = function handleKeyPress(event) { // Check for space bar (32) or enter (13) keys if (event.which === 32 || event.which === 13) { if (this.buttonPressed_) { this.unpressButton(); } else { this.pressButton(); } event.preventDefault(); // Check for escape (27) key } else if (event.which === 27) { if (this.buttonPressed_) { this.unpressButton(); } event.preventDefault(); } }; /** * Makes changes based on button pressed * * @method pressButton */ MenuButton.prototype.pressButton = function pressButton() { this.buttonPressed_ = true; this.menu.lockShowing(); this.el_.setAttribute('aria-pressed', true); if (this.items && this.items.length > 0) { this.items[0].el().focus(); // set the focus to the title of the submenu } }; /** * Makes changes based on button unpressed * * @method unpressButton */ MenuButton.prototype.unpressButton = function unpressButton() { this.buttonPressed_ = false; this.menu.unlockShowing(); this.el_.setAttribute('aria-pressed', false); }; return MenuButton; })(_buttonJs2['default']); _componentJs2['default'].registerComponent('MenuButton', MenuButton); exports['default'] = MenuButton; module.exports = exports['default']; },{"../button.js":57,"../component.js":58,"../utils/dom.js":118,"../utils/fn.js":120,"../utils/to-title-case.js":127,"./menu.js":97}],96:[function(_dereq_,module,exports){ /** * @file menu-item.js */ 'use strict'; exports.__esModule = true; function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { 'default': obj }; } function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError('Cannot call a class as a function'); } } function _inherits(subClass, superClass) { if (typeof superClass !== 'function' && superClass !== null) { throw new TypeError('Super expression must either be null or a function, not ' + typeof superClass); } subClass.prototype = Object.create(superClass && superClass.prototype, { constructor: { value: subClass, enumerable: false, writable: true, configurable: true } }); if (superClass) Object.setPrototypeOf ? Object.setPrototypeOf(subClass, superClass) : subClass.__proto__ = superClass; } var _buttonJs = _dereq_('../button.js'); var _buttonJs2 = _interopRequireDefault(_buttonJs); var _componentJs = _dereq_('../component.js'); var _componentJs2 = _interopRequireDefault(_componentJs); var _objectAssign = _dereq_('object.assign'); var _objectAssign2 = _interopRequireDefault(_objectAssign); /** * The component for a menu item. `<li>` * * @param {Player|Object} player * @param {Object=} options * @extends Button * @class MenuItem */ var MenuItem = (function (_Button) { _inherits(MenuItem, _Button); function MenuItem(player, options) { _classCallCheck(this, MenuItem); _Button.call(this, player, options); this.selected(options['selected']); } /** * Create the component's DOM element * * @param {String=} type Desc * @param {Object=} props Desc * @return {Element} * @method createEl */ MenuItem.prototype.createEl = function createEl(type, props, attrs) { return _Button.prototype.createEl.call(this, 'li', _objectAssign2['default']({ className: 'vjs-menu-item', innerHTML: this.localize(this.options_['label']) }, props), attrs); }; /** * Handle a click on the menu item, and set it to selected * * @method handleClick */ MenuItem.prototype.handleClick = function handleClick() { this.selected(true); }; /** * Set this menu item as selected or not * * @param {Boolean} selected * @method selected */ MenuItem.prototype.selected = function selected(_selected) { if (_selected) { this.addClass('vjs-selected'); this.el_.setAttribute('aria-selected', true); } else { this.removeClass('vjs-selected'); this.el_.setAttribute('aria-selected', false); } }; return MenuItem; })(_buttonJs2['default']); _componentJs2['default'].registerComponent('MenuItem', MenuItem); exports['default'] = MenuItem; module.exports = exports['default']; },{"../button.js":57,"../component.js":58,"object.assign":43}],97:[function(_dereq_,module,exports){ /** * @file menu.js */ 'use strict'; exports.__esModule = true; function _interopRequireWildcard(obj) { if (obj && obj.__esModule) { return obj; } else { var newObj = {}; if (obj != null) { for (var key in obj) { if (Object.prototype.hasOwnProperty.call(obj, key)) newObj[key] = obj[key]; } } newObj['default'] = obj; return newObj; } } function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { 'default': obj }; } function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError('Cannot call a class as a function'); } } function _inherits(subClass, superClass) { if (typeof superClass !== 'function' && superClass !== null) { throw new TypeError('Super expression must either be null or a function, not ' + typeof superClass); } subClass.prototype = Object.create(superClass && superClass.prototype, { constructor: { value: subClass, enumerable: false, writable: true, configurable: true } }); if (superClass) Object.setPrototypeOf ? Object.setPrototypeOf(subClass, superClass) : subClass.__proto__ = superClass; } var _componentJs = _dereq_('../component.js'); var _componentJs2 = _interopRequireDefault(_componentJs); var _utilsDomJs = _dereq_('../utils/dom.js'); var Dom = _interopRequireWildcard(_utilsDomJs); var _utilsFnJs = _dereq_('../utils/fn.js'); var Fn = _interopRequireWildcard(_utilsFnJs); var _utilsEventsJs = _dereq_('../utils/events.js'); var Events = _interopRequireWildcard(_utilsEventsJs); /** * The Menu component is used to build pop up menus, including subtitle and * captions selection menus. * * @extends Component * @class Menu */ var Menu = (function (_Component) { _inherits(Menu, _Component); function Menu() { _classCallCheck(this, Menu); _Component.apply(this, arguments); } /** * Add a menu item to the menu * * @param {Object|String} component Component or component type to add * @method addItem */ Menu.prototype.addItem = function addItem(component) { this.addChild(component); component.on('click', Fn.bind(this, function () { this.unlockShowing(); })); }; /** * Create the component's DOM element * * @return {Element} * @method createEl */ Menu.prototype.createEl = function createEl() { var contentElType = this.options_.contentElType || 'ul'; this.contentEl_ = Dom.createEl(contentElType, { className: 'vjs-menu-content' }); var el = _Component.prototype.createEl.call(this, 'div', { append: this.contentEl_, className: 'vjs-menu' }); el.appendChild(this.contentEl_); // Prevent clicks from bubbling up. Needed for Menu Buttons, // where a click on the parent is significant Events.on(el, 'click', function (event) { event.preventDefault(); event.stopImmediatePropagation(); }); return el; }; return Menu; })(_componentJs2['default']); _componentJs2['default'].registerComponent('Menu', Menu); exports['default'] = Menu; module.exports = exports['default']; },{"../component.js":58,"../utils/dom.js":118,"../utils/events.js":119,"../utils/fn.js":120}],98:[function(_dereq_,module,exports){ /** * @file player.js */ // Subclasses Component 'use strict'; exports.__esModule = true; function _interopRequireWildcard(obj) { if (obj && obj.__esModule) { return obj; } else { var newObj = {}; if (obj != null) { for (var key in obj) { if (Object.prototype.hasOwnProperty.call(obj, key)) newObj[key] = obj[key]; } } newObj['default'] = obj; return newObj; } } function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { 'default': obj }; } function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError('Cannot call a class as a function'); } } function _inherits(subClass, superClass) { if (typeof superClass !== 'function' && superClass !== null) { throw new TypeError('Super expression must either be null or a function, not ' + typeof superClass); } subClass.prototype = Object.create(superClass && superClass.prototype, { constructor: { value: subClass, enumerable: false, writable: true, configurable: true } }); if (superClass) Object.setPrototypeOf ? Object.setPrototypeOf(subClass, superClass) : subClass.__proto__ = superClass; } var _componentJs = _dereq_('./component.js'); var _componentJs2 = _interopRequireDefault(_componentJs); var _globalDocument = _dereq_('global/document'); var _globalDocument2 = _interopRequireDefault(_globalDocument); var _globalWindow = _dereq_('global/window'); var _globalWindow2 = _interopRequireDefault(_globalWindow); var _utilsEventsJs = _dereq_('./utils/events.js'); var Events = _interopRequireWildcard(_utilsEventsJs); var _utilsDomJs = _dereq_('./utils/dom.js'); var Dom = _interopRequireWildcard(_utilsDomJs); var _utilsFnJs = _dereq_('./utils/fn.js'); var Fn = _interopRequireWildcard(_utilsFnJs); var _utilsGuidJs = _dereq_('./utils/guid.js'); var Guid = _interopRequireWildcard(_utilsGuidJs); var _utilsBrowserJs = _dereq_('./utils/browser.js'); var browser = _interopRequireWildcard(_utilsBrowserJs); var _utilsLogJs = _dereq_('./utils/log.js'); var _utilsLogJs2 = _interopRequireDefault(_utilsLogJs); var _utilsToTitleCaseJs = _dereq_('./utils/to-title-case.js'); var _utilsToTitleCaseJs2 = _interopRequireDefault(_utilsToTitleCaseJs); var _utilsTimeRangesJs = _dereq_('./utils/time-ranges.js'); var _utilsBufferJs = _dereq_('./utils/buffer.js'); var _utilsStylesheetJs = _dereq_('./utils/stylesheet.js'); var stylesheet = _interopRequireWildcard(_utilsStylesheetJs); var _fullscreenApiJs = _dereq_('./fullscreen-api.js'); var _fullscreenApiJs2 = _interopRequireDefault(_fullscreenApiJs); var _mediaErrorJs = _dereq_('./media-error.js'); var _mediaErrorJs2 = _interopRequireDefault(_mediaErrorJs); var _safeJsonParseTuple = _dereq_('safe-json-parse/tuple'); var _safeJsonParseTuple2 = _interopRequireDefault(_safeJsonParseTuple); var _objectAssign = _dereq_('object.assign'); var _objectAssign2 = _interopRequireDefault(_objectAssign); var _utilsMergeOptionsJs = _dereq_('./utils/merge-options.js'); var _utilsMergeOptionsJs2 = _interopRequireDefault(_utilsMergeOptionsJs); var _tracksTextTrackListConverterJs = _dereq_('./tracks/text-track-list-converter.js'); var _tracksTextTrackListConverterJs2 = _interopRequireDefault(_tracksTextTrackListConverterJs); // Include required child components (importing also registers them) var _techLoaderJs = _dereq_('./tech/loader.js'); var _techLoaderJs2 = _interopRequireDefault(_techLoaderJs); var _posterImageJs = _dereq_('./poster-image.js'); var _posterImageJs2 = _interopRequireDefault(_posterImageJs); var _tracksTextTrackDisplayJs = _dereq_('./tracks/text-track-display.js'); var _tracksTextTrackDisplayJs2 = _interopRequireDefault(_tracksTextTrackDisplayJs); var _loadingSpinnerJs = _dereq_('./loading-spinner.js'); var _loadingSpinnerJs2 = _interopRequireDefault(_loadingSpinnerJs); var _bigPlayButtonJs = _dereq_('./big-play-button.js'); var _bigPlayButtonJs2 = _interopRequireDefault(_bigPlayButtonJs); var _controlBarControlBarJs = _dereq_('./control-bar/control-bar.js'); var _controlBarControlBarJs2 = _interopRequireDefault(_controlBarControlBarJs); var _errorDisplayJs = _dereq_('./error-display.js'); var _errorDisplayJs2 = _interopRequireDefault(_errorDisplayJs); var _tracksTextTrackSettingsJs = _dereq_('./tracks/text-track-settings.js'); var _tracksTextTrackSettingsJs2 = _interopRequireDefault(_tracksTextTrackSettingsJs); // Require html5 tech, at least for disposing the original video tag var _techHtml5Js = _dereq_('./tech/html5.js'); var _techHtml5Js2 = _interopRequireDefault(_techHtml5Js); /** * An instance of the `Player` class is created when any of the Video.js setup methods are used to initialize a video. * ```js * var myPlayer = videojs('example_video_1'); * ``` * In the following example, the `data-setup` attribute tells the Video.js library to create a player instance when the library is ready. * ```html * <video id="example_video_1" data-setup='{}' controls> * <source src="my-source.mp4" type="video/mp4"> * </video> * ``` * After an instance has been created it can be accessed globally using `Video('example_video_1')`. * * @param {Element} tag The original video tag used for configuring options * @param {Object=} options Object of option names and values * @param {Function=} ready Ready callback function * @extends Component * @class Player */ var Player = (function (_Component) { _inherits(Player, _Component); /** * player's constructor function * * @constructs * @method init * @param {Element} tag The original video tag used for configuring options * @param {Object=} options Player options * @param {Function=} ready Ready callback function */ function Player(tag, options, ready) { var _this = this; _classCallCheck(this, Player); // Make sure tag ID exists tag.id = tag.id || 'vjs_video_' + Guid.newGUID(); // Set Options // The options argument overrides options set in the video tag // which overrides globally set options. // This latter part coincides with the load order // (tag must exist before Player) options = _objectAssign2['default'](Player.getTagSettings(tag), options); // Delay the initialization of children because we need to set up // player properties first, and can't use `this` before `super()` options.initChildren = false; // Same with creating the element options.createEl = false; // we don't want the player to report touch activity on itself // see enableTouchActivity in Component options.reportTouchActivity = false; // Run base component initializing with new options _Component.call(this, null, options, ready); // if the global option object was accidentally blown away by // someone, bail early with an informative error if (!this.options_ || !this.options_.techOrder || !this.options_.techOrder.length) { throw new Error('No techOrder specified. Did you overwrite ' + 'videojs.options instead of just changing the ' + 'properties you want to override?'); } this.tag = tag; // Store the original tag used to set options // Store the tag attributes used to restore html5 element this.tagAttributes = tag && Dom.getElAttributes(tag); // Update current language this.language(this.options_.language); // Update Supported Languages if (options.languages) { (function () { // Normalise player option languages to lowercase var languagesToLower = {}; Object.getOwnPropertyNames(options.languages).forEach(function (name) { languagesToLower[name.toLowerCase()] = options.languages[name]; }); _this.languages_ = languagesToLower; })(); } else { this.languages_ = Player.prototype.options_.languages; } // Cache for video property values. this.cache_ = {}; // Set poster this.poster_ = options.poster || ''; // Set controls this.controls_ = !!options.controls; // Original tag settings stored in options // now remove immediately so native controls don't flash. // May be turned back on by HTML5 tech if nativeControlsForTouch is true tag.controls = false; /* * Store the internal state of scrubbing * * @private * @return {Boolean} True if the user is scrubbing */ this.scrubbing_ = false; this.el_ = this.createEl(); // We also want to pass the original player options to each component and plugin // as well so they don't need to reach back into the player for options later. // We also need to do another copy of this.options_ so we don't end up with // an infinite loop. var playerOptionsCopy = _utilsMergeOptionsJs2['default'](this.options_); // Load plugins if (options.plugins) { (function () { var plugins = options.plugins; Object.getOwnPropertyNames(plugins).forEach(function (name) { if (typeof this[name] === 'function') { this[name](plugins[name]); } else { _utilsLogJs2['default'].error('Unable to find plugin:', name); } }, _this); })(); } this.options_.playerOptions = playerOptionsCopy; this.initChildren(); // Set isAudio based on whether or not an audio tag was used this.isAudio(tag.nodeName.toLowerCase() === 'audio'); // Update controls className. Can't do this when the controls are initially // set because the element doesn't exist yet. if (this.controls()) { this.addClass('vjs-controls-enabled'); } else { this.addClass('vjs-controls-disabled'); } if (this.isAudio()) { this.addClass('vjs-audio'); } if (this.flexNotSupported_()) { this.addClass('vjs-no-flex'); } // TODO: Make this smarter. Toggle user state between touching/mousing // using events, since devices can have both touch and mouse events. // if (browser.TOUCH_ENABLED) { // this.addClass('vjs-touch-enabled'); // } // Make player easily findable by ID Player.players[this.id_] = this; // When the player is first initialized, trigger activity so components // like the control bar show themselves if needed this.userActive(true); this.reportUserActivity(); this.listenForUserActivity_(); this.on('fullscreenchange', this.handleFullscreenChange_); this.on('stageclick', this.handleStageClick_); } /* * Global player list * * @type {Object} */ /** * Destroys the video player and does any necessary cleanup * ```js * myPlayer.dispose(); * ``` * This is especially helpful if you are dynamically adding and removing videos * to/from the DOM. * * @method dispose */ Player.prototype.dispose = function dispose() { this.trigger('dispose'); // prevent dispose from being called twice this.off('dispose'); if (this.styleEl_) { this.styleEl_.parentNode.removeChild(this.styleEl_); } // Kill reference to this player Player.players[this.id_] = null; if (this.tag && this.tag.player) { this.tag.player = null; } if (this.el_ && this.el_.player) { this.el_.player = null; } if (this.tech_) { this.tech_.dispose(); } _Component.prototype.dispose.call(this); }; /** * Create the component's DOM element * * @return {Element} * @method createEl */ Player.prototype.createEl = function createEl() { var el = this.el_ = _Component.prototype.createEl.call(this, 'div'); var tag = this.tag; // Remove width/height attrs from tag so CSS can make it 100% width/height tag.removeAttribute('width'); tag.removeAttribute('height'); // Copy over all the attributes from the tag, including ID and class // ID will now reference player box, not the video tag var attrs = Dom.getElAttributes(tag); Object.getOwnPropertyNames(attrs).forEach(function (attr) { // workaround so we don't totally break IE7 // http://stackoverflow.com/questions/3653444/css-styles-not-applied-on-dynamic-elements-in-internet-explorer-7 if (attr === 'class') { el.className = attrs[attr]; } else { el.setAttribute(attr, attrs[attr]); } }); // Update tag id/class for use as HTML5 playback tech // Might think we should do this after embedding in container so .vjs-tech class // doesn't flash 100% width/height, but class only applies with .video-js parent tag.id += '_html5_api'; tag.className = 'vjs-tech'; // Make player findable on elements tag.player = el.player = this; // Default state of video is paused this.addClass('vjs-paused'); // Add a style element in the player that we'll use to set the width/height // of the player in a way that's still overrideable by CSS, just like the // video element this.styleEl_ = stylesheet.createStyleElement('vjs-styles-dimensions'); var defaultsStyleEl = _globalDocument2['default'].querySelector('.vjs-styles-defaults'); var head = _globalDocument2['default'].querySelector('head'); head.insertBefore(this.styleEl_, defaultsStyleEl ? defaultsStyleEl.nextSibling : head.firstChild); // Pass in the width/height/aspectRatio options which will update the style el this.width(this.options_.width); this.height(this.options_.height); this.fluid(this.options_.fluid); this.aspectRatio(this.options_.aspectRatio); // insertElFirst seems to cause the networkState to flicker from 3 to 2, so // keep track of the original for later so we can know if the source originally failed tag.initNetworkState_ = tag.networkState; // Wrap video tag in div (el/box) container if (tag.parentNode) { tag.parentNode.insertBefore(el, tag); } Dom.insertElFirst(tag, el); // Breaks iPhone, fixed in HTML5 setup. this.el_ = el; return el; }; /** * Get/set player width * * @param {Number=} value Value for width * @return {Number} Width when getting * @method width */ Player.prototype.width = function width(value) { return this.dimension('width', value); }; /** * Get/set player height * * @param {Number=} value Value for height * @return {Number} Height when getting * @method height */ Player.prototype.height = function height(value) { return this.dimension('height', value); }; /** * Get/set dimension for player * * @param {String} dimension Either width or height * @param {Number=} value Value for dimension * @return {Component} * @method dimension */ Player.prototype.dimension = function dimension(_dimension, value) { var privDimension = _dimension + '_'; if (value === undefined) { return this[privDimension] || 0; } if (value === '') { // If an empty string is given, reset the dimension to be automatic this[privDimension] = undefined; } else { var parsedVal = parseFloat(value); if (isNaN(parsedVal)) { _utilsLogJs2['default'].error('Improper value "' + value + '" supplied for for ' + _dimension); return this; } this[privDimension] = parsedVal; } this.updateStyleEl_(); return this; }; /** * Add/remove the vjs-fluid class * * @param {Boolean} bool Value of true adds the class, value of false removes the class * @method fluid */ Player.prototype.fluid = function fluid(bool) { if (bool === undefined) { return !!this.fluid_; } this.fluid_ = !!bool; if (bool) { this.addClass('vjs-fluid'); } else { this.removeClass('vjs-fluid'); } }; /** * Get/Set the aspect ratio * * @param {String=} ratio Aspect ratio for player * @return aspectRatio * @method aspectRatio */ Player.prototype.aspectRatio = function aspectRatio(ratio) { if (ratio === undefined) { return this.aspectRatio_; } // Check for width:height format if (!/^\d+\:\d+$/.test(ratio)) { throw new Error('Improper value supplied for aspect ratio. The format should be width:height, for example 16:9.'); } this.aspectRatio_ = ratio; // We're assuming if you set an aspect ratio you want fluid mode, // because in fixed mode you could calculate width and height yourself. this.fluid(true); this.updateStyleEl_(); }; /** * Update styles of the player element (height, width and aspect ratio) * * @method updateStyleEl_ */ Player.prototype.updateStyleEl_ = function updateStyleEl_() { var width = undefined; var height = undefined; var aspectRatio = undefined; // The aspect ratio is either used directly or to calculate width and height. if (this.aspectRatio_ !== undefined && this.aspectRatio_ !== 'auto') { // Use any aspectRatio that's been specifically set aspectRatio = this.aspectRatio_; } else if (this.videoWidth()) { // Otherwise try to get the aspect ratio from the video metadata aspectRatio = this.videoWidth() + ':' + this.videoHeight(); } else { // Or use a default. The video element's is 2:1, but 16:9 is more common. aspectRatio = '16:9'; } // Get the ratio as a decimal we can use to calculate dimensions var ratioParts = aspectRatio.split(':'); var ratioMultiplier = ratioParts[1] / ratioParts[0]; if (this.width_ !== undefined) { // Use any width that's been specifically set width = this.width_; } else if (this.height_ !== undefined) { // Or calulate the width from the aspect ratio if a height has been set width = this.height_ / ratioMultiplier; } else { // Or use the video's metadata, or use the video el's default of 300 width = this.videoWidth() || 300; } if (this.height_ !== undefined) { // Use any height that's been specifically set height = this.height_; } else { // Otherwise calculate the height from the ratio and the width height = width * ratioMultiplier; } var idClass = this.id() + '-dimensions'; // Ensure the right class is still on the player for the style element this.addClass(idClass); stylesheet.setTextContent(this.styleEl_, '\n .' + idClass + ' {\n width: ' + width + 'px;\n height: ' + height + 'px;\n }\n\n .' + idClass + '.vjs-fluid {\n padding-top: ' + ratioMultiplier * 100 + '%;\n }\n '); }; /** * Load the Media Playback Technology (tech) * Load/Create an instance of playback technology including element and API methods * And append playback element in player div. * * @param {String} techName Name of the playback technology * @param {String} source Video source * @method loadTech_ * @private */ Player.prototype.loadTech_ = function loadTech_(techName, source) { // Pause and remove current playback technology if (this.tech_) { this.unloadTech_(); } // get rid of the HTML5 video tag as soon as we are using another tech if (techName !== 'Html5' && this.tag) { _componentJs2['default'].getComponent('Html5').disposeMediaElement(this.tag); this.tag.player = null; this.tag = null; } this.techName_ = techName; // Turn off API access because we're loading a new tech that might load asynchronously this.isReady_ = false; // Grab tech-specific options from player options and add source and parent element to use. var techOptions = _objectAssign2['default']({ 'nativeControlsForTouch': this.options_.nativeControlsForTouch, 'source': source, 'playerId': this.id(), 'techId': this.id() + '_' + techName + '_api', 'textTracks': this.textTracks_, 'autoplay': this.options_.autoplay, 'preload': this.options_.preload, 'loop': this.options_.loop, 'muted': this.options_.muted, 'poster': this.poster(), 'language': this.language(), 'vtt.js': this.options_['vtt.js'] }, this.options_[techName.toLowerCase()]); if (this.tag) { techOptions.tag = this.tag; } if (source) { this.currentType_ = source.type; if (source.src === this.cache_.src && this.cache_.currentTime > 0) { techOptions.startTime = this.cache_.currentTime; } this.cache_.src = source.src; } // Initialize tech instance var techComponent = _componentJs2['default'].getComponent(techName); this.tech_ = new techComponent(techOptions); // player.triggerReady is always async, so don't need this to be async this.tech_.ready(Fn.bind(this, this.handleTechReady_), true); _tracksTextTrackListConverterJs2['default'].jsonToTextTracks(this.textTracksJson_ || [], this.tech_); // Listen to all HTML5-defined events and trigger them on the player this.on(this.tech_, 'loadstart', this.handleTechLoadStart_); this.on(this.tech_, 'waiting', this.handleTechWaiting_); this.on(this.tech_, 'canplay', this.handleTechCanPlay_); this.on(this.tech_, 'canplaythrough', this.handleTechCanPlayThrough_); this.on(this.tech_, 'playing', this.handleTechPlaying_); this.on(this.tech_, 'ended', this.handleTechEnded_); this.on(this.tech_, 'seeking', this.handleTechSeeking_); this.on(this.tech_, 'seeked', this.handleTechSeeked_); this.on(this.tech_, 'play', this.handleTechPlay_); this.on(this.tech_, 'firstplay', this.handleTechFirstPlay_); this.on(this.tech_, 'pause', this.handleTechPause_); this.on(this.tech_, 'progress', this.handleTechProgress_); this.on(this.tech_, 'durationchange', this.handleTechDurationChange_); this.on(this.tech_, 'fullscreenchange', this.handleTechFullscreenChange_); this.on(this.tech_, 'error', this.handleTechError_); this.on(this.tech_, 'suspend', this.handleTechSuspend_); this.on(this.tech_, 'abort', this.handleTechAbort_); this.on(this.tech_, 'emptied', this.handleTechEmptied_); this.on(this.tech_, 'stalled', this.handleTechStalled_); this.on(this.tech_, 'loadedmetadata', this.handleTechLoadedMetaData_); this.on(this.tech_, 'loadeddata', this.handleTechLoadedData_); this.on(this.tech_, 'timeupdate', this.handleTechTimeUpdate_); this.on(this.tech_, 'ratechange', this.handleTechRateChange_); this.on(this.tech_, 'volumechange', this.handleTechVolumeChange_); this.on(this.tech_, 'texttrackchange', this.handleTechTextTrackChange_); this.on(this.tech_, 'loadedmetadata', this.updateStyleEl_); this.on(this.tech_, 'posterchange', this.handleTechPosterChange_); this.usingNativeControls(this.techGet_('controls')); if (this.controls() && !this.usingNativeControls()) { this.addTechControlsListeners_(); } // Add the tech element in the DOM if it was not already there // Make sure to not insert the original video element if using Html5 if (this.tech_.el().parentNode !== this.el() && (techName !== 'Html5' || !this.tag)) { Dom.insertElFirst(this.tech_.el(), this.el()); } // Get rid of the original video tag reference after the first tech is loaded if (this.tag) { this.tag.player = null; this.tag = null; } }; /** * Unload playback technology * * @method unloadTech_ * @private */ Player.prototype.unloadTech_ = function unloadTech_() { // Save the current text tracks so that we can reuse the same text tracks with the next tech this.textTracks_ = this.textTracks(); this.textTracksJson_ = _tracksTextTrackListConverterJs2['default'].textTracksToJson(this); this.isReady_ = false; this.tech_.dispose(); this.tech_ = false; }; /** * Set up click and touch listeners for the playback element * * On desktops, a click on the video itself will toggle playback, * on a mobile device a click on the video toggles controls. * (toggling controls is done by toggling the user state between active and * inactive) * A tap can signal that a user has become active, or has become inactive * e.g. a quick tap on an iPhone movie should reveal the controls. Another * quick tap should hide them again (signaling the user is in an inactive * viewing state) * In addition to this, we still want the user to be considered inactive after * a few seconds of inactivity. * Note: the only part of iOS interaction we can't mimic with this setup * is a touch and hold on the video element counting as activity in order to * keep the controls showing, but that shouldn't be an issue. A touch and hold * on any controls will still keep the user active * * @private * @method addTechControlsListeners_ */ Player.prototype.addTechControlsListeners_ = function addTechControlsListeners_() { // Make sure to remove all the previous listeners in case we are called multiple times. this.removeTechControlsListeners_(); // Some browsers (Chrome & IE) don't trigger a click on a flash swf, but do // trigger mousedown/up. // http://stackoverflow.com/questions/1444562/javascript-onclick-event-over-flash-object // Any touch events are set to block the mousedown event from happening this.on(this.tech_, 'mousedown', this.handleTechClick_); // If the controls were hidden we don't want that to change without a tap event // so we'll check if the controls were already showing before reporting user // activity this.on(this.tech_, 'touchstart', this.handleTechTouchStart_); this.on(this.tech_, 'touchmove', this.handleTechTouchMove_); this.on(this.tech_, 'touchend', this.handleTechTouchEnd_); // The tap listener needs to come after the touchend listener because the tap // listener cancels out any reportedUserActivity when setting userActive(false) this.on(this.tech_, 'tap', this.handleTechTap_); }; /** * Remove the listeners used for click and tap controls. This is needed for * toggling to controls disabled, where a tap/touch should do nothing. * * @method removeTechControlsListeners_ * @private */ Player.prototype.removeTechControlsListeners_ = function removeTechControlsListeners_() { // We don't want to just use `this.off()` because there might be other needed // listeners added by techs that extend this. this.off(this.tech_, 'tap', this.handleTechTap_); this.off(this.tech_, 'touchstart', this.handleTechTouchStart_); this.off(this.tech_, 'touchmove', this.handleTechTouchMove_); this.off(this.tech_, 'touchend', this.handleTechTouchEnd_); this.off(this.tech_, 'mousedown', this.handleTechClick_); }; /** * Player waits for the tech to be ready * * @method handleTechReady_ * @private */ Player.prototype.handleTechReady_ = function handleTechReady_() { this.triggerReady(); // Keep the same volume as before if (this.cache_.volume) { this.techCall_('setVolume', this.cache_.volume); } // Look if the tech found a higher resolution poster while loading this.handleTechPosterChange_(); // Update the duration if available this.handleTechDurationChange_(); // Chrome and Safari both have issues with autoplay. // In Safari (5.1.1), when we move the video element into the container div, autoplay doesn't work. // In Chrome (15), if you have autoplay + a poster + no controls, the video gets hidden (but audio plays) // This fixes both issues. Need to wait for API, so it updates displays correctly if (this.tag && this.options_.autoplay && this.paused()) { delete this.tag.poster; // Chrome Fix. Fixed in Chrome v16. this.play(); } }; /** * Fired when the user agent begins looking for media data * * @private * @method handleTechLoadStart_ */ Player.prototype.handleTechLoadStart_ = function handleTechLoadStart_() { // TODO: Update to use `emptied` event instead. See #1277. this.removeClass('vjs-ended'); // reset the error state this.error(null); // If it's already playing we want to trigger a firstplay event now. // The firstplay event relies on both the play and loadstart events // which can happen in any order for a new source if (!this.paused()) { this.trigger('loadstart'); this.trigger('firstplay'); } else { // reset the hasStarted state this.hasStarted(false); this.trigger('loadstart'); } }; /** * Add/remove the vjs-has-started class * * @param {Boolean} hasStarted The value of true adds the class the value of false remove the class * @return {Boolean} Boolean value if has started * @private * @method hasStarted */ Player.prototype.hasStarted = function hasStarted(_hasStarted) { if (_hasStarted !== undefined) { // only update if this is a new value if (this.hasStarted_ !== _hasStarted) { this.hasStarted_ = _hasStarted; if (_hasStarted) { this.addClass('vjs-has-started'); // trigger the firstplay event if this newly has played this.trigger('firstplay'); } else { this.removeClass('vjs-has-started'); } } return this; } return !!this.hasStarted_; }; /** * Fired whenever the media begins or resumes playback * * @private * @method handleTechPlay_ */ Player.prototype.handleTechPlay_ = function handleTechPlay_() { this.removeClass('vjs-ended'); this.removeClass('vjs-paused'); this.addClass('vjs-playing'); // hide the poster when the user hits play // https://html.spec.whatwg.org/multipage/embedded-content.html#dom-media-play this.hasStarted(true); this.trigger('play'); }; /** * Fired whenever the media begins waiting * * @private * @method handleTechWaiting_ */ Player.prototype.handleTechWaiting_ = function handleTechWaiting_() { this.addClass('vjs-waiting'); this.trigger('waiting'); }; /** * A handler for events that signal that waiting has ended * which is not consistent between browsers. See #1351 * * @private * @method handleTechCanPlay_ */ Player.prototype.handleTechCanPlay_ = function handleTechCanPlay_() { this.removeClass('vjs-waiting'); this.trigger('canplay'); }; /** * A handler for events that signal that waiting has ended * which is not consistent between browsers. See #1351 * * @private * @method handleTechCanPlayThrough_ */ Player.prototype.handleTechCanPlayThrough_ = function handleTechCanPlayThrough_() { this.removeClass('vjs-waiting'); this.trigger('canplaythrough'); }; /** * A handler for events that signal that waiting has ended * which is not consistent between browsers. See #1351 * * @private * @method handleTechPlaying_ */ Player.prototype.handleTechPlaying_ = function handleTechPlaying_() { this.removeClass('vjs-waiting'); this.trigger('playing'); }; /** * Fired whenever the player is jumping to a new time * * @private * @method handleTechSeeking_ */ Player.prototype.handleTechSeeking_ = function handleTechSeeking_() { this.addClass('vjs-seeking'); this.trigger('seeking'); }; /** * Fired when the player has finished jumping to a new time * * @private * @method handleTechSeeked_ */ Player.prototype.handleTechSeeked_ = function handleTechSeeked_() { this.removeClass('vjs-seeking'); this.trigger('seeked'); }; /** * Fired the first time a video is played * Not part of the HLS spec, and we're not sure if this is the best * implementation yet, so use sparingly. If you don't have a reason to * prevent playback, use `myPlayer.one('play');` instead. * * @private * @method handleTechFirstPlay_ */ Player.prototype.handleTechFirstPlay_ = function handleTechFirstPlay_() { //If the first starttime attribute is specified //then we will start at the given offset in seconds if (this.options_.starttime) { this.currentTime(this.options_.starttime); } this.addClass('vjs-has-started'); this.trigger('firstplay'); }; /** * Fired whenever the media has been paused * * @private * @method handleTechPause_ */ Player.prototype.handleTechPause_ = function handleTechPause_() { this.removeClass('vjs-playing'); this.addClass('vjs-paused'); this.trigger('pause'); }; /** * Fired while the user agent is downloading media data * * @private * @method handleTechProgress_ */ Player.prototype.handleTechProgress_ = function handleTechProgress_() { this.trigger('progress'); }; /** * Fired when the end of the media resource is reached (currentTime == duration) * * @private * @method handleTechEnded_ */ Player.prototype.handleTechEnded_ = function handleTechEnded_() { this.addClass('vjs-ended'); if (this.options_.loop) { this.currentTime(0); this.play(); } else if (!this.paused()) { this.pause(); } this.trigger('ended'); }; /** * Fired when the duration of the media resource is first known or changed * * @private * @method handleTechDurationChange_ */ Player.prototype.handleTechDurationChange_ = function handleTechDurationChange_() { this.duration(this.techGet_('duration')); }; /** * Handle a click on the media element to play/pause * * @param {Object=} event Event object * @private * @method handleTechClick_ */ Player.prototype.handleTechClick_ = function handleTechClick_(event) { // We're using mousedown to detect clicks thanks to Flash, but mousedown // will also be triggered with right-clicks, so we need to prevent that if (event.button !== 0) return; // When controls are disabled a click should not toggle playback because // the click is considered a control if (this.controls()) { if (this.paused()) { this.play(); } else { this.pause(); } } }; /** * Handle a tap on the media element. It will toggle the user * activity state, which hides and shows the controls. * * @private * @method handleTechTap_ */ Player.prototype.handleTechTap_ = function handleTechTap_() { this.userActive(!this.userActive()); }; /** * Handle touch to start * * @private * @method handleTechTouchStart_ */ Player.prototype.handleTechTouchStart_ = function handleTechTouchStart_() { this.userWasActive = this.userActive(); }; /** * Handle touch to move * * @private * @method handleTechTouchMove_ */ Player.prototype.handleTechTouchMove_ = function handleTechTouchMove_() { if (this.userWasActive) { this.reportUserActivity(); } }; /** * Handle touch to end * * @private * @method handleTechTouchEnd_ */ Player.prototype.handleTechTouchEnd_ = function handleTechTouchEnd_(event) { // Stop the mouse events from also happening event.preventDefault(); }; /** * Fired when the player switches in or out of fullscreen mode * * @private * @method handleFullscreenChange_ */ Player.prototype.handleFullscreenChange_ = function handleFullscreenChange_() { if (this.isFullscreen()) { this.addClass('vjs-fullscreen'); } else { this.removeClass('vjs-fullscreen'); } }; /** * native click events on the SWF aren't triggered on IE11, Win8.1RT * use stageclick events triggered from inside the SWF instead * * @private * @method handleStageClick_ */ Player.prototype.handleStageClick_ = function handleStageClick_() { this.reportUserActivity(); }; /** * Handle Tech Fullscreen Change * * @private * @method handleTechFullscreenChange_ */ Player.prototype.handleTechFullscreenChange_ = function handleTechFullscreenChange_(event, data) { if (data) { this.isFullscreen(data.isFullscreen); } this.trigger('fullscreenchange'); }; /** * Fires when an error occurred during the loading of an audio/video * * @private * @method handleTechError_ */ Player.prototype.handleTechError_ = function handleTechError_() { var error = this.tech_.error(); this.error(error && error.code); }; /** * Fires when the browser is intentionally not getting media data * * @private * @method handleTechSuspend_ */ Player.prototype.handleTechSuspend_ = function handleTechSuspend_() { this.trigger('suspend'); }; /** * Fires when the loading of an audio/video is aborted * * @private * @method handleTechAbort_ */ Player.prototype.handleTechAbort_ = function handleTechAbort_() { this.trigger('abort'); }; /** * Fires when the current playlist is empty * * @private * @method handleTechEmptied_ */ Player.prototype.handleTechEmptied_ = function handleTechEmptied_() { this.trigger('emptied'); }; /** * Fires when the browser is trying to get media data, but data is not available * * @private * @method handleTechStalled_ */ Player.prototype.handleTechStalled_ = function handleTechStalled_() { this.trigger('stalled'); }; /** * Fires when the browser has loaded meta data for the audio/video * * @private * @method handleTechLoadedMetaData_ */ Player.prototype.handleTechLoadedMetaData_ = function handleTechLoadedMetaData_() { this.trigger('loadedmetadata'); }; /** * Fires when the browser has loaded the current frame of the audio/video * * @private * @method handleTechLoadedData_ */ Player.prototype.handleTechLoadedData_ = function handleTechLoadedData_() { this.trigger('loadeddata'); }; /** * Fires when the current playback position has changed * * @private * @method handleTechTimeUpdate_ */ Player.prototype.handleTechTimeUpdate_ = function handleTechTimeUpdate_() { this.trigger('timeupdate'); }; /** * Fires when the playing speed of the audio/video is changed * * @private * @method handleTechRateChange_ */ Player.prototype.handleTechRateChange_ = function handleTechRateChange_() { this.trigger('ratechange'); }; /** * Fires when the volume has been changed * * @private * @method handleTechVolumeChange_ */ Player.prototype.handleTechVolumeChange_ = function handleTechVolumeChange_() { this.trigger('volumechange'); }; /** * Fires when the text track has been changed * * @private * @method handleTechTextTrackChange_ */ Player.prototype.handleTechTextTrackChange_ = function handleTechTextTrackChange_() { this.trigger('texttrackchange'); }; /** * Get object for cached values. * * @return {Object} * @method getCache */ Player.prototype.getCache = function getCache() { return this.cache_; }; /** * Pass values to the playback tech * * @param {String=} method Method * @param {Object=} arg Argument * @private * @method techCall_ */ Player.prototype.techCall_ = function techCall_(method, arg) { // If it's not ready yet, call method when it is if (this.tech_ && !this.tech_.isReady_) { this.tech_.ready(function () { this[method](arg); }, true); // Otherwise call method now } else { try { this.tech_[method](arg); } catch (e) { _utilsLogJs2['default'](e); throw e; } } }; /** * Get calls can't wait for the tech, and sometimes don't need to. * * @param {String} method Tech method * @return {Method} * @private * @method techGet_ */ Player.prototype.techGet_ = function techGet_(method) { if (this.tech_ && this.tech_.isReady_) { // Flash likes to die and reload when you hide or reposition it. // In these cases the object methods go away and we get errors. // When that happens we'll catch the errors and inform tech that it's not ready any more. try { return this.tech_[method](); } catch (e) { // When building additional tech libs, an expected method may not be defined yet if (this.tech_[method] === undefined) { _utilsLogJs2['default']('Video.js: ' + method + ' method not defined for ' + this.techName_ + ' playback technology.', e); } else { // When a method isn't available on the object it throws a TypeError if (e.name === 'TypeError') { _utilsLogJs2['default']('Video.js: ' + method + ' unavailable on ' + this.techName_ + ' playback technology element.', e); this.tech_.isReady_ = false; } else { _utilsLogJs2['default'](e); } } throw e; } } return; }; /** * start media playback * ```js * myPlayer.play(); * ``` * * @return {Player} self * @method play */ Player.prototype.play = function play() { this.techCall_('play'); return this; }; /** * Pause the video playback * ```js * myPlayer.pause(); * ``` * * @return {Player} self * @method pause */ Player.prototype.pause = function pause() { this.techCall_('pause'); return this; }; /** * Check if the player is paused * ```js * var isPaused = myPlayer.paused(); * var isPlaying = !myPlayer.paused(); * ``` * * @return {Boolean} false if the media is currently playing, or true otherwise * @method paused */ Player.prototype.paused = function paused() { // The initial state of paused should be true (in Safari it's actually false) return this.techGet_('paused') === false ? false : true; }; /** * Returns whether or not the user is "scrubbing". Scrubbing is when the user * has clicked the progress bar handle and is dragging it along the progress bar. * * @param {Boolean} isScrubbing True/false the user is scrubbing * @return {Boolean} The scrubbing status when getting * @return {Object} The player when setting * @method scrubbing */ Player.prototype.scrubbing = function scrubbing(isScrubbing) { if (isScrubbing !== undefined) { this.scrubbing_ = !!isScrubbing; if (isScrubbing) { this.addClass('vjs-scrubbing'); } else { this.removeClass('vjs-scrubbing'); } return this; } return this.scrubbing_; }; /** * Get or set the current time (in seconds) * ```js * // get * var whereYouAt = myPlayer.currentTime(); * // set * myPlayer.currentTime(120); // 2 minutes into the video * ``` * * @param {Number|String=} seconds The time to seek to * @return {Number} The time in seconds, when not setting * @return {Player} self, when the current time is set * @method currentTime */ Player.prototype.currentTime = function currentTime(seconds) { if (seconds !== undefined) { this.techCall_('setCurrentTime', seconds); return this; } // cache last currentTime and return. default to 0 seconds // // Caching the currentTime is meant to prevent a massive amount of reads on the tech's // currentTime when scrubbing, but may not provide much performance benefit afterall. // Should be tested. Also something has to read the actual current time or the cache will // never get updated. return this.cache_.currentTime = this.techGet_('currentTime') || 0; }; /** * Get the length in time of the video in seconds * ```js * var lengthOfVideo = myPlayer.duration(); * ``` * **NOTE**: The video must have started loading before the duration can be * known, and in the case of Flash, may not be known until the video starts * playing. * * @param {Number} seconds Duration when setting * @return {Number} The duration of the video in seconds when getting * @method duration */ Player.prototype.duration = function duration(seconds) { if (seconds === undefined) { return this.cache_.duration || 0; } seconds = parseFloat(seconds) || 0; // Standardize on Inifity for signaling video is live if (seconds < 0) { seconds = Infinity; } if (seconds !== this.cache_.duration) { // Cache the last set value for optimized scrubbing (esp. Flash) this.cache_.duration = seconds; if (seconds === Infinity) { this.addClass('vjs-live'); } else { this.removeClass('vjs-live'); } this.trigger('durationchange'); } return this; }; /** * Calculates how much time is left. * ```js * var timeLeft = myPlayer.remainingTime(); * ``` * Not a native video element function, but useful * * @return {Number} The time remaining in seconds * @method remainingTime */ Player.prototype.remainingTime = function remainingTime() { return this.duration() - this.currentTime(); }; // http://dev.w3.org/html5/spec/video.html#dom-media-buffered // Buffered returns a timerange object. // Kind of like an array of portions of the video that have been downloaded. /** * Get a TimeRange object with the times of the video that have been downloaded * If you just want the percent of the video that's been downloaded, * use bufferedPercent. * ```js * // Number of different ranges of time have been buffered. Usually 1. * numberOfRanges = bufferedTimeRange.length, * // Time in seconds when the first range starts. Usually 0. * firstRangeStart = bufferedTimeRange.start(0), * // Time in seconds when the first range ends * firstRangeEnd = bufferedTimeRange.end(0), * // Length in seconds of the first time range * firstRangeLength = firstRangeEnd - firstRangeStart; * ``` * * @return {Object} A mock TimeRange object (following HTML spec) * @method buffered */ Player.prototype.buffered = function buffered() { var buffered = this.techGet_('buffered'); if (!buffered || !buffered.length) { buffered = _utilsTimeRangesJs.createTimeRange(0, 0); } return buffered; }; /** * Get the percent (as a decimal) of the video that's been downloaded * ```js * var howMuchIsDownloaded = myPlayer.bufferedPercent(); * ``` * 0 means none, 1 means all. * (This method isn't in the HTML5 spec, but it's very convenient) * * @return {Number} A decimal between 0 and 1 representing the percent * @method bufferedPercent */ Player.prototype.bufferedPercent = function bufferedPercent() { return _utilsBufferJs.bufferedPercent(this.buffered(), this.duration()); }; /** * Get the ending time of the last buffered time range * This is used in the progress bar to encapsulate all time ranges. * * @return {Number} The end of the last buffered time range * @method bufferedEnd */ Player.prototype.bufferedEnd = function bufferedEnd() { var buffered = this.buffered(), duration = this.duration(), end = buffered.end(buffered.length - 1); if (end > duration) { end = duration; } return end; }; /** * Get or set the current volume of the media * ```js * // get * var howLoudIsIt = myPlayer.volume(); * // set * myPlayer.volume(0.5); // Set volume to half * ``` * 0 is off (muted), 1.0 is all the way up, 0.5 is half way. * * @param {Number} percentAsDecimal The new volume as a decimal percent * @return {Number} The current volume when getting * @return {Player} self when setting * @method volume */ Player.prototype.volume = function volume(percentAsDecimal) { var vol = undefined; if (percentAsDecimal !== undefined) { vol = Math.max(0, Math.min(1, parseFloat(percentAsDecimal))); // Force value to between 0 and 1 this.cache_.volume = vol; this.techCall_('setVolume', vol); return this; } // Default to 1 when returning current volume. vol = parseFloat(this.techGet_('volume')); return isNaN(vol) ? 1 : vol; }; /** * Get the current muted state, or turn mute on or off * ```js * // get * var isVolumeMuted = myPlayer.muted(); * // set * myPlayer.muted(true); // mute the volume * ``` * * @param {Boolean=} muted True to mute, false to unmute * @return {Boolean} True if mute is on, false if not when getting * @return {Player} self when setting mute * @method muted */ Player.prototype.muted = function muted(_muted) { if (_muted !== undefined) { this.techCall_('setMuted', _muted); return this; } return this.techGet_('muted') || false; // Default to false }; // Check if current tech can support native fullscreen // (e.g. with built in controls like iOS, so not our flash swf) /** * Check to see if fullscreen is supported * * @return {Boolean} * @method supportsFullScreen */ Player.prototype.supportsFullScreen = function supportsFullScreen() { return this.techGet_('supportsFullScreen') || false; }; /** * Check if the player is in fullscreen mode * ```js * // get * var fullscreenOrNot = myPlayer.isFullscreen(); * // set * myPlayer.isFullscreen(true); // tell the player it's in fullscreen * ``` * NOTE: As of the latest HTML5 spec, isFullscreen is no longer an official * property and instead document.fullscreenElement is used. But isFullscreen is * still a valuable property for internal player workings. * * @param {Boolean=} isFS Update the player's fullscreen state * @return {Boolean} true if fullscreen false if not when getting * @return {Player} self when setting * @method isFullscreen */ Player.prototype.isFullscreen = function isFullscreen(isFS) { if (isFS !== undefined) { this.isFullscreen_ = !!isFS; return this; } return !!this.isFullscreen_; }; /** * Increase the size of the video to full screen * ```js * myPlayer.requestFullscreen(); * ``` * In some browsers, full screen is not supported natively, so it enters * "full window mode", where the video fills the browser window. * In browsers and devices that support native full screen, sometimes the * browser's default controls will be shown, and not the Video.js custom skin. * This includes most mobile devices (iOS, Android) and older versions of * Safari. * * @return {Player} self * @method requestFullscreen */ Player.prototype.requestFullscreen = function requestFullscreen() { var fsApi = _fullscreenApiJs2['default']; this.isFullscreen(true); if (fsApi.requestFullscreen) { // the browser supports going fullscreen at the element level so we can // take the controls fullscreen as well as the video // Trigger fullscreenchange event after change // We have to specifically add this each time, and remove // when canceling fullscreen. Otherwise if there's multiple // players on a page, they would all be reacting to the same fullscreen // events Events.on(_globalDocument2['default'], fsApi.fullscreenchange, Fn.bind(this, function documentFullscreenChange(e) { this.isFullscreen(_globalDocument2['default'][fsApi.fullscreenElement]); // If cancelling fullscreen, remove event listener. if (this.isFullscreen() === false) { Events.off(_globalDocument2['default'], fsApi.fullscreenchange, documentFullscreenChange); } this.trigger('fullscreenchange'); })); this.el_[fsApi.requestFullscreen](); } else if (this.tech_.supportsFullScreen()) { // we can't take the video.js controls fullscreen but we can go fullscreen // with native controls this.techCall_('enterFullScreen'); } else { // fullscreen isn't supported so we'll just stretch the video element to // fill the viewport this.enterFullWindow(); this.trigger('fullscreenchange'); } return this; }; /** * Return the video to its normal size after having been in full screen mode * ```js * myPlayer.exitFullscreen(); * ``` * * @return {Player} self * @method exitFullscreen */ Player.prototype.exitFullscreen = function exitFullscreen() { var fsApi = _fullscreenApiJs2['default']; this.isFullscreen(false); // Check for browser element fullscreen support if (fsApi.requestFullscreen) { _globalDocument2['default'][fsApi.exitFullscreen](); } else if (this.tech_.supportsFullScreen()) { this.techCall_('exitFullScreen'); } else { this.exitFullWindow(); this.trigger('fullscreenchange'); } return this; }; /** * When fullscreen isn't supported we can stretch the video container to as wide as the browser will let us. * * @method enterFullWindow */ Player.prototype.enterFullWindow = function enterFullWindow() { this.isFullWindow = true; // Storing original doc overflow value to return to when fullscreen is off this.docOrigOverflow = _globalDocument2['default'].documentElement.style.overflow; // Add listener for esc key to exit fullscreen Events.on(_globalDocument2['default'], 'keydown', Fn.bind(this, this.fullWindowOnEscKey)); // Hide any scroll bars _globalDocument2['default'].documentElement.style.overflow = 'hidden'; // Apply fullscreen styles Dom.addElClass(_globalDocument2['default'].body, 'vjs-full-window'); this.trigger('enterFullWindow'); }; /** * Check for call to either exit full window or full screen on ESC key * * @param {String} event Event to check for key press * @method fullWindowOnEscKey */ Player.prototype.fullWindowOnEscKey = function fullWindowOnEscKey(event) { if (event.keyCode === 27) { if (this.isFullscreen() === true) { this.exitFullscreen(); } else { this.exitFullWindow(); } } }; /** * Exit full window * * @method exitFullWindow */ Player.prototype.exitFullWindow = function exitFullWindow() { this.isFullWindow = false; Events.off(_globalDocument2['default'], 'keydown', this.fullWindowOnEscKey); // Unhide scroll bars. _globalDocument2['default'].documentElement.style.overflow = this.docOrigOverflow; // Remove fullscreen styles Dom.removeElClass(_globalDocument2['default'].body, 'vjs-full-window'); // Resize the box, controller, and poster to original sizes // this.positionAll(); this.trigger('exitFullWindow'); }; /** * Select source based on tech order * * @param {Array} sources The sources for a media asset * @return {Object|Boolean} Object of source and tech order, otherwise false * @method selectSource */ Player.prototype.selectSource = function selectSource(sources) { // Loop through each playback technology in the options order for (var i = 0, j = this.options_.techOrder; i < j.length; i++) { var techName = _utilsToTitleCaseJs2['default'](j[i]); var tech = _componentJs2['default'].getComponent(techName); // Check if the current tech is defined before continuing if (!tech) { _utilsLogJs2['default'].error('The "' + techName + '" tech is undefined. Skipped browser support check for that tech.'); continue; } // Check if the browser supports this technology if (tech.isSupported()) { // Loop through each source object for (var a = 0, b = sources; a < b.length; a++) { var source = b[a]; // Check if source can be played with this technology if (tech.canPlaySource(source)) { return { source: source, tech: techName }; } } } } return false; }; /** * The source function updates the video source * There are three types of variables you can pass as the argument. * **URL String**: A URL to the the video file. Use this method if you are sure * the current playback technology (HTML5/Flash) can support the source you * provide. Currently only MP4 files can be used in both HTML5 and Flash. * ```js * myPlayer.src("http://www.example.com/path/to/video.mp4"); * ``` * **Source Object (or element):* * A javascript object containing information * about the source file. Use this method if you want the player to determine if * it can support the file using the type information. * ```js * myPlayer.src({ type: "video/mp4", src: "http://www.example.com/path/to/video.mp4" }); * ``` * **Array of Source Objects:* * To provide multiple versions of the source so * that it can be played using HTML5 across browsers you can use an array of * source objects. Video.js will detect which version is supported and load that * file. * ```js * myPlayer.src([ * { type: "video/mp4", src: "http://www.example.com/path/to/video.mp4" }, * { type: "video/webm", src: "http://www.example.com/path/to/video.webm" }, * { type: "video/ogg", src: "http://www.example.com/path/to/video.ogv" } * ]); * ``` * * @param {String|Object|Array=} source The source URL, object, or array of sources * @return {String} The current video source when getting * @return {String} The player when setting * @method src */ Player.prototype.src = function src(source) { if (source === undefined) { return this.techGet_('src'); } var currentTech = _componentJs2['default'].getComponent(this.techName_); // case: Array of source objects to choose from and pick the best to play if (Array.isArray(source)) { this.sourceList_(source); // case: URL String (http://myvideo...) } else if (typeof source === 'string') { // create a source object from the string this.src({ src: source }); // case: Source object { src: '', type: '' ... } } else if (source instanceof Object) { // check if the source has a type and the loaded tech cannot play the source // if there's no type we'll just try the current tech if (source.type && !currentTech.canPlaySource(source)) { // create a source list with the current source and send through // the tech loop to check for a compatible technology this.sourceList_([source]); } else { this.cache_.src = source.src; this.currentType_ = source.type || ''; // wait until the tech is ready to set the source this.ready(function () { // The setSource tech method was added with source handlers // so older techs won't support it // We need to check the direct prototype for the case where subclasses // of the tech do not support source handlers if (currentTech.prototype.hasOwnProperty('setSource')) { this.techCall_('setSource', source); } else { this.techCall_('src', source.src); } if (this.options_.preload === 'auto') { this.load(); } if (this.options_.autoplay) { this.play(); } // Set the source synchronously if possible (#2326) }, true); } } return this; }; /** * Handle an array of source objects * * @param {Array} sources Array of source objects * @private * @method sourceList_ */ Player.prototype.sourceList_ = function sourceList_(sources) { var sourceTech = this.selectSource(sources); if (sourceTech) { if (sourceTech.tech === this.techName_) { // if this technology is already loaded, set the source this.src(sourceTech.source); } else { // load this technology with the chosen source this.loadTech_(sourceTech.tech, sourceTech.source); } } else { // We need to wrap this in a timeout to give folks a chance to add error event handlers this.setTimeout(function () { this.error({ code: 4, message: this.localize(this.options_.notSupportedMessage) }); }, 0); // we could not find an appropriate tech, but let's still notify the delegate that this is it // this needs a better comment about why this is needed this.triggerReady(); } }; /** * Begin loading the src data. * * @return {Player} Returns the player * @method load */ Player.prototype.load = function load() { this.techCall_('load'); return this; }; /** * Returns the fully qualified URL of the current source value e.g. http://mysite.com/video.mp4 * Can be used in conjuction with `currentType` to assist in rebuilding the current source object. * * @return {String} The current source * @method currentSrc */ Player.prototype.currentSrc = function currentSrc() { return this.techGet_('currentSrc') || this.cache_.src || ''; }; /** * Get the current source type e.g. video/mp4 * This can allow you rebuild the current source object so that you could load the same * source and tech later * * @return {String} The source MIME type * @method currentType */ Player.prototype.currentType = function currentType() { return this.currentType_ || ''; }; /** * Get or set the preload attribute * * @param {Boolean} value Boolean to determine if preload should be used * @return {String} The preload attribute value when getting * @return {Player} Returns the player when setting * @method preload */ Player.prototype.preload = function preload(value) { if (value !== undefined) { this.techCall_('setPreload', value); this.options_.preload = value; return this; } return this.techGet_('preload'); }; /** * Get or set the autoplay attribute. * * @param {Boolean} value Boolean to determine if preload should be used * @return {String} The autoplay attribute value when getting * @return {Player} Returns the player when setting * @method autoplay */ Player.prototype.autoplay = function autoplay(value) { if (value !== undefined) { this.techCall_('setAutoplay', value); this.options_.autoplay = value; return this; } return this.techGet_('autoplay', value); }; /** * Get or set the loop attribute on the video element. * * @param {Boolean} value Boolean to determine if preload should be used * @return {String} The loop attribute value when getting * @return {Player} Returns the player when setting * @method loop */ Player.prototype.loop = function loop(value) { if (value !== undefined) { this.techCall_('setLoop', value); this.options_['loop'] = value; return this; } return this.techGet_('loop'); }; /** * Get or set the poster image source url * * ##### EXAMPLE: * ```js * // get * var currentPoster = myPlayer.poster(); * // set * myPlayer.poster('http://example.com/myImage.jpg'); * ``` * * @param {String=} src Poster image source URL * @return {String} poster URL when getting * @return {Player} self when setting * @method poster */ Player.prototype.poster = function poster(src) { if (src === undefined) { return this.poster_; } // The correct way to remove a poster is to set as an empty string // other falsey values will throw errors if (!src) { src = ''; } // update the internal poster variable this.poster_ = src; // update the tech's poster this.techCall_('setPoster', src); // alert components that the poster has been set this.trigger('posterchange'); return this; }; /** * Some techs (e.g. YouTube) can provide a poster source in an * asynchronous way. We want the poster component to use this * poster source so that it covers up the tech's controls. * (YouTube's play button). However we only want to use this * soruce if the player user hasn't set a poster through * the normal APIs. * * @private * @method handleTechPosterChange_ */ Player.prototype.handleTechPosterChange_ = function handleTechPosterChange_() { if (!this.poster_ && this.tech_ && this.tech_.poster) { this.poster_ = this.tech_.poster() || ''; // Let components know the poster has changed this.trigger('posterchange'); } }; /** * Get or set whether or not the controls are showing. * * @param {Boolean} bool Set controls to showing or not * @return {Boolean} Controls are showing * @method controls */ Player.prototype.controls = function controls(bool) { if (bool !== undefined) { bool = !!bool; // force boolean // Don't trigger a change event unless it actually changed if (this.controls_ !== bool) { this.controls_ = bool; if (this.usingNativeControls()) { this.techCall_('setControls', bool); } if (bool) { this.removeClass('vjs-controls-disabled'); this.addClass('vjs-controls-enabled'); this.trigger('controlsenabled'); if (!this.usingNativeControls()) { this.addTechControlsListeners_(); } } else { this.removeClass('vjs-controls-enabled'); this.addClass('vjs-controls-disabled'); this.trigger('controlsdisabled'); if (!this.usingNativeControls()) { this.removeTechControlsListeners_(); } } } return this; } return !!this.controls_; }; /** * Toggle native controls on/off. Native controls are the controls built into * devices (e.g. default iPhone controls), Flash, or other techs * (e.g. Vimeo Controls) * **This should only be set by the current tech, because only the tech knows * if it can support native controls** * * @param {Boolean} bool True signals that native controls are on * @return {Player} Returns the player * @private * @method usingNativeControls */ Player.prototype.usingNativeControls = function usingNativeControls(bool) { if (bool !== undefined) { bool = !!bool; // force boolean // Don't trigger a change event unless it actually changed if (this.usingNativeControls_ !== bool) { this.usingNativeControls_ = bool; if (bool) { this.addClass('vjs-using-native-controls'); /** * player is using the native device controls * * @event usingnativecontrols * @memberof Player * @instance * @private */ this.trigger('usingnativecontrols'); } else { this.removeClass('vjs-using-native-controls'); /** * player is using the custom HTML controls * * @event usingcustomcontrols * @memberof Player * @instance * @private */ this.trigger('usingcustomcontrols'); } } return this; } return !!this.usingNativeControls_; }; /** * Set or get the current MediaError * * @param {*} err A MediaError or a String/Number to be turned into a MediaError * @return {MediaError|null} when getting * @return {Player} when setting * @method error */ Player.prototype.error = function error(err) { if (err === undefined) { return this.error_ || null; } // restoring to default if (err === null) { this.error_ = err; this.removeClass('vjs-error'); return this; } // error instance if (err instanceof _mediaErrorJs2['default']) { this.error_ = err; } else { this.error_ = new _mediaErrorJs2['default'](err); } // fire an error event on the player this.trigger('error'); // add the vjs-error classname to the player this.addClass('vjs-error'); // log the name of the error type and any message // ie8 just logs "[object object]" if you just log the error object _utilsLogJs2['default'].error('(CODE:' + this.error_.code + ' ' + _mediaErrorJs2['default'].errorTypes[this.error_.code] + ')', this.error_.message, this.error_); return this; }; /** * Returns whether or not the player is in the "ended" state. * * @return {Boolean} True if the player is in the ended state, false if not. * @method ended */ Player.prototype.ended = function ended() { return this.techGet_('ended'); }; /** * Returns whether or not the player is in the "seeking" state. * * @return {Boolean} True if the player is in the seeking state, false if not. * @method seeking */ Player.prototype.seeking = function seeking() { return this.techGet_('seeking'); }; /** * Returns the TimeRanges of the media that are currently available * for seeking to. * * @return {TimeRanges} the seekable intervals of the media timeline * @method seekable */ Player.prototype.seekable = function seekable() { return this.techGet_('seekable'); }; /** * Report user activity * * @param {Object} event Event object * @method reportUserActivity */ Player.prototype.reportUserActivity = function reportUserActivity(event) { this.userActivity_ = true; }; /** * Get/set if user is active * * @param {Boolean} bool Value when setting * @return {Boolean} Value if user is active user when getting * @method userActive */ Player.prototype.userActive = function userActive(bool) { if (bool !== undefined) { bool = !!bool; if (bool !== this.userActive_) { this.userActive_ = bool; if (bool) { // If the user was inactive and is now active we want to reset the // inactivity timer this.userActivity_ = true; this.removeClass('vjs-user-inactive'); this.addClass('vjs-user-active'); this.trigger('useractive'); } else { // We're switching the state to inactive manually, so erase any other // activity this.userActivity_ = false; // Chrome/Safari/IE have bugs where when you change the cursor it can // trigger a mousemove event. This causes an issue when you're hiding // the cursor when the user is inactive, and a mousemove signals user // activity. Making it impossible to go into inactive mode. Specifically // this happens in fullscreen when we really need to hide the cursor. // // When this gets resolved in ALL browsers it can be removed // https://code.google.com/p/chromium/issues/detail?id=103041 if (this.tech_) { this.tech_.one('mousemove', function (e) { e.stopPropagation(); e.preventDefault(); }); } this.removeClass('vjs-user-active'); this.addClass('vjs-user-inactive'); this.trigger('userinactive'); } } return this; } return this.userActive_; }; /** * Listen for user activity based on timeout value * * @private * @method listenForUserActivity_ */ Player.prototype.listenForUserActivity_ = function listenForUserActivity_() { var mouseInProgress = undefined, lastMoveX = undefined, lastMoveY = undefined; var handleActivity = Fn.bind(this, this.reportUserActivity); var handleMouseMove = function handleMouseMove(e) { // #1068 - Prevent mousemove spamming // Chrome Bug: https://code.google.com/p/chromium/issues/detail?id=366970 if (e.screenX !== lastMoveX || e.screenY !== lastMoveY) { lastMoveX = e.screenX; lastMoveY = e.screenY; handleActivity(); } }; var handleMouseDown = function handleMouseDown() { handleActivity(); // For as long as the they are touching the device or have their mouse down, // we consider them active even if they're not moving their finger or mouse. // So we want to continue to update that they are active this.clearInterval(mouseInProgress); // Setting userActivity=true now and setting the interval to the same time // as the activityCheck interval (250) should ensure we never miss the // next activityCheck mouseInProgress = this.setInterval(handleActivity, 250); }; var handleMouseUp = function handleMouseUp(event) { handleActivity(); // Stop the interval that maintains activity if the mouse/touch is down this.clearInterval(mouseInProgress); }; // Any mouse movement will be considered user activity this.on('mousedown', handleMouseDown); this.on('mousemove', handleMouseMove); this.on('mouseup', handleMouseUp); // Listen for keyboard navigation // Shouldn't need to use inProgress interval because of key repeat this.on('keydown', handleActivity); this.on('keyup', handleActivity); // Run an interval every 250 milliseconds instead of stuffing everything into // the mousemove/touchmove function itself, to prevent performance degradation. // `this.reportUserActivity` simply sets this.userActivity_ to true, which // then gets picked up by this loop // http://ejohn.org/blog/learning-from-twitter/ var inactivityTimeout = undefined; var activityCheck = this.setInterval(function () { // Check to see if mouse/touch activity has happened if (this.userActivity_) { // Reset the activity tracker this.userActivity_ = false; // If the user state was inactive, set the state to active this.userActive(true); // Clear any existing inactivity timeout to start the timer over this.clearTimeout(inactivityTimeout); var timeout = this.options_['inactivityTimeout']; if (timeout > 0) { // In <timeout> milliseconds, if no more activity has occurred the // user will be considered inactive inactivityTimeout = this.setTimeout(function () { // Protect against the case where the inactivityTimeout can trigger just // before the next user activity is picked up by the activityCheck loop // causing a flicker if (!this.userActivity_) { this.userActive(false); } }, timeout); } } }, 250); }; /** * Gets or sets the current playback rate. A playback rate of * 1.0 represents normal speed and 0.5 would indicate half-speed * playback, for instance. * @see https://html.spec.whatwg.org/multipage/embedded-content.html#dom-media-playbackrate * * @param {Number} rate New playback rate to set. * @return {Number} Returns the new playback rate when setting * @return {Number} Returns the current playback rate when getting * @method playbackRate */ Player.prototype.playbackRate = function playbackRate(rate) { if (rate !== undefined) { this.techCall_('setPlaybackRate', rate); return this; } if (this.tech_ && this.tech_['featuresPlaybackRate']) { return this.techGet_('playbackRate'); } else { return 1.0; } }; /** * Gets or sets the audio flag * * @param {Boolean} bool True signals that this is an audio player. * @return {Boolean} Returns true if player is audio, false if not when getting * @return {Player} Returns the player if setting * @private * @method isAudio */ Player.prototype.isAudio = function isAudio(bool) { if (bool !== undefined) { this.isAudio_ = !!bool; return this; } return !!this.isAudio_; }; /** * Returns the current state of network activity for the element, from * the codes in the list below. * - NETWORK_EMPTY (numeric value 0) * The element has not yet been initialised. All attributes are in * their initial states. * - NETWORK_IDLE (numeric value 1) * The element's resource selection algorithm is active and has * selected a resource, but it is not actually using the network at * this time. * - NETWORK_LOADING (numeric value 2) * The user agent is actively trying to download data. * - NETWORK_NO_SOURCE (numeric value 3) * The element's resource selection algorithm is active, but it has * not yet found a resource to use. * * @see https://html.spec.whatwg.org/multipage/embedded-content.html#network-states * @return {Number} the current network activity state * @method networkState */ Player.prototype.networkState = function networkState() { return this.techGet_('networkState'); }; /** * Returns a value that expresses the current state of the element * with respect to rendering the current playback position, from the * codes in the list below. * - HAVE_NOTHING (numeric value 0) * No information regarding the media resource is available. * - HAVE_METADATA (numeric value 1) * Enough of the resource has been obtained that the duration of the * resource is available. * - HAVE_CURRENT_DATA (numeric value 2) * Data for the immediate current playback position is available. * - HAVE_FUTURE_DATA (numeric value 3) * Data for the immediate current playback position is available, as * well as enough data for the user agent to advance the current * playback position in the direction of playback. * - HAVE_ENOUGH_DATA (numeric value 4) * The user agent estimates that enough data is available for * playback to proceed uninterrupted. * * @see https://html.spec.whatwg.org/multipage/embedded-content.html#dom-media-readystate * @return {Number} the current playback rendering state * @method readyState */ Player.prototype.readyState = function readyState() { return this.techGet_('readyState'); }; /* * Text tracks are tracks of timed text events. * Captions - text displayed over the video for the hearing impaired * Subtitles - text displayed over the video for those who don't understand language in the video * Chapters - text displayed in a menu allowing the user to jump to particular points (chapters) in the video * Descriptions (not supported yet) - audio descriptions that are read back to the user by a screen reading device */ /** * Get an array of associated text tracks. captions, subtitles, chapters, descriptions * http://www.w3.org/html/wg/drafts/html/master/embedded-content-0.html#dom-media-texttracks * * @return {Array} Array of track objects * @method textTracks */ Player.prototype.textTracks = function textTracks() { // cannot use techGet_ directly because it checks to see whether the tech is ready. // Flash is unlikely to be ready in time but textTracks should still work. return this.tech_ && this.tech_['textTracks'](); }; /** * Get an array of remote text tracks * * @return {Array} * @method remoteTextTracks */ Player.prototype.remoteTextTracks = function remoteTextTracks() { return this.tech_ && this.tech_['remoteTextTracks'](); }; /** * Add a text track * In addition to the W3C settings we allow adding additional info through options. * http://www.w3.org/html/wg/drafts/html/master/embedded-content-0.html#dom-media-addtexttrack * * @param {String} kind Captions, subtitles, chapters, descriptions, or metadata * @param {String=} label Optional label * @param {String=} language Optional language * @method addTextTrack */ Player.prototype.addTextTrack = function addTextTrack(kind, label, language) { return this.tech_ && this.tech_['addTextTrack'](kind, label, language); }; /** * Add a remote text track * * @param {Object} options Options for remote text track * @method addRemoteTextTrack */ Player.prototype.addRemoteTextTrack = function addRemoteTextTrack(options) { return this.tech_ && this.tech_['addRemoteTextTrack'](options); }; /** * Remove a remote text track * * @param {Object} track Remote text track to remove * @method removeRemoteTextTrack */ Player.prototype.removeRemoteTextTrack = function removeRemoteTextTrack(track) { this.tech_ && this.tech_['removeRemoteTextTrack'](track); }; /** * Get video width * * @return {Number} Video width * @method videoWidth */ Player.prototype.videoWidth = function videoWidth() { return this.tech_ && this.tech_.videoWidth && this.tech_.videoWidth() || 0; }; /** * Get video height * * @return {Number} Video height * @method videoHeight */ Player.prototype.videoHeight = function videoHeight() { return this.tech_ && this.tech_.videoHeight && this.tech_.videoHeight() || 0; }; // Methods to add support for // initialTime: function(){ return this.techCall_('initialTime'); }, // startOffsetTime: function(){ return this.techCall_('startOffsetTime'); }, // played: function(){ return this.techCall_('played'); }, // videoTracks: function(){ return this.techCall_('videoTracks'); }, // audioTracks: function(){ return this.techCall_('audioTracks'); }, // defaultPlaybackRate: function(){ return this.techCall_('defaultPlaybackRate'); }, // defaultMuted: function(){ return this.techCall_('defaultMuted'); } /** * The player's language code * NOTE: The language should be set in the player options if you want the * the controls to be built with a specific language. Changing the lanugage * later will not update controls text. * * @param {String} code The locale string * @return {String} The locale string when getting * @return {Player} self when setting * @method language */ Player.prototype.language = function language(code) { if (code === undefined) { return this.language_; } this.language_ = ('' + code).toLowerCase(); return this; }; /** * Get the player's language dictionary * Merge every time, because a newly added plugin might call videojs.addLanguage() at any time * Languages specified directly in the player options have precedence * * @return {Array} Array of languages * @method languages */ Player.prototype.languages = function languages() { return _utilsMergeOptionsJs2['default'](Player.prototype.options_.languages, this.languages_); }; /** * Converts track info to JSON * * @return {Object} JSON object of options * @method toJSON */ Player.prototype.toJSON = function toJSON() { var options = _utilsMergeOptionsJs2['default'](this.options_); var tracks = options.tracks; options.tracks = []; for (var i = 0; i < tracks.length; i++) { var track = tracks[i]; // deep merge tracks and null out player so no circular references track = _utilsMergeOptionsJs2['default'](track); track.player = undefined; options.tracks[i] = track; } return options; }; /** * Gets tag settings * * @param {Element} tag The player tag * @return {Array} An array of sources and track objects * @static * @method getTagSettings */ Player.getTagSettings = function getTagSettings(tag) { var baseOptions = { 'sources': [], 'tracks': [] }; var tagOptions = Dom.getElAttributes(tag); var dataSetup = tagOptions['data-setup']; // Check if data-setup attr exists. if (dataSetup !== null) { // Parse options JSON var _safeParseTuple = _safeJsonParseTuple2['default'](dataSetup || '{}'); var err = _safeParseTuple[0]; var data = _safeParseTuple[1]; if (err) { _utilsLogJs2['default'].error(err); } _objectAssign2['default'](tagOptions, data); } _objectAssign2['default'](baseOptions, tagOptions); // Get tag children settings if (tag.hasChildNodes()) { var children = tag.childNodes; for (var i = 0, j = children.length; i < j; i++) { var child = children[i]; // Change case needed: http://ejohn.org/blog/nodename-case-sensitivity/ var childName = child.nodeName.toLowerCase(); if (childName === 'source') { baseOptions.sources.push(Dom.getElAttributes(child)); } else if (childName === 'track') { baseOptions.tracks.push(Dom.getElAttributes(child)); } } } return baseOptions; }; return Player; })(_componentJs2['default']); Player.players = {}; var navigator = _globalWindow2['default'].navigator; /* * Player instance options, surfaced using options * options = Player.prototype.options_ * Make changes in options, not here. * * @type {Object} * @private */ Player.prototype.options_ = { // Default order of fallback technology techOrder: ['html5', 'flash'], // techOrder: ['flash','html5'], html5: {}, flash: {}, // defaultVolume: 0.85, defaultVolume: 0.00, // The freakin seaguls are driving me crazy! // default inactivity timeout inactivityTimeout: 2000, // default playback rates playbackRates: [], // Add playback rate selection by adding rates // 'playbackRates': [0.5, 1, 1.5, 2], // Included control sets children: ['mediaLoader', 'posterImage', 'textTrackDisplay', 'loadingSpinner', 'bigPlayButton', 'controlBar', 'errorDisplay', 'textTrackSettings'], language: _globalDocument2['default'].getElementsByTagName('html')[0].getAttribute('lang') || navigator.languages && navigator.languages[0] || navigator.userLanguage || navigator.language || 'en', // locales and their language translations languages: {}, // Default message to show when a video cannot be played. notSupportedMessage: 'No compatible source was found for this video.' }; /** * Fired when the player has initial duration and dimension information * * @event loadedmetadata */ Player.prototype.handleLoadedMetaData_; /** * Fired when the player has downloaded data at the current playback position * * @event loadeddata */ Player.prototype.handleLoadedData_; /** * Fired when the user is active, e.g. moves the mouse over the player * * @event useractive */ Player.prototype.handleUserActive_; /** * Fired when the user is inactive, e.g. a short delay after the last mouse move or control interaction * * @event userinactive */ Player.prototype.handleUserInactive_; /** * Fired when the current playback position has changed * * During playback this is fired every 15-250 milliseconds, depending on the * playback technology in use. * * @event timeupdate */ Player.prototype.handleTimeUpdate_; /** * Fired when the volume changes * * @event volumechange */ Player.prototype.handleVolumeChange_; /** * Fired when an error occurs * * @event error */ Player.prototype.handleError_; Player.prototype.flexNotSupported_ = function () { var elem = _globalDocument2['default'].createElement('i'); // Note: We don't actually use flexBasis (or flexOrder), but it's one of the more // common flex features that we can rely on when checking for flex support. return !('flexBasis' in elem.style || 'webkitFlexBasis' in elem.style || 'mozFlexBasis' in elem.style || 'msFlexBasis' in elem.style || 'msFlexOrder' in elem.style) /* IE10-specific (2012 flex spec) */; }; _componentJs2['default'].registerComponent('Player', Player); exports['default'] = Player; module.exports = exports['default']; // If empty string, make it a parsable json object. },{"./big-play-button.js":56,"./component.js":58,"./control-bar/control-bar.js":59,"./error-display.js":89,"./fullscreen-api.js":92,"./loading-spinner.js":93,"./media-error.js":94,"./poster-image.js":100,"./tech/html5.js":105,"./tech/loader.js":106,"./tracks/text-track-display.js":109,"./tracks/text-track-list-converter.js":111,"./tracks/text-track-settings.js":113,"./utils/browser.js":115,"./utils/buffer.js":116,"./utils/dom.js":118,"./utils/events.js":119,"./utils/fn.js":120,"./utils/guid.js":122,"./utils/log.js":123,"./utils/merge-options.js":124,"./utils/stylesheet.js":125,"./utils/time-ranges.js":126,"./utils/to-title-case.js":127,"global/document":1,"global/window":2,"object.assign":43,"safe-json-parse/tuple":48}],99:[function(_dereq_,module,exports){ /** * @file plugins.js */ 'use strict'; exports.__esModule = true; function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { 'default': obj }; } var _playerJs = _dereq_('./player.js'); var _playerJs2 = _interopRequireDefault(_playerJs); /** * The method for registering a video.js plugin * * @param {String} name The name of the plugin * @param {Function} init The function that is run when the player inits * @method plugin */ var plugin = function plugin(name, init) { _playerJs2['default'].prototype[name] = init; }; exports['default'] = plugin; module.exports = exports['default']; },{"./player.js":98}],100:[function(_dereq_,module,exports){ /** * @file poster-image.js */ 'use strict'; exports.__esModule = true; function _interopRequireWildcard(obj) { if (obj && obj.__esModule) { return obj; } else { var newObj = {}; if (obj != null) { for (var key in obj) { if (Object.prototype.hasOwnProperty.call(obj, key)) newObj[key] = obj[key]; } } newObj['default'] = obj; return newObj; } } function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { 'default': obj }; } function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError('Cannot call a class as a function'); } } function _inherits(subClass, superClass) { if (typeof superClass !== 'function' && superClass !== null) { throw new TypeError('Super expression must either be null or a function, not ' + typeof superClass); } subClass.prototype = Object.create(superClass && superClass.prototype, { constructor: { value: subClass, enumerable: false, writable: true, configurable: true } }); if (superClass) Object.setPrototypeOf ? Object.setPrototypeOf(subClass, superClass) : subClass.__proto__ = superClass; } var _buttonJs = _dereq_('./button.js'); var _buttonJs2 = _interopRequireDefault(_buttonJs); var _componentJs = _dereq_('./component.js'); var _componentJs2 = _interopRequireDefault(_componentJs); var _utilsFnJs = _dereq_('./utils/fn.js'); var Fn = _interopRequireWildcard(_utilsFnJs); var _utilsDomJs = _dereq_('./utils/dom.js'); var Dom = _interopRequireWildcard(_utilsDomJs); var _utilsBrowserJs = _dereq_('./utils/browser.js'); var browser = _interopRequireWildcard(_utilsBrowserJs); /** * The component that handles showing the poster image. * * @param {Player|Object} player * @param {Object=} options * @extends Button * @class PosterImage */ var PosterImage = (function (_Button) { _inherits(PosterImage, _Button); function PosterImage(player, options) { _classCallCheck(this, PosterImage); _Button.call(this, player, options); this.update(); player.on('posterchange', Fn.bind(this, this.update)); } /** * Clean up the poster image * * @method dispose */ PosterImage.prototype.dispose = function dispose() { this.player().off('posterchange', this.update); _Button.prototype.dispose.call(this); }; /** * Create the poster's image element * * @return {Element} * @method createEl */ PosterImage.prototype.createEl = function createEl() { var el = Dom.createEl('div', { className: 'vjs-poster', // Don't want poster to be tabbable. tabIndex: -1 }); // To ensure the poster image resizes while maintaining its original aspect // ratio, use a div with `background-size` when available. For browsers that // do not support `background-size` (e.g. IE8), fall back on using a regular // img element. if (!browser.BACKGROUND_SIZE_SUPPORTED) { this.fallbackImg_ = Dom.createEl('img'); el.appendChild(this.fallbackImg_); } return el; }; /** * Event handler for updates to the player's poster source * * @method update */ PosterImage.prototype.update = function update() { var url = this.player().poster(); this.setSrc(url); // If there's no poster source we should display:none on this component // so it's not still clickable or right-clickable if (url) { this.show(); } else { this.hide(); } }; /** * Set the poster source depending on the display method * * @param {String} url The URL to the poster source * @method setSrc */ PosterImage.prototype.setSrc = function setSrc(url) { if (this.fallbackImg_) { this.fallbackImg_.src = url; } else { var backgroundImage = ''; // Any falsey values should stay as an empty string, otherwise // this will throw an extra error if (url) { backgroundImage = 'url("' + url + '")'; } this.el_.style.backgroundImage = backgroundImage; } }; /** * Event handler for clicks on the poster image * * @method handleClick */ PosterImage.prototype.handleClick = function handleClick() { // We don't want a click to trigger playback when controls are disabled // but CSS should be hiding the poster to prevent that from happening if (this.player_.paused()) { this.player_.play(); } else { this.player_.pause(); } }; return PosterImage; })(_buttonJs2['default']); _componentJs2['default'].registerComponent('PosterImage', PosterImage); exports['default'] = PosterImage; module.exports = exports['default']; },{"./button.js":57,"./component.js":58,"./utils/browser.js":115,"./utils/dom.js":118,"./utils/fn.js":120}],101:[function(_dereq_,module,exports){ /** * @file setup.js * * Functions for automatically setting up a player * based on the data-setup attribute of the video tag */ 'use strict'; exports.__esModule = true; function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { 'default': obj }; } function _interopRequireWildcard(obj) { if (obj && obj.__esModule) { return obj; } else { var newObj = {}; if (obj != null) { for (var key in obj) { if (Object.prototype.hasOwnProperty.call(obj, key)) newObj[key] = obj[key]; } } newObj['default'] = obj; return newObj; } } var _utilsEventsJs = _dereq_('./utils/events.js'); var Events = _interopRequireWildcard(_utilsEventsJs); var _globalDocument = _dereq_('global/document'); var _globalDocument2 = _interopRequireDefault(_globalDocument); var _globalWindow = _dereq_('global/window'); var _globalWindow2 = _interopRequireDefault(_globalWindow); var _windowLoaded = false; var videojs = undefined; // Automatically set up any tags that have a data-setup attribute var autoSetup = function autoSetup() { // One day, when we stop supporting IE8, go back to this, but in the meantime...*hack hack hack* // var vids = Array.prototype.slice.call(document.getElementsByTagName('video')); // var audios = Array.prototype.slice.call(document.getElementsByTagName('audio')); // var mediaEls = vids.concat(audios); // Because IE8 doesn't support calling slice on a node list, we need to loop through each list of elements // to build up a new, combined list of elements. var vids = _globalDocument2['default'].getElementsByTagName('video'); var audios = _globalDocument2['default'].getElementsByTagName('audio'); var mediaEls = []; if (vids && vids.length > 0) { for (var i = 0, e = vids.length; i < e; i++) { mediaEls.push(vids[i]); } } if (audios && audios.length > 0) { for (var i = 0, e = audios.length; i < e; i++) { mediaEls.push(audios[i]); } } // Check if any media elements exist if (mediaEls && mediaEls.length > 0) { for (var i = 0, e = mediaEls.length; i < e; i++) { var mediaEl = mediaEls[i]; // Check if element exists, has getAttribute func. // IE seems to consider typeof el.getAttribute == 'object' instead of 'function' like expected, at least when loading the player immediately. if (mediaEl && mediaEl.getAttribute) { // Make sure this player hasn't already been set up. if (mediaEl['player'] === undefined) { var options = mediaEl.getAttribute('data-setup'); // Check if data-setup attr exists. // We only auto-setup if they've added the data-setup attr. if (options !== null) { // Create new video.js instance. var player = videojs(mediaEl); } } // If getAttribute isn't defined, we need to wait for the DOM. } else { autoSetupTimeout(1); break; } } // No videos were found, so keep looping unless page is finished loading. } else if (!_windowLoaded) { autoSetupTimeout(1); } }; // Pause to let the DOM keep processing var autoSetupTimeout = function autoSetupTimeout(wait, vjs) { videojs = vjs; setTimeout(autoSetup, wait); }; if (_globalDocument2['default'].readyState === 'complete') { _windowLoaded = true; } else { Events.one(_globalWindow2['default'], 'load', function () { _windowLoaded = true; }); } var hasLoaded = function hasLoaded() { return _windowLoaded; }; exports.autoSetup = autoSetup; exports.autoSetupTimeout = autoSetupTimeout; exports.hasLoaded = hasLoaded; },{"./utils/events.js":119,"global/document":1,"global/window":2}],102:[function(_dereq_,module,exports){ /** * @file slider.js */ 'use strict'; exports.__esModule = true; function _interopRequireWildcard(obj) { if (obj && obj.__esModule) { return obj; } else { var newObj = {}; if (obj != null) { for (var key in obj) { if (Object.prototype.hasOwnProperty.call(obj, key)) newObj[key] = obj[key]; } } newObj['default'] = obj; return newObj; } } function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { 'default': obj }; } function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError('Cannot call a class as a function'); } } function _inherits(subClass, superClass) { if (typeof superClass !== 'function' && superClass !== null) { throw new TypeError('Super expression must either be null or a function, not ' + typeof superClass); } subClass.prototype = Object.create(superClass && superClass.prototype, { constructor: { value: subClass, enumerable: false, writable: true, configurable: true } }); if (superClass) Object.setPrototypeOf ? Object.setPrototypeOf(subClass, superClass) : subClass.__proto__ = superClass; } var _componentJs = _dereq_('../component.js'); var _componentJs2 = _interopRequireDefault(_componentJs); var _utilsDomJs = _dereq_('../utils/dom.js'); var Dom = _interopRequireWildcard(_utilsDomJs); var _globalDocument = _dereq_('global/document'); var _globalDocument2 = _interopRequireDefault(_globalDocument); var _objectAssign = _dereq_('object.assign'); var _objectAssign2 = _interopRequireDefault(_objectAssign); /** * The base functionality for sliders like the volume bar and seek bar * * @param {Player|Object} player * @param {Object=} options * @extends Component * @class Slider */ var Slider = (function (_Component) { _inherits(Slider, _Component); function Slider(player, options) { _classCallCheck(this, Slider); _Component.call(this, player, options); // Set property names to bar to match with the child Slider class is looking for this.bar = this.getChild(this.options_.barName); // Set a horizontal or vertical class on the slider depending on the slider type this.vertical(!!this.options_.vertical); this.on('mousedown', this.handleMouseDown); this.on('touchstart', this.handleMouseDown); this.on('focus', this.handleFocus); this.on('blur', this.handleBlur); this.on('click', this.handleClick); this.on(player, 'controlsvisible', this.update); this.on(player, this.playerEvent, this.update); } /** * Create the component's DOM element * * @param {String} type Type of element to create * @param {Object=} props List of properties in Object form * @return {Element} * @method createEl */ Slider.prototype.createEl = function createEl(type) { var props = arguments.length <= 1 || arguments[1] === undefined ? {} : arguments[1]; var attributes = arguments.length <= 2 || arguments[2] === undefined ? {} : arguments[2]; // Add the slider element class to all sub classes props.className = props.className + ' vjs-slider'; props = _objectAssign2['default']({ tabIndex: 0 }, props); attributes = _objectAssign2['default']({ 'role': 'slider', 'aria-valuenow': 0, 'aria-valuemin': 0, 'aria-valuemax': 100, tabIndex: 0 }, attributes); return _Component.prototype.createEl.call(this, type, props, attributes); }; /** * Handle mouse down on slider * * @param {Object} event Mouse down event object * @method handleMouseDown */ Slider.prototype.handleMouseDown = function handleMouseDown(event) { event.preventDefault(); Dom.blockTextSelection(); this.addClass('vjs-sliding'); this.trigger('slideractive'); this.on(_globalDocument2['default'], 'mousemove', this.handleMouseMove); this.on(_globalDocument2['default'], 'mouseup', this.handleMouseUp); this.on(_globalDocument2['default'], 'touchmove', this.handleMouseMove); this.on(_globalDocument2['default'], 'touchend', this.handleMouseUp); this.handleMouseMove(event); }; /** * To be overridden by a subclass * * @method handleMouseMove */ Slider.prototype.handleMouseMove = function handleMouseMove() {}; /** * Handle mouse up on Slider * * @method handleMouseUp */ Slider.prototype.handleMouseUp = function handleMouseUp() { Dom.unblockTextSelection(); this.removeClass('vjs-sliding'); this.trigger('sliderinactive'); this.off(_globalDocument2['default'], 'mousemove', this.handleMouseMove); this.off(_globalDocument2['default'], 'mouseup', this.handleMouseUp); this.off(_globalDocument2['default'], 'touchmove', this.handleMouseMove); this.off(_globalDocument2['default'], 'touchend', this.handleMouseUp); this.update(); }; /** * Update slider * * @method update */ Slider.prototype.update = function update() { // In VolumeBar init we have a setTimeout for update that pops and update to the end of the // execution stack. The player is destroyed before then update will cause an error if (!this.el_) return; // If scrubbing, we could use a cached value to make the handle keep up with the user's mouse. // On HTML5 browsers scrubbing is really smooth, but some flash players are slow, so we might want to utilize this later. // var progress = (this.player_.scrubbing()) ? this.player_.getCache().currentTime / this.player_.duration() : this.player_.currentTime() / this.player_.duration(); var progress = this.getPercent(); var bar = this.bar; // If there's no bar... if (!bar) return; // Protect against no duration and other division issues if (typeof progress !== 'number' || progress !== progress || progress < 0 || progress === Infinity) { progress = 0; } // Convert to a percentage for setting var percentage = (progress * 100).toFixed(2) + '%'; // Set the new bar width or height if (this.vertical()) { bar.el().style.height = percentage; } else { bar.el().style.width = percentage; } }; /** * Calculate distance for slider * * @param {Object} event Event object * @method calculateDistance */ Slider.prototype.calculateDistance = function calculateDistance(event) { var position = Dom.getPointerPosition(this.el_, event); if (this.vertical()) { return position.y; } return position.x; }; /** * Handle on focus for slider * * @method handleFocus */ Slider.prototype.handleFocus = function handleFocus() { this.on(_globalDocument2['default'], 'keydown', this.handleKeyPress); }; /** * Handle key press for slider * * @param {Object} event Event object * @method handleKeyPress */ Slider.prototype.handleKeyPress = function handleKeyPress(event) { if (event.which === 37 || event.which === 40) { // Left and Down Arrows event.preventDefault(); this.stepBack(); } else if (event.which === 38 || event.which === 39) { // Up and Right Arrows event.preventDefault(); this.stepForward(); } }; /** * Handle on blur for slider * * @method handleBlur */ Slider.prototype.handleBlur = function handleBlur() { this.off(_globalDocument2['default'], 'keydown', this.handleKeyPress); }; /** * Listener for click events on slider, used to prevent clicks * from bubbling up to parent elements like button menus. * * @param {Object} event Event object * @method handleClick */ Slider.prototype.handleClick = function handleClick(event) { event.stopImmediatePropagation(); event.preventDefault(); }; /** * Get/set if slider is horizontal for vertical * * @param {Boolean} bool True if slider is vertical, false is horizontal * @return {Boolean} True if slider is vertical, false is horizontal * @method vertical */ Slider.prototype.vertical = function vertical(bool) { if (bool === undefined) { return this.vertical_ || false; } this.vertical_ = !!bool; if (this.vertical_) { this.addClass('vjs-slider-vertical'); } else { this.addClass('vjs-slider-horizontal'); } return this; }; return Slider; })(_componentJs2['default']); _componentJs2['default'].registerComponent('Slider', Slider); exports['default'] = Slider; module.exports = exports['default']; },{"../component.js":58,"../utils/dom.js":118,"global/document":1,"object.assign":43}],103:[function(_dereq_,module,exports){ /** * @file flash-rtmp.js */ 'use strict'; exports.__esModule = true; function FlashRtmpDecorator(Flash) { Flash.streamingFormats = { 'rtmp/mp4': 'MP4', 'rtmp/flv': 'FLV' }; Flash.streamFromParts = function (connection, stream) { return connection + '&' + stream; }; Flash.streamToParts = function (src) { var parts = { connection: '', stream: '' }; if (!src) return parts; // Look for the normal URL separator we expect, '&'. // If found, we split the URL into two pieces around the // first '&'. var connEnd = src.indexOf('&'); var streamBegin = undefined; if (connEnd !== -1) { streamBegin = connEnd + 1; } else { // If there's not a '&', we use the last '/' as the delimiter. connEnd = streamBegin = src.lastIndexOf('/') + 1; if (connEnd === 0) { // really, there's not a '/'? connEnd = streamBegin = src.length; } } parts.connection = src.substring(0, connEnd); parts.stream = src.substring(streamBegin, src.length); return parts; }; Flash.isStreamingType = function (srcType) { return srcType in Flash.streamingFormats; }; // RTMP has four variations, any string starting // with one of these protocols should be valid Flash.RTMP_RE = /^rtmp[set]?:\/\//i; Flash.isStreamingSrc = function (src) { return Flash.RTMP_RE.test(src); }; /** * A source handler for RTMP urls * @type {Object} */ Flash.rtmpSourceHandler = {}; /** * Check Flash can handle the source natively * @param {Object} source The source object * @return {String} 'probably', 'maybe', or '' (empty string) */ Flash.rtmpSourceHandler.canHandleSource = function (source) { if (Flash.isStreamingType(source.type) || Flash.isStreamingSrc(source.src)) { return 'maybe'; } return ''; }; /** * Pass the source to the flash object * Adaptive source handlers will have more complicated workflows before passing * video data to the video element * @param {Object} source The source object * @param {Flash} tech The instance of the Flash tech */ Flash.rtmpSourceHandler.handleSource = function (source, tech) { var srcParts = Flash.streamToParts(source.src); tech['setRtmpConnection'](srcParts.connection); tech['setRtmpStream'](srcParts.stream); }; // Register the native source handler Flash.registerSourceHandler(Flash.rtmpSourceHandler); return Flash; } exports['default'] = FlashRtmpDecorator; module.exports = exports['default']; },{}],104:[function(_dereq_,module,exports){ /** * @file flash.js * VideoJS-SWF - Custom Flash Player with HTML5-ish API * https://github.com/zencoder/video-js-swf * Not using setupTriggers. Using global onEvent func to distribute events */ 'use strict'; exports.__esModule = true; function _interopRequireWildcard(obj) { if (obj && obj.__esModule) { return obj; } else { var newObj = {}; if (obj != null) { for (var key in obj) { if (Object.prototype.hasOwnProperty.call(obj, key)) newObj[key] = obj[key]; } } newObj['default'] = obj; return newObj; } } function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { 'default': obj }; } function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError('Cannot call a class as a function'); } } function _inherits(subClass, superClass) { if (typeof superClass !== 'function' && superClass !== null) { throw new TypeError('Super expression must either be null or a function, not ' + typeof superClass); } subClass.prototype = Object.create(superClass && superClass.prototype, { constructor: { value: subClass, enumerable: false, writable: true, configurable: true } }); if (superClass) Object.setPrototypeOf ? Object.setPrototypeOf(subClass, superClass) : subClass.__proto__ = superClass; } var _tech = _dereq_('./tech'); var _tech2 = _interopRequireDefault(_tech); var _utilsDomJs = _dereq_('../utils/dom.js'); var Dom = _interopRequireWildcard(_utilsDomJs); var _utilsUrlJs = _dereq_('../utils/url.js'); var Url = _interopRequireWildcard(_utilsUrlJs); var _utilsTimeRangesJs = _dereq_('../utils/time-ranges.js'); var _flashRtmp = _dereq_('./flash-rtmp'); var _flashRtmp2 = _interopRequireDefault(_flashRtmp); var _component = _dereq_('../component'); var _component2 = _interopRequireDefault(_component); var _globalWindow = _dereq_('global/window'); var _globalWindow2 = _interopRequireDefault(_globalWindow); var _objectAssign = _dereq_('object.assign'); var _objectAssign2 = _interopRequireDefault(_objectAssign); var navigator = _globalWindow2['default'].navigator; /** * Flash Media Controller - Wrapper for fallback SWF API * * @param {Object=} options Object of option names and values * @param {Function=} ready Ready callback function * @extends Tech * @class Flash */ var Flash = (function (_Tech) { _inherits(Flash, _Tech); function Flash(options, ready) { _classCallCheck(this, Flash); _Tech.call(this, options, ready); // Set the source when ready if (options.source) { this.ready(function () { this.setSource(options.source); }, true); } // Having issues with Flash reloading on certain page actions (hide/resize/fullscreen) in certain browsers // This allows resetting the playhead when we catch the reload if (options.startTime) { this.ready(function () { this.load(); this.play(); this.currentTime(options.startTime); }, true); } // Add global window functions that the swf expects // A 4.x workflow we weren't able to solve for in 5.0 // because of the need to hard code these functions // into the swf for security reasons _globalWindow2['default'].videojs = _globalWindow2['default'].videojs || {}; _globalWindow2['default'].videojs.Flash = _globalWindow2['default'].videojs.Flash || {}; _globalWindow2['default'].videojs.Flash.onReady = Flash.onReady; _globalWindow2['default'].videojs.Flash.onEvent = Flash.onEvent; _globalWindow2['default'].videojs.Flash.onError = Flash.onError; this.on('seeked', function () { this.lastSeekTarget_ = undefined; }); } // Create setters and getters for attributes /** * Create the component's DOM element * * @return {Element} * @method createEl */ Flash.prototype.createEl = function createEl() { var options = this.options_; // If video.js is hosted locally you should also set the location // for the hosted swf, which should be relative to the page (not video.js) // Otherwise this adds a CDN url. // The CDN also auto-adds a swf URL for that specific version. if (!options.swf) { options.swf = '//vjs.zencdn.net/swf/5.0.0-rc1/video-js.swf'; } // Generate ID for swf object var objId = options.techId; // Merge default flashvars with ones passed in to init var flashVars = _objectAssign2['default']({ // SWF Callback Functions 'readyFunction': 'videojs.Flash.onReady', 'eventProxyFunction': 'videojs.Flash.onEvent', 'errorEventProxyFunction': 'videojs.Flash.onError', // Player Settings 'autoplay': options.autoplay, 'preload': options.preload, 'loop': options.loop, 'muted': options.muted }, options.flashVars); // Merge default parames with ones passed in var params = _objectAssign2['default']({ 'wmode': 'opaque', // Opaque is needed to overlay controls, but can affect playback performance 'bgcolor': '#000000' // Using bgcolor prevents a white flash when the object is loading }, options.params); // Merge default attributes with ones passed in var attributes = _objectAssign2['default']({ 'id': objId, 'name': objId, // Both ID and Name needed or swf to identify itself 'class': 'vjs-tech' }, options.attributes); this.el_ = Flash.embed(options.swf, flashVars, params, attributes); this.el_.tech = this; return this.el_; }; /** * Play for flash tech * * @method play */ Flash.prototype.play = function play() { if (this.ended()) { this.setCurrentTime(0); } this.el_.vjs_play(); }; /** * Pause for flash tech * * @method pause */ Flash.prototype.pause = function pause() { this.el_.vjs_pause(); }; /** * Get/set video * * @param {Object=} src Source object * @return {Object} * @method src */ Flash.prototype.src = function src(_src) { if (_src === undefined) { return this.currentSrc(); } // Setting src through `src` not `setSrc` will be deprecated return this.setSrc(_src); }; /** * Set video * * @param {Object=} src Source object * @deprecated * @method setSrc */ Flash.prototype.setSrc = function setSrc(src) { // Make sure source URL is absolute. src = Url.getAbsoluteURL(src); this.el_.vjs_src(src); // Currently the SWF doesn't autoplay if you load a source later. // e.g. Load player w/ no source, wait 2s, set src. if (this.autoplay()) { var tech = this; this.setTimeout(function () { tech.play(); }, 0); } }; /** * Returns true if the tech is currently seeking. * @return {boolean} true if seeking */ Flash.prototype.seeking = function seeking() { return this.lastSeekTarget_ !== undefined; }; /** * Set current time * * @param {Number} time Current time of video * @method setCurrentTime */ Flash.prototype.setCurrentTime = function setCurrentTime(time) { var seekable = this.seekable(); if (seekable.length) { // clamp to the current seekable range time = time > seekable.start(0) ? time : seekable.start(0); time = time < seekable.end(seekable.length - 1) ? time : seekable.end(seekable.length - 1); this.lastSeekTarget_ = time; this.trigger('seeking'); this.el_.vjs_setProperty('currentTime', time); _Tech.prototype.setCurrentTime.call(this); } }; /** * Get current time * * @param {Number=} time Current time of video * @return {Number} Current time * @method currentTime */ Flash.prototype.currentTime = function currentTime(time) { // when seeking make the reported time keep up with the requested time // by reading the time we're seeking to if (this.seeking()) { return this.lastSeekTarget_ || 0; } return this.el_.vjs_getProperty('currentTime'); }; /** * Get current source * * @method currentSrc */ Flash.prototype.currentSrc = function currentSrc() { if (this.currentSource_) { return this.currentSource_.src; } else { return this.el_.vjs_getProperty('currentSrc'); } }; /** * Load media into player * * @method load */ Flash.prototype.load = function load() { this.el_.vjs_load(); }; /** * Get poster * * @method poster */ Flash.prototype.poster = function poster() { this.el_.vjs_getProperty('poster'); }; /** * Poster images are not handled by the Flash tech so make this a no-op * * @method setPoster */ Flash.prototype.setPoster = function setPoster() {}; /** * Determine if can seek in media * * @return {TimeRangeObject} * @method seekable */ Flash.prototype.seekable = function seekable() { var duration = this.duration(); if (duration === 0) { return _utilsTimeRangesJs.createTimeRange(); } return _utilsTimeRangesJs.createTimeRange(0, duration); }; /** * Get buffered time range * * @return {TimeRangeObject} * @method buffered */ Flash.prototype.buffered = function buffered() { var ranges = this.el_.vjs_getProperty('buffered'); if (ranges.length === 0) { return _utilsTimeRangesJs.createTimeRange(); } return _utilsTimeRangesJs.createTimeRange(ranges[0][0], ranges[0][1]); }; /** * Get fullscreen support - * Flash does not allow fullscreen through javascript * so always returns false * * @return {Boolean} false * @method supportsFullScreen */ Flash.prototype.supportsFullScreen = function supportsFullScreen() { return false; // Flash does not allow fullscreen through javascript }; /** * Request to enter fullscreen * Flash does not allow fullscreen through javascript * so always returns false * * @return {Boolean} false * @method enterFullScreen */ Flash.prototype.enterFullScreen = function enterFullScreen() { return false; }; return Flash; })(_tech2['default']); var _api = Flash.prototype; var _readWrite = 'rtmpConnection,rtmpStream,preload,defaultPlaybackRate,playbackRate,autoplay,loop,mediaGroup,controller,controls,volume,muted,defaultMuted'.split(','); var _readOnly = 'networkState,readyState,initialTime,duration,startOffsetTime,paused,ended,videoTracks,audioTracks,videoWidth,videoHeight'.split(','); function _createSetter(attr) { var attrUpper = attr.charAt(0).toUpperCase() + attr.slice(1); _api['set' + attrUpper] = function (val) { return this.el_.vjs_setProperty(attr, val); }; } function _createGetter(attr) { _api[attr] = function () { return this.el_.vjs_getProperty(attr); }; } // Create getter and setters for all read/write attributes for (var i = 0; i < _readWrite.length; i++) { _createGetter(_readWrite[i]); _createSetter(_readWrite[i]); } // Create getters for read-only attributes for (var i = 0; i < _readOnly.length; i++) { _createGetter(_readOnly[i]); } /* Flash Support Testing -------------------------------------------------------- */ Flash.isSupported = function () { return Flash.version()[0] >= 10; // return swfobject.hasFlashPlayerVersion('10'); }; // Add Source Handler pattern functions to this tech _tech2['default'].withSourceHandlers(Flash); /* * The default native source handler. * This simply passes the source to the video element. Nothing fancy. * * @param {Object} source The source object * @param {Flash} tech The instance of the Flash tech */ Flash.nativeSourceHandler = {}; /* * Check Flash can handle the source natively * * @param {Object} source The source object * @return {String} 'probably', 'maybe', or '' (empty string) */ Flash.nativeSourceHandler.canHandleSource = function (source) { var type; function guessMimeType(src) { var ext = Url.getFileExtension(src); if (ext) { return 'video/' + ext; } return ''; } if (!source.type) { type = guessMimeType(source.src); } else { // Strip code information from the type because we don't get that specific type = source.type.replace(/;.*/, '').toLowerCase(); } if (type in Flash.formats) { return 'maybe'; } return ''; }; /* * Pass the source to the flash object * Adaptive source handlers will have more complicated workflows before passing * video data to the video element * * @param {Object} source The source object * @param {Flash} tech The instance of the Flash tech */ Flash.nativeSourceHandler.handleSource = function (source, tech) { tech.setSrc(source.src); }; /* * Clean up the source handler when disposing the player or switching sources.. * (no cleanup is needed when supporting the format natively) */ Flash.nativeSourceHandler.dispose = function () {}; // Register the native source handler Flash.registerSourceHandler(Flash.nativeSourceHandler); Flash.formats = { 'video/flv': 'FLV', 'video/x-flv': 'FLV', 'video/mp4': 'MP4', 'video/m4v': 'MP4' }; Flash.onReady = function (currSwf) { var el = Dom.getEl(currSwf); var tech = el && el.tech; // if there is no el then the tech has been disposed // and the tech element was removed from the player div if (tech && tech.el()) { // check that the flash object is really ready Flash.checkReady(tech); } }; // The SWF isn't always ready when it says it is. Sometimes the API functions still need to be added to the object. // If it's not ready, we set a timeout to check again shortly. Flash.checkReady = function (tech) { // stop worrying if the tech has been disposed if (!tech.el()) { return; } // check if API property exists if (tech.el().vjs_getProperty) { // tell tech it's ready tech.triggerReady(); } else { // wait longer this.setTimeout(function () { Flash['checkReady'](tech); }, 50); } }; // Trigger events from the swf on the player Flash.onEvent = function (swfID, eventName) { var tech = Dom.getEl(swfID).tech; tech.trigger(eventName); }; // Log errors from the swf Flash.onError = function (swfID, err) { var tech = Dom.getEl(swfID).tech; // trigger MEDIA_ERR_SRC_NOT_SUPPORTED if (err === 'srcnotfound') { return tech.error(4); } // trigger a custom error tech.error('FLASH: ' + err); }; // Flash Version Check Flash.version = function () { var version = '0,0,0'; // IE try { version = new _globalWindow2['default'].ActiveXObject('ShockwaveFlash.ShockwaveFlash').GetVariable('$version').replace(/\D+/g, ',').match(/^,?(.+),?$/)[1]; // other browsers } catch (e) { try { if (navigator.mimeTypes['application/x-shockwave-flash'].enabledPlugin) { version = (navigator.plugins['Shockwave Flash 2.0'] || navigator.plugins['Shockwave Flash']).description.replace(/\D+/g, ',').match(/^,?(.+),?$/)[1]; } } catch (err) {} } return version.split(','); }; // Flash embedding method. Only used in non-iframe mode Flash.embed = function (swf, flashVars, params, attributes) { var code = Flash.getEmbedCode(swf, flashVars, params, attributes); // Get element by embedding code and retrieving created element var obj = Dom.createEl('div', { innerHTML: code }).childNodes[0]; return obj; }; Flash.getEmbedCode = function (swf, flashVars, params, attributes) { var objTag = '<object type="application/x-shockwave-flash" '; var flashVarsString = ''; var paramsString = ''; var attrsString = ''; // Convert flash vars to string if (flashVars) { Object.getOwnPropertyNames(flashVars).forEach(function (key) { flashVarsString += key + '=' + flashVars[key] + '&amp;'; }); } // Add swf, flashVars, and other default params params = _objectAssign2['default']({ 'movie': swf, 'flashvars': flashVarsString, 'allowScriptAccess': 'always', // Required to talk to swf 'allowNetworking': 'all' // All should be default, but having security issues. }, params); // Create param tags string Object.getOwnPropertyNames(params).forEach(function (key) { paramsString += '<param name="' + key + '" value="' + params[key] + '" />'; }); attributes = _objectAssign2['default']({ // Add swf to attributes (need both for IE and Others to work) 'data': swf, // Default to 100% width/height 'width': '100%', 'height': '100%' }, attributes); // Create Attributes string Object.getOwnPropertyNames(attributes).forEach(function (key) { attrsString += key + '="' + attributes[key] + '" '; }); return '' + objTag + attrsString + '>' + paramsString + '</object>'; }; // Run Flash through the RTMP decorator _flashRtmp2['default'](Flash); _component2['default'].registerComponent('Flash', Flash); exports['default'] = Flash; module.exports = exports['default']; },{"../component":58,"../utils/dom.js":118,"../utils/time-ranges.js":126,"../utils/url.js":128,"./flash-rtmp":103,"./tech":107,"global/window":2,"object.assign":43}],105:[function(_dereq_,module,exports){ /** * @file html5.js * HTML5 Media Controller - Wrapper for HTML5 Media API */ 'use strict'; exports.__esModule = true; function _interopRequireWildcard(obj) { if (obj && obj.__esModule) { return obj; } else { var newObj = {}; if (obj != null) { for (var key in obj) { if (Object.prototype.hasOwnProperty.call(obj, key)) newObj[key] = obj[key]; } } newObj['default'] = obj; return newObj; } } function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { 'default': obj }; } function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError('Cannot call a class as a function'); } } function _inherits(subClass, superClass) { if (typeof superClass !== 'function' && superClass !== null) { throw new TypeError('Super expression must either be null or a function, not ' + typeof superClass); } subClass.prototype = Object.create(superClass && superClass.prototype, { constructor: { value: subClass, enumerable: false, writable: true, configurable: true } }); if (superClass) Object.setPrototypeOf ? Object.setPrototypeOf(subClass, superClass) : subClass.__proto__ = superClass; } var _techJs = _dereq_('./tech.js'); var _techJs2 = _interopRequireDefault(_techJs); var _component = _dereq_('../component'); var _component2 = _interopRequireDefault(_component); var _utilsDomJs = _dereq_('../utils/dom.js'); var Dom = _interopRequireWildcard(_utilsDomJs); var _utilsUrlJs = _dereq_('../utils/url.js'); var Url = _interopRequireWildcard(_utilsUrlJs); var _utilsFnJs = _dereq_('../utils/fn.js'); var Fn = _interopRequireWildcard(_utilsFnJs); var _utilsLogJs = _dereq_('../utils/log.js'); var _utilsLogJs2 = _interopRequireDefault(_utilsLogJs); var _utilsBrowserJs = _dereq_('../utils/browser.js'); var browser = _interopRequireWildcard(_utilsBrowserJs); var _globalDocument = _dereq_('global/document'); var _globalDocument2 = _interopRequireDefault(_globalDocument); var _globalWindow = _dereq_('global/window'); var _globalWindow2 = _interopRequireDefault(_globalWindow); var _objectAssign = _dereq_('object.assign'); var _objectAssign2 = _interopRequireDefault(_objectAssign); var _utilsMergeOptionsJs = _dereq_('../utils/merge-options.js'); var _utilsMergeOptionsJs2 = _interopRequireDefault(_utilsMergeOptionsJs); /** * HTML5 Media Controller - Wrapper for HTML5 Media API * * @param {Object=} options Object of option names and values * @param {Function=} ready Ready callback function * @extends Tech * @class Html5 */ var Html5 = (function (_Tech) { _inherits(Html5, _Tech); function Html5(options, ready) { _classCallCheck(this, Html5); _Tech.call(this, options, ready); var source = options.source; // Set the source if one is provided // 1) Check if the source is new (if not, we want to keep the original so playback isn't interrupted) // 2) Check to see if the network state of the tag was failed at init, and if so, reset the source // anyway so the error gets fired. if (source && (this.el_.currentSrc !== source.src || options.tag && options.tag.initNetworkState_ === 3)) { this.setSource(source); } else { this.handleLateInit_(this.el_); } if (this.el_.hasChildNodes()) { var nodes = this.el_.childNodes; var nodesLength = nodes.length; var removeNodes = []; while (nodesLength--) { var node = nodes[nodesLength]; var nodeName = node.nodeName.toLowerCase(); if (nodeName === 'track') { if (!this.featuresNativeTextTracks) { // Empty video tag tracks so the built-in player doesn't use them also. // This may not be fast enough to stop HTML5 browsers from reading the tags // so we'll need to turn off any default tracks if we're manually doing // captions and subtitles. videoElement.textTracks removeNodes.push(node); } else { this.remoteTextTracks().addTrack_(node.track); } } } for (var i = 0; i < removeNodes.length; i++) { this.el_.removeChild(removeNodes[i]); } } if (this.featuresNativeTextTracks) { this.handleTextTrackChange_ = Fn.bind(this, this.handleTextTrackChange); this.handleTextTrackAdd_ = Fn.bind(this, this.handleTextTrackAdd); this.handleTextTrackRemove_ = Fn.bind(this, this.handleTextTrackRemove); this.proxyNativeTextTracks_(); } // Determine if native controls should be used // Our goal should be to get the custom controls on mobile solid everywhere // so we can remove this all together. Right now this will block custom // controls on touch enabled laptops like the Chrome Pixel if (browser.TOUCH_ENABLED && options.nativeControlsForTouch === true || browser.IS_IPHONE || browser.IS_NATIVE_ANDROID) { this.setControls(true); } this.triggerReady(); } /* HTML5 Support Testing ---------------------------------------------------- */ /* * Element for testing browser HTML5 video capabilities * * @type {Element} * @constant * @private */ /** * Dispose of html5 media element * * @method dispose */ Html5.prototype.dispose = function dispose() { var tt = this.el().textTracks; var emulatedTt = this.textTracks(); // remove native event listeners if (tt && tt.removeEventListener) { tt.removeEventListener('change', this.handleTextTrackChange_); tt.removeEventListener('addtrack', this.handleTextTrackAdd_); tt.removeEventListener('removetrack', this.handleTextTrackRemove_); } // clearout the emulated text track list. var i = emulatedTt.length; while (i--) { emulatedTt.removeTrack_(emulatedTt[i]); } Html5.disposeMediaElement(this.el_); _Tech.prototype.dispose.call(this); }; /** * Create the component's DOM element * * @return {Element} * @method createEl */ Html5.prototype.createEl = function createEl() { var el = this.options_.tag; // Check if this browser supports moving the element into the box. // On the iPhone video will break if you move the element, // So we have to create a brand new element. if (!el || this['movingMediaElementInDOM'] === false) { // If the original tag is still there, clone and remove it. if (el) { var clone = el.cloneNode(true); el.parentNode.insertBefore(clone, el); Html5.disposeMediaElement(el); el = clone; } else { el = _globalDocument2['default'].createElement('video'); // determine if native controls should be used var tagAttributes = this.options_.tag && Dom.getElAttributes(this.options_.tag); var attributes = _utilsMergeOptionsJs2['default']({}, tagAttributes); if (!browser.TOUCH_ENABLED || this.options_.nativeControlsForTouch !== true) { delete attributes.controls; } Dom.setElAttributes(el, _objectAssign2['default'](attributes, { id: this.options_.techId, 'class': 'vjs-tech' })); } } // Update specific tag settings, in case they were overridden var settingsAttrs = ['autoplay', 'preload', 'loop', 'muted']; for (var i = settingsAttrs.length - 1; i >= 0; i--) { var attr = settingsAttrs[i]; var overwriteAttrs = {}; if (typeof this.options_[attr] !== 'undefined') { overwriteAttrs[attr] = this.options_[attr]; } Dom.setElAttributes(el, overwriteAttrs); } return el; // jenniisawesome = true; }; // If we're loading the playback object after it has started loading // or playing the video (often with autoplay on) then the loadstart event // has already fired and we need to fire it manually because many things // rely on it. Html5.prototype.handleLateInit_ = function handleLateInit_(el) { var _this = this; if (el.networkState === 0 || el.networkState === 3) { // The video element hasn't started loading the source yet // or didn't find a source return; } if (el.readyState === 0) { var _ret = (function () { // NetworkState is set synchronously BUT loadstart is fired at the // end of the current stack, usually before setInterval(fn, 0). // So at this point we know loadstart may have already fired or is // about to fire, and either way the player hasn't seen it yet. // We don't want to fire loadstart prematurely here and cause a // double loadstart so we'll wait and see if it happens between now // and the next loop, and fire it if not. // HOWEVER, we also want to make sure it fires before loadedmetadata // which could also happen between now and the next loop, so we'll // watch for that also. var loadstartFired = false; var setLoadstartFired = function setLoadstartFired() { loadstartFired = true; }; _this.on('loadstart', setLoadstartFired); var triggerLoadstart = function triggerLoadstart() { // We did miss the original loadstart. Make sure the player // sees loadstart before loadedmetadata if (!loadstartFired) { this.trigger('loadstart'); } }; _this.on('loadedmetadata', triggerLoadstart); _this.ready(function () { this.off('loadstart', setLoadstartFired); this.off('loadedmetadata', triggerLoadstart); if (!loadstartFired) { // We did miss the original native loadstart. Fire it now. this.trigger('loadstart'); } }); return { v: undefined }; })(); if (typeof _ret === 'object') return _ret.v; } // From here on we know that loadstart already fired and we missed it. // The other readyState events aren't as much of a problem if we double // them, so not going to go to as much trouble as loadstart to prevent // that unless we find reason to. var eventsToTrigger = ['loadstart']; // loadedmetadata: newly equal to HAVE_METADATA (1) or greater eventsToTrigger.push('loadedmetadata'); // loadeddata: newly increased to HAVE_CURRENT_DATA (2) or greater if (el.readyState >= 2) { eventsToTrigger.push('loadeddata'); } // canplay: newly increased to HAVE_FUTURE_DATA (3) or greater if (el.readyState >= 3) { eventsToTrigger.push('canplay'); } // canplaythrough: newly equal to HAVE_ENOUGH_DATA (4) if (el.readyState >= 4) { eventsToTrigger.push('canplaythrough'); } // We still need to give the player time to add event listeners this.ready(function () { eventsToTrigger.forEach(function (type) { this.trigger(type); }, this); }); }; Html5.prototype.proxyNativeTextTracks_ = function proxyNativeTextTracks_() { var tt = this.el().textTracks; if (tt && tt.addEventListener) { tt.addEventListener('change', this.handleTextTrackChange_); tt.addEventListener('addtrack', this.handleTextTrackAdd_); tt.addEventListener('removetrack', this.handleTextTrackRemove_); } }; Html5.prototype.handleTextTrackChange = function handleTextTrackChange(e) { var tt = this.textTracks(); this.textTracks().trigger({ type: 'change', target: tt, currentTarget: tt, srcElement: tt }); }; Html5.prototype.handleTextTrackAdd = function handleTextTrackAdd(e) { this.textTracks().addTrack_(e.track); }; Html5.prototype.handleTextTrackRemove = function handleTextTrackRemove(e) { this.textTracks().removeTrack_(e.track); }; /** * Play for html5 tech * * @method play */ Html5.prototype.play = function play() { this.el_.play(); }; /** * Pause for html5 tech * * @method pause */ Html5.prototype.pause = function pause() { this.el_.pause(); }; /** * Paused for html5 tech * * @return {Boolean} * @method paused */ Html5.prototype.paused = function paused() { return this.el_.paused; }; /** * Get current time * * @return {Number} * @method currentTime */ Html5.prototype.currentTime = function currentTime() { return this.el_.currentTime; }; /** * Set current time * * @param {Number} seconds Current time of video * @method setCurrentTime */ Html5.prototype.setCurrentTime = function setCurrentTime(seconds) { try { this.el_.currentTime = seconds; } catch (e) { _utilsLogJs2['default'](e, 'Video is not ready. (Video.js)'); // this.warning(VideoJS.warnings.videoNotReady); } }; /** * Get duration * * @return {Number} * @method duration */ Html5.prototype.duration = function duration() { return this.el_.duration || 0; }; /** * Get a TimeRange object that represents the intersection * of the time ranges for which the user agent has all * relevant media * * @return {TimeRangeObject} * @method buffered */ Html5.prototype.buffered = function buffered() { return this.el_.buffered; }; /** * Get volume level * * @return {Number} * @method volume */ Html5.prototype.volume = function volume() { return this.el_.volume; }; /** * Set volume level * * @param {Number} percentAsDecimal Volume percent as a decimal * @method setVolume */ Html5.prototype.setVolume = function setVolume(percentAsDecimal) { this.el_.volume = percentAsDecimal; }; /** * Get if muted * * @return {Boolean} * @method muted */ Html5.prototype.muted = function muted() { return this.el_.muted; }; /** * Set muted * * @param {Boolean} If player is to be muted or note * @method setMuted */ Html5.prototype.setMuted = function setMuted(muted) { this.el_.muted = muted; }; /** * Get player width * * @return {Number} * @method width */ Html5.prototype.width = function width() { return this.el_.offsetWidth; }; /** * Get player height * * @return {Number} * @method height */ Html5.prototype.height = function height() { return this.el_.offsetHeight; }; /** * Get if there is fullscreen support * * @return {Boolean} * @method supportsFullScreen */ Html5.prototype.supportsFullScreen = function supportsFullScreen() { if (typeof this.el_.webkitEnterFullScreen === 'function') { var userAgent = _globalWindow2['default'].navigator.userAgent; // Seems to be broken in Chromium/Chrome && Safari in Leopard if (/Android/.test(userAgent) || !/Chrome|Mac OS X 10.5/.test(userAgent)) { return true; } } return false; }; /** * Request to enter fullscreen * * @method enterFullScreen */ Html5.prototype.enterFullScreen = function enterFullScreen() { var video = this.el_; if ('webkitDisplayingFullscreen' in video) { this.one('webkitbeginfullscreen', function () { this.one('webkitendfullscreen', function () { this.trigger('fullscreenchange', { isFullscreen: false }); }); this.trigger('fullscreenchange', { isFullscreen: true }); }); } if (video.paused && video.networkState <= video.HAVE_METADATA) { // attempt to prime the video element for programmatic access // this isn't necessary on the desktop but shouldn't hurt this.el_.play(); // playing and pausing synchronously during the transition to fullscreen // can get iOS ~6.1 devices into a play/pause loop this.setTimeout(function () { video.pause(); video.webkitEnterFullScreen(); }, 0); } else { video.webkitEnterFullScreen(); } }; /** * Request to exit fullscreen * * @method exitFullScreen */ Html5.prototype.exitFullScreen = function exitFullScreen() { this.el_.webkitExitFullScreen(); }; /** * Get/set video * * @param {Object=} src Source object * @return {Object} * @method src */ Html5.prototype.src = function src(_src) { if (_src === undefined) { return this.el_.src; } else { // Setting src through `src` instead of `setSrc` will be deprecated this.setSrc(_src); } }; /** * Set video * * @param {Object} src Source object * @deprecated * @method setSrc */ Html5.prototype.setSrc = function setSrc(src) { this.el_.src = src; }; /** * Load media into player * * @method load */ Html5.prototype.load = function load() { this.el_.load(); }; /** * Get current source * * @return {Object} * @method currentSrc */ Html5.prototype.currentSrc = function currentSrc() { return this.el_.currentSrc; }; /** * Get poster * * @return {String} * @method poster */ Html5.prototype.poster = function poster() { return this.el_.poster; }; /** * Set poster * * @param {String} val URL to poster image * @method */ Html5.prototype.setPoster = function setPoster(val) { this.el_.poster = val; }; /** * Get preload attribute * * @return {String} * @method preload */ Html5.prototype.preload = function preload() { return this.el_.preload; }; /** * Set preload attribute * * @param {String} val Value for preload attribute * @method setPreload */ Html5.prototype.setPreload = function setPreload(val) { this.el_.preload = val; }; /** * Get autoplay attribute * * @return {String} * @method autoplay */ Html5.prototype.autoplay = function autoplay() { return this.el_.autoplay; }; /** * Set autoplay attribute * * @param {String} val Value for preload attribute * @method setAutoplay */ Html5.prototype.setAutoplay = function setAutoplay(val) { this.el_.autoplay = val; }; /** * Get controls attribute * * @return {String} * @method controls */ Html5.prototype.controls = function controls() { return this.el_.controls; }; /** * Set controls attribute * * @param {String} val Value for controls attribute * @method setControls */ Html5.prototype.setControls = function setControls(val) { this.el_.controls = !!val; }; /** * Get loop attribute * * @return {String} * @method loop */ Html5.prototype.loop = function loop() { return this.el_.loop; }; /** * Set loop attribute * * @param {String} val Value for loop attribute * @method setLoop */ Html5.prototype.setLoop = function setLoop(val) { this.el_.loop = val; }; /** * Get error value * * @return {String} * @method error */ Html5.prototype.error = function error() { return this.el_.error; }; /** * Get whether or not the player is in the "seeking" state * * @return {Boolean} * @method seeking */ Html5.prototype.seeking = function seeking() { return this.el_.seeking; }; /** * Get a TimeRanges object that represents the * ranges of the media resource to which it is possible * for the user agent to seek. * * @return {TimeRangeObject} * @method seekable */ Html5.prototype.seekable = function seekable() { return this.el_.seekable; }; /** * Get if video ended * * @return {Boolean} * @method ended */ Html5.prototype.ended = function ended() { return this.el_.ended; }; /** * Get the value of the muted content attribute * This attribute has no dynamic effect, it only * controls the default state of the element * * @return {Boolean} * @method defaultMuted */ Html5.prototype.defaultMuted = function defaultMuted() { return this.el_.defaultMuted; }; /** * Get desired speed at which the media resource is to play * * @return {Number} * @method playbackRate */ Html5.prototype.playbackRate = function playbackRate() { return this.el_.playbackRate; }; /** * Returns a TimeRanges object that represents the ranges of the * media resource that the user agent has played. * @return {TimeRangeObject} the range of points on the media * timeline that has been reached through normal playback * @see https://html.spec.whatwg.org/multipage/embedded-content.html#dom-media-played */ Html5.prototype.played = function played() { return this.el_.played; }; /** * Set desired speed at which the media resource is to play * * @param {Number} val Speed at which the media resource is to play * @method setPlaybackRate */ Html5.prototype.setPlaybackRate = function setPlaybackRate(val) { this.el_.playbackRate = val; }; /** * Get the current state of network activity for the element, from * the list below * NETWORK_EMPTY (numeric value 0) * NETWORK_IDLE (numeric value 1) * NETWORK_LOADING (numeric value 2) * NETWORK_NO_SOURCE (numeric value 3) * * @return {Number} * @method networkState */ Html5.prototype.networkState = function networkState() { return this.el_.networkState; }; /** * Get a value that expresses the current state of the element * with respect to rendering the current playback position, from * the codes in the list below * HAVE_NOTHING (numeric value 0) * HAVE_METADATA (numeric value 1) * HAVE_CURRENT_DATA (numeric value 2) * HAVE_FUTURE_DATA (numeric value 3) * HAVE_ENOUGH_DATA (numeric value 4) * * @return {Number} * @method readyState */ Html5.prototype.readyState = function readyState() { return this.el_.readyState; }; /** * Get width of video * * @return {Number} * @method videoWidth */ Html5.prototype.videoWidth = function videoWidth() { return this.el_.videoWidth; }; /** * Get height of video * * @return {Number} * @method videoHeight */ Html5.prototype.videoHeight = function videoHeight() { return this.el_.videoHeight; }; /** * Get text tracks * * @return {TextTrackList} * @method textTracks */ Html5.prototype.textTracks = function textTracks() { return _Tech.prototype.textTracks.call(this); }; /** * Creates and returns a text track object * * @param {String} kind Text track kind (subtitles, captions, descriptions * chapters and metadata) * @param {String=} label Label to identify the text track * @param {String=} language Two letter language abbreviation * @return {TextTrackObject} * @method addTextTrack */ Html5.prototype.addTextTrack = function addTextTrack(kind, label, language) { if (!this['featuresNativeTextTracks']) { return _Tech.prototype.addTextTrack.call(this, kind, label, language); } return this.el_.addTextTrack(kind, label, language); }; /** * Creates and returns a remote text track object * * @param {Object} options The object should contain values for * kind, language, label and src (location of the WebVTT file) * @return {TextTrackObject} * @method addRemoteTextTrack */ Html5.prototype.addRemoteTextTrack = function addRemoteTextTrack() { var options = arguments.length <= 0 || arguments[0] === undefined ? {} : arguments[0]; if (!this['featuresNativeTextTracks']) { return _Tech.prototype.addRemoteTextTrack.call(this, options); } var track = _globalDocument2['default'].createElement('track'); if (options['kind']) { track['kind'] = options['kind']; } if (options['label']) { track['label'] = options['label']; } if (options['language'] || options['srclang']) { track['srclang'] = options['language'] || options['srclang']; } if (options['default']) { track['default'] = options['default']; } if (options['id']) { track['id'] = options['id']; } if (options['src']) { track['src'] = options['src']; } this.el().appendChild(track); this.remoteTextTracks().addTrack_(track.track); return track; }; /** * Remove remote text track from TextTrackList object * * @param {TextTrackObject} track Texttrack object to remove * @method removeRemoteTextTrack */ Html5.prototype.removeRemoteTextTrack = function removeRemoteTextTrack(track) { if (!this['featuresNativeTextTracks']) { return _Tech.prototype.removeRemoteTextTrack.call(this, track); } var tracks, i; this.remoteTextTracks().removeTrack_(track); tracks = this.el().querySelectorAll('track'); i = tracks.length; while (i--) { if (track === tracks[i] || track === tracks[i].track) { this.el().removeChild(tracks[i]); } } }; return Html5; })(_techJs2['default']); Html5.TEST_VID = _globalDocument2['default'].createElement('video'); var track = _globalDocument2['default'].createElement('track'); track.kind = 'captions'; track.srclang = 'en'; track.label = 'English'; Html5.TEST_VID.appendChild(track); /* * Check if HTML5 video is supported by this browser/device * * @return {Boolean} */ Html5.isSupported = function () { // IE9 with no Media Player is a LIAR! (#984) try { Html5.TEST_VID['volume'] = 0.5; } catch (e) { return false; } return !!Html5.TEST_VID.canPlayType; }; // Add Source Handler pattern functions to this tech _techJs2['default'].withSourceHandlers(Html5); /* * The default native source handler. * This simply passes the source to the video element. Nothing fancy. * * @param {Object} source The source object * @param {Html5} tech The instance of the HTML5 tech */ Html5.nativeSourceHandler = {}; /* * Check if the video element can handle the source natively * * @param {Object} source The source object * @return {String} 'probably', 'maybe', or '' (empty string) */ Html5.nativeSourceHandler.canHandleSource = function (source) { var match, ext; function canPlayType(type) { // IE9 on Windows 7 without MediaPlayer throws an error here // https://github.com/videojs/video.js/issues/519 try { return Html5.TEST_VID.canPlayType(type); } catch (e) { return ''; } } // If a type was provided we should rely on that if (source.type) { return canPlayType(source.type); } else if (source.src) { // If no type, fall back to checking 'video/[EXTENSION]' ext = Url.getFileExtension(source.src); return canPlayType('video/' + ext); } return ''; }; /* * Pass the source to the video element * Adaptive source handlers will have more complicated workflows before passing * video data to the video element * * @param {Object} source The source object * @param {Html5} tech The instance of the Html5 tech */ Html5.nativeSourceHandler.handleSource = function (source, tech) { tech.setSrc(source.src); }; /* * Clean up the source handler when disposing the player or switching sources.. * (no cleanup is needed when supporting the format natively) */ Html5.nativeSourceHandler.dispose = function () {}; // Register the native source handler Html5.registerSourceHandler(Html5.nativeSourceHandler); /* * Check if the volume can be changed in this browser/device. * Volume cannot be changed in a lot of mobile devices. * Specifically, it can't be changed from 1 on iOS. * * @return {Boolean} */ Html5.canControlVolume = function () { var volume = Html5.TEST_VID.volume; Html5.TEST_VID.volume = volume / 2 + 0.1; return volume !== Html5.TEST_VID.volume; }; /* * Check if playbackRate is supported in this browser/device. * * @return {Number} [description] */ Html5.canControlPlaybackRate = function () { var playbackRate = Html5.TEST_VID.playbackRate; Html5.TEST_VID.playbackRate = playbackRate / 2 + 0.1; return playbackRate !== Html5.TEST_VID.playbackRate; }; /* * Check to see if native text tracks are supported by this browser/device * * @return {Boolean} */ Html5.supportsNativeTextTracks = function () { var supportsTextTracks; // Figure out native text track support // If mode is a number, we cannot change it because it'll disappear from view. // Browsers with numeric modes include IE10 and older (<=2013) samsung android models. // Firefox isn't playing nice either with modifying the mode // TODO: Investigate firefox: https://github.com/videojs/video.js/issues/1862 supportsTextTracks = !!Html5.TEST_VID.textTracks; if (supportsTextTracks && Html5.TEST_VID.textTracks.length > 0) { supportsTextTracks = typeof Html5.TEST_VID.textTracks[0]['mode'] !== 'number'; } if (supportsTextTracks && browser.IS_FIREFOX) { supportsTextTracks = false; } if (supportsTextTracks && !('onremovetrack' in Html5.TEST_VID.textTracks)) { supportsTextTracks = false; } return supportsTextTracks; }; /** * An array of events available on the Html5 tech. * * @private * @type {Array} */ Html5.Events = ['loadstart', 'suspend', 'abort', 'error', 'emptied', 'stalled', 'loadedmetadata', 'loadeddata', 'canplay', 'canplaythrough', 'playing', 'waiting', 'seeking', 'seeked', 'ended', 'durationchange', 'timeupdate', 'progress', 'play', 'pause', 'ratechange', 'volumechange']; /* * Set the tech's volume control support status * * @type {Boolean} */ Html5.prototype['featuresVolumeControl'] = Html5.canControlVolume(); /* * Set the tech's playbackRate support status * * @type {Boolean} */ Html5.prototype['featuresPlaybackRate'] = Html5.canControlPlaybackRate(); /* * Set the tech's status on moving the video element. * In iOS, if you move a video element in the DOM, it breaks video playback. * * @type {Boolean} */ Html5.prototype['movingMediaElementInDOM'] = !browser.IS_IOS; /* * Set the the tech's fullscreen resize support status. * HTML video is able to automatically resize when going to fullscreen. * (No longer appears to be used. Can probably be removed.) */ Html5.prototype['featuresFullscreenResize'] = true; /* * Set the tech's progress event support status * (this disables the manual progress events of the Tech) */ Html5.prototype['featuresProgressEvents'] = true; /* * Sets the tech's status on native text track support * * @type {Boolean} */ Html5.prototype['featuresNativeTextTracks'] = Html5.supportsNativeTextTracks(); // HTML5 Feature detection and Device Fixes --------------------------------- // var canPlayType = undefined; var mpegurlRE = /^application\/(?:x-|vnd\.apple\.)mpegurl/i; var mp4RE = /^video\/mp4/i; Html5.patchCanPlayType = function () { // Android 4.0 and above can play HLS to some extent but it reports being unable to do so if (browser.ANDROID_VERSION >= 4.0) { if (!canPlayType) { canPlayType = Html5.TEST_VID.constructor.prototype.canPlayType; } Html5.TEST_VID.constructor.prototype.canPlayType = function (type) { if (type && mpegurlRE.test(type)) { return 'maybe'; } return canPlayType.call(this, type); }; } // Override Android 2.2 and less canPlayType method which is broken if (browser.IS_OLD_ANDROID) { if (!canPlayType) { canPlayType = Html5.TEST_VID.constructor.prototype.canPlayType; } Html5.TEST_VID.constructor.prototype.canPlayType = function (type) { if (type && mp4RE.test(type)) { return 'maybe'; } return canPlayType.call(this, type); }; } }; Html5.unpatchCanPlayType = function () { var r = Html5.TEST_VID.constructor.prototype.canPlayType; Html5.TEST_VID.constructor.prototype.canPlayType = canPlayType; canPlayType = null; return r; }; // by default, patch the video element Html5.patchCanPlayType(); Html5.disposeMediaElement = function (el) { if (!el) { return; } if (el.parentNode) { el.parentNode.removeChild(el); } // remove any child track or source nodes to prevent their loading while (el.hasChildNodes()) { el.removeChild(el.firstChild); } // remove any src reference. not setting `src=''` because that causes a warning // in firefox el.removeAttribute('src'); // force the media element to update its loading state by calling load() // however IE on Windows 7N has a bug that throws an error so need a try/catch (#793) if (typeof el.load === 'function') { // wrapping in an iife so it's not deoptimized (#1060#discussion_r10324473) (function () { try { el.load(); } catch (e) { // not supported } })(); } }; _component2['default'].registerComponent('Html5', Html5); exports['default'] = Html5; module.exports = exports['default']; },{"../component":58,"../utils/browser.js":115,"../utils/dom.js":118,"../utils/fn.js":120,"../utils/log.js":123,"../utils/merge-options.js":124,"../utils/url.js":128,"./tech.js":107,"global/document":1,"global/window":2,"object.assign":43}],106:[function(_dereq_,module,exports){ /** * @file loader.js */ 'use strict'; exports.__esModule = true; function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { 'default': obj }; } function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError('Cannot call a class as a function'); } } function _inherits(subClass, superClass) { if (typeof superClass !== 'function' && superClass !== null) { throw new TypeError('Super expression must either be null or a function, not ' + typeof superClass); } subClass.prototype = Object.create(superClass && superClass.prototype, { constructor: { value: subClass, enumerable: false, writable: true, configurable: true } }); if (superClass) Object.setPrototypeOf ? Object.setPrototypeOf(subClass, superClass) : subClass.__proto__ = superClass; } var _component = _dereq_('../component'); var _component2 = _interopRequireDefault(_component); var _globalWindow = _dereq_('global/window'); var _globalWindow2 = _interopRequireDefault(_globalWindow); var _utilsToTitleCaseJs = _dereq_('../utils/to-title-case.js'); var _utilsToTitleCaseJs2 = _interopRequireDefault(_utilsToTitleCaseJs); /** * The Media Loader is the component that decides which playback technology to load * when the player is initialized. * * @param {Object} player Main Player * @param {Object=} options Object of option names and values * @param {Function=} ready Ready callback function * @extends Component * @class MediaLoader */ var MediaLoader = (function (_Component) { _inherits(MediaLoader, _Component); function MediaLoader(player, options, ready) { _classCallCheck(this, MediaLoader); _Component.call(this, player, options, ready); // If there are no sources when the player is initialized, // load the first supported playback technology. if (!options.playerOptions['sources'] || options.playerOptions['sources'].length === 0) { for (var i = 0, j = options.playerOptions['techOrder']; i < j.length; i++) { var techName = _utilsToTitleCaseJs2['default'](j[i]); var tech = _component2['default'].getComponent(techName); // Check if the browser supports this technology if (tech && tech.isSupported()) { player.loadTech_(techName); break; } } } else { // // Loop through playback technologies (HTML5, Flash) and check for support. // // Then load the best source. // // A few assumptions here: // // All playback technologies respect preload false. player.src(options.playerOptions['sources']); } } return MediaLoader; })(_component2['default']); _component2['default'].registerComponent('MediaLoader', MediaLoader); exports['default'] = MediaLoader; module.exports = exports['default']; },{"../component":58,"../utils/to-title-case.js":127,"global/window":2}],107:[function(_dereq_,module,exports){ /** * @file tech.js * Media Technology Controller - Base class for media playback * technology controllers like Flash and HTML5 */ 'use strict'; exports.__esModule = true; function _interopRequireWildcard(obj) { if (obj && obj.__esModule) { return obj; } else { var newObj = {}; if (obj != null) { for (var key in obj) { if (Object.prototype.hasOwnProperty.call(obj, key)) newObj[key] = obj[key]; } } newObj['default'] = obj; return newObj; } } function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { 'default': obj }; } function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError('Cannot call a class as a function'); } } function _inherits(subClass, superClass) { if (typeof superClass !== 'function' && superClass !== null) { throw new TypeError('Super expression must either be null or a function, not ' + typeof superClass); } subClass.prototype = Object.create(superClass && superClass.prototype, { constructor: { value: subClass, enumerable: false, writable: true, configurable: true } }); if (superClass) Object.setPrototypeOf ? Object.setPrototypeOf(subClass, superClass) : subClass.__proto__ = superClass; } var _component = _dereq_('../component'); var _component2 = _interopRequireDefault(_component); var _tracksTextTrack = _dereq_('../tracks/text-track'); var _tracksTextTrack2 = _interopRequireDefault(_tracksTextTrack); var _tracksTextTrackList = _dereq_('../tracks/text-track-list'); var _tracksTextTrackList2 = _interopRequireDefault(_tracksTextTrackList); var _utilsFnJs = _dereq_('../utils/fn.js'); var Fn = _interopRequireWildcard(_utilsFnJs); var _utilsLogJs = _dereq_('../utils/log.js'); var _utilsLogJs2 = _interopRequireDefault(_utilsLogJs); var _utilsTimeRangesJs = _dereq_('../utils/time-ranges.js'); var _utilsBufferJs = _dereq_('../utils/buffer.js'); var _mediaErrorJs = _dereq_('../media-error.js'); var _mediaErrorJs2 = _interopRequireDefault(_mediaErrorJs); var _globalWindow = _dereq_('global/window'); var _globalWindow2 = _interopRequireDefault(_globalWindow); var _globalDocument = _dereq_('global/document'); var _globalDocument2 = _interopRequireDefault(_globalDocument); /** * Base class for media (HTML5 Video, Flash) controllers * * @param {Object=} options Options object * @param {Function=} ready Ready callback function * @extends Component * @class Tech */ var Tech = (function (_Component) { _inherits(Tech, _Component); function Tech() { var options = arguments.length <= 0 || arguments[0] === undefined ? {} : arguments[0]; var ready = arguments.length <= 1 || arguments[1] === undefined ? function () {} : arguments[1]; _classCallCheck(this, Tech); // we don't want the tech to report user activity automatically. // This is done manually in addControlsListeners options.reportTouchActivity = false; _Component.call(this, null, options, ready); // keep track of whether the current source has played at all to // implement a very limited played() this.hasStarted_ = false; this.on('playing', function () { this.hasStarted_ = true; }); this.on('loadstart', function () { this.hasStarted_ = false; }); this.textTracks_ = options.textTracks; // Manually track progress in cases where the browser/flash player doesn't report it. if (!this.featuresProgressEvents) { this.manualProgressOn(); } // Manually track timeupdates in cases where the browser/flash player doesn't report it. if (!this.featuresTimeupdateEvents) { this.manualTimeUpdatesOn(); } if (options.nativeCaptions === false || options.nativeTextTracks === false) { this.featuresNativeTextTracks = false; } if (!this.featuresNativeTextTracks) { this.emulateTextTracks(); } this.initTextTrackListeners(); // Turn on component tap events this.emitTapEvents(); } /* * List of associated text tracks * * @type {Array} * @private */ /* Fallbacks for unsupported event types ================================================================================ */ // Manually trigger progress events based on changes to the buffered amount // Many flash players and older HTML5 browsers don't send progress or progress-like events /** * Turn on progress events * * @method manualProgressOn */ Tech.prototype.manualProgressOn = function manualProgressOn() { this.on('durationchange', this.onDurationChange); this.manualProgress = true; // Trigger progress watching when a source begins loading this.one('ready', this.trackProgress); }; /** * Turn off progress events * * @method manualProgressOff */ Tech.prototype.manualProgressOff = function manualProgressOff() { this.manualProgress = false; this.stopTrackingProgress(); this.off('durationchange', this.onDurationChange); }; /** * Track progress * * @method trackProgress */ Tech.prototype.trackProgress = function trackProgress() { this.stopTrackingProgress(); this.progressInterval = this.setInterval(Fn.bind(this, function () { // Don't trigger unless buffered amount is greater than last time var numBufferedPercent = this.bufferedPercent(); if (this.bufferedPercent_ !== numBufferedPercent) { this.trigger('progress'); } this.bufferedPercent_ = numBufferedPercent; if (numBufferedPercent === 1) { this.stopTrackingProgress(); } }), 500); }; /** * Update duration * * @method onDurationChange */ Tech.prototype.onDurationChange = function onDurationChange() { this.duration_ = this.duration(); }; /** * Create and get TimeRange object for buffering * * @return {TimeRangeObject} * @method buffered */ Tech.prototype.buffered = function buffered() { return _utilsTimeRangesJs.createTimeRange(0, 0); }; /** * Get buffered percent * * @return {Number} * @method bufferedPercent */ Tech.prototype.bufferedPercent = function bufferedPercent() { return _utilsBufferJs.bufferedPercent(this.buffered(), this.duration_); }; /** * Stops tracking progress by clearing progress interval * * @method stopTrackingProgress */ Tech.prototype.stopTrackingProgress = function stopTrackingProgress() { this.clearInterval(this.progressInterval); }; /*! Time Tracking -------------------------------------------------------------- */ /** * Set event listeners for on play and pause and tracking current time * * @method manualTimeUpdatesOn */ Tech.prototype.manualTimeUpdatesOn = function manualTimeUpdatesOn() { this.manualTimeUpdates = true; this.on('play', this.trackCurrentTime); this.on('pause', this.stopTrackingCurrentTime); }; /** * Remove event listeners for on play and pause and tracking current time * * @method manualTimeUpdatesOff */ Tech.prototype.manualTimeUpdatesOff = function manualTimeUpdatesOff() { this.manualTimeUpdates = false; this.stopTrackingCurrentTime(); this.off('play', this.trackCurrentTime); this.off('pause', this.stopTrackingCurrentTime); }; /** * Tracks current time * * @method trackCurrentTime */ Tech.prototype.trackCurrentTime = function trackCurrentTime() { if (this.currentTimeInterval) { this.stopTrackingCurrentTime(); } this.currentTimeInterval = this.setInterval(function () { this.trigger({ type: 'timeupdate', target: this, manuallyTriggered: true }); }, 250); // 42 = 24 fps // 250 is what Webkit uses // FF uses 15 }; /** * Turn off play progress tracking (when paused or dragging) * * @method stopTrackingCurrentTime */ Tech.prototype.stopTrackingCurrentTime = function stopTrackingCurrentTime() { this.clearInterval(this.currentTimeInterval); // #1002 - if the video ends right before the next timeupdate would happen, // the progress bar won't make it all the way to the end this.trigger({ type: 'timeupdate', target: this, manuallyTriggered: true }); }; /** * Turn off any manual progress or timeupdate tracking * * @method dispose */ Tech.prototype.dispose = function dispose() { // clear out text tracks because we can't reuse them between techs var textTracks = this.textTracks(); if (textTracks) { var i = textTracks.length; while (i--) { this.removeRemoteTextTrack(textTracks[i]); } } // Turn off any manual progress or timeupdate tracking if (this.manualProgress) { this.manualProgressOff(); } if (this.manualTimeUpdates) { this.manualTimeUpdatesOff(); } _Component.prototype.dispose.call(this); }; /** * When invoked without an argument, returns a MediaError object * representing the current error state of the player or null if * there is no error. When invoked with an argument, set the current * error state of the player. * @param {MediaError=} err Optional an error object * @return {MediaError} the current error object or null * @method error */ Tech.prototype.error = function error(err) { if (err !== undefined) { if (err instanceof _mediaErrorJs2['default']) { this.error_ = err; } else { this.error_ = new _mediaErrorJs2['default'](err); } this.trigger('error'); } return this.error_; }; /** * Return the time ranges that have been played through for the * current source. This implementation is incomplete. It does not * track the played time ranges, only whether the source has played * at all or not. * @return {TimeRangeObject} a single time range if this video has * played or an empty set of ranges if not. * @method played */ Tech.prototype.played = function played() { if (this.hasStarted_) { return _utilsTimeRangesJs.createTimeRange(0, 0); } return _utilsTimeRangesJs.createTimeRange(); }; /** * Set current time * * @method setCurrentTime */ Tech.prototype.setCurrentTime = function setCurrentTime() { // improve the accuracy of manual timeupdates if (this.manualTimeUpdates) { this.trigger({ type: 'timeupdate', target: this, manuallyTriggered: true }); } }; /** * Initialize texttrack listeners * * @method initTextTrackListeners */ Tech.prototype.initTextTrackListeners = function initTextTrackListeners() { var textTrackListChanges = Fn.bind(this, function () { this.trigger('texttrackchange'); }); var tracks = this.textTracks(); if (!tracks) return; tracks.addEventListener('removetrack', textTrackListChanges); tracks.addEventListener('addtrack', textTrackListChanges); this.on('dispose', Fn.bind(this, function () { tracks.removeEventListener('removetrack', textTrackListChanges); tracks.removeEventListener('addtrack', textTrackListChanges); })); }; /** * Emulate texttracks * * @method emulateTextTracks */ Tech.prototype.emulateTextTracks = function emulateTextTracks() { if (!_globalWindow2['default']['WebVTT'] && this.el().parentNode != null) { var script = _globalDocument2['default'].createElement('script'); script.src = this.options_['vtt.js'] || '../node_modules/vtt.js/dist/vtt.js'; this.el().parentNode.appendChild(script); _globalWindow2['default']['WebVTT'] = true; } var tracks = this.textTracks(); if (!tracks) { return; } var textTracksChanges = Fn.bind(this, function () { var _this = this; var updateDisplay = function updateDisplay() { return _this.trigger('texttrackchange'); }; updateDisplay(); for (var i = 0; i < tracks.length; i++) { var track = tracks[i]; track.removeEventListener('cuechange', updateDisplay); if (track.mode === 'showing') { track.addEventListener('cuechange', updateDisplay); } } }); tracks.addEventListener('change', textTracksChanges); this.on('dispose', function () { tracks.removeEventListener('change', textTracksChanges); }); }; /* * Provide default methods for text tracks. * * Html5 tech overrides these. */ /** * Get texttracks * * @returns {TextTrackList} * @method textTracks */ Tech.prototype.textTracks = function textTracks() { this.textTracks_ = this.textTracks_ || new _tracksTextTrackList2['default'](); return this.textTracks_; }; /** * Get remote texttracks * * @returns {TextTrackList} * @method remoteTextTracks */ Tech.prototype.remoteTextTracks = function remoteTextTracks() { this.remoteTextTracks_ = this.remoteTextTracks_ || new _tracksTextTrackList2['default'](); return this.remoteTextTracks_; }; /** * Creates and returns a remote text track object * * @param {String} kind Text track kind (subtitles, captions, descriptions * chapters and metadata) * @param {String=} label Label to identify the text track * @param {String=} language Two letter language abbreviation * @return {TextTrackObject} * @method addTextTrack */ Tech.prototype.addTextTrack = function addTextTrack(kind, label, language) { if (!kind) { throw new Error('TextTrack kind is required but was not provided'); } return createTrackHelper(this, kind, label, language); }; /** * Creates and returns a remote text track object * * @param {Object} options The object should contain values for * kind, language, label and src (location of the WebVTT file) * @return {TextTrackObject} * @method addRemoteTextTrack */ Tech.prototype.addRemoteTextTrack = function addRemoteTextTrack(options) { var track = createTrackHelper(this, options.kind, options.label, options.language, options); this.remoteTextTracks().addTrack_(track); return { track: track }; }; /** * Remove remote texttrack * * @param {TextTrackObject} track Texttrack to remove * @method removeRemoteTextTrack */ Tech.prototype.removeRemoteTextTrack = function removeRemoteTextTrack(track) { this.textTracks().removeTrack_(track); this.remoteTextTracks().removeTrack_(track); }; /** * Provide a default setPoster method for techs * Poster support for techs should be optional, so we don't want techs to * break if they don't have a way to set a poster. * * @method setPoster */ Tech.prototype.setPoster = function setPoster() {}; return Tech; })(_component2['default']); Tech.prototype.textTracks_; var createTrackHelper = function createTrackHelper(self, kind, label, language) { var options = arguments.length <= 4 || arguments[4] === undefined ? {} : arguments[4]; var tracks = self.textTracks(); options.kind = kind; if (label) { options.label = label; } if (language) { options.language = language; } options.tech = self; var track = new _tracksTextTrack2['default'](options); tracks.addTrack_(track); return track; }; Tech.prototype.featuresVolumeControl = true; // Resizing plugins using request fullscreen reloads the plugin Tech.prototype.featuresFullscreenResize = false; Tech.prototype.featuresPlaybackRate = false; // Optional events that we can manually mimic with timers // currently not triggered by video-js-swf Tech.prototype.featuresProgressEvents = false; Tech.prototype.featuresTimeupdateEvents = false; Tech.prototype.featuresNativeTextTracks = false; /* * A functional mixin for techs that want to use the Source Handler pattern. * * ##### EXAMPLE: * * Tech.withSourceHandlers.call(MyTech); * */ Tech.withSourceHandlers = function (_Tech) { /* * Register a source handler * Source handlers are scripts for handling specific formats. * The source handler pattern is used for adaptive formats (HLS, DASH) that * manually load video data and feed it into a Source Buffer (Media Source Extensions) * @param {Function} handler The source handler * @param {Boolean} first Register it before any existing handlers */ _Tech.registerSourceHandler = function (handler, index) { var handlers = _Tech.sourceHandlers; if (!handlers) { handlers = _Tech.sourceHandlers = []; } if (index === undefined) { // add to the end of the list index = handlers.length; } handlers.splice(index, 0, handler); }; /* * Return the first source handler that supports the source * TODO: Answer question: should 'probably' be prioritized over 'maybe' * @param {Object} source The source object * @returns {Object} The first source handler that supports the source * @returns {null} Null if no source handler is found */ _Tech.selectSourceHandler = function (source) { var handlers = _Tech.sourceHandlers || []; var can = undefined; for (var i = 0; i < handlers.length; i++) { can = handlers[i].canHandleSource(source); if (can) { return handlers[i]; } } return null; }; /* * Check if the tech can support the given source * @param {Object} srcObj The source object * @return {String} 'probably', 'maybe', or '' (empty string) */ _Tech.canPlaySource = function (srcObj) { var sh = _Tech.selectSourceHandler(srcObj); if (sh) { return sh.canHandleSource(srcObj); } return ''; }; var originalSeekable = _Tech.prototype.seekable; // when a source handler is registered, prefer its implementation of // seekable when present. _Tech.prototype.seekable = function () { if (this.sourceHandler_ && this.sourceHandler_.seekable) { return this.sourceHandler_.seekable(); } return originalSeekable.call(this); }; /* * Create a function for setting the source using a source object * and source handlers. * Should never be called unless a source handler was found. * @param {Object} source A source object with src and type keys * @return {Tech} self */ _Tech.prototype.setSource = function (source) { var sh = _Tech.selectSourceHandler(source); if (!sh) { // Fall back to a native source hander when unsupported sources are // deliberately set if (_Tech.nativeSourceHandler) { sh = _Tech.nativeSourceHandler; } else { _utilsLogJs2['default'].error('No source hander found for the current source.'); } } // Dispose any existing source handler this.disposeSourceHandler(); this.off('dispose', this.disposeSourceHandler); this.currentSource_ = source; this.sourceHandler_ = sh.handleSource(source, this); this.on('dispose', this.disposeSourceHandler); return this; }; /* * Clean up any existing source handler */ _Tech.prototype.disposeSourceHandler = function () { if (this.sourceHandler_ && this.sourceHandler_.dispose) { this.sourceHandler_.dispose(); } }; }; _component2['default'].registerComponent('Tech', Tech); // Old name for Tech _component2['default'].registerComponent('MediaTechController', Tech); exports['default'] = Tech; module.exports = exports['default']; },{"../component":58,"../media-error.js":94,"../tracks/text-track":114,"../tracks/text-track-list":112,"../utils/buffer.js":116,"../utils/fn.js":120,"../utils/log.js":123,"../utils/time-ranges.js":126,"global/document":1,"global/window":2}],108:[function(_dereq_,module,exports){ /** * @file text-track-cue-list.js */ 'use strict'; exports.__esModule = true; function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { 'default': obj }; } function _interopRequireWildcard(obj) { if (obj && obj.__esModule) { return obj; } else { var newObj = {}; if (obj != null) { for (var key in obj) { if (Object.prototype.hasOwnProperty.call(obj, key)) newObj[key] = obj[key]; } } newObj['default'] = obj; return newObj; } } var _utilsBrowserJs = _dereq_('../utils/browser.js'); var browser = _interopRequireWildcard(_utilsBrowserJs); var _globalDocument = _dereq_('global/document'); var _globalDocument2 = _interopRequireDefault(_globalDocument); /* * https://html.spec.whatwg.org/multipage/embedded-content.html#texttrackcuelist * * interface TextTrackCueList { * readonly attribute unsigned long length; * getter TextTrackCue (unsigned long index); * TextTrackCue? getCueById(DOMString id); * }; */ var TextTrackCueList = function TextTrackCueList(cues) { var list = this; if (browser.IS_IE8) { list = _globalDocument2['default'].createElement('custom'); for (var prop in TextTrackCueList.prototype) { list[prop] = TextTrackCueList.prototype[prop]; } } TextTrackCueList.prototype.setCues_.call(list, cues); Object.defineProperty(list, 'length', { get: function get() { return this.length_; } }); if (browser.IS_IE8) { return list; } }; TextTrackCueList.prototype.setCues_ = function (cues) { var oldLength = this.length || 0; var i = 0; var l = cues.length; this.cues_ = cues; this.length_ = cues.length; var defineProp = function defineProp(i) { if (!('' + i in this)) { Object.defineProperty(this, '' + i, { get: function get() { return this.cues_[i]; } }); } }; if (oldLength < l) { i = oldLength; for (; i < l; i++) { defineProp.call(this, i); } } }; TextTrackCueList.prototype.getCueById = function (id) { var result = null; for (var i = 0, l = this.length; i < l; i++) { var cue = this[i]; if (cue.id === id) { result = cue; break; } } return result; }; exports['default'] = TextTrackCueList; module.exports = exports['default']; },{"../utils/browser.js":115,"global/document":1}],109:[function(_dereq_,module,exports){ /** * @file text-track-display.js */ 'use strict'; exports.__esModule = true; function _interopRequireWildcard(obj) { if (obj && obj.__esModule) { return obj; } else { var newObj = {}; if (obj != null) { for (var key in obj) { if (Object.prototype.hasOwnProperty.call(obj, key)) newObj[key] = obj[key]; } } newObj['default'] = obj; return newObj; } } function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { 'default': obj }; } function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError('Cannot call a class as a function'); } } function _inherits(subClass, superClass) { if (typeof superClass !== 'function' && superClass !== null) { throw new TypeError('Super expression must either be null or a function, not ' + typeof superClass); } subClass.prototype = Object.create(superClass && superClass.prototype, { constructor: { value: subClass, enumerable: false, writable: true, configurable: true } }); if (superClass) Object.setPrototypeOf ? Object.setPrototypeOf(subClass, superClass) : subClass.__proto__ = superClass; } var _component = _dereq_('../component'); var _component2 = _interopRequireDefault(_component); var _menuMenuJs = _dereq_('../menu/menu.js'); var _menuMenuJs2 = _interopRequireDefault(_menuMenuJs); var _menuMenuItemJs = _dereq_('../menu/menu-item.js'); var _menuMenuItemJs2 = _interopRequireDefault(_menuMenuItemJs); var _menuMenuButtonJs = _dereq_('../menu/menu-button.js'); var _menuMenuButtonJs2 = _interopRequireDefault(_menuMenuButtonJs); var _utilsFnJs = _dereq_('../utils/fn.js'); var Fn = _interopRequireWildcard(_utilsFnJs); var _globalDocument = _dereq_('global/document'); var _globalDocument2 = _interopRequireDefault(_globalDocument); var _globalWindow = _dereq_('global/window'); var _globalWindow2 = _interopRequireDefault(_globalWindow); var darkGray = '#222'; var lightGray = '#ccc'; var fontMap = { monospace: 'monospace', sansSerif: 'sans-serif', serif: 'serif', monospaceSansSerif: '"Andale Mono", "Lucida Console", monospace', monospaceSerif: '"Courier New", monospace', proportionalSansSerif: 'sans-serif', proportionalSerif: 'serif', casual: '"Comic Sans MS", Impact, fantasy', script: '"Monotype Corsiva", cursive', smallcaps: '"Andale Mono", "Lucida Console", monospace, sans-serif' }; /** * The component for displaying text track cues * * @param {Object} player Main Player * @param {Object=} options Object of option names and values * @param {Function=} ready Ready callback function * @extends Component * @class TextTrackDisplay */ var TextTrackDisplay = (function (_Component) { _inherits(TextTrackDisplay, _Component); function TextTrackDisplay(player, options, ready) { _classCallCheck(this, TextTrackDisplay); _Component.call(this, player, options, ready); player.on('loadstart', Fn.bind(this, this.toggleDisplay)); player.on('texttrackchange', Fn.bind(this, this.updateDisplay)); // This used to be called during player init, but was causing an error // if a track should show by default and the display hadn't loaded yet. // Should probably be moved to an external track loader when we support // tracks that don't need a display. player.ready(Fn.bind(this, function () { if (player.tech_ && player.tech_['featuresNativeTextTracks']) { this.hide(); return; } player.on('fullscreenchange', Fn.bind(this, this.updateDisplay)); var tracks = this.options_.playerOptions['tracks'] || []; for (var i = 0; i < tracks.length; i++) { var track = tracks[i]; this.player_.addRemoteTextTrack(track); } })); } /** * Add cue HTML to display * * @param {Number} color Hex number for color, like #f0e * @param {Number} opacity Value for opacity,0.0 - 1.0 * @return {RGBAColor} In the form 'rgba(255, 0, 0, 0.3)' * @method constructColor */ /** * Toggle display texttracks * * @method toggleDisplay */ TextTrackDisplay.prototype.toggleDisplay = function toggleDisplay() { if (this.player_.tech_ && this.player_.tech_['featuresNativeTextTracks']) { this.hide(); } else { this.show(); } }; /** * Create the component's DOM element * * @return {Element} * @method createEl */ TextTrackDisplay.prototype.createEl = function createEl() { return _Component.prototype.createEl.call(this, 'div', { className: 'vjs-text-track-display' }); }; /** * Clear display texttracks * * @method clearDisplay */ TextTrackDisplay.prototype.clearDisplay = function clearDisplay() { if (typeof _globalWindow2['default']['WebVTT'] === 'function') { _globalWindow2['default']['WebVTT']['processCues'](_globalWindow2['default'], [], this.el_); } }; /** * Update display texttracks * * @method updateDisplay */ TextTrackDisplay.prototype.updateDisplay = function updateDisplay() { var tracks = this.player_.textTracks(); this.clearDisplay(); if (!tracks) { return; } for (var i = 0; i < tracks.length; i++) { var track = tracks[i]; if (track['mode'] === 'showing') { this.updateForTrack(track); } } }; /** * Add texttrack to texttrack list * * @param {TextTrackObject} track Texttrack object to be added to list * @method updateForTrack */ TextTrackDisplay.prototype.updateForTrack = function updateForTrack(track) { if (typeof _globalWindow2['default']['WebVTT'] !== 'function' || !track['activeCues']) { return; } var overrides = this.player_['textTrackSettings'].getValues(); var cues = []; for (var _i = 0; _i < track['activeCues'].length; _i++) { cues.push(track['activeCues'][_i]); } _globalWindow2['default']['WebVTT']['processCues'](_globalWindow2['default'], track['activeCues'], this.el_); var i = cues.length; while (i--) { var cueDiv = cues[i].displayState; if (overrides.color) { cueDiv.firstChild.style.color = overrides.color; } if (overrides.textOpacity) { tryUpdateStyle(cueDiv.firstChild, 'color', constructColor(overrides.color || '#fff', overrides.textOpacity)); } if (overrides.backgroundColor) { cueDiv.firstChild.style.backgroundColor = overrides.backgroundColor; } if (overrides.backgroundOpacity) { tryUpdateStyle(cueDiv.firstChild, 'backgroundColor', constructColor(overrides.backgroundColor || '#000', overrides.backgroundOpacity)); } if (overrides.windowColor) { if (overrides.windowOpacity) { tryUpdateStyle(cueDiv, 'backgroundColor', constructColor(overrides.windowColor, overrides.windowOpacity)); } else { cueDiv.style.backgroundColor = overrides.windowColor; } } if (overrides.edgeStyle) { if (overrides.edgeStyle === 'dropshadow') { cueDiv.firstChild.style.textShadow = '2px 2px 3px ' + darkGray + ', 2px 2px 4px ' + darkGray + ', 2px 2px 5px ' + darkGray; } else if (overrides.edgeStyle === 'raised') { cueDiv.firstChild.style.textShadow = '1px 1px ' + darkGray + ', 2px 2px ' + darkGray + ', 3px 3px ' + darkGray; } else if (overrides.edgeStyle === 'depressed') { cueDiv.firstChild.style.textShadow = '1px 1px ' + lightGray + ', 0 1px ' + lightGray + ', -1px -1px ' + darkGray + ', 0 -1px ' + darkGray; } else if (overrides.edgeStyle === 'uniform') { cueDiv.firstChild.style.textShadow = '0 0 4px ' + darkGray + ', 0 0 4px ' + darkGray + ', 0 0 4px ' + darkGray + ', 0 0 4px ' + darkGray; } } if (overrides.fontPercent && overrides.fontPercent !== 1) { var fontSize = _globalWindow2['default'].parseFloat(cueDiv.style.fontSize); cueDiv.style.fontSize = fontSize * overrides.fontPercent + 'px'; cueDiv.style.height = 'auto'; cueDiv.style.top = 'auto'; cueDiv.style.bottom = '2px'; } if (overrides.fontFamily && overrides.fontFamily !== 'default') { if (overrides.fontFamily === 'small-caps') { cueDiv.firstChild.style.fontVariant = 'small-caps'; } else { cueDiv.firstChild.style.fontFamily = fontMap[overrides.fontFamily]; } } } }; return TextTrackDisplay; })(_component2['default']); function constructColor(color, opacity) { return 'rgba(' + // color looks like "#f0e" parseInt(color[1] + color[1], 16) + ',' + parseInt(color[2] + color[2], 16) + ',' + parseInt(color[3] + color[3], 16) + ',' + opacity + ')'; } /** * Try to update style * Some style changes will throw an error, particularly in IE8. Those should be noops. * * @param {Element} el The element to be styles * @param {CSSProperty} style The CSS property to be styled * @param {CSSStyle} rule The actual style to be applied to the property * @method tryUpdateStyle */ function tryUpdateStyle(el, style, rule) { // try { el.style[style] = rule; } catch (e) {} } _component2['default'].registerComponent('TextTrackDisplay', TextTrackDisplay); exports['default'] = TextTrackDisplay; module.exports = exports['default']; },{"../component":58,"../menu/menu-button.js":95,"../menu/menu-item.js":96,"../menu/menu.js":97,"../utils/fn.js":120,"global/document":1,"global/window":2}],110:[function(_dereq_,module,exports){ /** * @file text-track-enums.js * * https://html.spec.whatwg.org/multipage/embedded-content.html#texttrackmode * * enum TextTrackMode { "disabled", "hidden", "showing" }; */ 'use strict'; exports.__esModule = true; var TextTrackMode = { 'disabled': 'disabled', 'hidden': 'hidden', 'showing': 'showing' }; /* * https://html.spec.whatwg.org/multipage/embedded-content.html#texttrackkind * * enum TextTrackKind { "subtitles", "captions", "descriptions", "chapters", "metadata" }; */ var TextTrackKind = { 'subtitles': 'subtitles', 'captions': 'captions', 'descriptions': 'descriptions', 'chapters': 'chapters', 'metadata': 'metadata' }; exports.TextTrackMode = TextTrackMode; exports.TextTrackKind = TextTrackKind; },{}],111:[function(_dereq_,module,exports){ /** * Utilities for capturing text track state and re-creating tracks * based on a capture. * * @file text-track-list-converter.js */ /** * Examine a single text track and return a JSON-compatible javascript * object that represents the text track's state. * @param track {TextTrackObject} the text track to query * @return {Object} a serializable javascript representation of the * @private */ 'use strict'; exports.__esModule = true; var trackToJson_ = function trackToJson_(track) { return { kind: track.kind, label: track.label, language: track.language, id: track.id, inBandMetadataTrackDispatchType: track.inBandMetadataTrackDispatchType, mode: track.mode, cues: track.cues && Array.prototype.map.call(track.cues, function (cue) { return { startTime: cue.startTime, endTime: cue.endTime, text: cue.text, id: cue.id }; }), src: track.src }; }; /** * Examine a tech and return a JSON-compatible javascript array that * represents the state of all text tracks currently configured. The * return array is compatible with `jsonToTextTracks`. * @param tech {tech} the tech object to query * @return {Array} a serializable javascript representation of the * @function textTracksToJson */ var textTracksToJson = function textTracksToJson(tech) { var trackEls = tech.el().querySelectorAll('track'); var trackObjs = Array.prototype.map.call(trackEls, function (t) { return t.track; }); var tracks = Array.prototype.map.call(trackEls, function (trackEl) { var json = trackToJson_(trackEl.track); json.src = trackEl.src; return json; }); return tracks.concat(Array.prototype.filter.call(tech.textTracks(), function (track) { return trackObjs.indexOf(track) === -1; }).map(trackToJson_)); }; /** * Creates a set of remote text tracks on a tech based on an array of * javascript text track representations. * @param json {Array} an array of text track representation objects, * like those that would be produced by `textTracksToJson` * @param tech {tech} the tech to create text tracks on * @function jsonToTextTracks */ var jsonToTextTracks = function jsonToTextTracks(json, tech) { json.forEach(function (track) { var addedTrack = tech.addRemoteTextTrack(track).track; if (!track.src && track.cues) { track.cues.forEach(function (cue) { return addedTrack.addCue(cue); }); } }); return tech.textTracks(); }; exports['default'] = { textTracksToJson: textTracksToJson, jsonToTextTracks: jsonToTextTracks, trackToJson_: trackToJson_ }; module.exports = exports['default']; },{}],112:[function(_dereq_,module,exports){ /** * @file text-track-list.js */ 'use strict'; exports.__esModule = true; function _interopRequireWildcard(obj) { if (obj && obj.__esModule) { return obj; } else { var newObj = {}; if (obj != null) { for (var key in obj) { if (Object.prototype.hasOwnProperty.call(obj, key)) newObj[key] = obj[key]; } } newObj['default'] = obj; return newObj; } } function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { 'default': obj }; } var _eventTarget = _dereq_('../event-target'); var _eventTarget2 = _interopRequireDefault(_eventTarget); var _utilsFnJs = _dereq_('../utils/fn.js'); var Fn = _interopRequireWildcard(_utilsFnJs); var _utilsBrowserJs = _dereq_('../utils/browser.js'); var browser = _interopRequireWildcard(_utilsBrowserJs); var _globalDocument = _dereq_('global/document'); var _globalDocument2 = _interopRequireDefault(_globalDocument); /* * https://html.spec.whatwg.org/multipage/embedded-content.html#texttracklist * * interface TextTrackList : EventTarget { * readonly attribute unsigned long length; * getter TextTrack (unsigned long index); * TextTrack? getTrackById(DOMString id); * * attribute EventHandler onchange; * attribute EventHandler onaddtrack; * attribute EventHandler onremovetrack; * }; */ var TextTrackList = function TextTrackList(tracks) { var list = this; if (browser.IS_IE8) { list = _globalDocument2['default'].createElement('custom'); for (var prop in TextTrackList.prototype) { list[prop] = TextTrackList.prototype[prop]; } } tracks = tracks || []; list.tracks_ = []; Object.defineProperty(list, 'length', { get: function get() { return this.tracks_.length; } }); for (var i = 0; i < tracks.length; i++) { list.addTrack_(tracks[i]); } if (browser.IS_IE8) { return list; } }; TextTrackList.prototype = Object.create(_eventTarget2['default'].prototype); TextTrackList.prototype.constructor = TextTrackList; /* * change - One or more tracks in the track list have been enabled or disabled. * addtrack - A track has been added to the track list. * removetrack - A track has been removed from the track list. */ TextTrackList.prototype.allowedEvents_ = { 'change': 'change', 'addtrack': 'addtrack', 'removetrack': 'removetrack' }; // emulate attribute EventHandler support to allow for feature detection for (var _event in TextTrackList.prototype.allowedEvents_) { TextTrackList.prototype['on' + _event] = null; } TextTrackList.prototype.addTrack_ = function (track) { var index = this.tracks_.length; if (!('' + index in this)) { Object.defineProperty(this, index, { get: function get() { return this.tracks_[index]; } }); } track.addEventListener('modechange', Fn.bind(this, function () { this.trigger('change'); })); this.tracks_.push(track); this.trigger({ type: 'addtrack', track: track }); }; TextTrackList.prototype.removeTrack_ = function (rtrack) { var result = null; var track = undefined; for (var i = 0, l = this.length; i < l; i++) { track = this[i]; if (track === rtrack) { this.tracks_.splice(i, 1); break; } } this.trigger({ type: 'removetrack', track: track }); }; TextTrackList.prototype.getTrackById = function (id) { var result = null; for (var i = 0, l = this.length; i < l; i++) { var track = this[i]; if (track.id === id) { result = track; break; } } return result; }; exports['default'] = TextTrackList; module.exports = exports['default']; },{"../event-target":90,"../utils/browser.js":115,"../utils/fn.js":120,"global/document":1}],113:[function(_dereq_,module,exports){ /** * @file text-track-settings.js */ 'use strict'; exports.__esModule = true; function _interopRequireWildcard(obj) { if (obj && obj.__esModule) { return obj; } else { var newObj = {}; if (obj != null) { for (var key in obj) { if (Object.prototype.hasOwnProperty.call(obj, key)) newObj[key] = obj[key]; } } newObj['default'] = obj; return newObj; } } function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { 'default': obj }; } function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError('Cannot call a class as a function'); } } function _inherits(subClass, superClass) { if (typeof superClass !== 'function' && superClass !== null) { throw new TypeError('Super expression must either be null or a function, not ' + typeof superClass); } subClass.prototype = Object.create(superClass && superClass.prototype, { constructor: { value: subClass, enumerable: false, writable: true, configurable: true } }); if (superClass) Object.setPrototypeOf ? Object.setPrototypeOf(subClass, superClass) : subClass.__proto__ = superClass; } var _component = _dereq_('../component'); var _component2 = _interopRequireDefault(_component); var _utilsEventsJs = _dereq_('../utils/events.js'); var Events = _interopRequireWildcard(_utilsEventsJs); var _utilsFnJs = _dereq_('../utils/fn.js'); var Fn = _interopRequireWildcard(_utilsFnJs); var _utilsLogJs = _dereq_('../utils/log.js'); var _utilsLogJs2 = _interopRequireDefault(_utilsLogJs); var _safeJsonParseTuple = _dereq_('safe-json-parse/tuple'); var _safeJsonParseTuple2 = _interopRequireDefault(_safeJsonParseTuple); var _globalWindow = _dereq_('global/window'); var _globalWindow2 = _interopRequireDefault(_globalWindow); /** * Manipulate settings of texttracks * * @param {Object} player Main Player * @param {Object=} options Object of option names and values * @extends Component * @class TextTrackSettings */ var TextTrackSettings = (function (_Component) { _inherits(TextTrackSettings, _Component); function TextTrackSettings(player, options) { _classCallCheck(this, TextTrackSettings); _Component.call(this, player, options); this.hide(); // Grab `persistTextTrackSettings` from the player options if not passed in child options if (options.persistTextTrackSettings === undefined) { this.options_.persistTextTrackSettings = this.options_.playerOptions.persistTextTrackSettings; } Events.on(this.el().querySelector('.vjs-done-button'), 'click', Fn.bind(this, function () { this.saveSettings(); this.hide(); })); Events.on(this.el().querySelector('.vjs-default-button'), 'click', Fn.bind(this, function () { this.el().querySelector('.vjs-fg-color > select').selectedIndex = 0; this.el().querySelector('.vjs-bg-color > select').selectedIndex = 0; this.el().querySelector('.window-color > select').selectedIndex = 0; this.el().querySelector('.vjs-text-opacity > select').selectedIndex = 0; this.el().querySelector('.vjs-bg-opacity > select').selectedIndex = 0; this.el().querySelector('.vjs-window-opacity > select').selectedIndex = 0; this.el().querySelector('.vjs-edge-style select').selectedIndex = 0; this.el().querySelector('.vjs-font-family select').selectedIndex = 0; this.el().querySelector('.vjs-font-percent select').selectedIndex = 2; this.updateDisplay(); })); Events.on(this.el().querySelector('.vjs-fg-color > select'), 'change', Fn.bind(this, this.updateDisplay)); Events.on(this.el().querySelector('.vjs-bg-color > select'), 'change', Fn.bind(this, this.updateDisplay)); Events.on(this.el().querySelector('.window-color > select'), 'change', Fn.bind(this, this.updateDisplay)); Events.on(this.el().querySelector('.vjs-text-opacity > select'), 'change', Fn.bind(this, this.updateDisplay)); Events.on(this.el().querySelector('.vjs-bg-opacity > select'), 'change', Fn.bind(this, this.updateDisplay)); Events.on(this.el().querySelector('.vjs-window-opacity > select'), 'change', Fn.bind(this, this.updateDisplay)); Events.on(this.el().querySelector('.vjs-font-percent select'), 'change', Fn.bind(this, this.updateDisplay)); Events.on(this.el().querySelector('.vjs-edge-style select'), 'change', Fn.bind(this, this.updateDisplay)); Events.on(this.el().querySelector('.vjs-font-family select'), 'change', Fn.bind(this, this.updateDisplay)); if (this.options_.persistTextTrackSettings) { this.restoreSettings(); } } /** * Create the component's DOM element * * @return {Element} * @method createEl */ TextTrackSettings.prototype.createEl = function createEl() { return _Component.prototype.createEl.call(this, 'div', { className: 'vjs-caption-settings vjs-modal-overlay', innerHTML: captionOptionsMenuTemplate() }); }; /** * Get texttrack settings * Settings are * .vjs-edge-style * .vjs-font-family * .vjs-fg-color * .vjs-text-opacity * .vjs-bg-color * .vjs-bg-opacity * .window-color * .vjs-window-opacity * * @return {Object} * @method getValues */ TextTrackSettings.prototype.getValues = function getValues() { var el = this.el(); var textEdge = getSelectedOptionValue(el.querySelector('.vjs-edge-style select')); var fontFamily = getSelectedOptionValue(el.querySelector('.vjs-font-family select')); var fgColor = getSelectedOptionValue(el.querySelector('.vjs-fg-color > select')); var textOpacity = getSelectedOptionValue(el.querySelector('.vjs-text-opacity > select')); var bgColor = getSelectedOptionValue(el.querySelector('.vjs-bg-color > select')); var bgOpacity = getSelectedOptionValue(el.querySelector('.vjs-bg-opacity > select')); var windowColor = getSelectedOptionValue(el.querySelector('.window-color > select')); var windowOpacity = getSelectedOptionValue(el.querySelector('.vjs-window-opacity > select')); var fontPercent = _globalWindow2['default']['parseFloat'](getSelectedOptionValue(el.querySelector('.vjs-font-percent > select'))); var result = { 'backgroundOpacity': bgOpacity, 'textOpacity': textOpacity, 'windowOpacity': windowOpacity, 'edgeStyle': textEdge, 'fontFamily': fontFamily, 'color': fgColor, 'backgroundColor': bgColor, 'windowColor': windowColor, 'fontPercent': fontPercent }; for (var _name in result) { if (result[_name] === '' || result[_name] === 'none' || _name === 'fontPercent' && result[_name] === 1.00) { delete result[_name]; } } return result; }; /** * Set texttrack settings * Settings are * .vjs-edge-style * .vjs-font-family * .vjs-fg-color * .vjs-text-opacity * .vjs-bg-color * .vjs-bg-opacity * .window-color * .vjs-window-opacity * * @param {Object} values Object with texttrack setting values * @method setValues */ TextTrackSettings.prototype.setValues = function setValues(values) { var el = this.el(); setSelectedOption(el.querySelector('.vjs-edge-style select'), values.edgeStyle); setSelectedOption(el.querySelector('.vjs-font-family select'), values.fontFamily); setSelectedOption(el.querySelector('.vjs-fg-color > select'), values.color); setSelectedOption(el.querySelector('.vjs-text-opacity > select'), values.textOpacity); setSelectedOption(el.querySelector('.vjs-bg-color > select'), values.backgroundColor); setSelectedOption(el.querySelector('.vjs-bg-opacity > select'), values.backgroundOpacity); setSelectedOption(el.querySelector('.window-color > select'), values.windowColor); setSelectedOption(el.querySelector('.vjs-window-opacity > select'), values.windowOpacity); var fontPercent = values.fontPercent; if (fontPercent) { fontPercent = fontPercent.toFixed(2); } setSelectedOption(el.querySelector('.vjs-font-percent > select'), fontPercent); }; /** * Restore texttrack settings * * @method restoreSettings */ TextTrackSettings.prototype.restoreSettings = function restoreSettings() { var _safeParseTuple = _safeJsonParseTuple2['default'](_globalWindow2['default'].localStorage.getItem('vjs-text-track-settings')); var err = _safeParseTuple[0]; var values = _safeParseTuple[1]; if (err) { _utilsLogJs2['default'].error(err); } if (values) { this.setValues(values); } }; /** * Save texttrack settings to local storage * * @method saveSettings */ TextTrackSettings.prototype.saveSettings = function saveSettings() { if (!this.options_.persistTextTrackSettings) { return; } var values = this.getValues(); try { if (Object.getOwnPropertyNames(values).length > 0) { _globalWindow2['default'].localStorage.setItem('vjs-text-track-settings', JSON.stringify(values)); } else { _globalWindow2['default'].localStorage.removeItem('vjs-text-track-settings'); } } catch (e) {} }; /** * Update display of texttrack settings * * @method updateDisplay */ TextTrackSettings.prototype.updateDisplay = function updateDisplay() { var ttDisplay = this.player_.getChild('textTrackDisplay'); if (ttDisplay) { ttDisplay.updateDisplay(); } }; return TextTrackSettings; })(_component2['default']); _component2['default'].registerComponent('TextTrackSettings', TextTrackSettings); function getSelectedOptionValue(target) { var selectedOption = undefined; // not all browsers support selectedOptions, so, fallback to options if (target.selectedOptions) { selectedOption = target.selectedOptions[0]; } else if (target.options) { selectedOption = target.options[target.options.selectedIndex]; } return selectedOption.value; } function setSelectedOption(target, value) { if (!value) { return; } var i = undefined; for (i = 0; i < target.options.length; i++) { var option = target.options[i]; if (option.value === value) { break; } } target.selectedIndex = i; } function captionOptionsMenuTemplate() { var template = '<div class="vjs-tracksettings">\n <div class="vjs-tracksettings-colors">\n <div class="vjs-fg-color vjs-tracksetting">\n <label class="vjs-label">Foreground</label>\n <select>\n <option value="">---</option>\n <option value="#FFF">White</option>\n <option value="#000">Black</option>\n <option value="#F00">Red</option>\n <option value="#0F0">Green</option>\n <option value="#00F">Blue</option>\n <option value="#FF0">Yellow</option>\n <option value="#F0F">Magenta</option>\n <option value="#0FF">Cyan</option>\n </select>\n <span class="vjs-text-opacity vjs-opacity">\n <select>\n <option value="">---</option>\n <option value="1">Opaque</option>\n <option value="0.5">Semi-Opaque</option>\n </select>\n </span>\n </div> <!-- vjs-fg-color -->\n <div class="vjs-bg-color vjs-tracksetting">\n <label class="vjs-label">Background</label>\n <select>\n <option value="">---</option>\n <option value="#FFF">White</option>\n <option value="#000">Black</option>\n <option value="#F00">Red</option>\n <option value="#0F0">Green</option>\n <option value="#00F">Blue</option>\n <option value="#FF0">Yellow</option>\n <option value="#F0F">Magenta</option>\n <option value="#0FF">Cyan</option>\n </select>\n <span class="vjs-bg-opacity vjs-opacity">\n <select>\n <option value="">---</option>\n <option value="1">Opaque</option>\n <option value="0.5">Semi-Transparent</option>\n <option value="0">Transparent</option>\n </select>\n </span>\n </div> <!-- vjs-bg-color -->\n <div class="window-color vjs-tracksetting">\n <label class="vjs-label">Window</label>\n <select>\n <option value="">---</option>\n <option value="#FFF">White</option>\n <option value="#000">Black</option>\n <option value="#F00">Red</option>\n <option value="#0F0">Green</option>\n <option value="#00F">Blue</option>\n <option value="#FF0">Yellow</option>\n <option value="#F0F">Magenta</option>\n <option value="#0FF">Cyan</option>\n </select>\n <span class="vjs-window-opacity vjs-opacity">\n <select>\n <option value="">---</option>\n <option value="1">Opaque</option>\n <option value="0.5">Semi-Transparent</option>\n <option value="0">Transparent</option>\n </select>\n </span>\n </div> <!-- vjs-window-color -->\n </div> <!-- vjs-tracksettings -->\n <div class="vjs-tracksettings-font">\n <div class="vjs-font-percent vjs-tracksetting">\n <label class="vjs-label">Font Size</label>\n <select>\n <option value="0.50">50%</option>\n <option value="0.75">75%</option>\n <option value="1.00" selected>100%</option>\n <option value="1.25">125%</option>\n <option value="1.50">150%</option>\n <option value="1.75">175%</option>\n <option value="2.00">200%</option>\n <option value="3.00">300%</option>\n <option value="4.00">400%</option>\n </select>\n </div> <!-- vjs-font-percent -->\n <div class="vjs-edge-style vjs-tracksetting">\n <label class="vjs-label">Text Edge Style</label>\n <select>\n <option value="none">None</option>\n <option value="raised">Raised</option>\n <option value="depressed">Depressed</option>\n <option value="uniform">Uniform</option>\n <option value="dropshadow">Dropshadow</option>\n </select>\n </div> <!-- vjs-edge-style -->\n <div class="vjs-font-family vjs-tracksetting">\n <label class="vjs-label">Font Family</label>\n <select>\n <option value="">Default</option>\n <option value="monospaceSerif">Monospace Serif</option>\n <option value="proportionalSerif">Proportional Serif</option>\n <option value="monospaceSansSerif">Monospace Sans-Serif</option>\n <option value="proportionalSansSerif">Proportional Sans-Serif</option>\n <option value="casual">Casual</option>\n <option value="script">Script</option>\n <option value="small-caps">Small Caps</option>\n </select>\n </div> <!-- vjs-font-family -->\n </div>\n </div>\n <div class="vjs-tracksettings-controls">\n <button class="vjs-default-button">Defaults</button>\n <button class="vjs-done-button">Done</button>\n </div>'; return template; } exports['default'] = TextTrackSettings; module.exports = exports['default']; },{"../component":58,"../utils/events.js":119,"../utils/fn.js":120,"../utils/log.js":123,"global/window":2,"safe-json-parse/tuple":48}],114:[function(_dereq_,module,exports){ /** * @file text-track.js */ 'use strict'; exports.__esModule = true; function _interopRequireWildcard(obj) { if (obj && obj.__esModule) { return obj; } else { var newObj = {}; if (obj != null) { for (var key in obj) { if (Object.prototype.hasOwnProperty.call(obj, key)) newObj[key] = obj[key]; } } newObj['default'] = obj; return newObj; } } function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { 'default': obj }; } var _textTrackCueList = _dereq_('./text-track-cue-list'); var _textTrackCueList2 = _interopRequireDefault(_textTrackCueList); var _utilsFnJs = _dereq_('../utils/fn.js'); var Fn = _interopRequireWildcard(_utilsFnJs); var _utilsGuidJs = _dereq_('../utils/guid.js'); var Guid = _interopRequireWildcard(_utilsGuidJs); var _utilsBrowserJs = _dereq_('../utils/browser.js'); var browser = _interopRequireWildcard(_utilsBrowserJs); var _textTrackEnums = _dereq_('./text-track-enums'); var TextTrackEnum = _interopRequireWildcard(_textTrackEnums); var _utilsLogJs = _dereq_('../utils/log.js'); var _utilsLogJs2 = _interopRequireDefault(_utilsLogJs); var _eventTarget = _dereq_('../event-target'); var _eventTarget2 = _interopRequireDefault(_eventTarget); var _globalDocument = _dereq_('global/document'); var _globalDocument2 = _interopRequireDefault(_globalDocument); var _globalWindow = _dereq_('global/window'); var _globalWindow2 = _interopRequireDefault(_globalWindow); var _utilsUrlJs = _dereq_('../utils/url.js'); var _xhr = _dereq_('xhr'); var _xhr2 = _interopRequireDefault(_xhr); /* * https://html.spec.whatwg.org/multipage/embedded-content.html#texttrack * * interface TextTrack : EventTarget { * readonly attribute TextTrackKind kind; * readonly attribute DOMString label; * readonly attribute DOMString language; * * readonly attribute DOMString id; * readonly attribute DOMString inBandMetadataTrackDispatchType; * * attribute TextTrackMode mode; * * readonly attribute TextTrackCueList? cues; * readonly attribute TextTrackCueList? activeCues; * * void addCue(TextTrackCue cue); * void removeCue(TextTrackCue cue); * * attribute EventHandler oncuechange; * }; */ var TextTrack = function TextTrack() { var options = arguments.length <= 0 || arguments[0] === undefined ? {} : arguments[0]; if (!options.tech) { throw new Error('A tech was not provided.'); } var tt = this; if (browser.IS_IE8) { tt = _globalDocument2['default'].createElement('custom'); for (var prop in TextTrack.prototype) { tt[prop] = TextTrack.prototype[prop]; } } tt.tech_ = options.tech; var mode = TextTrackEnum.TextTrackMode[options['mode']] || 'disabled'; var kind = TextTrackEnum.TextTrackKind[options['kind']] || 'subtitles'; var label = options['label'] || ''; var language = options['language'] || options['srclang'] || ''; var id = options['id'] || 'vjs_text_track_' + Guid.newGUID(); if (kind === 'metadata' || kind === 'chapters') { mode = 'hidden'; } tt.cues_ = []; tt.activeCues_ = []; var cues = new _textTrackCueList2['default'](tt.cues_); var activeCues = new _textTrackCueList2['default'](tt.activeCues_); var changed = false; var timeupdateHandler = Fn.bind(tt, function () { this['activeCues']; if (changed) { this['trigger']('cuechange'); changed = false; } }); if (mode !== 'disabled') { tt.tech_.on('timeupdate', timeupdateHandler); } Object.defineProperty(tt, 'kind', { get: function get() { return kind; }, set: Function.prototype }); Object.defineProperty(tt, 'label', { get: function get() { return label; }, set: Function.prototype }); Object.defineProperty(tt, 'language', { get: function get() { return language; }, set: Function.prototype }); Object.defineProperty(tt, 'id', { get: function get() { return id; }, set: Function.prototype }); Object.defineProperty(tt, 'mode', { get: function get() { return mode; }, set: function set(newMode) { if (!TextTrackEnum.TextTrackMode[newMode]) { return; } mode = newMode; if (mode === 'showing') { this.tech_.on('timeupdate', timeupdateHandler); } this.trigger('modechange'); } }); Object.defineProperty(tt, 'cues', { get: function get() { if (!this.loaded_) { return null; } return cues; }, set: Function.prototype }); Object.defineProperty(tt, 'activeCues', { get: function get() { if (!this.loaded_) { return null; } if (this['cues'].length === 0) { return activeCues; // nothing to do } var ct = this.tech_.currentTime(); var active = []; for (var i = 0, l = this['cues'].length; i < l; i++) { var cue = this['cues'][i]; if (cue['startTime'] <= ct && cue['endTime'] >= ct) { active.push(cue); } else if (cue['startTime'] === cue['endTime'] && cue['startTime'] <= ct && cue['startTime'] + 0.5 >= ct) { active.push(cue); } } changed = false; if (active.length !== this.activeCues_.length) { changed = true; } else { for (var i = 0; i < active.length; i++) { if (indexOf.call(this.activeCues_, active[i]) === -1) { changed = true; } } } this.activeCues_ = active; activeCues.setCues_(this.activeCues_); return activeCues; }, set: Function.prototype }); if (options.src) { tt.src = options.src; loadTrack(options.src, tt); } else { tt.loaded_ = true; } if (browser.IS_IE8) { return tt; } }; TextTrack.prototype = Object.create(_eventTarget2['default'].prototype); TextTrack.prototype.constructor = TextTrack; /* * cuechange - One or more cues in the track have become active or stopped being active. */ TextTrack.prototype.allowedEvents_ = { 'cuechange': 'cuechange' }; TextTrack.prototype.addCue = function (cue) { var tracks = this.tech_.textTracks(); if (tracks) { for (var i = 0; i < tracks.length; i++) { if (tracks[i] !== this) { tracks[i].removeCue(cue); } } } this.cues_.push(cue); this['cues'].setCues_(this.cues_); }; TextTrack.prototype.removeCue = function (removeCue) { var removed = false; for (var i = 0, l = this.cues_.length; i < l; i++) { var cue = this.cues_[i]; if (cue === removeCue) { this.cues_.splice(i, 1); removed = true; } } if (removed) { this.cues.setCues_(this.cues_); } }; /* * Downloading stuff happens below this point */ var parseCues = function parseCues(srcContent, track) { if (typeof _globalWindow2['default']['WebVTT'] !== 'function') { //try again a bit later return _globalWindow2['default'].setTimeout(function () { parseCues(srcContent, track); }, 25); } var parser = new _globalWindow2['default']['WebVTT']['Parser'](_globalWindow2['default'], _globalWindow2['default']['vttjs'], _globalWindow2['default']['WebVTT']['StringDecoder']()); parser['oncue'] = function (cue) { track.addCue(cue); }; parser['onparsingerror'] = function (error) { _utilsLogJs2['default'].error(error); }; parser['parse'](srcContent); parser['flush'](); }; var loadTrack = function loadTrack(src, track) { var opts = { uri: src }; var crossOrigin = _utilsUrlJs.isCrossOrigin(src); if (crossOrigin) { opts.cors = crossOrigin; } _xhr2['default'](opts, Fn.bind(this, function (err, response, responseBody) { if (err) { return _utilsLogJs2['default'].error(err, response); } track.loaded_ = true; parseCues(responseBody, track); })); }; var indexOf = function indexOf(searchElement, fromIndex) { if (this == null) { throw new TypeError('"this" is null or not defined'); } var O = Object(this); var len = O.length >>> 0; if (len === 0) { return -1; } var n = +fromIndex || 0; if (Math.abs(n) === Infinity) { n = 0; } if (n >= len) { return -1; } var k = Math.max(n >= 0 ? n : len - Math.abs(n), 0); while (k < len) { if (k in O && O[k] === searchElement) { return k; } k++; } return -1; }; exports['default'] = TextTrack; module.exports = exports['default']; },{"../event-target":90,"../utils/browser.js":115,"../utils/fn.js":120,"../utils/guid.js":122,"../utils/log.js":123,"../utils/url.js":128,"./text-track-cue-list":108,"./text-track-enums":110,"global/document":1,"global/window":2,"xhr":50}],115:[function(_dereq_,module,exports){ /** * @file browser.js */ 'use strict'; exports.__esModule = true; function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { 'default': obj }; } var _globalDocument = _dereq_('global/document'); var _globalDocument2 = _interopRequireDefault(_globalDocument); var _globalWindow = _dereq_('global/window'); var _globalWindow2 = _interopRequireDefault(_globalWindow); var USER_AGENT = _globalWindow2['default'].navigator.userAgent; var webkitVersionMap = /AppleWebKit\/([\d.]+)/i.exec(USER_AGENT); var appleWebkitVersion = webkitVersionMap ? parseFloat(webkitVersionMap.pop()) : null; /* * Device is an iPhone * * @type {Boolean} * @constant * @private */ var IS_IPHONE = /iPhone/i.test(USER_AGENT); exports.IS_IPHONE = IS_IPHONE; var IS_IPAD = /iPad/i.test(USER_AGENT); exports.IS_IPAD = IS_IPAD; var IS_IPOD = /iPod/i.test(USER_AGENT); exports.IS_IPOD = IS_IPOD; var IS_IOS = IS_IPHONE || IS_IPAD || IS_IPOD; exports.IS_IOS = IS_IOS; var IOS_VERSION = (function () { var match = USER_AGENT.match(/OS (\d+)_/i); if (match && match[1]) { return match[1]; } })(); exports.IOS_VERSION = IOS_VERSION; var IS_ANDROID = /Android/i.test(USER_AGENT); exports.IS_ANDROID = IS_ANDROID; var ANDROID_VERSION = (function () { // This matches Android Major.Minor.Patch versions // ANDROID_VERSION is Major.Minor as a Number, if Minor isn't available, then only Major is returned var match = USER_AGENT.match(/Android (\d+)(?:\.(\d+))?(?:\.(\d+))*/i), major, minor; if (!match) { return null; } major = match[1] && parseFloat(match[1]); minor = match[2] && parseFloat(match[2]); if (major && minor) { return parseFloat(match[1] + '.' + match[2]); } else if (major) { return major; } else { return null; } })(); exports.ANDROID_VERSION = ANDROID_VERSION; // Old Android is defined as Version older than 2.3, and requiring a webkit version of the android browser var IS_OLD_ANDROID = IS_ANDROID && /webkit/i.test(USER_AGENT) && ANDROID_VERSION < 2.3; exports.IS_OLD_ANDROID = IS_OLD_ANDROID; var IS_NATIVE_ANDROID = IS_ANDROID && ANDROID_VERSION < 5 && appleWebkitVersion < 537; exports.IS_NATIVE_ANDROID = IS_NATIVE_ANDROID; var IS_FIREFOX = /Firefox/i.test(USER_AGENT); exports.IS_FIREFOX = IS_FIREFOX; var IS_CHROME = /Chrome/i.test(USER_AGENT); exports.IS_CHROME = IS_CHROME; var IS_IE8 = /MSIE\s8\.0/.test(USER_AGENT); exports.IS_IE8 = IS_IE8; var TOUCH_ENABLED = !!('ontouchstart' in _globalWindow2['default'] || _globalWindow2['default'].DocumentTouch && _globalDocument2['default'] instanceof _globalWindow2['default'].DocumentTouch); exports.TOUCH_ENABLED = TOUCH_ENABLED; var BACKGROUND_SIZE_SUPPORTED = ('backgroundSize' in _globalDocument2['default'].createElement('video').style); exports.BACKGROUND_SIZE_SUPPORTED = BACKGROUND_SIZE_SUPPORTED; },{"global/document":1,"global/window":2}],116:[function(_dereq_,module,exports){ /** * @file buffer.js */ 'use strict'; exports.__esModule = true; exports.bufferedPercent = bufferedPercent; var _timeRangesJs = _dereq_('./time-ranges.js'); /** * Compute how much your video has been buffered * * @param {Object} Buffered object * @param {Number} Total duration * @return {Number} Percent buffered of the total duration * @private * @function bufferedPercent */ function bufferedPercent(buffered, duration) { var bufferedDuration = 0, start, end; if (!duration) { return 0; } if (!buffered || !buffered.length) { buffered = _timeRangesJs.createTimeRange(0, 0); } for (var i = 0; i < buffered.length; i++) { start = buffered.start(i); end = buffered.end(i); // buffered end can be bigger than duration by a very small fraction if (end > duration) { end = duration; } bufferedDuration += end - start; } return bufferedDuration / duration; } },{"./time-ranges.js":126}],117:[function(_dereq_,module,exports){ 'use strict'; exports.__esModule = true; function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { 'default': obj }; } var _logJs = _dereq_('./log.js'); var _logJs2 = _interopRequireDefault(_logJs); /** * Object containing the default behaviors for available handler methods. * * @private * @type {Object} */ var defaultBehaviors = { get: function get(obj, key) { return obj[key]; }, set: function set(obj, key, value) { obj[key] = value; return true; } }; /** * Expose private objects publicly using a Proxy to log deprecation warnings. * * Browsers that do not support Proxy objects will simply return the `target` * object, so it can be directly exposed. * * @param {Object} target The target object. * @param {Object} messages Messages to display from a Proxy. Only operations * with an associated message will be proxied. * @param {String} [messages.get] * @param {String} [messages.set] * @return {Object} A Proxy if supported or the `target` argument. */ exports['default'] = function (target) { var messages = arguments.length <= 1 || arguments[1] === undefined ? {} : arguments[1]; if (typeof Proxy === 'function') { var _ret = (function () { var handler = {}; // Build a handler object based on those keys that have both messages // and default behaviors. Object.keys(messages).forEach(function (key) { if (defaultBehaviors.hasOwnProperty(key)) { handler[key] = function () { _logJs2['default'].warn(messages[key]); return defaultBehaviors[key].apply(this, arguments); }; } }); return { v: new Proxy(target, handler) }; })(); if (typeof _ret === 'object') return _ret.v; } return target; }; module.exports = exports['default']; },{"./log.js":123}],118:[function(_dereq_,module,exports){ /** * @file dom.js */ 'use strict'; exports.__esModule = true; exports.getEl = getEl; exports.createEl = createEl; exports.insertElFirst = insertElFirst; exports.getElData = getElData; exports.hasElData = hasElData; exports.removeElData = removeElData; exports.hasElClass = hasElClass; exports.addElClass = addElClass; exports.removeElClass = removeElClass; exports.setElAttributes = setElAttributes; exports.getElAttributes = getElAttributes; exports.blockTextSelection = blockTextSelection; exports.unblockTextSelection = unblockTextSelection; exports.findElPosition = findElPosition; exports.getPointerPosition = getPointerPosition; var _templateObject = _taggedTemplateLiteralLoose(['Setting attributes in the second argument of createEl()\n has been deprecated. Use the third argument instead.\n createEl(type, properties, attributes). Attempting to set ', ' to ', '.'], ['Setting attributes in the second argument of createEl()\n has been deprecated. Use the third argument instead.\n createEl(type, properties, attributes). Attempting to set ', ' to ', '.']); function _interopRequireWildcard(obj) { if (obj && obj.__esModule) { return obj; } else { var newObj = {}; if (obj != null) { for (var key in obj) { if (Object.prototype.hasOwnProperty.call(obj, key)) newObj[key] = obj[key]; } } newObj['default'] = obj; return newObj; } } function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { 'default': obj }; } function _taggedTemplateLiteralLoose(strings, raw) { strings.raw = raw; return strings; } var _globalDocument = _dereq_('global/document'); var _globalDocument2 = _interopRequireDefault(_globalDocument); var _globalWindow = _dereq_('global/window'); var _globalWindow2 = _interopRequireDefault(_globalWindow); var _guidJs = _dereq_('./guid.js'); var Guid = _interopRequireWildcard(_guidJs); var _logJs = _dereq_('./log.js'); var _logJs2 = _interopRequireDefault(_logJs); var _tsml = _dereq_('tsml'); var _tsml2 = _interopRequireDefault(_tsml); /** * Shorthand for document.getElementById() * Also allows for CSS (jQuery) ID syntax. But nothing other than IDs. * * @param {String} id Element ID * @return {Element} Element with supplied ID * @function getEl */ function getEl(id) { if (id.indexOf('#') === 0) { id = id.slice(1); } return _globalDocument2['default'].getElementById(id); } /** * Creates an element and applies properties. * * @param {String=} tagName Name of tag to be created. * @param {Object=} properties Element properties to be applied. * @return {Element} * @function createEl */ function createEl() { var tagName = arguments.length <= 0 || arguments[0] === undefined ? 'div' : arguments[0]; var properties = arguments.length <= 1 || arguments[1] === undefined ? {} : arguments[1]; var attributes = arguments.length <= 2 || arguments[2] === undefined ? {} : arguments[2]; var el = _globalDocument2['default'].createElement(tagName); Object.getOwnPropertyNames(properties).forEach(function (propName) { var val = properties[propName]; // See #2176 // We originally were accepting both properties and attributes in the // same object, but that doesn't work so well. if (propName.indexOf('aria-') !== -1 || propName === 'role' || propName === 'type') { _logJs2['default'].warn(_tsml2['default'](_templateObject, propName, val)); el.setAttribute(propName, val); } else { el[propName] = val; } }); Object.getOwnPropertyNames(attributes).forEach(function (attrName) { var val = attributes[attrName]; el.setAttribute(attrName, attributes[attrName]); }); return el; } /** * Insert an element as the first child node of another * * @param {Element} child Element to insert * @param {Element} parent Element to insert child into * @private * @function insertElFirst */ function insertElFirst(child, parent) { if (parent.firstChild) { parent.insertBefore(child, parent.firstChild); } else { parent.appendChild(child); } } /** * Element Data Store. Allows for binding data to an element without putting it directly on the element. * Ex. Event listeners are stored here. * (also from jsninja.com, slightly modified and updated for closure compiler) * * @type {Object} * @private */ var elData = {}; /* * Unique attribute name to store an element's guid in * * @type {String} * @constant * @private */ var elIdAttr = 'vdata' + new Date().getTime(); /** * Returns the cache object where data for an element is stored * * @param {Element} el Element to store data for. * @return {Object} * @function getElData */ function getElData(el) { var id = el[elIdAttr]; if (!id) { id = el[elIdAttr] = Guid.newGUID(); } if (!elData[id]) { elData[id] = {}; } return elData[id]; } /** * Returns whether or not an element has cached data * * @param {Element} el A dom element * @return {Boolean} * @private * @function hasElData */ function hasElData(el) { var id = el[elIdAttr]; if (!id) { return false; } return !!Object.getOwnPropertyNames(elData[id]).length; } /** * Delete data for the element from the cache and the guid attr from getElementById * * @param {Element} el Remove data for an element * @private * @function removeElData */ function removeElData(el) { var id = el[elIdAttr]; if (!id) { return; } // Remove all stored data delete elData[id]; // Remove the elIdAttr property from the DOM node try { delete el[elIdAttr]; } catch (e) { if (el.removeAttribute) { el.removeAttribute(elIdAttr); } else { // IE doesn't appear to support removeAttribute on the document element el[elIdAttr] = null; } } } /** * Check if an element has a CSS class * * @param {Element} element Element to check * @param {String} classToCheck Classname to check * @function hasElClass */ function hasElClass(element, classToCheck) { return (' ' + element.className + ' ').indexOf(' ' + classToCheck + ' ') !== -1; } /** * Add a CSS class name to an element * * @param {Element} element Element to add class name to * @param {String} classToAdd Classname to add * @function addElClass */ function addElClass(element, classToAdd) { if (!hasElClass(element, classToAdd)) { element.className = element.className === '' ? classToAdd : element.className + ' ' + classToAdd; } } /** * Remove a CSS class name from an element * * @param {Element} element Element to remove from class name * @param {String} classToRemove Classname to remove * @function removeElClass */ function removeElClass(element, classToRemove) { if (!hasElClass(element, classToRemove)) { return; } var classNames = element.className.split(' '); // no arr.indexOf in ie8, and we don't want to add a big shim for (var i = classNames.length - 1; i >= 0; i--) { if (classNames[i] === classToRemove) { classNames.splice(i, 1); } } element.className = classNames.join(' '); } /** * Apply attributes to an HTML element. * * @param {Element} el Target element. * @param {Object=} attributes Element attributes to be applied. * @private * @function setElAttributes */ function setElAttributes(el, attributes) { Object.getOwnPropertyNames(attributes).forEach(function (attrName) { var attrValue = attributes[attrName]; if (attrValue === null || typeof attrValue === 'undefined' || attrValue === false) { el.removeAttribute(attrName); } else { el.setAttribute(attrName, attrValue === true ? '' : attrValue); } }); } /** * Get an element's attribute values, as defined on the HTML tag * Attributes are not the same as properties. They're defined on the tag * or with setAttribute (which shouldn't be used with HTML) * This will return true or false for boolean attributes. * * @param {Element} tag Element from which to get tag attributes * @return {Object} * @private * @function getElAttributes */ function getElAttributes(tag) { var obj, knownBooleans, attrs, attrName, attrVal; obj = {}; // known boolean attributes // we can check for matching boolean properties, but older browsers // won't know about HTML5 boolean attributes that we still read from knownBooleans = ',' + 'autoplay,controls,loop,muted,default' + ','; if (tag && tag.attributes && tag.attributes.length > 0) { attrs = tag.attributes; for (var i = attrs.length - 1; i >= 0; i--) { attrName = attrs[i].name; attrVal = attrs[i].value; // check for known booleans // the matching element property will return a value for typeof if (typeof tag[attrName] === 'boolean' || knownBooleans.indexOf(',' + attrName + ',') !== -1) { // the value of an included boolean attribute is typically an empty // string ('') which would equal false if we just check for a false value. // we also don't want support bad code like autoplay='false' attrVal = attrVal !== null ? true : false; } obj[attrName] = attrVal; } } return obj; } /** * Attempt to block the ability to select text while dragging controls * * @return {Boolean} * @method blockTextSelection */ function blockTextSelection() { _globalDocument2['default'].body.focus(); _globalDocument2['default'].onselectstart = function () { return false; }; } /** * Turn off text selection blocking * * @return {Boolean} * @method unblockTextSelection */ function unblockTextSelection() { _globalDocument2['default'].onselectstart = function () { return true; }; } /** * Offset Left * getBoundingClientRect technique from * John Resig http://ejohn.org/blog/getboundingclientrect-is-awesome/ * * @param {Element} el Element from which to get offset * @return {Object=} * @method findElPosition */ function findElPosition(el) { var box = undefined; if (el.getBoundingClientRect && el.parentNode) { box = el.getBoundingClientRect(); } if (!box) { return { left: 0, top: 0 }; } var docEl = _globalDocument2['default'].documentElement; var body = _globalDocument2['default'].body; var clientLeft = docEl.clientLeft || body.clientLeft || 0; var scrollLeft = _globalWindow2['default'].pageXOffset || body.scrollLeft; var left = box.left + scrollLeft - clientLeft; var clientTop = docEl.clientTop || body.clientTop || 0; var scrollTop = _globalWindow2['default'].pageYOffset || body.scrollTop; var top = box.top + scrollTop - clientTop; // Android sometimes returns slightly off decimal values, so need to round return { left: Math.round(left), top: Math.round(top) }; } /** * Get pointer position in element * Returns an object with x and y coordinates. * The base on the coordinates are the bottom left of the element. * * @param {Element} el Element on which to get the pointer position on * @param {Event} event Event object * @return {Object=} position This object will have x and y coordinates corresponding to the mouse position * @metho getPointerPosition */ function getPointerPosition(el, event) { var position = {}; var box = findElPosition(el); var boxW = el.offsetWidth; var boxH = el.offsetHeight; var boxY = box.top; var boxX = box.left; var pageY = event.pageY; var pageX = event.pageX; if (event.changedTouches) { pageX = event.changedTouches[0].pageX; pageY = event.changedTouches[0].pageY; } position.y = Math.max(0, Math.min(1, (boxY - pageY + boxH) / boxH)); position.x = Math.max(0, Math.min(1, (pageX - boxX) / boxW)); return position; } },{"./guid.js":122,"./log.js":123,"global/document":1,"global/window":2,"tsml":49}],119:[function(_dereq_,module,exports){ /** * @file events.js * * Event System (John Resig - Secrets of a JS Ninja http://jsninja.com/) * (Original book version wasn't completely usable, so fixed some things and made Closure Compiler compatible) * This should work very similarly to jQuery's events, however it's based off the book version which isn't as * robust as jquery's, so there's probably some differences. */ 'use strict'; exports.__esModule = true; exports.on = on; exports.off = off; exports.trigger = trigger; exports.one = one; exports.fixEvent = fixEvent; function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { 'default': obj }; } function _interopRequireWildcard(obj) { if (obj && obj.__esModule) { return obj; } else { var newObj = {}; if (obj != null) { for (var key in obj) { if (Object.prototype.hasOwnProperty.call(obj, key)) newObj[key] = obj[key]; } } newObj['default'] = obj; return newObj; } } var _domJs = _dereq_('./dom.js'); var Dom = _interopRequireWildcard(_domJs); var _guidJs = _dereq_('./guid.js'); var Guid = _interopRequireWildcard(_guidJs); var _globalWindow = _dereq_('global/window'); var _globalWindow2 = _interopRequireDefault(_globalWindow); var _globalDocument = _dereq_('global/document'); var _globalDocument2 = _interopRequireDefault(_globalDocument); /** * Add an event listener to element * It stores the handler function in a separate cache object * and adds a generic handler to the element's event, * along with a unique id (guid) to the element. * * @param {Element|Object} elem Element or object to bind listeners to * @param {String|Array} type Type of event to bind to. * @param {Function} fn Event listener. * @method on */ function on(elem, type, fn) { if (Array.isArray(type)) { return _handleMultipleEvents(on, elem, type, fn); } var data = Dom.getElData(elem); // We need a place to store all our handler data if (!data.handlers) data.handlers = {}; if (!data.handlers[type]) data.handlers[type] = []; if (!fn.guid) fn.guid = Guid.newGUID(); data.handlers[type].push(fn); if (!data.dispatcher) { data.disabled = false; data.dispatcher = function (event, hash) { if (data.disabled) return; event = fixEvent(event); var handlers = data.handlers[event.type]; if (handlers) { // Copy handlers so if handlers are added/removed during the process it doesn't throw everything off. var handlersCopy = handlers.slice(0); for (var m = 0, n = handlersCopy.length; m < n; m++) { if (event.isImmediatePropagationStopped()) { break; } else { handlersCopy[m].call(elem, event, hash); } } } }; } if (data.handlers[type].length === 1) { if (elem.addEventListener) { elem.addEventListener(type, data.dispatcher, false); } else if (elem.attachEvent) { elem.attachEvent('on' + type, data.dispatcher); } } } /** * Removes event listeners from an element * * @param {Element|Object} elem Object to remove listeners from * @param {String|Array=} type Type of listener to remove. Don't include to remove all events from element. * @param {Function} fn Specific listener to remove. Don't include to remove listeners for an event type. * @method off */ function off(elem, type, fn) { // Don't want to add a cache object through getElData if not needed if (!Dom.hasElData(elem)) return; var data = Dom.getElData(elem); // If no events exist, nothing to unbind if (!data.handlers) { return; } if (Array.isArray(type)) { return _handleMultipleEvents(off, elem, type, fn); } // Utility function var removeType = function removeType(t) { data.handlers[t] = []; _cleanUpEvents(elem, t); }; // Are we removing all bound events? if (!type) { for (var t in data.handlers) { removeType(t); }return; } var handlers = data.handlers[type]; // If no handlers exist, nothing to unbind if (!handlers) return; // If no listener was provided, remove all listeners for type if (!fn) { removeType(type); return; } // We're only removing a single handler if (fn.guid) { for (var n = 0; n < handlers.length; n++) { if (handlers[n].guid === fn.guid) { handlers.splice(n--, 1); } } } _cleanUpEvents(elem, type); } /** * Trigger an event for an element * * @param {Element|Object} elem Element to trigger an event on * @param {Event|Object|String} event A string (the type) or an event object with a type attribute * @param {Object} [hash] data hash to pass along with the event * @return {Boolean=} Returned only if default was prevented * @method trigger */ function trigger(elem, event, hash) { // Fetches element data and a reference to the parent (for bubbling). // Don't want to add a data object to cache for every parent, // so checking hasElData first. var elemData = Dom.hasElData(elem) ? Dom.getElData(elem) : {}; var parent = elem.parentNode || elem.ownerDocument; // type = event.type || event, // handler; // If an event name was passed as a string, creates an event out of it if (typeof event === 'string') { event = { type: event, target: elem }; } // Normalizes the event properties. event = fixEvent(event); // If the passed element has a dispatcher, executes the established handlers. if (elemData.dispatcher) { elemData.dispatcher.call(elem, event, hash); } // Unless explicitly stopped or the event does not bubble (e.g. media events) // recursively calls this function to bubble the event up the DOM. if (parent && !event.isPropagationStopped() && event.bubbles === true) { trigger.call(null, parent, event, hash); // If at the top of the DOM, triggers the default action unless disabled. } else if (!parent && !event.defaultPrevented) { var targetData = Dom.getElData(event.target); // Checks if the target has a default action for this event. if (event.target[event.type]) { // Temporarily disables event dispatching on the target as we have already executed the handler. targetData.disabled = true; // Executes the default action. if (typeof event.target[event.type] === 'function') { event.target[event.type](); } // Re-enables event dispatching. targetData.disabled = false; } } // Inform the triggerer if the default was prevented by returning false return !event.defaultPrevented; } /** * Trigger a listener only once for an event * * @param {Element|Object} elem Element or object to * @param {String|Array} type Name/type of event * @param {Function} fn Event handler function * @method one */ function one(elem, type, fn) { if (Array.isArray(type)) { return _handleMultipleEvents(one, elem, type, fn); } var func = function func() { off(elem, type, func); fn.apply(this, arguments); }; // copy the guid to the new function so it can removed using the original function's ID func.guid = fn.guid = fn.guid || Guid.newGUID(); on(elem, type, func); } /** * Fix a native event to have standard property values * * @param {Object} event Event object to fix * @return {Object} * @private * @method fixEvent */ function fixEvent(event) { function returnTrue() { return true; } function returnFalse() { return false; } // Test if fixing up is needed // Used to check if !event.stopPropagation instead of isPropagationStopped // But native events return true for stopPropagation, but don't have // other expected methods like isPropagationStopped. Seems to be a problem // with the Javascript Ninja code. So we're just overriding all events now. if (!event || !event.isPropagationStopped) { var old = event || _globalWindow2['default'].event; event = {}; // Clone the old object so that we can modify the values event = {}; // IE8 Doesn't like when you mess with native event properties // Firefox returns false for event.hasOwnProperty('type') and other props // which makes copying more difficult. // TODO: Probably best to create a whitelist of event props for (var key in old) { // Safari 6.0.3 warns you if you try to copy deprecated layerX/Y // Chrome warns you if you try to copy deprecated keyboardEvent.keyLocation // and webkitMovementX/Y if (key !== 'layerX' && key !== 'layerY' && key !== 'keyLocation' && key !== 'webkitMovementX' && key !== 'webkitMovementY') { // Chrome 32+ warns if you try to copy deprecated returnValue, but // we still want to if preventDefault isn't supported (IE8). if (!(key === 'returnValue' && old.preventDefault)) { event[key] = old[key]; } } } // The event occurred on this element if (!event.target) { event.target = event.srcElement || _globalDocument2['default']; } // Handle which other element the event is related to if (!event.relatedTarget) { event.relatedTarget = event.fromElement === event.target ? event.toElement : event.fromElement; } // Stop the default browser action event.preventDefault = function () { if (old.preventDefault) { old.preventDefault(); } event.returnValue = false; old.returnValue = false; event.defaultPrevented = true; }; event.defaultPrevented = false; // Stop the event from bubbling event.stopPropagation = function () { if (old.stopPropagation) { old.stopPropagation(); } event.cancelBubble = true; old.cancelBubble = true; event.isPropagationStopped = returnTrue; }; event.isPropagationStopped = returnFalse; // Stop the event from bubbling and executing other handlers event.stopImmediatePropagation = function () { if (old.stopImmediatePropagation) { old.stopImmediatePropagation(); } event.isImmediatePropagationStopped = returnTrue; event.stopPropagation(); }; event.isImmediatePropagationStopped = returnFalse; // Handle mouse position if (event.clientX != null) { var doc = _globalDocument2['default'].documentElement, body = _globalDocument2['default'].body; event.pageX = event.clientX + (doc && doc.scrollLeft || body && body.scrollLeft || 0) - (doc && doc.clientLeft || body && body.clientLeft || 0); event.pageY = event.clientY + (doc && doc.scrollTop || body && body.scrollTop || 0) - (doc && doc.clientTop || body && body.clientTop || 0); } // Handle key presses event.which = event.charCode || event.keyCode; // Fix button for mouse clicks: // 0 == left; 1 == middle; 2 == right if (event.button != null) { event.button = event.button & 1 ? 0 : event.button & 4 ? 1 : event.button & 2 ? 2 : 0; } } // Returns fixed-up instance return event; } /** * Clean up the listener cache and dispatchers * * @param {Element|Object} elem Element to clean up * @param {String} type Type of event to clean up * @private * @method _cleanUpEvents */ function _cleanUpEvents(elem, type) { var data = Dom.getElData(elem); // Remove the events of a particular type if there are none left if (data.handlers[type].length === 0) { delete data.handlers[type]; // data.handlers[type] = null; // Setting to null was causing an error with data.handlers // Remove the meta-handler from the element if (elem.removeEventListener) { elem.removeEventListener(type, data.dispatcher, false); } else if (elem.detachEvent) { elem.detachEvent('on' + type, data.dispatcher); } } // Remove the events object if there are no types left if (Object.getOwnPropertyNames(data.handlers).length <= 0) { delete data.handlers; delete data.dispatcher; delete data.disabled; } // Finally remove the element data if there is no data left if (Object.getOwnPropertyNames(data).length === 0) { Dom.removeElData(elem); } } /** * Loops through an array of event types and calls the requested method for each type. * * @param {Function} fn The event method we want to use. * @param {Element|Object} elem Element or object to bind listeners to * @param {String} type Type of event to bind to. * @param {Function} callback Event listener. * @private * @function _handleMultipleEvents */ function _handleMultipleEvents(fn, elem, types, callback) { types.forEach(function (type) { //Call the event method for each one of the types fn(elem, type, callback); }); } },{"./dom.js":118,"./guid.js":122,"global/document":1,"global/window":2}],120:[function(_dereq_,module,exports){ /** * @file fn.js */ 'use strict'; exports.__esModule = true; var _guidJs = _dereq_('./guid.js'); /** * Bind (a.k.a proxy or Context). A simple method for changing the context of a function * It also stores a unique id on the function so it can be easily removed from events * * @param {*} context The object to bind as scope * @param {Function} fn The function to be bound to a scope * @param {Number=} uid An optional unique ID for the function to be set * @return {Function} * @private * @method bind */ var bind = function bind(context, fn, uid) { // Make sure the function has a unique ID if (!fn.guid) { fn.guid = _guidJs.newGUID(); } // Create the new function that changes the context var ret = function ret() { return fn.apply(context, arguments); }; // Allow for the ability to individualize this function // Needed in the case where multiple objects might share the same prototype // IF both items add an event listener with the same function, then you try to remove just one // it will remove both because they both have the same guid. // when using this, you need to use the bind method when you remove the listener as well. // currently used in text tracks ret.guid = uid ? uid + '_' + fn.guid : fn.guid; return ret; }; exports.bind = bind; },{"./guid.js":122}],121:[function(_dereq_,module,exports){ /** * @file format-time.js * * Format seconds as a time string, H:MM:SS or M:SS * Supplying a guide (in seconds) will force a number of leading zeros * to cover the length of the guide * * @param {Number} seconds Number of seconds to be turned into a string * @param {Number} guide Number (in seconds) to model the string after * @return {String} Time formatted as H:MM:SS or M:SS * @private * @function formatTime */ 'use strict'; exports.__esModule = true; function formatTime(seconds) { var guide = arguments.length <= 1 || arguments[1] === undefined ? seconds : arguments[1]; return (function () { var s = Math.floor(seconds % 60); var m = Math.floor(seconds / 60 % 60); var h = Math.floor(seconds / 3600); var gm = Math.floor(guide / 60 % 60); var gh = Math.floor(guide / 3600); // handle invalid times if (isNaN(seconds) || seconds === Infinity) { // '-' is false for all relational operators (e.g. <, >=) so this setting // will add the minimum number of fields specified by the guide h = m = s = '-'; } // Check if we need to show hours h = h > 0 || gh > 0 ? h + ':' : ''; // If hours are showing, we may need to add a leading zero. // Always show at least one digit of minutes. m = ((h || gm >= 10) && m < 10 ? '0' + m : m) + ':'; // Check if leading zero is need for seconds s = s < 10 ? '0' + s : s; return h + m + s; })(); } exports['default'] = formatTime; module.exports = exports['default']; },{}],122:[function(_dereq_,module,exports){ /** * @file guid.js * * Unique ID for an element or function * @type {Number} * @private */ "use strict"; exports.__esModule = true; exports.newGUID = newGUID; var _guid = 1; /** * Get the next unique ID * * @return {String} * @function newGUID */ function newGUID() { return _guid++; } },{}],123:[function(_dereq_,module,exports){ /** * @file log.js */ 'use strict'; exports.__esModule = true; function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { 'default': obj }; } var _globalWindow = _dereq_('global/window'); var _globalWindow2 = _interopRequireDefault(_globalWindow); /** * Log plain debug messages */ var log = function log() { _logType(null, arguments); }; /** * Keep a history of log messages * @type {Array} */ log.history = []; /** * Log error messages */ log.error = function () { _logType('error', arguments); }; /** * Log warning messages */ log.warn = function () { _logType('warn', arguments); }; /** * Log messages to the console and history based on the type of message * * @param {String} type The type of message, or `null` for `log` * @param {Object} args The args to be passed to the log * @private * @method _logType */ function _logType(type, args) { // convert args to an array to get array functions var argsArray = Array.prototype.slice.call(args); // if there's no console then don't try to output messages // they will still be stored in log.history // Was setting these once outside of this function, but containing them // in the function makes it easier to test cases where console doesn't exist var noop = function noop() {}; var console = _globalWindow2['default']['console'] || { 'log': noop, 'warn': noop, 'error': noop }; if (type) { // add the type to the front of the message argsArray.unshift(type.toUpperCase() + ':'); } else { // default to log with no prefix type = 'log'; } // add to history log.history.push(argsArray); // add console prefix after adding to history argsArray.unshift('VIDEOJS:'); // call appropriate log function if (console[type].apply) { console[type].apply(console, argsArray); } else { // ie8 doesn't allow error.apply, but it will just join() the array anyway console[type](argsArray.join(' ')); } } exports['default'] = log; module.exports = exports['default']; },{"global/window":2}],124:[function(_dereq_,module,exports){ /** * @file merge-options.js */ 'use strict'; exports.__esModule = true; exports['default'] = mergeOptions; function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { 'default': obj }; } var _lodashCompatObjectMerge = _dereq_('lodash-compat/object/merge'); var _lodashCompatObjectMerge2 = _interopRequireDefault(_lodashCompatObjectMerge); function isPlain(obj) { return !!obj && typeof obj === 'object' && obj.toString() === '[object Object]' && obj.constructor === Object; } /** * Merge customizer. video.js simply overwrites non-simple objects * (like arrays) instead of attempting to overlay them. * @see https://lodash.com/docs#merge */ var customizer = function customizer(destination, source) { // If we're not working with a plain object, copy the value as is // If source is an array, for instance, it will replace destination if (!isPlain(source)) { return source; } // If the new value is a plain object but the first object value is not // we need to create a new object for the first object to merge with. // This makes it consistent with how merge() works by default // and also protects from later changes the to first object affecting // the second object's values. if (!isPlain(destination)) { return mergeOptions(source); } }; /** * Merge one or more options objects, recursively merging **only** * plain object properties. Previously `deepMerge`. * * @param {...Object} source One or more objects to merge * @returns {Object} a new object that is the union of all * provided objects * @function mergeOptions */ function mergeOptions() { // contruct the call dynamically to handle the variable number of // objects to merge var args = Array.prototype.slice.call(arguments); // unshift an empty object into the front of the call as the target // of the merge args.unshift({}); // customize conflict resolution to match our historical merge behavior args.push(customizer); _lodashCompatObjectMerge2['default'].apply(null, args); // return the mutated result object return args[0]; } module.exports = exports['default']; },{"lodash-compat/object/merge":40}],125:[function(_dereq_,module,exports){ 'use strict'; exports.__esModule = true; function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { 'default': obj }; } var _globalDocument = _dereq_('global/document'); var _globalDocument2 = _interopRequireDefault(_globalDocument); var createStyleElement = function createStyleElement(className) { var style = _globalDocument2['default'].createElement('style'); style.className = className; return style; }; exports.createStyleElement = createStyleElement; var setTextContent = function setTextContent(el, content) { if (el.styleSheet) { el.styleSheet.cssText = content; } else { el.textContent = content; } }; exports.setTextContent = setTextContent; },{"global/document":1}],126:[function(_dereq_,module,exports){ 'use strict'; exports.__esModule = true; exports.createTimeRanges = createTimeRanges; function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { 'default': obj }; } var _logJs = _dereq_('./log.js'); var _logJs2 = _interopRequireDefault(_logJs); /** * @file time-ranges.js * * Should create a fake TimeRange object * Mimics an HTML5 time range instance, which has functions that * return the start and end times for a range * TimeRanges are returned by the buffered() method * * @param {(Number|Array)} Start of a single range or an array of ranges * @param {Number} End of a single range * @private * @method createTimeRanges */ function createTimeRanges(start, end) { if (Array.isArray(start)) { return createTimeRangesObj(start); } else if (start === undefined || end === undefined) { return createTimeRangesObj(); } return createTimeRangesObj([[start, end]]); } exports.createTimeRange = createTimeRanges; function createTimeRangesObj(ranges) { if (ranges === undefined || ranges.length === 0) { return { length: 0, start: function start() { throw new Error('This TimeRanges object is empty'); }, end: function end() { throw new Error('This TimeRanges object is empty'); } }; } return { length: ranges.length, start: getRange.bind(null, 'start', 0, ranges), end: getRange.bind(null, 'end', 1, ranges) }; } function getRange(fnName, valueIndex, ranges, rangeIndex) { if (rangeIndex === undefined) { _logJs2['default'].warn('DEPRECATED: Function \'' + fnName + '\' on \'TimeRanges\' called without an index argument.'); rangeIndex = 0; } rangeCheck(fnName, rangeIndex, ranges.length - 1); return ranges[rangeIndex][valueIndex]; } function rangeCheck(fnName, index, maxIndex) { if (index < 0 || index > maxIndex) { throw new Error('Failed to execute \'' + fnName + '\' on \'TimeRanges\': The index provided (' + index + ') is greater than or equal to the maximum bound (' + maxIndex + ').'); } } },{"./log.js":123}],127:[function(_dereq_,module,exports){ /** * @file to-title-case.js * * Uppercase the first letter of a string * * @param {String} string String to be uppercased * @return {String} * @private * @method toTitleCase */ "use strict"; exports.__esModule = true; function toTitleCase(string) { return string.charAt(0).toUpperCase() + string.slice(1); } exports["default"] = toTitleCase; module.exports = exports["default"]; },{}],128:[function(_dereq_,module,exports){ /** * @file url.js */ 'use strict'; exports.__esModule = true; function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { 'default': obj }; } var _globalDocument = _dereq_('global/document'); var _globalDocument2 = _interopRequireDefault(_globalDocument); var _globalWindow = _dereq_('global/window'); var _globalWindow2 = _interopRequireDefault(_globalWindow); /** * Resolve and parse the elements of a URL * * @param {String} url The url to parse * @return {Object} An object of url details * @method parseUrl */ var parseUrl = function parseUrl(url) { var props = ['protocol', 'hostname', 'port', 'pathname', 'search', 'hash', 'host']; // add the url to an anchor and let the browser parse the URL var a = _globalDocument2['default'].createElement('a'); a.href = url; // IE8 (and 9?) Fix // ie8 doesn't parse the URL correctly until the anchor is actually // added to the body, and an innerHTML is needed to trigger the parsing var addToBody = a.host === '' && a.protocol !== 'file:'; var div = undefined; if (addToBody) { div = _globalDocument2['default'].createElement('div'); div.innerHTML = '<a href="' + url + '"></a>'; a = div.firstChild; // prevent the div from affecting layout div.setAttribute('style', 'display:none; position:absolute;'); _globalDocument2['default'].body.appendChild(div); } // Copy the specific URL properties to a new object // This is also needed for IE8 because the anchor loses its // properties when it's removed from the dom var details = {}; for (var i = 0; i < props.length; i++) { details[props[i]] = a[props[i]]; } // IE9 adds the port to the host property unlike everyone else. If // a port identifier is added for standard ports, strip it. if (details.protocol === 'http:') { details.host = details.host.replace(/:80$/, ''); } if (details.protocol === 'https:') { details.host = details.host.replace(/:443$/, ''); } if (addToBody) { _globalDocument2['default'].body.removeChild(div); } return details; }; exports.parseUrl = parseUrl; /** * Get absolute version of relative URL. Used to tell flash correct URL. * http://stackoverflow.com/questions/470832/getting-an-absolute-url-from-a-relative-one-ie6-issue * * @param {String} url URL to make absolute * @return {String} Absolute URL * @private * @method getAbsoluteURL */ var getAbsoluteURL = function getAbsoluteURL(url) { // Check if absolute URL if (!url.match(/^https?:\/\//)) { // Convert to absolute URL. Flash hosted off-site needs an absolute URL. var div = _globalDocument2['default'].createElement('div'); div.innerHTML = '<a href="' + url + '">x</a>'; url = div.firstChild.href; } return url; }; exports.getAbsoluteURL = getAbsoluteURL; /** * Returns the extension of the passed file name. It will return an empty string if you pass an invalid path * * @param {String} path The fileName path like '/path/to/file.mp4' * @returns {String} The extension in lower case or an empty string if no extension could be found. * @method getFileExtension */ var getFileExtension = function getFileExtension(path) { if (typeof path === 'string') { var splitPathRe = /^(\/?)([\s\S]*?)((?:\.{1,2}|[^\/]+?)(\.([^\.\/\?]+)))(?:[\/]*|[\?].*)$/i; var pathParts = splitPathRe.exec(path); if (pathParts) { return pathParts.pop().toLowerCase(); } } return ''; }; exports.getFileExtension = getFileExtension; /** * Returns whether the url passed is a cross domain request or not. * * @param {String} url The url to check * @return {Boolean} Whether it is a cross domain request or not * @method isCrossOrigin */ var isCrossOrigin = function isCrossOrigin(url) { var urlInfo = parseUrl(url); var winLoc = _globalWindow2['default'].location; // IE8 protocol relative urls will return ':' for protocol var srcProtocol = urlInfo.protocol === ':' ? winLoc.protocol : urlInfo.protocol; // Check if url is for another domain/origin // IE8 doesn't know location.origin, so we won't rely on it here var crossOrigin = srcProtocol + urlInfo.host !== winLoc.protocol + winLoc.host; return crossOrigin; }; exports.isCrossOrigin = isCrossOrigin; },{"global/document":1,"global/window":2}],129:[function(_dereq_,module,exports){ /** * @file video.js */ 'use strict'; exports.__esModule = true; function _interopRequireWildcard(obj) { if (obj && obj.__esModule) { return obj; } else { var newObj = {}; if (obj != null) { for (var key in obj) { if (Object.prototype.hasOwnProperty.call(obj, key)) newObj[key] = obj[key]; } } newObj['default'] = obj; return newObj; } } function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { 'default': obj }; } var _globalDocument = _dereq_('global/document'); var _globalDocument2 = _interopRequireDefault(_globalDocument); var _setup = _dereq_('./setup'); var setup = _interopRequireWildcard(_setup); var _utilsStylesheetJs = _dereq_('./utils/stylesheet.js'); var stylesheet = _interopRequireWildcard(_utilsStylesheetJs); var _component = _dereq_('./component'); var _component2 = _interopRequireDefault(_component); var _eventTarget = _dereq_('./event-target'); var _eventTarget2 = _interopRequireDefault(_eventTarget); var _utilsEventsJs = _dereq_('./utils/events.js'); var Events = _interopRequireWildcard(_utilsEventsJs); var _player = _dereq_('./player'); var _player2 = _interopRequireDefault(_player); var _pluginsJs = _dereq_('./plugins.js'); var _pluginsJs2 = _interopRequireDefault(_pluginsJs); var _srcJsUtilsMergeOptionsJs = _dereq_('../../src/js/utils/merge-options.js'); var _srcJsUtilsMergeOptionsJs2 = _interopRequireDefault(_srcJsUtilsMergeOptionsJs); var _utilsFnJs = _dereq_('./utils/fn.js'); var Fn = _interopRequireWildcard(_utilsFnJs); var _tracksTextTrackJs = _dereq_('./tracks/text-track.js'); var _tracksTextTrackJs2 = _interopRequireDefault(_tracksTextTrackJs); var _objectAssign = _dereq_('object.assign'); var _objectAssign2 = _interopRequireDefault(_objectAssign); var _utilsTimeRangesJs = _dereq_('./utils/time-ranges.js'); var _utilsFormatTimeJs = _dereq_('./utils/format-time.js'); var _utilsFormatTimeJs2 = _interopRequireDefault(_utilsFormatTimeJs); var _utilsLogJs = _dereq_('./utils/log.js'); var _utilsLogJs2 = _interopRequireDefault(_utilsLogJs); var _utilsDomJs = _dereq_('./utils/dom.js'); var Dom = _interopRequireWildcard(_utilsDomJs); var _utilsBrowserJs = _dereq_('./utils/browser.js'); var browser = _interopRequireWildcard(_utilsBrowserJs); var _utilsUrlJs = _dereq_('./utils/url.js'); var Url = _interopRequireWildcard(_utilsUrlJs); var _extendJs = _dereq_('./extend.js'); var _extendJs2 = _interopRequireDefault(_extendJs); var _lodashCompatObjectMerge = _dereq_('lodash-compat/object/merge'); var _lodashCompatObjectMerge2 = _interopRequireDefault(_lodashCompatObjectMerge); var _utilsCreateDeprecationProxyJs = _dereq_('./utils/create-deprecation-proxy.js'); var _utilsCreateDeprecationProxyJs2 = _interopRequireDefault(_utilsCreateDeprecationProxyJs); var _xhr = _dereq_('xhr'); var _xhr2 = _interopRequireDefault(_xhr); // Include the built-in techs var _techHtml5Js = _dereq_('./tech/html5.js'); var _techHtml5Js2 = _interopRequireDefault(_techHtml5Js); var _techFlashJs = _dereq_('./tech/flash.js'); var _techFlashJs2 = _interopRequireDefault(_techFlashJs); // HTML5 Element Shim for IE8 if (typeof HTMLVideoElement === 'undefined') { _globalDocument2['default'].createElement('video'); _globalDocument2['default'].createElement('audio'); _globalDocument2['default'].createElement('track'); } /** * Doubles as the main function for users to create a player instance and also * the main library object. * The `videojs` function can be used to initialize or retrieve a player. * ```js * var myPlayer = videojs('my_video_id'); * ``` * * @param {String|Element} id Video element or video element ID * @param {Object=} options Optional options object for config/settings * @param {Function=} ready Optional ready callback * @return {Player} A player instance * @mixes videojs * @method videojs */ var videojs = function videojs(id, options, ready) { var tag; // Element of ID // Allow for element or ID to be passed in // String ID if (typeof id === 'string') { // Adjust for jQuery ID syntax if (id.indexOf('#') === 0) { id = id.slice(1); } // If a player instance has already been created for this ID return it. if (videojs.getPlayers()[id]) { // If options or ready funtion are passed, warn if (options) { _utilsLogJs2['default'].warn('Player "' + id + '" is already initialised. Options will not be applied.'); } if (ready) { videojs.getPlayers()[id].ready(ready); } return videojs.getPlayers()[id]; // Otherwise get element for ID } else { tag = Dom.getEl(id); } // ID is a media element } else { tag = id; } // Check for a useable element if (!tag || !tag.nodeName) { // re: nodeName, could be a box div also throw new TypeError('The element or ID supplied is not valid. (videojs)'); // Returns } // Element may have a player attr referring to an already created player instance. // If not, set up a new player and return the instance. return tag['player'] || new _player2['default'](tag, options, ready); }; // Add default styles var style = _globalDocument2['default'].querySelector('.vjs-styles-defaults'); if (!style) { style = stylesheet.createStyleElement('vjs-styles-defaults'); var head = _globalDocument2['default'].querySelector('head'); head.insertBefore(style, head.firstChild); stylesheet.setTextContent(style, '\n .video-js {\n width: 300px;\n height: 150px;\n }\n\n .vjs-fluid {\n padding-top: 56.25%\n }\n '); } // Run Auto-load players // You have to wait at least once in case this script is loaded after your video in the DOM (weird behavior only with minified version) setup.autoSetupTimeout(1, videojs); /* * Current software version (semver) * * @type {String} */ videojs.VERSION = '5.0.0-rc.104'; /** * The global options object. These are the settings that take effect * if no overrides are specified when the player is created. * * ```js * videojs.options.autoplay = true * // -> all players will autoplay by default * ``` * * @type {Object} */ videojs.options = _player2['default'].prototype.options_; /** * Get an object with the currently created players, keyed by player ID * * @return {Object} The created players * @mixes videojs * @method getPlayers */ videojs.getPlayers = function () { return _player2['default'].players; }; /** * For backward compatibility, expose players object. * * @deprecated * @memberOf videojs * @property {Object|Proxy} players */ videojs.players = _utilsCreateDeprecationProxyJs2['default'](_player2['default'].players, { get: 'Access to videojs.players is deprecated; use videojs.getPlayers instead', set: 'Modification of videojs.players is deprecated' }); /** * Get a component class object by name * ```js * var VjsButton = videojs.getComponent('Button'); * // Create a new instance of the component * var myButton = new VjsButton(myPlayer); * ``` * * @return {Component} Component identified by name * @mixes videojs * @method getComponent */ videojs.getComponent = _component2['default'].getComponent; /** * Register a component so it can referred to by name * Used when adding to other * components, either through addChild * `component.addChild('myComponent')` * or through default children options * `{ children: ['myComponent'] }`. * ```js * // Get a component to subclass * var VjsButton = videojs.getComponent('Button'); * // Subclass the component (see 'extend' doc for more info) * var MySpecialButton = videojs.extend(VjsButton, {}); * // Register the new component * VjsButton.registerComponent('MySepcialButton', MySepcialButton); * // (optionally) add the new component as a default player child * myPlayer.addChild('MySepcialButton'); * ``` * NOTE: You could also just initialize the component before adding. * `component.addChild(new MyComponent());` * * @param {String} The class name of the component * @param {Component} The component class * @return {Component} The newly registered component * @mixes videojs * @method registerComponent */ videojs.registerComponent = _component2['default'].registerComponent; /** * A suite of browser and device tests * * @type {Object} * @private */ videojs.browser = browser; /** * Whether or not the browser supports touch events. Included for backward * compatibility with 4.x, but deprecated. Use `videojs.browser.TOUCH_ENABLED` * instead going forward. * * @deprecated * @type {Boolean} */ videojs.TOUCH_ENABLED = browser.TOUCH_ENABLED; /** * Subclass an existing class * Mimics ES6 subclassing with the `extend` keyword * ```js * // Create a basic javascript 'class' * function MyClass(name){ * // Set a property at initialization * this.myName = name; * } * // Create an instance method * MyClass.prototype.sayMyName = function(){ * alert(this.myName); * }; * // Subclass the exisitng class and change the name * // when initializing * var MySubClass = videojs.extend(MyClass, { * constructor: function(name) { * // Call the super class constructor for the subclass * MyClass.call(this, name) * } * }); * // Create an instance of the new sub class * var myInstance = new MySubClass('John'); * myInstance.sayMyName(); // -> should alert "John" * ``` * * @param {Function} The Class to subclass * @param {Object} An object including instace methods for the new class * Optionally including a `constructor` function * @return {Function} The newly created subclass * @mixes videojs * @method extend */ videojs.extend = _extendJs2['default']; /** * Merge two options objects recursively * Performs a deep merge like lodash.merge but **only merges plain objects** * (not arrays, elements, anything else) * Other values will be copied directly from the second object. * ```js * var defaultOptions = { * foo: true, * bar: { * a: true, * b: [1,2,3] * } * }; * var newOptions = { * foo: false, * bar: { * b: [4,5,6] * } * }; * var result = videojs.mergeOptions(defaultOptions, newOptions); * // result.foo = false; * // result.bar.a = true; * // result.bar.b = [4,5,6]; * ``` * * @param {Object} The options object whose values will be overriden * @param {Object} The options object with values to override the first * @param {Object} Any number of additional options objects * * @return {Object} a new object with the merged values * @mixes videojs * @method mergeOptions */ videojs.mergeOptions = _srcJsUtilsMergeOptionsJs2['default']; /** * Change the context (this) of a function * * videojs.bind(newContext, function(){ * this === newContext * }); * * NOTE: as of v5.0 we require an ES5 shim, so you should use the native * `function(){}.bind(newContext);` instead of this. * * @param {*} context The object to bind as scope * @param {Function} fn The function to be bound to a scope * @param {Number=} uid An optional unique ID for the function to be set * @return {Function} */ videojs.bind = Fn.bind; /** * Create a Video.js player plugin * Plugins are only initialized when options for the plugin are included * in the player options, or the plugin function on the player instance is * called. * **See the plugin guide in the docs for a more detailed example** * ```js * // Make a plugin that alerts when the player plays * videojs.plugin('myPlugin', function(myPluginOptions) { * myPluginOptions = myPluginOptions || {}; * * var player = this; * var alertText = myPluginOptions.text || 'Player is playing!' * * player.on('play', function(){ * alert(alertText); * }); * }); * // USAGE EXAMPLES * // EXAMPLE 1: New player with plugin options, call plugin immediately * var player1 = videojs('idOne', { * myPlugin: { * text: 'Custom text!' * } * }); * // Click play * // --> Should alert 'Custom text!' * // EXAMPLE 3: New player, initialize plugin later * var player3 = videojs('idThree'); * // Click play * // --> NO ALERT * // Click pause * // Initialize plugin using the plugin function on the player instance * player3.myPlugin({ * text: 'Plugin added later!' * }); * // Click play * // --> Should alert 'Plugin added later!' * ``` * * @param {String} The plugin name * @param {Function} The plugin function that will be called with options * @mixes videojs * @method plugin */ videojs.plugin = _pluginsJs2['default']; /** * Adding languages so that they're available to all players. * ```js * videojs.addLanguage('es', { 'Hello': 'Hola' }); * ``` * * @param {String} code The language code or dictionary property * @param {Object} data The data values to be translated * @return {Object} The resulting language dictionary object * @mixes videojs * @method addLanguage */ videojs.addLanguage = function (code, data) { var _merge; code = ('' + code).toLowerCase(); return _lodashCompatObjectMerge2['default'](videojs.options.languages, (_merge = {}, _merge[code] = data, _merge))[code]; }; /** * Log debug messages. * * @param {...Object} messages One or more messages to log */ videojs.log = _utilsLogJs2['default']; /** * Creates an emulated TimeRange object. * * @param {Number|Array} start Start time in seconds or an array of ranges * @param {Number} end End time in seconds * @return {Object} Fake TimeRange object * @method createTimeRange */ videojs.createTimeRange = videojs.createTimeRanges = _utilsTimeRangesJs.createTimeRanges; /** * Format seconds as a time string, H:MM:SS or M:SS * Supplying a guide (in seconds) will force a number of leading zeros * to cover the length of the guide * * @param {Number} seconds Number of seconds to be turned into a string * @param {Number} guide Number (in seconds) to model the string after * @return {String} Time formatted as H:MM:SS or M:SS * @method formatTime */ videojs.formatTime = _utilsFormatTimeJs2['default']; /** * Resolve and parse the elements of a URL * * @param {String} url The url to parse * @return {Object} An object of url details * @method parseUrl */ videojs.parseUrl = Url.parseUrl; /** * Returns whether the url passed is a cross domain request or not. * * @param {String} url The url to check * @return {Boolean} Whether it is a cross domain request or not * @method isCrossOrigin */ videojs.isCrossOrigin = Url.isCrossOrigin; /** * Event target class. * * @type {Function} */ videojs.EventTarget = _eventTarget2['default']; /** * Add an event listener to element * It stores the handler function in a separate cache object * and adds a generic handler to the element's event, * along with a unique id (guid) to the element. * * @param {Element|Object} elem Element or object to bind listeners to * @param {String|Array} type Type of event to bind to. * @param {Function} fn Event listener. * @method on */ videojs.on = Events.on; /** * Trigger a listener only once for an event * * @param {Element|Object} elem Element or object to * @param {String|Array} type Name/type of event * @param {Function} fn Event handler function * @method one */ videojs.one = Events.one; /** * Removes event listeners from an element * * @param {Element|Object} elem Object to remove listeners from * @param {String|Array=} type Type of listener to remove. Don't include to remove all events from element. * @param {Function} fn Specific listener to remove. Don't include to remove listeners for an event type. * @method off */ videojs.off = Events.off; /** * Trigger an event for an element * * @param {Element|Object} elem Element to trigger an event on * @param {Event|Object|String} event A string (the type) or an event object with a type attribute * @param {Object} [hash] data hash to pass along with the event * @return {Boolean=} Returned only if default was prevented * @method trigger */ videojs.trigger = Events.trigger; /** * A cross-browser XMLHttpRequest wrapper. Here's a simple example: * * videojs.xhr({ * body: someJSONString, * uri: "/foo", * headers: { * "Content-Type": "application/json" * } * }, function (err, resp, body) { * // check resp.statusCode * }); * * Check out the [full * documentation](https://github.com/Raynos/xhr/blob/v2.1.0/README.md) * for more options. * * @param {Object} options settings for the request. * @return {XMLHttpRequest|XDomainRequest} the request object. * @see https://github.com/Raynos/xhr */ videojs.xhr = _xhr2['default']; /** * TextTrack class * * @type {Function} */ videojs.TextTrack = _tracksTextTrackJs2['default']; // REMOVING: We probably should add this to the migration plugin // // Expose but deprecate the window[componentName] method for accessing components // Object.getOwnPropertyNames(Component.components).forEach(function(name){ // let component = Component.components[name]; // // // A deprecation warning as the constuctor // module.exports[name] = function(player, options, ready){ // log.warn('Using videojs.'+name+' to access the '+name+' component has been deprecated. Please use videojs.getComponent("componentName")'); // // return new Component(player, options, ready); // }; // // // Allow the prototype and class methods to be accessible still this way // // Though anything that attempts to override class methods will no longer work // assign(module.exports[name], component); // }); /* * Custom Universal Module Definition (UMD) * * Video.js will never be a non-browser lib so we can simplify UMD a bunch and * still support requirejs and browserify. This also needs to be closure * compiler compatible, so string keys are used. */ if (typeof define === 'function' && define['amd']) { define('videojs', [], function () { return videojs; }); // checking that module is an object too because of umdjs/umd#35 } else if (typeof exports === 'object' && typeof module === 'object') { module['exports'] = videojs; } exports['default'] = videojs; module.exports = exports['default']; },{"../../src/js/utils/merge-options.js":124,"./component":58,"./event-target":90,"./extend.js":91,"./player":98,"./plugins.js":99,"./setup":101,"./tech/flash.js":104,"./tech/html5.js":105,"./tracks/text-track.js":114,"./utils/browser.js":115,"./utils/create-deprecation-proxy.js":117,"./utils/dom.js":118,"./utils/events.js":119,"./utils/fn.js":120,"./utils/format-time.js":121,"./utils/log.js":123,"./utils/stylesheet.js":125,"./utils/time-ranges.js":126,"./utils/url.js":128,"global/document":1,"lodash-compat/object/merge":40,"object.assign":43,"xhr":50}]},{},[129])(129) }); //# sourceMappingURL=video.js.map
example/main.js
teosz/react-chartist
import React from 'react'; import ChartistGraph from '../index'; class Pie extends React.Component { render() { var data = { labels: ['W1', 'W2', 'W3', 'W4', 'W5', 'W6', 'W7', 'W8', 'W9', 'W10'], series: [ [1, 2, 4, 8, 6, -2, -1, -4, -6, -2] ] }; var options = { high: 10, low: -10, axisX: { labelInterpolationFnc: function(value, index) { return index % 2 === 0 ? value : null; } } }; var type = 'Bar' return ( <div> <ChartistGraph data={data} options={options} type={type} /> </div> ) } } React.render(<Pie />, document.body)
src/components/Layout/Header.js
wolfpilot/Traveller
import _ from 'lodash'; import React, { Component } from 'react'; import PropTypes from 'prop-types'; import { Link } from 'react-router-dom'; import history from '../../routes/history'; import SearchBar from '../SearchBar'; class Header extends Component { static contextTypes = { router: PropTypes.object, }; constructor(props) { super(props); this.state = { newTerm: '' }; this.placeholder = "Search destinations"; } search(term) { this.setState({ newTerm: term }); this.context.router.history.push(term ? `/search/${term}` : '/'); } render() { const search = _.debounce((term) => { this.search(term) }, 250); return ( <header className="header"> <div className="container container--padded"> <h1 className="heading">Where would you like to go today?</h1> <SearchBar onSearchTermChange={search} placeholder={this.placeholder} /> </div> </header> ); } } export default Header;
src/svg-icons/device/battery-std.js
w01fgang/material-ui
import React from 'react'; import pure from 'recompose/pure'; import SvgIcon from '../../SvgIcon'; let DeviceBatteryStd = (props) => ( <SvgIcon {...props}> <path d="M15.67 4H14V2h-4v2H8.33C7.6 4 7 4.6 7 5.33v15.33C7 21.4 7.6 22 8.33 22h7.33c.74 0 1.34-.6 1.34-1.33V5.33C17 4.6 16.4 4 15.67 4z"/> </SvgIcon> ); DeviceBatteryStd = pure(DeviceBatteryStd); DeviceBatteryStd.displayName = 'DeviceBatteryStd'; DeviceBatteryStd.muiName = 'SvgIcon'; export default DeviceBatteryStd;